const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/BoostCompanion-TvSTrEwx.js","assets/BoostPanel-Dxhq7cOf.js","assets/useAssistantChat-D-bLdVqH.js","assets/useSmartQueue-KYCSvoTX.js","assets/useBoostGift-sUdFeJxE.js","assets/sun-DOXiBQZb.js","assets/announcements-CHWMrHjI.js","assets/pause-C289TPyh.js","assets/bell-off-CoEttNqU.js","assets/LeadSiteHome-_sM8RJp9.js","assets/useLeadSiteSearchSuggestions-BeEoHqbV.js","assets/hash-CPVRroBT.js","assets/map-DCpkZFeq.js","assets/AgentReviewsSection-Dqbmu6Qm.js","assets/credits-PIR_bev7.js","assets/ExchangeListingsSection-B7OvYxqX.js","assets/leadSiteAgent--GbV6IdE.js","assets/ScrollLivingHero-Cuv8ZLmK.js","assets/LeadSiteLuxuryHome-DnKoiQRJ.js","assets/RecentSalesSnapshot-B0a-Jt79.js","assets/LeadSiteExchangeListings-GnHa8_Zr.js","assets/truck-CUEmScc1.js","assets/LeadSiteLuxuryHome-DKt_VWIz.css","assets/LeadSiteLandRanchHome-C-gl2im8.js","assets/use-in-view-CqSkX5cg.js","assets/tree-pine-DBFfR7gL.js","assets/mountain-D1mJ-3xL.js","assets/LeadSiteSearch-Dc_z8dAt.js","assets/ListingCardExtras-CFGm63Pm.js","assets/bell-ring-BnpeOd8h.js","assets/useInfiniteQuery-CNNiVNX5.js","assets/LeadSiteMap-BsHVVWjW.js","assets/LeadSiteLuxurySearch-srNM2dpt.js","assets/LeadSiteListingDetail-C7J2H_ry.js","assets/ListingVideoTour-39bXplv3.js","assets/expand-Dbaa5H93.js","assets/car-HDNdZGng.js","assets/thermometer-B_mKkonZ.js","assets/snowflake-DrvEw0qQ.js","assets/waves-3zOs9vmh.js","assets/useListingVideos-DO_4PpQF.js","assets/LeadSiteLuxuryListingDetail-DpKa3KxF.js","assets/LeadSiteAbout-S3o2vCyS.js","assets/LeadSiteLuxuryAbout-c_5Z2AX2.js","assets/ExpReadySpotlight-LKjQzWuT.js","assets/LeadSiteBlog-Bc3LsBIb.js","assets/renderPostContent-Czn49UfS.js","assets/LeadSiteCommunity-Gi2eOLE7.js","assets/wine-BKG1lrJX.js","assets/trees-BUwwkiXu.js","assets/plane-B5wQ9eMP.js","assets/music-BxEpoGXo.js","assets/LeadSiteSellers-IDGpfDNO.js","assets/LeadSiteCityPage-COrxgaKu.js","assets/CityFaqSection-lwHCjtyh.js","assets/LeadSiteFocusPage-vIxaVDWJ.js","assets/LeadSiteExpReady-DzcVszMX.js","assets/paintbrush-Cjy3gHdr.js","assets/OrgSiteLayout-CjVommSx.js","assets/orgSiteBrand-DKMUe12O.js","assets/OrgSiteHome-BEQqu82m.js","assets/OrgSiteAgents-C0z63oMv.js","assets/OrgSitePages-Dwj554ng.js","assets/OrgSiteListings-BCxz1F37.js","assets/CanvaSupport-Cgvr3T57.js","assets/unplug-Am9yvVhb.js","assets/SmsOptIn-D8hS2Lrs.js","assets/signpost-DEJ65ED1.js","assets/ConnectChatGPT-B5mQpA05.js","assets/circle-check-big-D6YUNGRH.js","assets/LevelUpMCP-DGz77OC6.js","assets/terminal-CZmfKaWF.js","assets/SubscriptionSuccess-C5CYZX6a.js","assets/SetupBrokerage-Bv6P0LmB.js","assets/InviteSignup-ABw54DPK.js","assets/eye-off-CZGWzVqh.js","assets/CoachingHub-DmhdK55n.js","assets/useCoaching-CoRhVUWk.js","assets/CoachAgentWorkspace-BX9ZprNL.js","assets/CoachingFiles-CJeYpX_3.js","assets/folder-open-DuNgim3a.js","assets/save-IJ6uqj6v.js","assets/MyCoach-CxcIObJb.js","assets/CoachReviews-hoJLYsE7.js","assets/circle-x-yrHGNlXz.js","assets/AdminCoaching-CeNEAT5C.js","assets/arrow-left-right-C-ze2XZV.js","assets/user-minus-CgiSg-e0.js","assets/inbox-rYblPotg.js","assets/CoachBilling-D8-nRbBp.js","assets/credit-card-B0f6SM5_.js","assets/CoachSettings-CMJdnssC.js","assets/GoogleCalendarCard-tmoqZBv1.js","assets/calendar-off-C_DcNiHO.js","assets/useCoachGoogleCalendar-C6eXC2oS.js","assets/link-B4Kz_jg_.js","assets/Microsoft365Return-ZkE_j7yT.js","assets/useMicrosoft365-DZbjRLbv.js","assets/freshAccessToken-BxrId54d.js","assets/CoachWaitlist-xqAwrmDA.js","assets/mail-check-DUN1bQ1r.js","assets/CoachProfile-D-TMrJRh.js","assets/Trial-CxV6-V7n.js","assets/testimonial-avatar-5-DBoTqx4u.js","assets/TrialSuccess-_GOlDSjK.js","assets/party-popper-3qU_kG6q.js","assets/LaborDaySale-BkgASybZ.js","assets/OpenHouseInviteModal-DLPuXQht.js","assets/infinity-eyZW-U0S.js","assets/workflow-DIvX2K9I.js","assets/BrokerageLaborDaySale-CGuTr8Go.js","assets/BrokerageSolutions-MW5zHqHO.js","assets/receipt-B_UfmxfH.js","assets/banknote-lHiJCxMh.js","assets/pencil-line-SpLhZlpg.js","assets/Upgrade-C3ZqRgzS.js","assets/log-in-DyKgIdJS.js","assets/InstagramGift-D7Se_yfk.js","assets/VideoShare-CgtOcGQB.js","assets/VideoPageTemplates-BND8vPWP.js","assets/message-circle-heart-Cx89YF_6.js","assets/door-open-BgdFUdZ2.js","assets/brain-6Q58GUtJ.js","assets/coffee-DcLhetQA.js","assets/CommercialWizard-CwveRjPR.js","assets/useListingExchange-a6AKKvis.js","assets/useTeamListingAccess-D53Jpt_e.js","assets/CommercialWorkspace-0yn0CM4e.js","assets/ListingSocialDialog-CzlrO3Qm.js","assets/useAgentBrand-RpmLaz7t.js","assets/listingGraphic-DK4hceaL.js","assets/ListingPhotoGrid-B32rWDS4.js","assets/sortable.esm-prOvUd-c.js","assets/grip-vertical-C6w6ksD-.js","assets/ShareListingDialog-NUuUdQhf.js","assets/EmailListingToSphereDialog-cKCAxiee.js","assets/index-DAUVZ2Gb.js","assets/separator-DFSCzSBh.js","assets/GmailComposeDialog-n1xeXzB8.js","assets/useMassEmailReady-Fc8Jd7oE.js","assets/useSenderIdentity-C2iYMCJ0.js","assets/useVerifiedSenderCheck-BGK7xWSi.js","assets/VerifySenderRequiredDialog-DTunYGmZ.js","assets/useContactIntakePage-CbP0s_W5.js","assets/ToContactAutocomplete-DZdYs2Ix.js","assets/outlookSend-CYh3p-3j.js","assets/paperclip-CQQhR0y2.js","assets/file-search-DCEgnML8.js","assets/qr-code-DfKc8Rwl.js","assets/CommercialPitchPreview-CHOEGUYh.js","assets/PublicLiveEvent-BYG5sOY9.js","assets/pin-CvYwAeGi.js","assets/arrow-up-BSuMdHVS.js","assets/useLiveEngagement-gqdspeJB.js","assets/sparkle-DM3TZ5Ew.js","assets/LiveEvents-Bm2U_BYG.js","assets/AdminPageHeader-MgA8ZSqX.js","assets/useLiveEvents-DU3v6xx9.js","assets/image-plus-CPbSZFjC.js","assets/LiveEventConsole-ClNMboVK.js","assets/mouse-pointer-click-CC5JAvbr.js","assets/ban-CK_YkDTJ.js","assets/Dashboard-Afc2AIaQ.js","assets/useContentEngagement-DX_if0b1.js","assets/usePrograms-DwKHePim.js","assets/timezone-ET2C_CYc.js","assets/addMilliseconds-C6DMzCUz.js","assets/isWithinInterval-DzV5s3GK.js","assets/useGmailIntegration-h2q5CCpf.js","assets/GoalTargetsDialog-CZNWJpZ0.js","assets/useBrokerageContent-BA-vEv7w.js","assets/beta-badge-CRdBH-AN.js","assets/useEventGamification-tdBP3wTf.js","assets/RelationshipHealthWidget-CUB4lpEO.js","assets/useRelationshipScore-BQIcLPxH.js","assets/file-image-DLV3ASiW.js","assets/Profile-BM8_PBs9.js","assets/RichTextEditor-BhNMn3L0.js","assets/index-CeGfUPTM.js","assets/index-BXuVkzlN.js","assets/index-uZrAzHOR.js","assets/heading-1-BtsmFR2J.js","assets/heading-2-r-8tUNYT.js","assets/undo-mVTMJn0p.js","assets/list-ordered-CCMVpd28.js","assets/align-left-D7e96N78.js","assets/align-right-DKeKKfxe.js","assets/ImageCropper-DpS2Dpwp.js","assets/zoom-out-QCDpVcnc.js","assets/rotate-cw-B_QWK-vr.js","assets/ImageCropper-D8Md-CES.css","assets/useBrandKit-BHR3Js9o.js","assets/useStagingStudio-BqX3yqjq.js","assets/checkoutTab-CHR6_Yej.js","assets/BrokerageLogoUpload-CwH4h373.js","assets/user-round-DN2Yrd3W.js","assets/mail-x-BoZgQGeS.js","assets/Events-CxrcD9-d.js","assets/EventLeaderboard-NNEXl7Rt.js","assets/medal-bQqvwrgd.js","assets/MainStageSchedule-OvXphQAL.js","assets/history-DvVRhPtt.js","assets/EventDetail-Cmb91V4S.js","assets/ShareButton-BaZzmMEO.js","assets/user-cog-CXsCGQiY.js","assets/Apps-XeDNmIn9.js","assets/monitor-play-COQuflJw.js","assets/skip-forward-DiZPhJDC.js","assets/Templates-TsymEUVH.js","assets/TemplateDetail-B1N287tk.js","assets/Programs-Bsoh9ayq.js","assets/ProgramDetail-iNFKI2C8.js","assets/accordion-R8Km9Gdq.js","assets/index-C5PGl7W7.js","assets/ProgramEnroll-cx7XoAoU.js","assets/tag-Dr5BL_i-.js","assets/ProgramWorkspace-9BSCK1hi.js","assets/file-spreadsheet-Ccuj5WhE.js","assets/layout-template-BrtKmimQ.js","assets/Programs-BuQk0nOR.js","assets/route-Czftd8wX.js","assets/collapsible-DawKjX6i.js","assets/AcademyVideoDetail-DdkzEEtt.js","assets/LinkedTemplatePills-Ba6_BxaM.js","assets/ToolboxDetail-D9f0sYa0.js","assets/SocialSwag-CYIISl5_.js","assets/SocialStudio-BbR7c5Y3.js","assets/CanvaImportDialog-CFCViHe9.js","assets/useCanvaMailStudio-CMS7LhFl.js","assets/unlink-BoU2TToT.js","assets/platforms-kyyJKz9s.js","assets/music-2-D3gw9IP4.js","assets/jpegConvert-DWTsW_Wr.js","assets/repeat-2-lPxQUI3M.js","assets/type-CzeCKD81.js","assets/settings-2-Cgzdmg1n.js","assets/scheduleTz-B2PWEOYN.js","assets/calendarTz-JHe45SGp.js","assets/YouTubePublishing-gF2c6bfu.js","assets/useCalendarTimezone-Diu2SUiW.js","assets/CalendarSettingsDialog-BNqJ9Spo.js","assets/earth-DF7neZqy.js","assets/tiktokCallbackError-HhZqZSBp.js","assets/edgeError-D_dYKmsd.js","assets/jszip.min-CxtybJqt.js","assets/MarketingStudio-BnLvvIFk.js","assets/message-square-quote-CDEuOIga.js","assets/BrandKit-BR7Jdldt.js","assets/useBrandPresets-DAk8IQ2F.js","assets/BrandingBarEditor-B1Y6nEgv.js","assets/ReactKonvaCore-D1KrGzID.js","assets/index-CCvSXrho.js","assets/ListingTemplates-DOYrxbqV.js","assets/index-xVp0PEHv.js","assets/EditorialTemplate-Dv9DNmck.js","assets/PersonalBranding-Bd7HPa-i.js","assets/toggle-group-0fPqrjK9.js","assets/SocialSwagDetail-D-ZNVPKE.js","assets/Community-B2Dp2myL.js","assets/MentionTextarea-BXUm2Ii0.js","assets/reply-Sl8kGx3N.js","assets/pin-off-4NUTrzqs.js","assets/Support-DzT_PogT.js","assets/SupportAttachmentList-i8U_ZMPG.js","assets/file-video-CP88ZT4p.js","assets/BrokerageResources-BjYiVSs2.js","assets/AdminDashboard-CzHg3Xt4.js","assets/coins-DMJH-faU.js","assets/shopping-bag-D4Exv7bN.js","assets/flask-conical-CR7QCGV-.js","assets/database-DjtetGDF.js","assets/MemberManagement-cxcpRKLI.js","assets/SendCelebrationDialog-BQW6l1m4.js","assets/sortable-table-head-BxItKI1r.js","assets/arrow-down-D-XvA23f.js","assets/useTeams-mxzpdH_z.js","assets/CreateTeamDialog-CeBKx8om.js","assets/TeamSharedAssetsView-DEORX1_6.js","assets/LeadPondView-CMjdcZaR.js","assets/arrow-right-left-C94P6VPM.js","assets/sticky-note-WhC2KqQz.js","assets/droplets-Ckl3dYyB.js","assets/hand-DUhSmu9f.js","assets/contact-CTlljwqU.js","assets/crown-BPPWpR5z.js","assets/calendar-heart-GUTkmc6Y.js","assets/UnassignedMembers-Csy7ImAg.js","assets/InviteCodes-DhM9gKw2.js","assets/Events-CfuML_Ps.js","assets/useNotifications-DtMPapku.js","assets/repeat-CcyAtg4L.js","assets/MCPAuditLog-DG612QPL.js","assets/shield-alert-BJqbNFbz.js","assets/Templates-Doy9z7LB.js","assets/Academy-CrpR9RWC.js","assets/LinkedTemplatePicker-BWuZu6A5.js","assets/VideoLibraryPicker-PzW2-nNc.js","assets/Toolbox-Cq2uxxCZ.js","assets/SocialSwag-BitQA1Ek.js","assets/SocialSwag2-CNhiftvC.js","assets/Community-n41Ks1AX.js","assets/Analytics-CNYgl3t9.js","assets/ShareAnalytics-Lr4h_7kL.js","assets/mouse-pointer-CXbMiPPt.js","assets/panels-top-left-Zx3XSQq2.js","assets/LineChart-BMsSCYPl.js","assets/chrome-D8IaRjCV.js","assets/BrokerageResources-4SRxJW-7.js","assets/DashboardManagement-G3LlFMOI.js","assets/SupportTickets-BteGBgrk.js","assets/EmailTemplates-CE4JgfGe.js","assets/index-BumWqfk1.js","assets/code-B1wraCzW.js","assets/variable-6S1XZ0Cy.js","assets/monitor-Cd7Pva9n.js","assets/AgentEmailTemplates-DZkvrT6Q.js","assets/BrokerageDashboard-sSP5mkhT.js","assets/BrokerageLenderReport-D6QdAASz.js","assets/MyBrokerage-BSViSleE.js","assets/useBrokerageOnboarding-Bjin9B-_.js","assets/OnboardingChecklist-B8c-TwVh.js","assets/BrokerageContent-ctKtRiVH.js","assets/BrokerageHelpBoard-BnZouWXV.js","assets/useBrokerageHelpBoard-K9J3hXn1.js","assets/BrokerageHelpBoardNew-OdSwdyfo.js","assets/BrokerageHelpBoardDetail-CIgKRnwm.js","assets/Newsletters-S8gfYlyB.js","assets/useMailingAddressGate-DJ6gBXYS.js","assets/NewsletterGraphicsPicker-CJptFDQf.js","assets/underline-Dh0lLVAI.js","assets/SenderAddressDialog-DGAsHTWb.js","assets/uploadBase64Images-BJqjZpfU.js","assets/SendNewsletterDialog-DDJUriEW.js","assets/undo-2-DbzyMjTc.js","assets/useContactCustomTags-751BSvPr.js","assets/useSmartLists-tEDdHcMB.js","assets/code-xml-CTLdH1TE.js","assets/list-filter-hUB59R_8.js","assets/NewsletterDetail-BjTJStXY.js","assets/Newsletters-CqFSo02i.js","assets/library-BmCI_W7t.js","assets/MemberBroadcasts-C0c2buDf.js","assets/bookmark-plus-zIN3Va-H.js","assets/BoostAnnouncements-DwPphQyB.js","assets/NewsletterGraphics-D-yvnLJ_.js","assets/Wishlist-slkkyAd4.js","assets/WishlistDetail-D_1MvFvq.js","assets/LevelUpBrief-Bh3NE97g.js","assets/AdditionalServices-BOtGsJ_b.js","assets/Discounts-BGKiWw04.js","assets/Subscriptions-BDQe2JLo.js","assets/instagramEmailReview-DK4Cq88H.js","assets/InstagramGiftEmails-DjnEnGBC.js","assets/Referrals-BoyeJWO0.js","assets/AgentOSControlCenter-DMnfqV2R.js","assets/AskAI-D7jwcJH_.js","assets/InnerCircleHome-B8KnEBPH.js","assets/SnoozeContactDialog-Czlpke1H.js","assets/pen-tool-Bjoi3LAz.js","assets/milestoneMail-Cs6qfJaR.js","assets/handoff-B7AOa2Ye.js","assets/milestones-De303X1G.js","assets/stamp-l7Tvt6n3.js","assets/mail-open-CiEfvtmS.js","assets/InnerCircleContacts-xo1YCZJY.js","assets/mailingAddress-BJ5Zh-Ye.js","assets/SyncDirectionSelector-CfoeNj7e.js","assets/refresh-ccw-JUUToKK5.js","assets/merge-Mu9r_LqM.js","assets/ContactCriteriaForm-C1C2Y6NY.js","assets/usePopbys-DwcAuqTc.js","assets/ContactTagChip-Ba6bpZf-.js","assets/info-Dv-WGn5D.js","assets/RelationshipScoreBadge-r63BmRxr.js","assets/MailStudioHandoffButton-BypucWui.js","assets/useVideoShareTracking-CPFwiUx4.js","assets/EnrollContactsDialog-DlljeIPF.js","assets/useDripCampaigns-BpDeWPM2.js","assets/CampaignBuilderDialog-BJqEia6g.js","assets/quill.snow-B6gne1Or.js","assets/quill-BzY4kI8E.css","assets/braces-B8q3obdF.js","assets/VideoUploadDialog-DNWt4BgS.js","assets/useVideoTouch-D9tWgAfU.js","assets/NeighborhoodFilter-B_osqmyR.js","assets/useNeighborhoods-DtXd04xl.js","assets/sphereMap-BEKmXMRz.js","assets/sprout-dWRv4kkS.js","assets/ContactAvatar-C8KfsyUo.js","assets/user-x-BA8tTKrw.js","assets/map-pinned-LN_9d74N.js","assets/InnerCircleContactDetail-DpXZxLC4.js","assets/useLenders-agLEMedW.js","assets/SendToLenderDialog-mczADbe6.js","assets/useCMA-D42LVM_J.js","assets/useClientPortal-BQhd5eVA.js","assets/AiCmaDialog-C4hTW3WY.js","assets/futureSeller-DwX_Pzaj.js","assets/useSentEmails-CM5ssAFY.js","assets/propertyService-CdlyCmAN.js","assets/building-CqRrjf1W.js","assets/archive-Cxq-Jxhp.js","assets/useContactFinder-BYWOXl_8.js","assets/SentEmails-CDSN0JE-.js","assets/InnerCirclePlans-9X32E1WP.js","assets/pen-BFY9g5Mh.js","assets/CMAList-guvf3-Ci.js","assets/SendCMADialog-BhXrcs5D.js","assets/UpgradeLockedCard-rNMBCxvg.js","assets/CMABuilder-47EgfXRE.js","assets/VideoRecorder-CRo_01Aj.js","assets/flip-horizontal-BNF8cbm_.js","assets/videoSegmentation-23AN6N06.js","assets/monitor-up-FI5JpbJW.js","assets/mic-1xN7CqDF.js","assets/ListingPresentations-DIhV93QW.js","assets/session-eLdkTH7C.js","assets/jspdf.es.min-B1Yy5NsX.js","assets/SendPresentationDialog-azu75e8J.js","assets/ListingPresentationBuilder-CMjJOxKe.js","assets/PdfCanvasPreview-BcfYMb6R.js","assets/pdf.worker.min-LRAbGNxL.js","assets/ImageUploadField-B3NzKRSs.js","assets/move-CI4L8ydn.js","assets/InnerCirclePopbys-D9Tmp363.js","assets/locate-CtQpYPqV.js","assets/navigation-Tz46KINs.js","assets/ListingExchange-CWrhA7-u.js","assets/ListingLaunchKitModal-DoHpETsH.js","assets/ListingSelectionBar-CwLDexiB.js","assets/musicVideoHandoff-Bs6IOG8F.js","assets/ListingDetail-C_MPhFjZ.js","assets/ListingForm-DafMk9SL.js","assets/CustomizeListingPage-C17JHlzB.js","assets/box-DBfi0uln.js","assets/VideoStudio-DU7a071t.js","assets/wifi-CuBWP7HJ.js","assets/VideoShareWithTemplate-Dh76X5MK.js","assets/useStageChat-C7X3NXZh.js","assets/chatHistory-BbSJc4Cq.js","assets/browser-CjSdxGTc.js","assets/tv-Lra-_hQc.js","assets/video-off-7rw92fPC.js","assets/guestRoom-J78VJHsB.js","assets/kits-DACmZcCF.js","assets/BackdropPanel-4nnXoxuF.js","assets/ListingPhotoImport-BTw5WH2p.js","assets/images-Bypl-pey.js","assets/panel-right-close-CcWMdim7.js","assets/clapperboard-Bhunvs24.js","assets/scissors-BMQZxQh3.js","assets/switch-camera-LDOjO_hv.js","assets/MainStageGate-B4Uw7Qvo.js","assets/survey-Dcck3MtS.js","assets/phone-off-CzAG5xxQ.js","assets/eraser-Dfaqa3zY.js","assets/theater-r17x4bOs.js","assets/MainStageAdmin-DxV_q4Kw.js","assets/StudioKitsAdmin-CuX1QWl4.js","assets/StudioGuestJoin-DcaSVH4Z.js","assets/VideoLibrary-tmj7uNYX.js","assets/tags-CcrcwOQX.js","assets/hard-drive-CV2RbmZA.js","assets/DealPipeline-QbuaHw0b.js","assets/lucide-react-Dxt7rLbN.js","assets/archive-restore-BpOklF9P.js","assets/arrow-down-left-BFgIhqds.js","assets/arrow-down-right-C177Zv1g.js","assets/badge-check-DtySY4m8.js","assets/circle-user-DHoMRmHL.js","assets/beaker-CZsy7CEn.js","assets/brain-circuit-C5qcoYXh.js","assets/calendar-x-BvLS9Lik.js","assets/chart-line-SpKDTRtD.js","assets/file-code-BNNwXMGY.js","assets/table-D7ZIsY-J.js","assets/circle-dollar-sign-Rh8BH-D_.js","assets/clock-3-CTQOIZyt.js","assets/sunset-DJRbmdaQ.js","assets/cloud-upload-DVp6h5rD.js","assets/corner-down-right-o3P1B0bp.js","assets/file-check-2-BUNqRm0A.js","assets/hammer-OreumBIM.js","assets/file-down-BJZX12rj.js","assets/file-plus-2-B-HYjmVm.js","assets/piggy-bank-Cy9m0MMx.js","assets/folder-plus-6cCqbl6p.js","assets/folder-wDLpRk0B.js","assets/footprints-C05iJ-16.js","assets/gem-BQiU6dRM.js","assets/hand-heart-0W_Nrvz1.js","assets/heading-3-f1vWE6Pb.js","assets/heart-handshake-C7vRUdNL.js","assets/id-card-mkNqFrsK.js","assets/locate-fixed-BP3WCiS_.js","assets/list-plus-JiWS2qWK.js","assets/lock-keyhole-CqAzy-FO.js","assets/mail-plus-DT_7MSpT.js","assets/mail-warning-k5rq-AAw.js","assets/message-square-more-Cc9eVDo7.js","assets/message-square-plus-oP2SspD2.js","assets/message-square-reply-BD4yQwAS.js","assets/messages-square-ouo83dEZ.js","assets/mouse-pointer-2-C3r70p04.js","assets/skip-back-EqAJ-aN6.js","assets/octagon-alert-jUbG0Q75.js","assets/power-off-DDZqlD10.js","assets/power-B6R80M8V.js","assets/rectangle-vertical-DEKBZr1j.js","assets/scroll-text-BbFCODrw.js","assets/shield-off-7gGFoc4K.js","assets/shield-question-Bq-_rj8C.js","assets/shuffle-CoVuOTpQ.js","assets/table-2-BavSF-el.js","assets/text-cursor-input-DQVldZ07.js","assets/thumbs-down-LlR7SsM9.js","assets/twitter-sRSD5w3I.js","assets/user-round-check-CGCWmIVm.js","assets/user-round-search-DSIHyTL4.js","assets/users-round-kbPmga4H.js","assets/useCommissionPlans-Cmfo3yCa.js","assets/ComplianceMessageThread-BNVUzoa8.js","assets/SendForSignatureDialog-B61KlPbF.js","assets/useFormEnvelopes-CHNgpU87.js","assets/PortalInviteDialog-BfJzjSiX.js","assets/CardVideoRecorderDialog-z9ixMHsN.js","assets/PlaybookLibraryDialog-4jTTZ-pX.js","assets/LenderPartnerDialog-C92D6Brn.js","assets/PhotoUploadField-BGcyXnOn.js","assets/PortalListView-CIgUAfSz.js","assets/complianceMetrics-Ce83UgLe.js","assets/FormsLibrary-De3RIdz1.js","assets/FormPlacementEditor-CF-lcwy4.js","assets/TransactionCoordinator-D2XbHWTc.js","assets/PortalReferrals-C7NW-Y4H.js","assets/usePortalReferrals-DJYrcv9P.js","assets/AgentVendors-BJ8jThMU.js","assets/VendorFormDialog-DZI7_6jH.js","assets/BrokerageForms-RWv1JLC3.js","assets/BrokerageVendors-BIvhnnOD.js","assets/ClientPortalsHub-D_tyXs_H.js","assets/PortalMessagesPanel-5I345loH.js","assets/ClientPortalDetail-nkeZNlyD.js","assets/MyCardEditor-C6QBwB9t.js","assets/CardBlocksEditor-DKm3T__m.js","assets/Integrations-BDikZQvU.js","assets/SesIntegrationCard-DcPDdVDh.js","assets/RecruitVerifiedSenders-D829rWqj.js","assets/Microsoft365Card-CTwFfACp.js","assets/BrowserExtension-C06WbHOM.js","assets/IntegrationsGmailCallback-DxY88wj1.js","assets/IntegrationsMetaCallback-9eVzPQOI.js","assets/AgentActivation-FLJrCW_T.js","assets/MembershipReviews-COlf0JbB.js","assets/LeadNotifications-doM3MgjP.js","assets/WeeklyDigest-ZSfzlSKI.js","assets/AgentPoints-Cf5WRuEW.js","assets/AgentCards-BU9G3s11.js","assets/Marketplace-Bzb2oux3.js","assets/RewardStore-hPRoflrv.js","assets/usePointRewardSettings-Cmcr8ldU.js","assets/Integrations-BVlbwjeL.js","assets/SocialConnections-DMkJMEHV.js","assets/SocialAutopilot-xmzlZwFM.js","assets/McpUpdates-D8CY_EE8.js","assets/NotificationSettings-Bx2i1C6j.js","assets/PresentationAnalytics-DPjrpxY2.js","assets/ListingPresentationStudioAdmin-CbF3HMJB.js","assets/ListingRevivalAdmin-BTOtZ3Rj.js","assets/useListingRevivalAccess-DtThzLub.js","assets/GuestBookAnalytics-BWK0XwbU.js","assets/IntegrationsCallback-Dl7WeLK-.js","assets/AdminRecruiting-UP_86DEI.js","assets/RecruitPipelineStageEditor-CnyFUgRx.js","assets/index-BxtpRxPJ.js","assets/BrokerageRecruiting-B7g8ZWpV.js","assets/600-BSKZD_mM.css","assets/BrokerageOnboarding-D1L1AgSi.js","assets/BrokerageTransactions-D8PgsjQi.js","assets/useDealEscrow-DiWCEQJG.js","assets/BrokerageOperations-DIkH5D8l.js","assets/renewals-DFeknAfX.js","assets/WebsitesHub-Byw3zjBO.js","assets/useMyWebsites-B8PXKcWG.js","assets/SiteGrade-iE3ogpqW.js","assets/TeamWebsite-DxZj13Oh.js","assets/OrgSiteBuilder-BwkpxbXK.js","assets/SiteSwitcher-Cky9obRr.js","assets/BrokerageWebsite-BTrvFlJH.js","assets/BrokerageAgentWebsites-BwP2VdeU.js","assets/BrokerageCommissionPlans-BmFF9V3g.js","assets/BrokerageContentActivity-2kphvxFa.js","assets/BetaSocialPostGenerator-DdVE6fVt.js","assets/AdminLMS-CZ6-n2Cz.js","assets/useLMS-C1F4vREM.js","assets/AdminCourseDetail-BVXMmMJ0.js","assets/LevelUpU-B2SJzzLH.js","assets/LevelUpUCourse-B0fdGALn.js","assets/MobileAgentApp-CyusgRdM.js","assets/StagingStudio-fXXJNsTF.js","assets/presets-CmSXL2UR.js","assets/download-BqCckdNk.js","assets/BeforeAfterSlider-DxZFsI2B.js","assets/BuyCreditsDialog-DlN-Sxka.js","assets/StagingLibrary-aOjj4nTg.js","assets/StagingCredits-Oj0tnJl5.js","assets/AgentWallet-LdZW9bBw.js","assets/useHomeReel-BBZjxqfe.js","assets/StagingSharePage-ChGCbJeo.js","assets/StagingStudioAdmin-CX8e7EYK.js","assets/ContactFinderAdmin-po0oW8Oc.js","assets/PostcardManager-1Ra-iLOj.js","assets/PostcardZoneEditor-DZ2BB_O_.js","assets/usePostcardZones-FL9dyhlF.js","assets/MailStudioTemplates-Ck05pGYj.js","assets/HomeReelManager-Ag8Yp9QC.js","assets/videoRenderSink-KDd1M0JO.js","assets/AdminMusicVideos-Ckd_TvRe.js","assets/AdminVideoLab-D7v90RiJ.js","assets/BoostPreview-B12VI4-p.js","assets/AdminCredits-7N2XOzli.js","assets/MailStudio-D7XoXqFN.js","assets/farmToCrm-CGPcROuE.js","assets/artwork-jEOl21Jb.js","assets/MailStudio-D-BotKHo.css","assets/InnerCirclePopbyMap-DDN1w81f.js","assets/SphereMap-BqygAVt3.js","assets/PropertyIntelligenceDashboard-ZE1fgtg7.js","assets/LiveVisitorFeed-BqkdE3HI.js","assets/LeadSites-KehlkHfV.js","assets/LeadSiteEditor-CKvC-7FK.js","assets/ImageUrlField-C0eh-x6n.js","assets/HomepageModuleManager-ejxX0y6v.js","assets/VideoUrlField-B3yvu2Dj.js","assets/AdminLeadSiteThemes-BhDxFO4r.js","assets/AdminFreeWebsiteOfferStudio-Beq0nwDX.js","assets/AdminMlsFeeds-DgnNXUTL.js","assets/AdminWebsiteRequests-DWu-_g8Y.js","assets/NeedAWebsite-D7tqwMaF.js","assets/MLSListings-BFtS-sDI.js","assets/MLSListingDetail-C3CuXAaX.js","assets/WebsiteActivityPage-DVEIN3_e.js","assets/PublicRecruitForm-Caa6Z4a7.js","assets/PublicEventInviteUnsubscribe-DOmoU3AX.js","assets/SocialConnections-IbODS_z7.js","assets/SocialConnectionsCallback-BSbskEOj.js","assets/LinkedInCallback-B71CMmGf.js","assets/TikTokCallback-De3mcM2F.js","assets/MarketplaceCart-Amx4J-1x.js","assets/MarketplaceOrderDetail-oIm1nX9Q.js","assets/RewardStore-DEdjn1dn.js","assets/ReferFriends-BwTQ2QeD.js","assets/SmartPresentations-Cg8GeEXc.js","assets/useSmartPresentations-D-1tUmp7.js","assets/SmartPresentationCreate-C1AGE_y7.js","assets/TeleprompterOverlay-5D6nOT4x.js","assets/GuestBook-CeBsSx6v.js","assets/SignDocument-BHYTghE4.js","assets/Blog-Bed3pjxD.js","assets/TrialCTA-B5W13Apt.js","assets/BlogPost-CNWxafYE.js","assets/AdminBlog-B-01j6th.js","assets/ReviewLanding-BpPM1oOg.js","assets/ReviewIntake-0-reEJmb.js","assets/PublicReviewsPage-B5vF9llo.js","assets/PublicReviewSubmit-y9wBElQW.js","assets/Reviews-CKg4u-V7.js","assets/NetSheets-C7JhI87-.js","assets/LenderHub-DrQ60Heq.js","assets/states-BVqvKcH4.js","assets/LendersLanding-CMXyBLBS.js","assets/LendingPartners-BDLahxGz.js","assets/AdminLenders-BhT0EAFC.js","assets/CardStudio-ClkrCWsW.js","assets/ListingStudio-QhZYQMv3.js","assets/SmartDrips-BxR9BmLh.js","assets/WeeklyReels-DrOr3AqK.js","assets/ReelCard-Gm0MDEmU.js","assets/useWeeklyReels-BG_sHMQB.js","assets/WeeklyReelsOnboarding-DU47GCow.js","assets/WeeklyReelsAdmin-BI-zcnDW.js","assets/AttractLayout-CULD9gBD.js","assets/useAttractSettings-Phrm0sIU.js","assets/useAttractIntelligence-CVGgUBS9.js","assets/HealthScoreBadge-DRn3QJSN.js","assets/AttractToday-DkZddU48.js","assets/useAttractIntelSync-B2owu9RX.js","assets/useAttractAgents-BdsCVN3j.js","assets/useAttractFollowUps-BphpY1dI.js","assets/useAttractActivities-O6hsRicE.js","assets/RecommendationCard-CnICpowM.js","assets/QuickAddRelationship-BqRI1SEP.js","assets/relationshipStages-Buh5_cBI.js","assets/useAttractEvents-B_fWCysO.js","assets/AttractRelationships-BNvClaPE.js","assets/AttractPageHeader-CxQib99C.js","assets/AgentEditSheet-BVCA1AN2.js","assets/AttractFollowUp-DOcqjDZv.js","assets/AttractTemplates-DbR_VSFn.js","assets/AttractReports-Cn4jG2wt.js","assets/AttractSettings-_PLHYmri.js","assets/AttractToolkit-DvMivc8A.js","assets/Objections-MONbHh0T.js","assets/AttractCalculator-MHJN8JeY.js","assets/attractionPageTemplate-C9AaZMgq.js","assets/AttractEventList-CTDVAdgV.js","assets/AttractEventBuilder-tt3FyuHf.js","assets/useAttractKits-CRwOjoM9.js","assets/AttractEventDetail-BD5uW4Mm.js","assets/AttractEventCheckIn-BBfAXUAd.js","assets/AttractOnboarding-CR-S5GfU.js","assets/ContentStudio-Df5AOye4.js","assets/KitList-BdejGJkW.js","assets/KitBuilder-ClY1X-Qz.js","assets/KitPreview-DQY1k9-1.js","assets/KitAnalytics-DOGaXLb1.js","assets/KitTemplates-Co9FHKAG.js","assets/AttractAgentDetail-DkCpFW1h.js","assets/AttractOpportunities-DMybbah_.js","assets/AttractIntelligenceDebug-COnxtcBA.js","assets/PublicAttractKit-DYEOKuY_.js","assets/PublicAttractEvent-DAMRSerC.js","assets/PublicAttractionPage-2nQrcWtc.js","assets/AttractionPageView-z53db-Fh.js","assets/RevivalLanding-BWAvUGCa.js","assets/types-Bbp_6W6m.js","assets/RevivalPlan-Di26h3L5.js","assets/revivalPdf-BtRDFU-r.js","assets/ListingRevival-BIR1oGkk.js","assets/useListingRevival-WAgcovfR.js","assets/AreaChart-Dh28UzC4.js","assets/RevivalCampaignWizard-C3G4lBGQ.js","assets/campaignMail-C5bYtnwt.js","assets/RevivalCampaignDetail-DGQyqLhz.js","assets/LetterEditor-CxykuPlw.js","assets/FsboBreakthrough-asc8qN42.js","assets/useFsboBreakthrough-ClPuPqC6.js","assets/types-CK1tolb7.js","assets/FsboPropertyDialog-t0Gp4glL.js","assets/FsboCampaignWizard-DTZ2nUmH.js","assets/FsboCampaignDetail-DsHLc3br.js","assets/FsboLanding-C1pI9vfI.js","assets/publicApi-BEaFpcRg.js","assets/FsboGuide-kIgR0N69.js","assets/FsboBreakthroughAdmin-DkNFhwlj.js","assets/AttractLandingPageBuilder-aZcf96JX.js","assets/AttractAccess-CbOdgL6K.js","assets/Teams-Dg6feFOs.js","assets/MyTeam-Bce6n08E.js","assets/TeamLeaderSettings-800-f0r1.js","assets/TeamHub-uHgkN3T9.js","assets/SchedulerSettings-BhzFe0uM.js","assets/MyCalendar-CNMgJ5uC.js","assets/BookingManagePage-BJkZgWd9.js","assets/LandingPages-BswntYeF.js","assets/BuyerMatch-DcMCxHYK.js","assets/SendBuyerMatchEmailDialog-BoWB9b2e.js","assets/BuyerMatchEditor-SHpctJOf.js","assets/matching-BdEgbJjD.js","assets/PublicBuyerMatch-CyBp2KB3.js","assets/LandingPageEditor-Dd6MR42e.js","assets/LandingPageDefaults-C-HPjxB5.js","assets/WebsiteAppsHub-BMCkUnop.js","assets/ClaimFreeLeadSiteCard-BKy8uM7K.js","assets/useWebsiteApps-BfaRKMEx.js","assets/ClaimWebsite-CO_ckbsB.js","assets/VideoGreeterEditor-BB2K8GZT.js","assets/ExitIntentEditor-Bx8ewHQ8.js","assets/widgetTemplates-keLygp7O.js","assets/LeadMagnetEditor-DK6Y1Hdt.js","assets/RelationshipScorecard-CuCvgDl9.js","assets/SphereGaps-DBtgVxsx.js","assets/ConnectPageSettings-XjNwhXim.js","assets/EmailCampaigns-BHeF4Xwi.js","assets/sesRequest-Be9btVY3.js","assets/EmailCompliance-D51gNi6S.js","assets/EmailCampaignComposer-jgJTAmlw.js","assets/EditorModeSelector-BPCFJRmf.js","assets/EmailCampaignDetail-Ol87jW6C.js","assets/SharedCampaignTemplates-DHok-wNG.js","assets/TemplateEditorDialog-7lN-5VaY.js","assets/AgentTemplates-C0CEy5IF.js","assets/TheLocalMoveHome-BnuzWJ0Y.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-2q9BHPYl.js","assets/TheLocalMoveCheckout-DlRQwVa5.js","assets/AdminWebsiteOrders-BLeniFss.js"])))=>i.map(i=>d[i]); var WIe=Object.defineProperty;var gJ=t=>{throw TypeError(t)};var KIe=(t,e,r)=>e in t?WIe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var dn=(t,e,r)=>KIe(t,typeof e!="symbol"?e+"":e,r),MB=(t,e,r)=>e.has(t)||gJ("Cannot "+r);var Tt=(t,e,r)=>(MB(t,e,"read from private field"),r?r.call(t):e.get(t)),Qn=(t,e,r)=>e.has(t)?gJ("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),_n=(t,e,r,n)=>(MB(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),qi=(t,e,r)=>(MB(t,e,"access private method"),r);var RP=(t,e,r,n)=>({set _(i){_n(t,e,i,r)},get _(){return Tt(t,e,n)}});function YIe(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 tc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ds(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function ZIe(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 yde={exports:{}},NO={},xde={exports:{}},Zi={};/** * @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 mC=Symbol.for("react.element"),XIe=Symbol.for("react.portal"),QIe=Symbol.for("react.fragment"),JIe=Symbol.for("react.strict_mode"),ePe=Symbol.for("react.profiler"),tPe=Symbol.for("react.provider"),rPe=Symbol.for("react.context"),nPe=Symbol.for("react.forward_ref"),iPe=Symbol.for("react.suspense"),sPe=Symbol.for("react.memo"),aPe=Symbol.for("react.lazy"),yJ=Symbol.iterator;function oPe(t){return t===null||typeof t!="object"?null:(t=yJ&&t[yJ]||t["@@iterator"],typeof t=="function"?t:null)}var vde={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_de=Object.assign,bde={};function HS(t,e,r){this.props=t,this.context=e,this.refs=bde,this.updater=r||vde}HS.prototype.isReactComponent={};HS.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")};HS.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function wde(){}wde.prototype=HS.prototype;function TG(t,e,r){this.props=t,this.context=e,this.refs=bde,this.updater=r||vde}var EG=TG.prototype=new wde;EG.constructor=TG;_de(EG,HS.prototype);EG.isPureReactComponent=!0;var xJ=Array.isArray,Sde=Object.prototype.hasOwnProperty,jG={current:null},Tde={key:!0,ref:!0,__self:!0,__source:!0};function Ede(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)Sde.call(e,n)&&!Tde.hasOwnProperty(n)&&(i[n]=e[n]);var a=arguments.length-2;if(a===1)i.children=r;else if(1>>1,we=me[Ee];if(0>>1;Eei(at,Ne))Eti(vt,at)?(me[Ee]=vt,me[Et]=Ne,Ee=Et):(me[Ee]=at,me[tt]=Ne,Ee=tt);else if(Eti(vt,Ne))me[Ee]=vt,me[Et]=Ne,Ee=Et;else break e}}return Te}function i(me,Te){var Ne=me.sortIndex-Te.sortIndex;return Ne!==0?Ne:me.id-Te.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=[],p=[],y=1,v=null,T=3,E=!1,k=!1,P=!1,R=typeof setTimeout=="function"?setTimeout:null,D=typeof clearTimeout=="function"?clearTimeout:null,M=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function B(me){for(var Te=r(p);Te!==null;){if(Te.callback===null)n(p);else if(Te.startTime<=me)n(p),Te.sortIndex=Te.expirationTime,e(f,Te);else break;Te=r(p)}}function V(me){if(P=!1,B(me),!k)if(r(f)!==null)k=!0,Ae(G);else{var Te=r(p);Te!==null&&be(V,Te.startTime-me)}}function G(me,Te){k=!1,P&&(P=!1,D(J),J=-1),E=!0;var Ne=T;try{for(B(Te),v=r(f);v!==null&&(!(v.expirationTime>Te)||me&&!le());){var Ee=v.callback;if(typeof Ee=="function"){v.callback=null,T=v.priorityLevel;var we=Ee(v.expirationTime<=Te);Te=t.unstable_now(),typeof we=="function"?v.callback=we:v===r(f)&&n(f),B(Te)}else n(f);v=r(f)}if(v!==null)var He=!0;else{var tt=r(p);tt!==null&&be(V,tt.startTime-Te),He=!1}return He}finally{v=null,T=Ne,E=!1}}var W=!1,Y=null,J=-1,Q=5,ee=-1;function le(){return!(t.unstable_now()-eeme||125Ee?(me.sortIndex=Ne,e(p,me),r(f)===null&&me===r(p)&&(P?(D(J),J=-1):P=!0,be(V,Ne-Ee))):(me.sortIndex=we,e(f,me),k||E||(k=!0,Ae(G))),me},t.unstable_shouldYield=le,t.unstable_wrapCallback=function(me){var Te=T;return function(){var Ne=T;T=Te;try{return me.apply(this,arguments)}finally{T=Ne}}}})(Nde);Cde.exports=Nde;var xPe=Cde.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 vPe=C,gd=xPe;function Vr(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),O6=Object.prototype.hasOwnProperty,_Pe=/^[: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]*$/,_J={},bJ={};function bPe(t){return O6.call(bJ,t)?!0:O6.call(_J,t)?!1:_Pe.test(t)?bJ[t]=!0:(_J[t]=!0,!1)}function wPe(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 SPe(t,e,r,n){if(e===null||typeof e>"u"||wPe(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 ou(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 ac={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){ac[t]=new ou(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];ac[e]=new ou(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){ac[t]=new ou(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){ac[t]=new ou(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){ac[t]=new ou(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){ac[t]=new ou(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){ac[t]=new ou(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){ac[t]=new ou(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){ac[t]=new ou(t,5,!1,t.toLowerCase(),null,!1,!1)});var CG=/[\-:]([a-z])/g;function NG(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(CG,NG);ac[e]=new ou(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(CG,NG);ac[e]=new ou(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(CG,NG);ac[e]=new ou(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){ac[t]=new ou(t,1,!1,t.toLowerCase(),null,!1,!1)});ac.xlinkHref=new ou("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){ac[t]=new ou(t,1,!1,t.toLowerCase(),null,!0,!0)});function IG(t,e,r,n){var i=ac.hasOwnProperty(e)?ac[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{BB=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?D2(t):""}function TPe(t){switch(t.tag){case 5:return D2(t.type);case 16:return D2("Lazy");case 13:return D2("Suspense");case 19:return D2("SuspenseList");case 0:case 2:case 15:return t=$B(t.type,!1),t;case 11:return t=$B(t.type.render,!1),t;case 1:return t=$B(t.type,!0),t;default:return""}}function z6(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 Bw:return"Fragment";case Fw:return"Portal";case F6:return"Profiler";case PG:return"StrictMode";case B6:return"Suspense";case $6:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case Rde:return(t.displayName||"Context")+".Consumer";case Pde:return(t._context.displayName||"Context")+".Provider";case RG:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case LG:return e=t.displayName||null,e!==null?e:z6(t.type)||"Memo";case _y:e=t._payload,t=t._init;try{return z6(t(e))}catch{}}return null}function EPe(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 z6(e);case 8:return e===PG?"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 lx(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function Dde(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function jPe(t){var e=Dde(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 MP(t){t._valueTracker||(t._valueTracker=jPe(t))}function Mde(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=Dde(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function rD(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 U6(t,e){var r=e.checked;return ao({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function SJ(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=lx(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 Ode(t,e){e=e.checked,e!=null&&IG(t,"checked",e,!1)}function V6(t,e){Ode(t,e);var r=lx(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")?q6(t,e.type,r):e.hasOwnProperty("defaultValue")&&q6(t,e.type,lx(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function TJ(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 q6(t,e,r){(e!=="number"||rD(t.ownerDocument)!==t)&&(r==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+r&&(t.defaultValue=""+r))}var M2=Array.isArray;function o1(t,e,r,n){if(t=t.options,e){e={};for(var i=0;i"+e.valueOf().toString()+"",e=OP.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function CA(t,e){if(e){var r=t.firstChild;if(r&&r===t.lastChild&&r.nodeType===3){r.nodeValue=e;return}}t.textContent=e}var Y2={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},APe=["Webkit","ms","Moz","O"];Object.keys(Y2).forEach(function(t){APe.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),Y2[e]=Y2[t]})});function zde(t,e,r){return e==null||typeof e=="boolean"||e===""?"":r||typeof e!="number"||e===0||Y2.hasOwnProperty(t)&&Y2[t]?(""+e).trim():e+"px"}function Ude(t,e){t=t.style;for(var r in e)if(e.hasOwnProperty(r)){var n=r.indexOf("--")===0,i=zde(r,e[r],n);r==="float"&&(r="cssFloat"),n?t.setProperty(r,i):t[r]=i}}var kPe=ao({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 W6(t,e){if(e){if(kPe[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(Vr(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(Vr(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(Vr(61))}if(e.style!=null&&typeof e.style!="object")throw Error(Vr(62))}}function K6(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 Y6=null;function DG(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var Z6=null,l1=null,c1=null;function AJ(t){if(t=yC(t)){if(typeof Z6!="function")throw Error(Vr(280));var e=t.stateNode;e&&(e=DO(e),Z6(t.stateNode,t.type,e))}}function Vde(t){l1?c1?c1.push(t):c1=[t]:l1=t}function qde(){if(l1){var t=l1,e=c1;if(c1=l1=null,AJ(t),e)for(t=0;t>>=0,t===0?32:31-(BPe(t)/$Pe|0)|0}var FP=64,BP=4194304;function O2(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 aD(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=O2(a):(o&=c,o!==0&&(n=O2(o)))}else c=r&~i,c!==0?n=O2(c):o!==0&&(n=O2(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 pC(t,e,r){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-uf(e),t[e]=r}function qPe(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=X2),MJ=" ",OJ=!1;function uhe(t,e){switch(t){case"keyup":return xRe.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function dhe(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var $w=!1;function _Re(t,e){switch(t){case"compositionend":return dhe(e);case"keypress":return e.which!==32?null:(OJ=!0,MJ);case"textInput":return t=e.data,t===MJ&&OJ?null:t;default:return null}}function bRe(t,e){if($w)return t==="compositionend"||!VG&&uhe(t,e)?(t=lhe(),hL=$G=Uy=null,$w=!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=zJ(r)}}function phe(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?phe(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function ghe(){for(var t=window,e=rD();e instanceof t.HTMLIFrameElement;){try{var r=typeof e.contentWindow.location.href=="string"}catch{r=!1}if(r)t=e.contentWindow;else break;e=rD(t.document)}return e}function qG(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 NRe(t){var e=ghe(),r=t.focusedElem,n=t.selectionRange;if(e!==r&&r&&r.ownerDocument&&phe(r.ownerDocument.documentElement,r)){if(n!==null&&qG(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=UJ(r,o);var c=UJ(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,zw=null,rU=null,J2=null,nU=!1;function VJ(t,e,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;nU||zw==null||zw!==rD(n)||(n=zw,"selectionStart"in n&&qG(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}),J2&&DA(J2,n)||(J2=n,n=cD(rU,"onSelect"),0qw||(t.current=cU[qw],cU[qw]=null,qw--)}function xa(t,e){qw++,cU[qw]=t.current,t.current=e}var cx={},Ec=kx(cx),Lu=kx(!1),Zv=cx;function H1(t,e){var r=t.type.contextTypes;if(!r)return cx;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 Du(t){return t=t.childContextTypes,t!=null}function dD(){Da(Lu),Da(Ec)}function ZJ(t,e,r){if(Ec.current!==cx)throw Error(Vr(168));xa(Ec,e),xa(Lu,r)}function Ehe(t,e,r){var n=t.stateNode;if(e=e.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var i in n)if(!(i in e))throw Error(Vr(108,EPe(t)||"Unknown",i));return ao({},r,n)}function hD(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||cx,Zv=Ec.current,xa(Ec,t),xa(Lu,Lu.current),!0}function XJ(t,e,r){var n=t.stateNode;if(!n)throw Error(Vr(169));r?(t=Ehe(t,e,Zv),n.__reactInternalMemoizedMergedChildContext=t,Da(Lu),Da(Ec),xa(Ec,t)):Da(Lu),xa(Lu,r)}var Cp=null,MO=!1,e$=!1;function jhe(t){Cp===null?Cp=[t]:Cp.push(t)}function URe(t){MO=!0,jhe(t)}function Cx(){if(!e$&&Cp!==null){e$=!0;var t=0,e=Gs;try{var r=Cp;for(Gs=1;t>=c,i-=c,Lp=1<<32-uf(e)+i|r<J?(Q=Y,Y=null):Q=Y.sibling;var ee=T(D,Y,B[J],V);if(ee===null){Y===null&&(Y=Q);break}t&&Y&&ee.alternate===null&&e(D,Y),M=o(ee,M,J),W===null?G=ee:W.sibling=ee,W=ee,Y=Q}if(J===B.length)return r(D,Y),Ua&&dv(D,J),G;if(Y===null){for(;JJ?(Q=Y,Y=null):Q=Y.sibling;var le=T(D,Y,ee.value,V);if(le===null){Y===null&&(Y=Q);break}t&&Y&&le.alternate===null&&e(D,Y),M=o(le,M,J),W===null?G=le:W.sibling=le,W=le,Y=Q}if(ee.done)return r(D,Y),Ua&&dv(D,J),G;if(Y===null){for(;!ee.done;J++,ee=B.next())ee=v(D,ee.value,V),ee!==null&&(M=o(ee,M,J),W===null?G=ee:W.sibling=ee,W=ee);return Ua&&dv(D,J),G}for(Y=n(D,Y);!ee.done;J++,ee=B.next())ee=E(Y,D,J,ee.value,V),ee!==null&&(t&&ee.alternate!==null&&Y.delete(ee.key===null?J:ee.key),M=o(ee,M,J),W===null?G=ee:W.sibling=ee,W=ee);return t&&Y.forEach(function(pe){return e(D,pe)}),Ua&&dv(D,J),G}function R(D,M,B,V){if(typeof B=="object"&&B!==null&&B.type===Bw&&B.key===null&&(B=B.props.children),typeof B=="object"&&B!==null){switch(B.$$typeof){case DP:e:{for(var G=B.key,W=M;W!==null;){if(W.key===G){if(G=B.type,G===Bw){if(W.tag===7){r(D,W.sibling),M=i(W,B.props.children),M.return=D,D=M;break e}}else if(W.elementType===G||typeof G=="object"&&G!==null&&G.$$typeof===_y&&eee(G)===W.type){r(D,W.sibling),M=i(W,B.props),M.ref=Xj(D,W,B),M.return=D,D=M;break e}r(D,W);break}else e(D,W);W=W.sibling}B.type===Bw?(M=Vv(B.props.children,D.mode,V,B.key),M.return=D,D=M):(V=_L(B.type,B.key,B.props,null,D.mode,V),V.ref=Xj(D,M,B),V.return=D,D=V)}return c(D);case Fw:e:{for(W=B.key;M!==null;){if(M.key===W)if(M.tag===4&&M.stateNode.containerInfo===B.containerInfo&&M.stateNode.implementation===B.implementation){r(D,M.sibling),M=i(M,B.children||[]),M.return=D,D=M;break e}else{r(D,M);break}else e(D,M);M=M.sibling}M=l$(B,D.mode,V),M.return=D,D=M}return c(D);case _y:return W=B._init,R(D,M,W(B._payload),V)}if(M2(B))return k(D,M,B,V);if(Hj(B))return P(D,M,B,V);HP(D,B)}return typeof B=="string"&&B!==""||typeof B=="number"?(B=""+B,M!==null&&M.tag===6?(r(D,M.sibling),M=i(M,B),M.return=D,D=M):(r(D,M),M=o$(B,D.mode,V),M.return=D,D=M),c(D)):r(D,M)}return R}var K1=Nhe(!0),Ihe=Nhe(!1),pD=kx(null),gD=null,Ww=null,KG=null;function YG(){KG=Ww=gD=null}function ZG(t){var e=pD.current;Da(pD),t._currentValue=e}function hU(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 d1(t,e){gD=t,KG=Ww=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(Iu=!0),t.firstContext=null)}function dh(t){var e=t._currentValue;if(KG!==t)if(t={context:t,memoizedValue:e,next:null},Ww===null){if(gD===null)throw Error(Vr(308));Ww=t,gD.dependencies={lanes:0,firstContext:t}}else Ww=Ww.next=t;return e}var Sv=null;function XG(t){Sv===null?Sv=[t]:Sv.push(t)}function Phe(t,e,r,n){var i=e.interleaved;return i===null?(r.next=r,XG(e)):(r.next=i.next,i.next=r),e.interleaved=r,Zp(t,n)}function Zp(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 by=!1;function QG(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Rhe(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 Bp(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function Xy(t,e,r){var n=t.updateQueue;if(n===null)return null;if(n=n.shared,ps&2){var i=n.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),n.pending=e,Zp(t,r)}return i=n.interleaved,i===null?(e.next=e,XG(n)):(e.next=i.next,i.next=e),n.interleaved=e,Zp(t,r)}function mL(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,OG(t,r)}}function tee(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 yD(t,e,r,n){var i=t.updateQueue;by=!1;var o=i.firstBaseUpdate,c=i.lastBaseUpdate,a=i.shared.pending;if(a!==null){i.shared.pending=null;var f=a,p=f.next;f.next=null,c===null?o=p:c.next=p,c=f;var y=t.alternate;y!==null&&(y=y.updateQueue,a=y.lastBaseUpdate,a!==c&&(a===null?y.firstBaseUpdate=p:a.next=p,y.lastBaseUpdate=f))}if(o!==null){var v=i.baseState;c=0,y=p=f=null,a=o;do{var T=a.lane,E=a.eventTime;if((n&T)===T){y!==null&&(y=y.next={eventTime:E,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var k=t,P=a;switch(T=e,E=r,P.tag){case 1:if(k=P.payload,typeof k=="function"){v=k.call(E,v,T);break e}v=k;break e;case 3:k.flags=k.flags&-65537|128;case 0:if(k=P.payload,T=typeof k=="function"?k.call(E,v,T):k,T==null)break e;v=ao({},v,T);break e;case 2:by=!0}}a.callback!==null&&a.lane!==0&&(t.flags|=64,T=i.effects,T===null?i.effects=[a]:T.push(a))}else E={eventTime:E,lane:T,tag:a.tag,payload:a.payload,callback:a.callback,next:null},y===null?(p=y=E,f=v):y=y.next=E,c|=T;if(a=a.next,a===null){if(a=i.shared.pending,a===null)break;T=a,a=T.next,T.next=null,i.lastBaseUpdate=T,i.shared.pending=null}}while(!0);if(y===null&&(f=v),i.baseState=f,i.firstBaseUpdate=p,i.lastBaseUpdate=y,e=i.shared.interleaved,e!==null){i=e;do c|=i.lane,i=i.next;while(i!==e)}else o===null&&(i.shared.lanes=0);Jv|=c,t.lanes=c,t.memoizedState=v}}function ree(t,e,r){if(t=e.effects,e.effects=null,t!==null)for(e=0;er?r:4,t(!0);var n=r$.transition;r$.transition={};try{t(!1),e()}finally{Gs=r,r$.transition=n}}function Zhe(){return hh().memoizedState}function HRe(t,e,r){var n=Jy(t);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},Xhe(t))Qhe(e,r);else if(r=Phe(t,e,r,n),r!==null){var i=nu();df(r,t,n,i),Jhe(r,e,n)}}function WRe(t,e,r){var n=Jy(t),i={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(Xhe(t))Qhe(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,pf(a,c)){var f=e.interleaved;f===null?(i.next=i,XG(e)):(i.next=f.next,f.next=i),e.interleaved=i;return}}catch{}finally{}r=Phe(t,e,i,n),r!==null&&(i=nu(),df(r,t,n,i),Jhe(r,e,n))}}function Xhe(t){var e=t.alternate;return t===io||e!==null&&e===io}function Qhe(t,e){eA=vD=!0;var r=t.pending;r===null?e.next=e:(e.next=r.next,r.next=e),t.pending=e}function Jhe(t,e,r){if(r&4194240){var n=e.lanes;n&=t.pendingLanes,r|=n,e.lanes=r,OG(t,r)}}var _D={readContext:dh,useCallback:xc,useContext:xc,useEffect:xc,useImperativeHandle:xc,useInsertionEffect:xc,useLayoutEffect:xc,useMemo:xc,useReducer:xc,useRef:xc,useState:xc,useDebugValue:xc,useDeferredValue:xc,useTransition:xc,useMutableSource:xc,useSyncExternalStore:xc,useId:xc,unstable_isNewReconciler:!1},KRe={readContext:dh,useCallback:function(t,e){return Zf().memoizedState=[t,e===void 0?null:e],t},useContext:dh,useEffect:iee,useImperativeHandle:function(t,e,r){return r=r!=null?r.concat([t]):null,gL(4194308,4,Ghe.bind(null,e,t),r)},useLayoutEffect:function(t,e){return gL(4194308,4,t,e)},useInsertionEffect:function(t,e){return gL(4,2,t,e)},useMemo:function(t,e){var r=Zf();return e=e===void 0?null:e,t=t(),r.memoizedState=[t,e],t},useReducer:function(t,e,r){var n=Zf();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=HRe.bind(null,io,t),[n.memoizedState,t]},useRef:function(t){var e=Zf();return t={current:t},e.memoizedState=t},useState:nee,useDebugValue:a9,useDeferredValue:function(t){return Zf().memoizedState=t},useTransition:function(){var t=nee(!1),e=t[0];return t=GRe.bind(null,t[1]),Zf().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,r){var n=io,i=Zf();if(Ua){if(r===void 0)throw Error(Vr(407));r=r()}else{if(r=e(),Ol===null)throw Error(Vr(349));Qv&30||Ohe(n,e,r)}i.memoizedState=r;var o={value:r,getSnapshot:e};return i.queue=o,iee(Bhe.bind(null,n,o,t),[t]),n.flags|=2048,VA(9,Fhe.bind(null,n,o,r,e),void 0,null),r},useId:function(){var t=Zf(),e=Ol.identifierPrefix;if(Ua){var r=Dp,n=Lp;r=(n&~(1<<32-uf(n)-1)).toString(32)+r,e=":"+e+"R"+r,r=zA++,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[im]=e,t[FA]=n,cfe(t,e,!1,!1),e.stateNode=t;e:{switch(c=K6(r,n),r){case"dialog":Ia("cancel",t),Ia("close",t),i=n;break;case"iframe":case"object":case"embed":Ia("load",t),i=n;break;case"video":case"audio":for(i=0;iX1&&(e.flags|=128,n=!0,Qj(o,!1),e.lanes=4194304)}else{if(!n)if(t=xD(c),t!==null){if(e.flags|=128,n=!0,r=t.updateQueue,r!==null&&(e.updateQueue=r,e.flags|=4),Qj(o,!0),o.tail===null&&o.tailMode==="hidden"&&!c.alternate&&!Ua)return vc(e),null}else 2*Co()-o.renderingStartTime>X1&&r!==1073741824&&(e.flags|=128,n=!0,Qj(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=Co(),e.sibling=null,r=eo.current,xa(eo,n?r&1|2:r&1),e):(vc(e),null);case 22:case 23:return h9(),n=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?nd&1073741824&&(vc(e),e.subtreeFlags&6&&(e.flags|=8192)):vc(e),null;case 24:return null;case 25:return null}throw Error(Vr(156,e.tag))}function rLe(t,e){switch(HG(e),e.tag){case 1:return Du(e.type)&&dD(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return Y1(),Da(Lu),Da(Ec),t9(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return e9(e),null;case 13:if(Da(eo),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(Vr(340));W1()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return Da(eo),null;case 4:return Y1(),null;case 10:return ZG(e.type._context),null;case 22:case 23:return h9(),null;case 24:return null;default:return null}}var KP=!1,wc=!1,nLe=typeof WeakSet=="function"?WeakSet:Set,An=null;function Kw(t,e){var r=t.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){yo(t,e,n)}else r.current=null}function bU(t,e,r){try{r()}catch(n){yo(t,e,n)}}var pee=!1;function iLe(t,e){if(iU=oD,t=ghe(),qG(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,p=0,y=0,v=t,T=null;t:for(;;){for(var E;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),(E=v.firstChild)!==null;)T=v,v=E;for(;;){if(v===t)break t;if(T===r&&++p===i&&(a=c),T===o&&++y===n&&(f=c),(E=v.nextSibling)!==null)break;v=T,T=v.parentNode}v=E}r=a===-1||f===-1?null:{start:a,end:f}}else r=null}r=r||{start:0,end:0}}else r=null;for(sU={focusedElem:t,selectionRange:r},oD=!1,An=e;An!==null;)if(e=An,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,An=t;else for(;An!==null;){e=An;try{var k=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(k!==null){var P=k.memoizedProps,R=k.memoizedState,D=e.stateNode,M=D.getSnapshotBeforeUpdate(e.elementType===e.type?P:Wh(e.type,P),R);D.__reactInternalSnapshotBeforeUpdate=M}break;case 3:var B=e.stateNode.containerInfo;B.nodeType===1?B.textContent="":B.nodeType===9&&B.documentElement&&B.removeChild(B.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Vr(163))}}catch(V){yo(e,e.return,V)}if(t=e.sibling,t!==null){t.return=e.return,An=t;break}An=e.return}return k=pee,pee=!1,k}function tA(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&&bU(e,r,o)}i=i.next}while(i!==n)}}function BO(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var r=e=e.next;do{if((r.tag&t)===t){var n=r.create;r.destroy=n()}r=r.next}while(r!==e)}}function wU(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 hfe(t){var e=t.alternate;e!==null&&(t.alternate=null,hfe(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[im],delete e[FA],delete e[lU],delete e[$Re],delete e[zRe])),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 ffe(t){return t.tag===5||t.tag===3||t.tag===4}function gee(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||ffe(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 SU(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=uD));else if(n!==4&&(t=t.child,t!==null))for(SU(t,e,r),t=t.sibling;t!==null;)SU(t,e,r),t=t.sibling}function TU(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(TU(t,e,r),t=t.sibling;t!==null;)TU(t,e,r),t=t.sibling}var Hl=null,Zh=!1;function sy(t,e,r){for(r=r.child;r!==null;)mfe(t,e,r),r=r.sibling}function mfe(t,e,r){if(fm&&typeof fm.onCommitFiberUnmount=="function")try{fm.onCommitFiberUnmount(IO,r)}catch{}switch(r.tag){case 5:wc||Kw(r,e);case 6:var n=Hl,i=Zh;Hl=null,sy(t,e,r),Hl=n,Zh=i,Hl!==null&&(Zh?(t=Hl,r=r.stateNode,t.nodeType===8?t.parentNode.removeChild(r):t.removeChild(r)):Hl.removeChild(r.stateNode));break;case 18:Hl!==null&&(Zh?(t=Hl,r=r.stateNode,t.nodeType===8?JB(t.parentNode,r):t.nodeType===1&&JB(t,r),RA(t)):JB(Hl,r.stateNode));break;case 4:n=Hl,i=Zh,Hl=r.stateNode.containerInfo,Zh=!0,sy(t,e,r),Hl=n,Zh=i;break;case 0:case 11:case 14:case 15:if(!wc&&(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)&&bU(r,e,c),i=i.next}while(i!==n)}sy(t,e,r);break;case 1:if(!wc&&(Kw(r,e),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(a){yo(r,e,a)}sy(t,e,r);break;case 21:sy(t,e,r);break;case 22:r.mode&1?(wc=(n=wc)||r.memoizedState!==null,sy(t,e,r),wc=n):sy(t,e,r);break;default:sy(t,e,r)}}function yee(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var r=t.stateNode;r===null&&(r=t.stateNode=new nLe),e.forEach(function(n){var i=fLe.bind(null,t,n);r.has(n)||(r.add(n),n.then(i,i))})}}function Fh(t,e){var r=e.deletions;if(r!==null)for(var n=0;ni&&(i=c),n&=~o}if(n=i,n=Co()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*aLe(n/1960))-n,10t?16:t,Vy===null)var n=!1;else{if(t=Vy,Vy=null,SD=0,ps&6)throw Error(Vr(331));var i=ps;for(ps|=4,An=t.current;An!==null;){var o=An,c=o.child;if(An.flags&16){var a=o.deletions;if(a!==null){for(var f=0;fCo()-u9?Uv(t,0):c9|=r),Mu(t,e)}function wfe(t,e){e===0&&(t.mode&1?(e=BP,BP<<=1,!(BP&130023424)&&(BP=4194304)):e=1);var r=nu();t=Zp(t,e),t!==null&&(pC(t,e,r),Mu(t,r))}function hLe(t){var e=t.memoizedState,r=0;e!==null&&(r=e.retryLane),wfe(t,r)}function fLe(t,e){var r=0;switch(t.tag){case 13:var n=t.stateNode,i=t.memoizedState;i!==null&&(r=i.retryLane);break;case 19:n=t.stateNode;break;default:throw Error(Vr(314))}n!==null&&n.delete(e),wfe(t,r)}var Sfe;Sfe=function(t,e,r){if(t!==null)if(t.memoizedProps!==e.pendingProps||Lu.current)Iu=!0;else{if(!(t.lanes&r)&&!(e.flags&128))return Iu=!1,eLe(t,e,r);Iu=!!(t.flags&131072)}else Iu=!1,Ua&&e.flags&1048576&&Ahe(e,mD,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;yL(t,e),t=e.pendingProps;var i=H1(e,Ec.current);d1(e,r),i=n9(null,e,n,t,i,r);var o=i9();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,Du(n)?(o=!0,hD(e)):o=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,QG(e),i.updater=FO,e.stateNode=i,i._reactInternals=e,mU(e,n,t,r),e=yU(null,e,n,!0,o,r)):(e.tag=0,Ua&&o&&GG(e),Wc(null,e,i,r),e=e.child),e;case 16:n=e.elementType;e:{switch(yL(t,e),t=e.pendingProps,i=n._init,n=i(n._payload),e.type=n,i=e.tag=pLe(n),t=Wh(n,t),i){case 0:e=gU(null,e,n,t,r);break e;case 1:e=hee(null,e,n,t,r);break e;case 11:e=uee(null,e,n,t,r);break e;case 14:e=dee(null,e,n,Wh(n.type,t),r);break e}throw Error(Vr(306,n,""))}return e;case 0:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Wh(n,i),gU(t,e,n,i,r);case 1:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Wh(n,i),hee(t,e,n,i,r);case 3:e:{if(afe(e),t===null)throw Error(Vr(387));n=e.pendingProps,o=e.memoizedState,i=o.element,Rhe(t,e),yD(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=Z1(Error(Vr(423)),e),e=fee(t,e,n,r,i);break e}else if(n!==i){i=Z1(Error(Vr(424)),e),e=fee(t,e,n,r,i);break e}else for(cd=Zy(e.stateNode.containerInfo.firstChild),hd=e,Ua=!0,ef=null,r=Ihe(e,null,n,r),e.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(W1(),n===i){e=Xp(t,e,r);break e}Wc(t,e,n,r)}e=e.child}return e;case 5:return Lhe(e),t===null&&dU(e),n=e.type,i=e.pendingProps,o=t!==null?t.memoizedProps:null,c=i.children,aU(n,i)?c=null:o!==null&&aU(n,o)&&(e.flags|=32),sfe(t,e),Wc(t,e,c,r),e.child;case 6:return t===null&&dU(e),null;case 13:return ofe(t,e,r);case 4:return JG(e,e.stateNode.containerInfo),n=e.pendingProps,t===null?e.child=K1(e,null,n,r):Wc(t,e,n,r),e.child;case 11:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Wh(n,i),uee(t,e,n,i,r);case 7:return Wc(t,e,e.pendingProps,r),e.child;case 8:return Wc(t,e,e.pendingProps.children,r),e.child;case 12:return Wc(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,xa(pD,n._currentValue),n._currentValue=c,o!==null)if(pf(o.value,c)){if(o.children===i.children&&!Lu.current){e=Xp(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=Bp(-1,r&-r),f.tag=2;var p=o.updateQueue;if(p!==null){p=p.shared;var y=p.pending;y===null?f.next=f:(f.next=y.next,y.next=f),p.pending=f}}o.lanes|=r,f=o.alternate,f!==null&&(f.lanes|=r),hU(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(Vr(341));c.lanes|=r,a=c.alternate,a!==null&&(a.lanes|=r),hU(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}Wc(t,e,i.children,r),e=e.child}return e;case 9:return i=e.type,n=e.pendingProps.children,d1(e,r),i=dh(i),n=n(i),e.flags|=1,Wc(t,e,n,r),e.child;case 14:return n=e.type,i=Wh(n,e.pendingProps),i=Wh(n.type,i),dee(t,e,n,i,r);case 15:return nfe(t,e,e.type,e.pendingProps,r);case 17:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Wh(n,i),yL(t,e),e.tag=1,Du(n)?(t=!0,hD(e)):t=!1,d1(e,r),efe(e,n,i),mU(e,n,i,r),yU(null,e,n,!0,t,r);case 19:return lfe(t,e,r);case 22:return ife(t,e,r)}throw Error(Vr(156,e.tag))};function Tfe(t,e){return Xde(t,e)}function mLe(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 nh(t,e,r,n){return new mLe(t,e,r,n)}function m9(t){return t=t.prototype,!(!t||!t.isReactComponent)}function pLe(t){if(typeof t=="function")return m9(t)?1:0;if(t!=null){if(t=t.$$typeof,t===RG)return 11;if(t===LG)return 14}return 2}function ex(t,e){var r=t.alternate;return r===null?(r=nh(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 _L(t,e,r,n,i,o){var c=2;if(n=t,typeof t=="function")m9(t)&&(c=1);else if(typeof t=="string")c=5;else e:switch(t){case Bw:return Vv(r.children,i,o,e);case PG:c=8,i|=8;break;case F6:return t=nh(12,r,e,i|2),t.elementType=F6,t.lanes=o,t;case B6:return t=nh(13,r,e,i),t.elementType=B6,t.lanes=o,t;case $6:return t=nh(19,r,e,i),t.elementType=$6,t.lanes=o,t;case Lde:return zO(r,i,o,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case Pde:c=10;break e;case Rde:c=9;break e;case RG:c=11;break e;case LG:c=14;break e;case _y:c=16,n=null;break e}throw Error(Vr(130,t==null?t:typeof t,""))}return e=nh(c,r,e,i),e.elementType=t,e.type=n,e.lanes=o,e}function Vv(t,e,r,n){return t=nh(7,t,n,e),t.lanes=r,t}function zO(t,e,r,n){return t=nh(22,t,n,e),t.elementType=Lde,t.lanes=r,t.stateNode={isHidden:!1},t}function o$(t,e,r){return t=nh(6,t,null,e),t.lanes=r,t}function l$(t,e,r){return e=nh(4,t.children!==null?t.children:[],t.key,e),e.lanes=r,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function gLe(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=UB(0),this.expirationTimes=UB(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=UB(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function p9(t,e,r,n,i,o,c,a,f){return t=new gLe(t,e,r,a,f),e===1?(e=1,o===!0&&(e|=8)):e=0,o=nh(3,null,null,e),t.current=o,o.stateNode=t,o.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},QG(o),t}function yLe(t,e,r){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(kfe)}catch(t){console.error(t)}}kfe(),kde.exports=Td;var dg=kde.exports;const Cfe=ds(dg);var Nfe,Eee=dg;Nfe=Eee.createRoot,Eee.hydrateRoot;const wLe="modulepreload",SLe=function(t){return"/"+t},jee={},Fe=function(e,r,n){let i=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),a=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));i=Promise.allSettled(r.map(f=>{if(f=SLe(f),f in jee)return;jee[f]=!0;const p=f.endsWith(".css"),y=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${y}`))return;const v=document.createElement("link");if(v.rel=p?"stylesheet":wLe,p||(v.as="script"),v.crossOrigin="",v.href=f,a&&v.setAttribute("nonce",a),document.head.appendChild(v),p)return new Promise((T,E)=>{v.addEventListener("load",T),v.addEventListener("error",()=>E(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)})},TLe=new Set(["localhost","relevelup.com","thelocalmove.com","www.thelocalmove.com"]),ELe=t=>t.toLowerCase().replace(/:\d+$/,"").replace(/^www\./,"");function jLe(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")||TLe.has(t))}function Ife(t){return Pfe(t)!==null}function Pfe(t){const e=ELe(t);return jLe(e)?null:e}const ALe=1,kLe=1e6;let c$=0;function CLe(){return c$=(c$+1)%Number.MAX_SAFE_INTEGER,c$.toString()}const u$=new Map,Aee=t=>{if(u$.has(t))return;const e=setTimeout(()=>{u$.delete(t),iA({type:"REMOVE_TOAST",toastId:t})},kLe);u$.set(t,e)},NLe=(t,e)=>{switch(e.type){case"ADD_TOAST":return{...t,toasts:[e.toast,...t.toasts].slice(0,ALe)};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?Aee(r):t.toasts.forEach(n=>{Aee(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)}}},bL=[];let wL={toasts:[]};function iA(t){wL=NLe(wL,t),bL.forEach(e=>{e(wL)})}function Ts({...t}){const e=CLe(),r=i=>iA({type:"UPDATE_TOAST",toast:{...i,id:e}}),n=()=>iA({type:"DISMISS_TOAST",toastId:e});return iA({type:"ADD_TOAST",toast:{...t,id:e,open:!0,onOpenChange:i=>{i||n()}}}),{id:e,dismiss:n,update:r}}function Rfe(){const[t,e]=C.useState(wL);return C.useEffect(()=>(bL.push(e),()=>{const r=bL.indexOf(e);r>-1&&bL.splice(r,1)}),[t]),{...t,toast:Ts,dismiss:r=>iA({type:"DISMISS_TOAST",toastId:r})}}function Or(t,e,{checkForDefaultPrevented:r=!0}={}){return function(i){if(t==null||t(i),r===!1||!i.defaultPrevented)return e==null?void 0:e(i)}}function kee(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Qp(...t){return e=>{let r=!1;const n=t.map(i=>{const o=kee(i,e);return!r&&typeof o=="function"&&(r=!0),o});if(r)return()=>{for(let i=0;i{const{children:c,...a}=o,f=C.useMemo(()=>a,Object.values(a));return s.jsx(r.Provider,{value:f,children:c})};n.displayName=t+"Provider";function i(o){const c=C.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 Qo(t,e=[]){let r=[];function n(o,c){const a=C.createContext(c),f=r.length;r=[...r,c];const p=v=>{var D;const{scope:T,children:E,...k}=v,P=((D=T==null?void 0:T[t])==null?void 0:D[f])||a,R=C.useMemo(()=>k,Object.values(k));return s.jsx(P.Provider,{value:R,children:E})};p.displayName=o+"Provider";function y(v,T){var P;const E=((P=T==null?void 0:T[t])==null?void 0:P[f])||a,k=C.useContext(E);if(k)return k;if(c!==void 0)return c;throw new Error(`\`${v}\` must be used within \`${o}\``)}return[p,y]}const i=()=>{const o=r.map(c=>C.createContext(c));return function(a){const f=(a==null?void 0:a[t])||o;return C.useMemo(()=>({[`__scope${t}`]:{...a,[t]:f}}),[a,f])}};return i.scopeName=t,[n,PLe(i,...e)]}function PLe(...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:p})=>{const v=f(o)[`__scope${p}`];return{...a,...v}},{});return C.useMemo(()=>({[`__scope${e.scopeName}`]:c}),[c])}};return r.scopeName=e.scopeName,r}function ux(t){const e=RLe(t),r=C.forwardRef((n,i)=>{const{children:o,...c}=n,a=C.Children.toArray(o),f=a.find(LLe);if(f){const p=f.props.children,y=a.map(v=>v===f?C.Children.count(p)>1?C.Children.only(null):C.isValidElement(p)?p.props.children:null:v);return s.jsx(e,{...c,ref:i,children:C.isValidElement(p)?C.cloneElement(p,void 0,y):null})}return s.jsx(e,{...c,ref:i,children:o})});return r.displayName=`${t}.Slot`,r}var Lfe=ux("Slot");function RLe(t){const e=C.forwardRef((r,n)=>{const{children:i,...o}=r;if(C.isValidElement(i)){const c=MLe(i),a=DLe(o,i.props);return i.type!==C.Fragment&&(a.ref=n?Qp(n,c):c),C.cloneElement(i,a)}return C.Children.count(i)>1?C.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var Dfe=Symbol("radix.slottable");function Mfe(t){const e=({children:r})=>s.jsx(s.Fragment,{children:r});return e.displayName=`${t}.Slottable`,e.__radixId=Dfe,e}function LLe(t){return C.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Dfe}function DLe(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 MLe(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 vC(t){const e=t+"CollectionProvider",[r,n]=Qo(e),[i,o]=r(e,{collectionRef:{current:null},itemMap:new Map}),c=P=>{const{scope:R,children:D}=P,M=Xe.useRef(null),B=Xe.useRef(new Map).current;return s.jsx(i,{scope:R,itemMap:B,collectionRef:M,children:D})};c.displayName=e;const a=t+"CollectionSlot",f=ux(a),p=Xe.forwardRef((P,R)=>{const{scope:D,children:M}=P,B=o(a,D),V=Yn(R,B.collectionRef);return s.jsx(f,{ref:V,children:M})});p.displayName=a;const y=t+"CollectionItemSlot",v="data-radix-collection-item",T=ux(y),E=Xe.forwardRef((P,R)=>{const{scope:D,children:M,...B}=P,V=Xe.useRef(null),G=Yn(R,V),W=o(y,D);return Xe.useEffect(()=>(W.itemMap.set(V,{ref:V,...B}),()=>void W.itemMap.delete(V))),s.jsx(T,{[v]:"",ref:G,children:M})});E.displayName=y;function k(P){const R=o(t+"CollectionConsumer",P);return Xe.useCallback(()=>{const M=R.collectionRef.current;if(!M)return[];const B=Array.from(M.querySelectorAll(`[${v}]`));return Array.from(R.itemMap.values()).sort((W,Y)=>B.indexOf(W.ref.current)-B.indexOf(Y.ref.current))},[R.collectionRef,R.itemMap])}return[{Provider:c,Slot:p,ItemSlot:E},k,n]}var OLe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],nn=OLe.reduce((t,e)=>{const r=ux(`Primitive.${e}`),n=C.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 v9(t,e){t&&dg.flushSync(()=>t.dispatchEvent(e))}function vo(t){const e=C.useRef(t);return C.useEffect(()=>{e.current=t}),C.useMemo(()=>(...r)=>{var n;return(n=e.current)==null?void 0:n.call(e,...r)},[])}function FLe(t,e=globalThis==null?void 0:globalThis.document){const r=vo(t);C.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 BLe="DismissableLayer",CU="dismissableLayer.update",$Le="dismissableLayer.pointerDownOutside",zLe="dismissableLayer.focusOutside",Cee,Ofe=C.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),v_=C.forwardRef((t,e)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:o,onInteractOutside:c,onDismiss:a,...f}=t,p=C.useContext(Ofe),[y,v]=C.useState(null),T=(y==null?void 0:y.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,E]=C.useState({}),k=Yn(e,Y=>v(Y)),P=Array.from(p.layers),[R]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),D=P.indexOf(R),M=y?P.indexOf(y):-1,B=p.layersWithOutsidePointerEventsDisabled.size>0,V=M>=D,G=VLe(Y=>{const J=Y.target,Q=[...p.branches].some(ee=>ee.contains(J));!V||Q||(i==null||i(Y),c==null||c(Y),Y.defaultPrevented||a==null||a())},T),W=qLe(Y=>{const J=Y.target;[...p.branches].some(ee=>ee.contains(J))||(o==null||o(Y),c==null||c(Y),Y.defaultPrevented||a==null||a())},T);return FLe(Y=>{M===p.layers.size-1&&(n==null||n(Y),!Y.defaultPrevented&&a&&(Y.preventDefault(),a()))},T),C.useEffect(()=>{if(y)return r&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(Cee=T.body.style.pointerEvents,T.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(y)),p.layers.add(y),Nee(),()=>{r&&p.layersWithOutsidePointerEventsDisabled.size===1&&(T.body.style.pointerEvents=Cee)}},[y,T,r,p]),C.useEffect(()=>()=>{y&&(p.layers.delete(y),p.layersWithOutsidePointerEventsDisabled.delete(y),Nee())},[y,p]),C.useEffect(()=>{const Y=()=>E({});return document.addEventListener(CU,Y),()=>document.removeEventListener(CU,Y)},[]),s.jsx(nn.div,{...f,ref:k,style:{pointerEvents:B?V?"auto":"none":void 0,...t.style},onFocusCapture:Or(t.onFocusCapture,W.onFocusCapture),onBlurCapture:Or(t.onBlurCapture,W.onBlurCapture),onPointerDownCapture:Or(t.onPointerDownCapture,G.onPointerDownCapture)})});v_.displayName=BLe;var ULe="DismissableLayerBranch",Ffe=C.forwardRef((t,e)=>{const r=C.useContext(Ofe),n=C.useRef(null),i=Yn(e,n);return C.useEffect(()=>{const o=n.current;if(o)return r.branches.add(o),()=>{r.branches.delete(o)}},[r.branches]),s.jsx(nn.div,{...t,ref:i})});Ffe.displayName=ULe;function VLe(t,e=globalThis==null?void 0:globalThis.document){const r=vo(t),n=C.useRef(!1),i=C.useRef(()=>{});return C.useEffect(()=>{const o=a=>{if(a.target&&!n.current){let f=function(){Bfe($Le,r,p,{discrete:!0})};const p={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 qLe(t,e=globalThis==null?void 0:globalThis.document){const r=vo(t),n=C.useRef(!1);return C.useEffect(()=>{const i=o=>{o.target&&!n.current&&Bfe(zLe,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 Nee(){const t=new CustomEvent(CU);document.dispatchEvent(t)}function Bfe(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?v9(i,o):i.dispatchEvent(o)}var GLe=v_,HLe=Ffe,Do=globalThis!=null&&globalThis.document?C.useLayoutEffect:()=>{},WLe="Portal",YS=C.forwardRef((t,e)=>{var a;const{container:r,...n}=t,[i,o]=C.useState(!1);Do(()=>o(!0),[]);const c=r||i&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return c?Cfe.createPortal(s.jsx(nn.div,{...n,ref:e}),c):null});YS.displayName=WLe;function KLe(t,e){return C.useReducer((r,n)=>e[r][n]??r,t)}var vl=t=>{const{present:e,children:r}=t,n=YLe(e),i=typeof r=="function"?r({present:n.isPresent}):C.Children.only(r),o=Yn(n.ref,ZLe(i));return typeof r=="function"||n.isPresent?C.cloneElement(i,{ref:o}):null};vl.displayName="Presence";function YLe(t){const[e,r]=C.useState(),n=C.useRef(null),i=C.useRef(t),o=C.useRef("none"),c=t?"mounted":"unmounted",[a,f]=KLe(c,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return C.useEffect(()=>{const p=XP(n.current);o.current=a==="mounted"?p:"none"},[a]),Do(()=>{const p=n.current,y=i.current;if(y!==t){const T=o.current,E=XP(p);t?f("MOUNT"):E==="none"||(p==null?void 0:p.display)==="none"?f("UNMOUNT"):f(y&&T!==E?"ANIMATION_OUT":"UNMOUNT"),i.current=t}},[t,f]),Do(()=>{if(e){let p;const y=e.ownerDocument.defaultView??window,v=E=>{const P=XP(n.current).includes(E.animationName);if(E.target===e&&P&&(f("ANIMATION_END"),!i.current)){const R=e.style.animationFillMode;e.style.animationFillMode="forwards",p=y.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=R)})}},T=E=>{E.target===e&&(o.current=XP(n.current))};return e.addEventListener("animationstart",T),e.addEventListener("animationcancel",v),e.addEventListener("animationend",v),()=>{y.clearTimeout(p),e.removeEventListener("animationstart",T),e.removeEventListener("animationcancel",v),e.removeEventListener("animationend",v)}}else f("ANIMATION_END")},[e,f]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:C.useCallback(p=>{n.current=p?getComputedStyle(p):null,r(p)},[])}}function XP(t){return(t==null?void 0:t.animationName)||"none"}function ZLe(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 XLe=kG[" useInsertionEffect ".trim().toString()]||Do;function yd({prop:t,defaultProp:e,onChange:r=()=>{},caller:n}){const[i,o,c]=QLe({defaultProp:e,onChange:r}),a=t!==void 0,f=a?t:i;{const y=C.useRef(t!==void 0);C.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 p=C.useCallback(y=>{var v;if(a){const T=JLe(y)?y(t):y;T!==t&&((v=c.current)==null||v.call(c,T))}else o(y)},[a,t,o,c]);return[f,p]}function QLe({defaultProp:t,onChange:e}){const[r,n]=C.useState(t),i=C.useRef(r),o=C.useRef(e);return XLe(()=>{o.current=e},[e]),C.useEffect(()=>{var c;i.current!==r&&((c=o.current)==null||c.call(o,r),i.current=r)},[r,i]),[r,n,o]}function JLe(t){return typeof t=="function"}var $fe=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"}),eDe="VisuallyHidden",HO=C.forwardRef((t,e)=>s.jsx(nn.span,{...t,ref:e,style:{...$fe,...t.style}}));HO.displayName=eDe;var tDe=HO,_9="ToastProvider",[b9,rDe,nDe]=vC("Toast"),[zfe,iqt]=Qo("Toast",[nDe]),[iDe,WO]=zfe(_9),Ufe=t=>{const{__scopeToast:e,label:r="Notification",duration:n=5e3,swipeDirection:i="right",swipeThreshold:o=50,children:c}=t,[a,f]=C.useState(null),[p,y]=C.useState(0),v=C.useRef(!1),T=C.useRef(!1);return r.trim()||console.error(`Invalid prop \`label\` supplied to \`${_9}\`. Expected non-empty \`string\`.`),s.jsx(b9.Provider,{scope:e,children:s.jsx(iDe,{scope:e,label:r,duration:n,swipeDirection:i,swipeThreshold:o,toastCount:p,viewport:a,onViewportChange:f,onToastAdd:C.useCallback(()=>y(E=>E+1),[]),onToastRemove:C.useCallback(()=>y(E=>E-1),[]),isFocusedToastEscapeKeyDownRef:v,isClosePausedRef:T,children:c})})};Ufe.displayName=_9;var Vfe="ToastViewport",sDe=["F8"],NU="toast.viewportPause",IU="toast.viewportResume",qfe=C.forwardRef((t,e)=>{const{__scopeToast:r,hotkey:n=sDe,label:i="Notifications ({hotkey})",...o}=t,c=WO(Vfe,r),a=rDe(r),f=C.useRef(null),p=C.useRef(null),y=C.useRef(null),v=C.useRef(null),T=Yn(e,v,c.onViewportChange),E=n.join("+").replace(/Key/g,"").replace(/Digit/g,""),k=c.toastCount>0;C.useEffect(()=>{const R=D=>{var B;n.length!==0&&n.every(V=>D[V]||D.code===V)&&((B=v.current)==null||B.focus())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[n]),C.useEffect(()=>{const R=f.current,D=v.current;if(k&&R&&D){const M=()=>{if(!c.isClosePausedRef.current){const W=new CustomEvent(NU);D.dispatchEvent(W),c.isClosePausedRef.current=!0}},B=()=>{if(c.isClosePausedRef.current){const W=new CustomEvent(IU);D.dispatchEvent(W),c.isClosePausedRef.current=!1}},V=W=>{!R.contains(W.relatedTarget)&&B()},G=()=>{R.contains(document.activeElement)||B()};return R.addEventListener("focusin",M),R.addEventListener("focusout",V),R.addEventListener("pointermove",M),R.addEventListener("pointerleave",G),window.addEventListener("blur",M),window.addEventListener("focus",B),()=>{R.removeEventListener("focusin",M),R.removeEventListener("focusout",V),R.removeEventListener("pointermove",M),R.removeEventListener("pointerleave",G),window.removeEventListener("blur",M),window.removeEventListener("focus",B)}}},[k,c.isClosePausedRef]);const P=C.useCallback(({tabbingDirection:R})=>{const M=a().map(B=>{const V=B.ref.current,G=[V,...xDe(V)];return R==="forwards"?G:G.reverse()});return(R==="forwards"?M.reverse():M).flat()},[a]);return C.useEffect(()=>{const R=v.current;if(R){const D=M=>{var G,W,Y;const B=M.altKey||M.ctrlKey||M.metaKey;if(M.key==="Tab"&&!B){const J=document.activeElement,Q=M.shiftKey;if(M.target===R&&Q){(G=p.current)==null||G.focus();return}const pe=P({tabbingDirection:Q?"backwards":"forwards"}),Se=pe.findIndex(je=>je===J);d$(pe.slice(Se+1))?M.preventDefault():Q?(W=p.current)==null||W.focus():(Y=y.current)==null||Y.focus()}};return R.addEventListener("keydown",D),()=>R.removeEventListener("keydown",D)}},[a,P]),s.jsxs(HLe,{ref:f,role:"region","aria-label":i.replace("{hotkey}",E),tabIndex:-1,style:{pointerEvents:k?void 0:"none"},children:[k&&s.jsx(PU,{ref:p,onFocusFromOutsideViewport:()=>{const R=P({tabbingDirection:"forwards"});d$(R)}}),s.jsx(b9.Slot,{scope:r,children:s.jsx(nn.ol,{tabIndex:-1,...o,ref:T})}),k&&s.jsx(PU,{ref:y,onFocusFromOutsideViewport:()=>{const R=P({tabbingDirection:"backwards"});d$(R)}})]})});qfe.displayName=Vfe;var Gfe="ToastFocusProxy",PU=C.forwardRef((t,e)=>{const{__scopeToast:r,onFocusFromOutsideViewport:n,...i}=t,o=WO(Gfe,r);return s.jsx(HO,{"aria-hidden":!0,tabIndex:0,...i,ref:e,style:{position:"fixed"},onFocus:c=>{var p;const a=c.relatedTarget;!((p=o.viewport)!=null&&p.contains(a))&&n()}})});PU.displayName=Gfe;var _C="Toast",aDe="toast.swipeStart",oDe="toast.swipeMove",lDe="toast.swipeCancel",cDe="toast.swipeEnd",Hfe=C.forwardRef((t,e)=>{const{forceMount:r,open:n,defaultOpen:i,onOpenChange:o,...c}=t,[a,f]=yd({prop:n,defaultProp:i??!0,onChange:o,caller:_C});return s.jsx(vl,{present:r||a,children:s.jsx(hDe,{open:a,...c,ref:e,onClose:()=>f(!1),onPause:vo(t.onPause),onResume:vo(t.onResume),onSwipeStart:Or(t.onSwipeStart,p=>{p.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:Or(t.onSwipeMove,p=>{const{x:y,y:v}=p.detail.delta;p.currentTarget.setAttribute("data-swipe","move"),p.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${y}px`),p.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${v}px`)}),onSwipeCancel:Or(t.onSwipeCancel,p=>{p.currentTarget.setAttribute("data-swipe","cancel"),p.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),p.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),p.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),p.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:Or(t.onSwipeEnd,p=>{const{x:y,y:v}=p.detail.delta;p.currentTarget.setAttribute("data-swipe","end"),p.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),p.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),p.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${y}px`),p.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${v}px`),f(!1)})})})});Hfe.displayName=_C;var[uDe,dDe]=zfe(_C,{onClose(){}}),hDe=C.forwardRef((t,e)=>{const{__scopeToast:r,type:n="foreground",duration:i,open:o,onClose:c,onEscapeKeyDown:a,onPause:f,onResume:p,onSwipeStart:y,onSwipeMove:v,onSwipeCancel:T,onSwipeEnd:E,...k}=t,P=WO(_C,r),[R,D]=C.useState(null),M=Yn(e,je=>D(je)),B=C.useRef(null),V=C.useRef(null),G=i||P.duration,W=C.useRef(0),Y=C.useRef(G),J=C.useRef(0),{onToastAdd:Q,onToastRemove:ee}=P,le=vo(()=>{var Le;(R==null?void 0:R.contains(document.activeElement))&&((Le=P.viewport)==null||Le.focus()),c()}),pe=C.useCallback(je=>{!je||je===1/0||(window.clearTimeout(J.current),W.current=new Date().getTime(),J.current=window.setTimeout(le,je))},[le]);C.useEffect(()=>{const je=P.viewport;if(je){const Le=()=>{pe(Y.current),p==null||p()},Ae=()=>{const be=new Date().getTime()-W.current;Y.current=Y.current-be,window.clearTimeout(J.current),f==null||f()};return je.addEventListener(NU,Ae),je.addEventListener(IU,Le),()=>{je.removeEventListener(NU,Ae),je.removeEventListener(IU,Le)}}},[P.viewport,G,f,p,pe]),C.useEffect(()=>{o&&!P.isClosePausedRef.current&&pe(G)},[o,G,P.isClosePausedRef,pe]),C.useEffect(()=>(Q(),()=>ee()),[Q,ee]);const Se=C.useMemo(()=>R?Jfe(R):null,[R]);return P.viewport?s.jsxs(s.Fragment,{children:[Se&&s.jsx(fDe,{__scopeToast:r,role:"status","aria-live":n==="foreground"?"assertive":"polite","aria-atomic":!0,children:Se}),s.jsx(uDe,{scope:r,onClose:le,children:dg.createPortal(s.jsx(b9.ItemSlot,{scope:r,children:s.jsx(GLe,{asChild:!0,onEscapeKeyDown:Or(a,()=>{P.isFocusedToastEscapeKeyDownRef.current||le(),P.isFocusedToastEscapeKeyDownRef.current=!1}),children:s.jsx(nn.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":o?"open":"closed","data-swipe-direction":P.swipeDirection,...k,ref:M,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:Or(t.onKeyDown,je=>{je.key==="Escape"&&(a==null||a(je.nativeEvent),je.nativeEvent.defaultPrevented||(P.isFocusedToastEscapeKeyDownRef.current=!0,le()))}),onPointerDown:Or(t.onPointerDown,je=>{je.button===0&&(B.current={x:je.clientX,y:je.clientY})}),onPointerMove:Or(t.onPointerMove,je=>{if(!B.current)return;const Le=je.clientX-B.current.x,Ae=je.clientY-B.current.y,be=!!V.current,me=["left","right"].includes(P.swipeDirection),Te=["left","up"].includes(P.swipeDirection)?Math.min:Math.max,Ne=me?Te(0,Le):0,Ee=me?0:Te(0,Ae),we=je.pointerType==="touch"?10:2,He={x:Ne,y:Ee},tt={originalEvent:je,delta:He};be?(V.current=He,QP(oDe,v,tt,{discrete:!1})):Iee(He,P.swipeDirection,we)?(V.current=He,QP(aDe,y,tt,{discrete:!1}),je.target.setPointerCapture(je.pointerId)):(Math.abs(Le)>we||Math.abs(Ae)>we)&&(B.current=null)}),onPointerUp:Or(t.onPointerUp,je=>{const Le=V.current,Ae=je.target;if(Ae.hasPointerCapture(je.pointerId)&&Ae.releasePointerCapture(je.pointerId),V.current=null,B.current=null,Le){const be=je.currentTarget,me={originalEvent:je,delta:Le};Iee(Le,P.swipeDirection,P.swipeThreshold)?QP(cDe,E,me,{discrete:!0}):QP(lDe,T,me,{discrete:!0}),be.addEventListener("click",Te=>Te.preventDefault(),{once:!0})}})})})}),P.viewport)})]}):null}),fDe=t=>{const{__scopeToast:e,children:r,...n}=t,i=WO(_C,e),[o,c]=C.useState(!1),[a,f]=C.useState(!1);return gDe(()=>c(!0)),C.useEffect(()=>{const p=window.setTimeout(()=>f(!0),1e3);return()=>window.clearTimeout(p)},[]),a?null:s.jsx(YS,{asChild:!0,children:s.jsx(HO,{...n,children:o&&s.jsxs(s.Fragment,{children:[i.label," ",r]})})})},mDe="ToastTitle",Wfe=C.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t;return s.jsx(nn.div,{...n,ref:e})});Wfe.displayName=mDe;var pDe="ToastDescription",Kfe=C.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t;return s.jsx(nn.div,{...n,ref:e})});Kfe.displayName=pDe;var Yfe="ToastAction",Zfe=C.forwardRef((t,e)=>{const{altText:r,...n}=t;return r.trim()?s.jsx(Qfe,{altText:r,asChild:!0,children:s.jsx(w9,{...n,ref:e})}):(console.error(`Invalid prop \`altText\` supplied to \`${Yfe}\`. Expected non-empty \`string\`.`),null)});Zfe.displayName=Yfe;var Xfe="ToastClose",w9=C.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t,i=dDe(Xfe,r);return s.jsx(Qfe,{asChild:!0,children:s.jsx(nn.button,{type:"button",...n,ref:e,onClick:Or(t.onClick,i.onClose)})})});w9.displayName=Xfe;var Qfe=C.forwardRef((t,e)=>{const{__scopeToast:r,altText:n,...i}=t;return s.jsx(nn.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":n||void 0,...i,ref:e})});function Jfe(t){const e=[];return Array.from(t.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&e.push(n.textContent),yDe(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(...Jfe(n))}}),e}function QP(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?v9(i,o):i.dispatchEvent(o)}var Iee=(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 gDe(t=()=>{}){const e=vo(t);Do(()=>{let r=0,n=0;return r=window.requestAnimationFrame(()=>n=window.requestAnimationFrame(e)),()=>{window.cancelAnimationFrame(r),window.cancelAnimationFrame(n)}},[e])}function yDe(t){return t.nodeType===t.ELEMENT_NODE}function xDe(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 d$(t){const e=document.activeElement;return t.some(r=>r===e?!0:(r.focus(),document.activeElement!==e))}var vDe=Ufe,eme=qfe,tme=Hfe,rme=Wfe,nme=Kfe,ime=Zfe,sme=w9;function ame(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,Ree=$i,ZS=(t,e)=>r=>{var n;if((e==null?void 0:e.variants)==null)return Ree(t,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:i,defaultVariants:o}=e,c=Object.keys(i).map(p=>{const y=r==null?void 0:r[p],v=o==null?void 0:o[p];if(y===null)return null;const T=Pee(y)||Pee(v);return i[p][T]}),a=r&&Object.entries(r).reduce((p,y)=>{let[v,T]=y;return T===void 0||(p[v]=T),p},{}),f=e==null||(n=e.compoundVariants)===null||n===void 0?void 0:n.reduce((p,y)=>{let{class:v,className:T,...E}=y;return Object.entries(E).every(k=>{let[P,R]=k;return Array.isArray(R)?R.includes({...o,...a}[P]):{...o,...a}[P]===R})?[...p,v,T]:p},[]);return Ree(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 _De=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ome=(...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 bDe={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 wDe=C.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:i="",children:o,iconNode:c,...a},f)=>C.createElement("svg",{ref:f,...bDe,width:e,height:e,stroke:t,strokeWidth:n?Number(r)*24/Number(e):r,className:ome("lucide",i),...a},[...c.map(([p,y])=>C.createElement(p,y)),...Array.isArray(o)?o:[o]]));/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const or=(t,e)=>{const r=C.forwardRef(({className:n,...i},o)=>C.createElement(wDe,{ref:o,iconNode:e,className:ome(`lucide-${_De(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 Lee=or("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 dx=or("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 Ds=or("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 SDe=or("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 GA=or("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 f1=or("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 __=or("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 TDe=or("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 XS=or("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 bC=or("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 Q1=or("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 jD=or("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 EDe=or("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 lme=or("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 _o=or("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 jDe=or("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 RU=or("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 S9=or("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 T9=or("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 pm=or("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 cme=or("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 oo=or("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 Dee=or("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 HA=or("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 no=or("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 yl=or("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 Cm=or("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 jd=or("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 ume=or("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 LU=or("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 dme=or("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 oc=or("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 ADe=or("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 E9=or("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 t_=or("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 DU=or("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 h$=or("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 Dl=or("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mee=or("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 MU=or("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 $p=or("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 sc=or("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 kDe=or("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 CDe=or("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 b_=or("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KO=or("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 hme=or("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 NDe=or("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 IDe=or("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 _m=or("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 Oee=or("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 PDe=or("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 RDe=or("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 fme=or("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 LDe=or("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 hf=or("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 qv=or("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 WA=or("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 DDe=or("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 MDe=or("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 OU=or("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 bm=or("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 va=or("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 Fee=or("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 mme=or("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 j9=or("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 ODe=or("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 pme=or("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 YO=or("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 FDe=or("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 gme=or("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 BDe=or("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 $De=or("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 zDe=or("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 Bee=or("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 yme=or("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 UDe=or("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 FU=or("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 su=or("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 hx=or("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 ZO=or("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 mi=or("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 Es=or("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 VDe=or("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 qDe=or("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 wC=or("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 QS=or("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 GDe=or("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 J1=or("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 fh=or("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 HDe=or("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 xme=or("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 WDe=or("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 $ee=or("Package",[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["path",{d:"m3.3 7 7.703 4.734a2 2 0 0 0 1.994 0L20.7 7",key:"yx3hmr"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XO=or("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 KDe=or("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 YDe=or("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 ZDe=or("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 XDe=or("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 ri=or("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 QDe=or("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 AD=or("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 gm=or("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 JDe=or("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 eMe=or("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 tMe=or("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 rMe=or("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 vme=or("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 nMe=or("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 zee=or("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 iMe=or("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 QO=or("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 sMe=or("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 aMe=or("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 xd=or("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 kD=or("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 A9=or("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 SC=or("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 oMe=or("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 k9=or("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 KA=or("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 _me=or("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 lMe=or("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 f$=or("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 cMe=or("Sofa",[["path",{d:"M20 9V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v3",key:"1dgpiv"}],["path",{d:"M2 16a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5a2 2 0 0 0-4 0v1.5a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5V11a2 2 0 0 0-4 0z",key:"xacw8m"}],["path",{d:"M4 18v2",key:"jwo5n2"}],["path",{d:"M20 18v2",key:"1ar1qi"}],["path",{d:"M12 4v9",key:"oqhhn3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xs=or("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 uMe=or("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 BU=or("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 C9=or("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 lc=or("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 N9=or("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 dMe=or("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 TC=or("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 hMe=or("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 bme=or("Ticket",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"M13 5v2",key:"dyzc3o"}],["path",{d:"M13 17v2",key:"1ont0d"}],["path",{d:"M13 11v2",key:"1wjjxi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CD=or("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 wme=or("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 Nx=or("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 JS=or("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 ND=or("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 $U=or("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 zU=or("UserCheck",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JO=or("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 Ml=or("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 fl=or("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 sA=or("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 fMe=or("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 mMe=or("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 I9=or("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 pMe=or("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 P9=or("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 Os=or("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 gMe=or("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 eS=or("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 Uee=or("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"}]]),R9="-",yMe=t=>{const e=vMe(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=t;return{getClassGroupId:c=>{const a=c.split(R9);return a[0]===""&&a.length!==1&&a.shift(),Sme(a,e)||xMe(c)},getConflictingClassGroupIds:(c,a)=>{const f=r[c]||[];return a&&n[c]?[...f,...n[c]]:f}}},Sme=(t,e)=>{var c;if(t.length===0)return e.classGroupId;const r=t[0],n=e.nextPart.get(r),i=n?Sme(t.slice(1),n):void 0;if(i)return i;if(e.validators.length===0)return;const o=t.join(R9);return(c=e.validators.find(({validator:a})=>a(o)))==null?void 0:c.classGroupId},Vee=/^\[(.+)\]$/,xMe=t=>{if(Vee.test(t)){const e=Vee.exec(t)[1],r=e==null?void 0:e.substring(0,e.indexOf(":"));if(r)return"arbitrary.."+r}},vMe=t=>{const{theme:e,prefix:r}=t,n={nextPart:new Map,validators:[]};return bMe(Object.entries(t.classGroups),r).forEach(([o,c])=>{UU(c,n,o,e)}),n},UU=(t,e,r,n)=>{t.forEach(i=>{if(typeof i=="string"){const o=i===""?e:qee(e,i);o.classGroupId=r;return}if(typeof i=="function"){if(_Me(i)){UU(i(n),e,r,n);return}e.validators.push({validator:i,classGroupId:r});return}Object.entries(i).forEach(([o,c])=>{UU(c,qee(e,o),r,n)})})},qee=(t,e)=>{let r=t;return e.split(R9).forEach(n=>{r.nextPart.has(n)||r.nextPart.set(n,{nextPart:new Map,validators:[]}),r=r.nextPart.get(n)}),r},_Me=t=>t.isThemeGetter,bMe=(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,wMe=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)}}},Tme="!",SMe=t=>{const{separator:e,experimentalParseClassName:r}=t,n=e.length===1,i=e[0],o=e.length,c=a=>{const f=[];let p=0,y=0,v;for(let R=0;Ry?v-y:void 0;return{modifiers:f,hasImportantModifier:E,baseClassName:k,maybePostfixModifierPosition:P}};return r?a=>r({className:a,parseClassName:c}):c},TMe=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},EMe=t=>({cache:wMe(t.cacheSize),parseClassName:SMe(t),...yMe(t)}),jMe=/\s+/,AMe=(t,e)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:i}=e,o=[],c=t.trim().split(jMe);let a="";for(let f=c.length-1;f>=0;f-=1){const p=c[f],{modifiers:y,hasImportantModifier:v,baseClassName:T,maybePostfixModifierPosition:E}=r(p);let k=!!E,P=n(k?T.substring(0,E):T);if(!P){if(!k){a=p+(a.length>0?" "+a:a);continue}if(P=n(T),!P){a=p+(a.length>0?" "+a:a);continue}k=!1}const R=TMe(y).join(":"),D=v?R+Tme:R,M=D+P;if(o.includes(M))continue;o.push(M);const B=i(P,k);for(let V=0;V0?" "+a:a)}return a};function kMe(){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=EMe(p),n=r.cache.get,i=r.cache.set,o=a,a(f)}function a(f){const p=n(f);if(p)return p;const y=AMe(f,r);return i(f,y),y}return function(){return o(kMe.apply(null,arguments))}}const Na=t=>{const e=r=>r[t]||[];return e.isThemeGetter=!0,e},jme=/^\[(?:([a-z-]+):)?(.+)\]$/i,NMe=/^\d+\/\d+$/,IMe=new Set(["px","full","screen"]),PMe=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,RMe=/\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$/,LMe=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,DMe=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,MMe=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,pp=t=>m1(t)||IMe.has(t)||NMe.test(t),ay=t=>eT(t,"length",qMe),m1=t=>!!t&&!Number.isNaN(Number(t)),m$=t=>eT(t,"number",m1),e2=t=>!!t&&Number.isInteger(Number(t)),OMe=t=>t.endsWith("%")&&m1(t.slice(0,-1)),Fi=t=>jme.test(t),oy=t=>PMe.test(t),FMe=new Set(["length","size","percentage"]),BMe=t=>eT(t,FMe,Ame),$Me=t=>eT(t,"position",Ame),zMe=new Set(["image","url"]),UMe=t=>eT(t,zMe,HMe),VMe=t=>eT(t,"",GMe),t2=()=>!0,eT=(t,e,r)=>{const n=jme.exec(t);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):r(n[2]):!1},qMe=t=>RMe.test(t)&&!LMe.test(t),Ame=()=>!1,GMe=t=>DMe.test(t),HMe=t=>MMe.test(t),WMe=()=>{const t=Na("colors"),e=Na("spacing"),r=Na("blur"),n=Na("brightness"),i=Na("borderColor"),o=Na("borderRadius"),c=Na("borderSpacing"),a=Na("borderWidth"),f=Na("contrast"),p=Na("grayscale"),y=Na("hueRotate"),v=Na("invert"),T=Na("gap"),E=Na("gradientColorStops"),k=Na("gradientColorStopPositions"),P=Na("inset"),R=Na("margin"),D=Na("opacity"),M=Na("padding"),B=Na("saturate"),V=Na("scale"),G=Na("sepia"),W=Na("skew"),Y=Na("space"),J=Na("translate"),Q=()=>["auto","contain","none"],ee=()=>["auto","hidden","clip","visible","scroll"],le=()=>["auto",Fi,e],pe=()=>[Fi,e],Se=()=>["",pp,ay],je=()=>["auto",m1,Fi],Le=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],Ae=()=>["solid","dashed","dotted","double","none"],be=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],me=()=>["start","end","center","between","around","evenly","stretch"],Te=()=>["","0",Fi],Ne=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Ee=()=>[m1,Fi];return{cacheSize:500,separator:":",theme:{colors:[t2],spacing:[pp,ay],blur:["none","",oy,Fi],brightness:Ee(),borderColor:[t],borderRadius:["none","","full",oy,Fi],borderSpacing:pe(),borderWidth:Se(),contrast:Ee(),grayscale:Te(),hueRotate:Ee(),invert:Te(),gap:pe(),gradientColorStops:[t],gradientColorStopPositions:[OMe,ay],inset:le(),margin:le(),opacity:Ee(),padding:pe(),saturate:Ee(),scale:Ee(),sepia:Te(),skew:Ee(),space:pe(),translate:pe()},classGroups:{aspect:[{aspect:["auto","square","video",Fi]}],container:["container"],columns:[{columns:[oy]}],"break-after":[{"break-after":Ne()}],"break-before":[{"break-before":Ne()}],"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(),Fi]}],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:[P]}],"inset-x":[{"inset-x":[P]}],"inset-y":[{"inset-y":[P]}],start:[{start:[P]}],end:[{end:[P]}],top:[{top:[P]}],right:[{right:[P]}],bottom:[{bottom:[P]}],left:[{left:[P]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",e2,Fi]}],basis:[{basis:le()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Fi]}],grow:[{grow:Te()}],shrink:[{shrink:Te()}],order:[{order:["first","last","none",e2,Fi]}],"grid-cols":[{"grid-cols":[t2]}],"col-start-end":[{col:["auto",{span:["full",e2,Fi]},Fi]}],"col-start":[{"col-start":je()}],"col-end":[{"col-end":je()}],"grid-rows":[{"grid-rows":[t2]}],"row-start-end":[{row:["auto",{span:[e2,Fi]},Fi]}],"row-start":[{"row-start":je()}],"row-end":[{"row-end":je()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Fi]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Fi]}],gap:[{gap:[T]}],"gap-x":[{"gap-x":[T]}],"gap-y":[{"gap-y":[T]}],"justify-content":[{justify:["normal",...me()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...me(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...me(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[M]}],px:[{px:[M]}],py:[{py:[M]}],ps:[{ps:[M]}],pe:[{pe:[M]}],pt:[{pt:[M]}],pr:[{pr:[M]}],pb:[{pb:[M]}],pl:[{pl:[M]}],m:[{m:[R]}],mx:[{mx:[R]}],my:[{my:[R]}],ms:[{ms:[R]}],me:[{me:[R]}],mt:[{mt:[R]}],mr:[{mr:[R]}],mb:[{mb:[R]}],ml:[{ml:[R]}],"space-x":[{"space-x":[Y]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[Y]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Fi,e]}],"min-w":[{"min-w":[Fi,e,"min","max","fit"]}],"max-w":[{"max-w":[Fi,e,"none","full","min","max","fit","prose",{screen:[oy]},oy]}],h:[{h:[Fi,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Fi,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Fi,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Fi,e,"auto","min","max","fit"]}],"font-size":[{text:["base",oy,ay]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",m$]}],"font-family":[{font:[t2]}],"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",Fi]}],"line-clamp":[{"line-clamp":["none",m1,m$]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",pp,Fi]}],"list-image":[{"list-image":["none",Fi]}],"list-style-type":[{list:["none","disc","decimal",Fi]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[D]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[D]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Ae(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",pp,ay]}],"underline-offset":[{"underline-offset":["auto",pp,Fi]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:pe()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Fi]}],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",Fi]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[D]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...Le(),$Me]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",BMe]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},UMe]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[k]}],"gradient-via-pos":[{via:[k]}],"gradient-to-pos":[{to:[k]}],"gradient-from":[{from:[E]}],"gradient-via":[{via:[E]}],"gradient-to":[{to:[E]}],rounded:[{rounded:[o]}],"rounded-s":[{"rounded-s":[o]}],"rounded-e":[{"rounded-e":[o]}],"rounded-t":[{"rounded-t":[o]}],"rounded-r":[{"rounded-r":[o]}],"rounded-b":[{"rounded-b":[o]}],"rounded-l":[{"rounded-l":[o]}],"rounded-ss":[{"rounded-ss":[o]}],"rounded-se":[{"rounded-se":[o]}],"rounded-ee":[{"rounded-ee":[o]}],"rounded-es":[{"rounded-es":[o]}],"rounded-tl":[{"rounded-tl":[o]}],"rounded-tr":[{"rounded-tr":[o]}],"rounded-br":[{"rounded-br":[o]}],"rounded-bl":[{"rounded-bl":[o]}],"border-w":[{border:[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":[D]}],"border-style":[{border:[...Ae(),"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":[D]}],"divide-style":[{divide:Ae()}],"border-color":[{border:[i]}],"border-color-x":[{"border-x":[i]}],"border-color-y":[{"border-y":[i]}],"border-color-s":[{"border-s":[i]}],"border-color-e":[{"border-e":[i]}],"border-color-t":[{"border-t":[i]}],"border-color-r":[{"border-r":[i]}],"border-color-b":[{"border-b":[i]}],"border-color-l":[{"border-l":[i]}],"divide-color":[{divide:[i]}],"outline-style":[{outline:["",...Ae()]}],"outline-offset":[{"outline-offset":[pp,Fi]}],"outline-w":[{outline:[pp,ay]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:Se()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[D]}],"ring-offset-w":[{"ring-offset":[pp,ay]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",oy,VMe]}],"shadow-color":[{shadow:[t2]}],opacity:[{opacity:[D]}],"mix-blend":[{"mix-blend":[...be(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":be()}],filter:[{filter:["","none"]}],blur:[{blur:[r]}],brightness:[{brightness:[n]}],contrast:[{contrast:[f]}],"drop-shadow":[{"drop-shadow":["","none",oy,Fi]}],grayscale:[{grayscale:[p]}],"hue-rotate":[{"hue-rotate":[y]}],invert:[{invert:[v]}],saturate:[{saturate:[B]}],sepia:[{sepia:[G]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[r]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[f]}],"backdrop-grayscale":[{"backdrop-grayscale":[p]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[y]}],"backdrop-invert":[{"backdrop-invert":[v]}],"backdrop-opacity":[{"backdrop-opacity":[D]}],"backdrop-saturate":[{"backdrop-saturate":[B]}],"backdrop-sepia":[{"backdrop-sepia":[G]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[c]}],"border-spacing-x":[{"border-spacing-x":[c]}],"border-spacing-y":[{"border-spacing-y":[c]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Fi]}],duration:[{duration:Ee()}],ease:[{ease:["linear","in","out","in-out",Fi]}],delay:[{delay:Ee()}],animate:[{animate:["none","spin","ping","pulse","bounce",Fi]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[V]}],"scale-x":[{"scale-x":[V]}],"scale-y":[{"scale-y":[V]}],rotate:[{rotate:[e2,Fi]}],"translate-x":[{"translate-x":[J]}],"translate-y":[{"translate-y":[J]}],"skew-x":[{"skew-x":[W]}],"skew-y":[{"skew-y":[W]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Fi]}],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",Fi]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":pe()}],"scroll-mx":[{"scroll-mx":pe()}],"scroll-my":[{"scroll-my":pe()}],"scroll-ms":[{"scroll-ms":pe()}],"scroll-me":[{"scroll-me":pe()}],"scroll-mt":[{"scroll-mt":pe()}],"scroll-mr":[{"scroll-mr":pe()}],"scroll-mb":[{"scroll-mb":pe()}],"scroll-ml":[{"scroll-ml":pe()}],"scroll-p":[{"scroll-p":pe()}],"scroll-px":[{"scroll-px":pe()}],"scroll-py":[{"scroll-py":pe()}],"scroll-ps":[{"scroll-ps":pe()}],"scroll-pe":[{"scroll-pe":pe()}],"scroll-pt":[{"scroll-pt":pe()}],"scroll-pr":[{"scroll-pr":pe()}],"scroll-pb":[{"scroll-pb":pe()}],"scroll-pl":[{"scroll-pl":pe()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Fi]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[pp,ay,m$]}],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"]}}},KMe=CMe(WMe);function qt(...t){return KMe($i(t))}function $a(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 Gee(t){const e=new Date(t);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(e)}function sqt(t){return t?t.replace(/<[^>]*>/g,""):""}const YMe=vDe,kme=C.forwardRef(({className:t,...e},r)=>s.jsx(eme,{ref:r,className:qt("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}));kme.displayName=eme.displayName;const ZMe=ZS("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"}}),Cme=C.forwardRef(({className:t,variant:e,...r},n)=>s.jsx(tme,{ref:n,className:qt(ZMe({variant:e}),t),...r}));Cme.displayName=tme.displayName;const XMe=C.forwardRef(({className:t,...e},r)=>s.jsx(ime,{ref:r,className:qt("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}));XMe.displayName=ime.displayName;const Nme=C.forwardRef(({className:t,...e},r)=>s.jsx(sme,{ref:r,className:qt("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(Os,{className:"h-4 w-4"})}));Nme.displayName=sme.displayName;const Ime=C.forwardRef(({className:t,...e},r)=>s.jsx(rme,{ref:r,className:qt("text-sm font-semibold",t),...e}));Ime.displayName=rme.displayName;const Pme=C.forwardRef(({className:t,...e},r)=>s.jsx(nme,{ref:r,className:qt("text-sm opacity-90",t),...e}));Pme.displayName=nme.displayName;function QMe(){const{toasts:t}=Rfe();return s.jsxs(YMe,{children:[t.map(function({id:e,title:r,description:n,action:i,...o}){return s.jsxs(Cme,{...o,children:[s.jsxs("div",{className:"grid gap-1",children:[r&&s.jsx(Ime,{children:r}),n&&s.jsx(Pme,{children:n})]}),i,s.jsx(Nme,{})]},e)}),s.jsx(kme,{})]})}var Hee=["light","dark"],JMe="(prefers-color-scheme: dark)",eOe=C.createContext(void 0),tOe={setTheme:t=>{},themes:[]},rOe=()=>{var t;return(t=C.useContext(eOe))!=null?t:tOe};C.memo(({forcedTheme:t,storageKey:e,attribute:r,enableSystem:n,enableColorScheme:i,defaultTheme:o,value:c,attrs:a,nonce:f})=>{let p=o==="system",y=r==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${a.map(k=>`'${k}'`).join(",")})`};`:`var d=document.documentElement,n='${r}',s='setAttribute';`,v=i?Hee.includes(o)&&o?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${o}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",T=(k,P=!1,R=!0)=>{let D=c?c[k]:k,M=P?k+"|| ''":`'${D}'`,B="";return i&&R&&!P&&Hee.includes(k)&&(B+=`d.style.colorScheme = '${k}';`),r==="class"?P||D?B+=`c.add(${M})`:B+="null":D&&(B+=`d[s](n,${M})`),B},E=t?`!function(){${y}${T(t)}}()`:n?`!function(){try{${y}var e=localStorage.getItem('${e}');if('system'===e||(!e&&${p})){var t='${JMe}',m=window.matchMedia(t);if(m.media!==t||m.matches){${T("dark")}}else{${T("light")}}}else if(e){${c?`var x=${JSON.stringify(c)};`:""}${T(c?"x[e]":"e",!0)}}${p?"":"else{"+T(o,!1,!1)+"}"}${v}}catch(e){}}()`:`!function(){try{${y}var e=localStorage.getItem('${e}');if(e){${c?`var x=${JSON.stringify(c)};`:""}${T(c?"x[e]":"e",!0)}}else{${T(o,!1,!1)};}${v}}catch(t){}}();`;return C.createElement("script",{nonce:f,dangerouslySetInnerHTML:{__html:E}})});var nOe=t=>{switch(t){case"success":return aOe;case"info":return lOe;case"warning":return oOe;case"error":return cOe;default:return null}},iOe=Array(12).fill(0),sOe=({visible:t,className:e})=>Xe.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":t},Xe.createElement("div",{className:"sonner-spinner"},iOe.map((r,n)=>Xe.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${n}`})))),aOe=Xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Xe.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),oOe=Xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Xe.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),lOe=Xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Xe.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),cOe=Xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Xe.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),uOe=Xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},Xe.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Xe.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),dOe=()=>{let[t,e]=Xe.useState(document.hidden);return Xe.useEffect(()=>{let r=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),t},VU=1,hOe=class{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{let e=this.subscribers.indexOf(t);this.subscribers.splice(e,1)}),this.publish=t=>{this.subscribers.forEach(e=>e(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var e;let{message:r,...n}=t,i=typeof(t==null?void 0:t.id)=="number"||((e=t.id)==null?void 0:e.length)>0?t.id:VU++,o=this.toasts.find(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],Xe.isValidElement(f))i=!1,this.create({id:r,type:"default",message:f});else if(mOe(f)&&!f.ok){i=!1;let p=typeof e.error=="function"?await e.error(`HTTP error! status: ${f.status}`):e.error,y=typeof e.description=="function"?await e.description(`HTTP error! status: ${f.status}`):e.description;this.create({id:r,type:"error",message:p,description:y})}else if(e.success!==void 0){i=!1;let p=typeof e.success=="function"?await e.success(f):e.success,y=typeof e.description=="function"?await e.description(f):e.description;this.create({id:r,type:"success",message:p,description:y})}}).catch(async f=>{if(o=["reject",f],e.error!==void 0){i=!1;let p=typeof e.error=="function"?await e.error(f):e.error,y=typeof e.description=="function"?await e.description(f):e.description;this.create({id:r,type:"error",message:p,description:y})}}).finally(()=>{var f;i&&(this.dismiss(r),r=void 0),(f=e.finally)==null||f.call(e)}),a=()=>new Promise((f,p)=>c.then(()=>o[0]==="reject"?p(o[1]):f(o[1])).catch(p));return typeof r!="string"&&typeof r!="number"?{unwrap:a}:Object.assign(r,{unwrap:a})},this.custom=(t,e)=>{let r=(e==null?void 0:e.id)||VU++;return this.create({jsx:t(r),id:r,...e}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},Au=new hOe,fOe=(t,e)=>{let r=(e==null?void 0:e.id)||VU++;return Au.addToast({title:t,...e,id:r}),r},mOe=t=>t&&typeof t=="object"&&"ok"in t&&typeof t.ok=="boolean"&&"status"in t&&typeof t.status=="number",pOe=fOe,gOe=()=>Au.toasts,yOe=()=>Au.getActiveToasts(),Vt=Object.assign(pOe,{success:Au.success,info:Au.info,warning:Au.warning,error:Au.error,custom:Au.custom,message:Au.message,promise:Au.promise,dismiss:Au.dismiss,loading:Au.loading},{getHistory:gOe,getToasts:yOe});function xOe(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))}xOe(`: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 JP(t){return t.label!==void 0}var vOe=3,_Oe="32px",bOe="16px",Wee=4e3,wOe=356,SOe=14,TOe=20,EOe=200;function Bh(...t){return t.filter(Boolean).join(" ")}function jOe(t){let[e,r]=t.split("-"),n=[];return e&&n.push(e),r&&n.push(r),n}var AOe=t=>{var e,r,n,i,o,c,a,f,p,y,v;let{invert:T,toast:E,unstyled:k,interacting:P,setHeights:R,visibleToasts:D,heights:M,index:B,toasts:V,expanded:G,removeToast:W,defaultRichColors:Y,closeButton:J,style:Q,cancelButtonStyle:ee,actionButtonStyle:le,className:pe="",descriptionClassName:Se="",duration:je,position:Le,gap:Ae,loadingIcon:be,expandByDefault:me,classNames:Te,icons:Ne,closeButtonAriaLabel:Ee="Close toast",pauseWhenPageIsHidden:we}=t,[He,tt]=Xe.useState(null),[at,Et]=Xe.useState(null),[vt,Gt]=Xe.useState(!1),[pt,Pt]=Xe.useState(!1),[tr,_t]=Xe.useState(!1),[cr,Tr]=Xe.useState(!1),[sn,ur]=Xe.useState(!1),[xr,rr]=Xe.useState(0),[vn,ct]=Xe.useState(0),jt=Xe.useRef(E.duration||je||Wee),er=Xe.useRef(null),Pr=Xe.useRef(null),dr=B===0,ar=B+1<=D,Nt=E.type,gr=E.dismissible!==!1,En=E.className||"",ni=E.descriptionClassName||"",ii=Xe.useMemo(()=>M.findIndex(en=>en.toastId===E.id)||0,[M,E.id]),Ui=Xe.useMemo(()=>{var en;return(en=E.closeButton)!=null?en:J},[E.closeButton,J]),Ta=Xe.useMemo(()=>E.duration||je||Wee,[E.duration,je]),vi=Xe.useRef(0),ca=Xe.useRef(0),Nr=Xe.useRef(0),Vn=Xe.useRef(null),[Ks,Ea]=Le.split("-"),wo=Xe.useMemo(()=>M.reduce((en,Fn,ts)=>ts>=ii?en:en+Fn.height,0),[M,ii]),Zr=dOe(),fn=E.invert||T,xn=Nt==="loading";ca.current=Xe.useMemo(()=>ii*Ae+wo,[ii,wo]),Xe.useEffect(()=>{jt.current=Ta},[Ta]),Xe.useEffect(()=>{Gt(!0)},[]),Xe.useEffect(()=>{let en=Pr.current;if(en){let Fn=en.getBoundingClientRect().height;return ct(Fn),R(ts=>[{toastId:E.id,height:Fn,position:E.position},...ts]),()=>R(ts=>ts.filter(bl=>bl.toastId!==E.id))}},[R,E.id]),Xe.useLayoutEffect(()=>{if(!vt)return;let en=Pr.current,Fn=en.style.height;en.style.height="auto";let ts=en.getBoundingClientRect().height;en.style.height=Fn,ct(ts),R(bl=>bl.find(Jo=>Jo.toastId===E.id)?bl.map(Jo=>Jo.toastId===E.id?{...Jo,height:ts}:Jo):[{toastId:E.id,height:ts,position:E.position},...bl])},[vt,E.title,E.description,R,E.id]);let Xr=Xe.useCallback(()=>{Pt(!0),rr(ca.current),R(en=>en.filter(Fn=>Fn.toastId!==E.id)),setTimeout(()=>{W(E)},EOe)},[E,W,R,ca]);Xe.useEffect(()=>{if(E.promise&&Nt==="loading"||E.duration===1/0||E.type==="loading")return;let en;return G||P||we&&Zr?(()=>{if(Nr.current{var Fn;(Fn=E.onAutoClose)==null||Fn.call(E,E),Xr()},jt.current)),()=>clearTimeout(en)},[G,P,E,Nt,we,Zr,Xr]),Xe.useEffect(()=>{E.delete&&Xr()},[Xr,E.delete]);function ui(){var en,Fn,ts;return Ne!=null&&Ne.loading?Xe.createElement("div",{className:Bh(Te==null?void 0:Te.loader,(en=E==null?void 0:E.classNames)==null?void 0:en.loader,"sonner-loader"),"data-visible":Nt==="loading"},Ne.loading):be?Xe.createElement("div",{className:Bh(Te==null?void 0:Te.loader,(Fn=E==null?void 0:E.classNames)==null?void 0:Fn.loader,"sonner-loader"),"data-visible":Nt==="loading"},be):Xe.createElement(sOe,{className:Bh(Te==null?void 0:Te.loader,(ts=E==null?void 0:E.classNames)==null?void 0:ts.loader),visible:Nt==="loading"})}return Xe.createElement("li",{tabIndex:0,ref:Pr,className:Bh(pe,En,Te==null?void 0:Te.toast,(e=E==null?void 0:E.classNames)==null?void 0:e.toast,Te==null?void 0:Te.default,Te==null?void 0:Te[Nt],(r=E==null?void 0:E.classNames)==null?void 0:r[Nt]),"data-sonner-toast":"","data-rich-colors":(n=E.richColors)!=null?n:Y,"data-styled":!(E.jsx||E.unstyled||k),"data-mounted":vt,"data-promise":!!E.promise,"data-swiped":sn,"data-removed":pt,"data-visible":ar,"data-y-position":Ks,"data-x-position":Ea,"data-index":B,"data-front":dr,"data-swiping":tr,"data-dismissible":gr,"data-type":Nt,"data-invert":fn,"data-swipe-out":cr,"data-swipe-direction":at,"data-expanded":!!(G||me&&vt),style:{"--index":B,"--toasts-before":B,"--z-index":V.length-B,"--offset":`${pt?xr:ca.current}px`,"--initial-height":me?"auto":`${vn}px`,...Q,...E.style},onDragEnd:()=>{_t(!1),tt(null),Vn.current=null},onPointerDown:en=>{xn||!gr||(er.current=new Date,rr(ca.current),en.target.setPointerCapture(en.pointerId),en.target.tagName!=="BUTTON"&&(_t(!0),Vn.current={x:en.clientX,y:en.clientY}))},onPointerUp:()=>{var en,Fn,ts,bl;if(cr||!gr)return;Vn.current=null;let Jo=Number(((en=Pr.current)==null?void 0:en.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Ot=Number(((Fn=Pr.current)==null?void 0:Fn.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Mo=new Date().getTime()-((ts=er.current)==null?void 0:ts.getTime()),Ei=He==="x"?Jo:Ot,As=Math.abs(Ei)/Mo;if(Math.abs(Ei)>=TOe||As>.11){rr(ca.current),(bl=E.onDismiss)==null||bl.call(E,E),Et(He==="x"?Jo>0?"right":"left":Ot>0?"down":"up"),Xr(),Tr(!0),ur(!1);return}_t(!1),tt(null)},onPointerMove:en=>{var Fn,ts,bl,Jo;if(!Vn.current||!gr||((Fn=window.getSelection())==null?void 0:Fn.toString().length)>0)return;let Ot=en.clientY-Vn.current.y,Mo=en.clientX-Vn.current.x,Ei=(ts=t.swipeDirections)!=null?ts:jOe(Le);!He&&(Math.abs(Mo)>1||Math.abs(Ot)>1)&&tt(Math.abs(Mo)>Math.abs(Ot)?"x":"y");let As={x:0,y:0};He==="y"?(Ei.includes("top")||Ei.includes("bottom"))&&(Ei.includes("top")&&Ot<0||Ei.includes("bottom")&&Ot>0)&&(As.y=Ot):He==="x"&&(Ei.includes("left")||Ei.includes("right"))&&(Ei.includes("left")&&Mo<0||Ei.includes("right")&&Mo>0)&&(As.x=Mo),(Math.abs(As.x)>0||Math.abs(As.y)>0)&&ur(!0),(bl=Pr.current)==null||bl.style.setProperty("--swipe-amount-x",`${As.x}px`),(Jo=Pr.current)==null||Jo.style.setProperty("--swipe-amount-y",`${As.y}px`)}},Ui&&!E.jsx?Xe.createElement("button",{"aria-label":Ee,"data-disabled":xn,"data-close-button":!0,onClick:xn||!gr?()=>{}:()=>{var en;Xr(),(en=E.onDismiss)==null||en.call(E,E)},className:Bh(Te==null?void 0:Te.closeButton,(i=E==null?void 0:E.classNames)==null?void 0:i.closeButton)},(o=Ne==null?void 0:Ne.close)!=null?o:uOe):null,E.jsx||C.isValidElement(E.title)?E.jsx?E.jsx:typeof E.title=="function"?E.title():E.title:Xe.createElement(Xe.Fragment,null,Nt||E.icon||E.promise?Xe.createElement("div",{"data-icon":"",className:Bh(Te==null?void 0:Te.icon,(c=E==null?void 0:E.classNames)==null?void 0:c.icon)},E.promise||E.type==="loading"&&!E.icon?E.icon||ui():null,E.type!=="loading"?E.icon||(Ne==null?void 0:Ne[Nt])||nOe(Nt):null):null,Xe.createElement("div",{"data-content":"",className:Bh(Te==null?void 0:Te.content,(a=E==null?void 0:E.classNames)==null?void 0:a.content)},Xe.createElement("div",{"data-title":"",className:Bh(Te==null?void 0:Te.title,(f=E==null?void 0:E.classNames)==null?void 0:f.title)},typeof E.title=="function"?E.title():E.title),E.description?Xe.createElement("div",{"data-description":"",className:Bh(Se,ni,Te==null?void 0:Te.description,(p=E==null?void 0:E.classNames)==null?void 0:p.description)},typeof E.description=="function"?E.description():E.description):null),C.isValidElement(E.cancel)?E.cancel:E.cancel&&JP(E.cancel)?Xe.createElement("button",{"data-button":!0,"data-cancel":!0,style:E.cancelButtonStyle||ee,onClick:en=>{var Fn,ts;JP(E.cancel)&&gr&&((ts=(Fn=E.cancel).onClick)==null||ts.call(Fn,en),Xr())},className:Bh(Te==null?void 0:Te.cancelButton,(y=E==null?void 0:E.classNames)==null?void 0:y.cancelButton)},E.cancel.label):null,C.isValidElement(E.action)?E.action:E.action&&JP(E.action)?Xe.createElement("button",{"data-button":!0,"data-action":!0,style:E.actionButtonStyle||le,onClick:en=>{var Fn,ts;JP(E.action)&&((ts=(Fn=E.action).onClick)==null||ts.call(Fn,en),!en.defaultPrevented&&Xr())},className:Bh(Te==null?void 0:Te.actionButton,(v=E==null?void 0:E.classNames)==null?void 0:v.actionButton)},E.action.label):null))};function Kee(){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 kOe(t,e){let r={};return[t,e].forEach((n,i)=>{let o=i===1,c=o?"--mobile-offset":"--offset",a=o?bOe:_Oe;function f(p){["top","right","bottom","left"].forEach(y=>{r[`${c}-${y}`]=typeof p=="number"?`${p}px`:p})}typeof n=="number"||typeof n=="string"?f(n):typeof n=="object"?["top","right","bottom","left"].forEach(p=>{n[p]===void 0?r[`${c}-${p}`]=a:r[`${c}-${p}`]=typeof n[p]=="number"?`${n[p]}px`:n[p]}):f(a)}),r}var COe=C.forwardRef(function(t,e){let{invert:r,position:n="bottom-right",hotkey:i=["altKey","KeyT"],expand:o,closeButton:c,className:a,offset:f,mobileOffset:p,theme:y="light",richColors:v,duration:T,style:E,visibleToasts:k=vOe,toastOptions:P,dir:R=Kee(),gap:D=SOe,loadingIcon:M,icons:B,containerAriaLabel:V="Notifications",pauseWhenPageIsHidden:G}=t,[W,Y]=Xe.useState([]),J=Xe.useMemo(()=>Array.from(new Set([n].concat(W.filter(we=>we.position).map(we=>we.position)))),[W,n]),[Q,ee]=Xe.useState([]),[le,pe]=Xe.useState(!1),[Se,je]=Xe.useState(!1),[Le,Ae]=Xe.useState(y!=="system"?y:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),be=Xe.useRef(null),me=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),Te=Xe.useRef(null),Ne=Xe.useRef(!1),Ee=Xe.useCallback(we=>{Y(He=>{var tt;return(tt=He.find(at=>at.id===we.id))!=null&&tt.delete||Au.dismiss(we.id),He.filter(({id:at})=>at!==we.id)})},[]);return Xe.useEffect(()=>Au.subscribe(we=>{if(we.dismiss){Y(He=>He.map(tt=>tt.id===we.id?{...tt,delete:!0}:tt));return}setTimeout(()=>{Cfe.flushSync(()=>{Y(He=>{let tt=He.findIndex(at=>at.id===we.id);return tt!==-1?[...He.slice(0,tt),{...He[tt],...we},...He.slice(tt+1)]:[we,...He]})})})}),[]),Xe.useEffect(()=>{if(y!=="system"){Ae(y);return}if(y==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Ae("dark"):Ae("light")),typeof window>"u")return;let we=window.matchMedia("(prefers-color-scheme: dark)");try{we.addEventListener("change",({matches:He})=>{Ae(He?"dark":"light")})}catch{we.addListener(({matches:tt})=>{try{Ae(tt?"dark":"light")}catch(at){console.error(at)}})}},[y]),Xe.useEffect(()=>{W.length<=1&&pe(!1)},[W]),Xe.useEffect(()=>{let we=He=>{var tt,at;i.every(Et=>He[Et]||He.code===Et)&&(pe(!0),(tt=be.current)==null||tt.focus()),He.code==="Escape"&&(document.activeElement===be.current||(at=be.current)!=null&&at.contains(document.activeElement))&&pe(!1)};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[i]),Xe.useEffect(()=>{if(be.current)return()=>{Te.current&&(Te.current.focus({preventScroll:!0}),Te.current=null,Ne.current=!1)}},[be.current]),Xe.createElement("section",{ref:e,"aria-label":`${V} ${me}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},J.map((we,He)=>{var tt;let[at,Et]=we.split("-");return W.length?Xe.createElement("ol",{key:we,dir:R==="auto"?Kee():R,tabIndex:-1,ref:be,className:a,"data-sonner-toaster":!0,"data-theme":Le,"data-y-position":at,"data-lifted":le&&W.length>1&&!o,"data-x-position":Et,style:{"--front-toast-height":`${((tt=Q[0])==null?void 0:tt.height)||0}px`,"--width":`${wOe}px`,"--gap":`${D}px`,...E,...kOe(f,p)},onBlur:vt=>{Ne.current&&!vt.currentTarget.contains(vt.relatedTarget)&&(Ne.current=!1,Te.current&&(Te.current.focus({preventScroll:!0}),Te.current=null))},onFocus:vt=>{vt.target instanceof HTMLElement&&vt.target.dataset.dismissible==="false"||Ne.current||(Ne.current=!0,Te.current=vt.relatedTarget)},onMouseEnter:()=>pe(!0),onMouseMove:()=>pe(!0),onMouseLeave:()=>{Se||pe(!1)},onDragEnd:()=>pe(!1),onPointerDown:vt=>{vt.target instanceof HTMLElement&&vt.target.dataset.dismissible==="false"||je(!0)},onPointerUp:()=>je(!1)},W.filter(vt=>!vt.position&&He===0||vt.position===we).map((vt,Gt)=>{var pt,Pt;return Xe.createElement(AOe,{key:vt.id,icons:B,index:Gt,toast:vt,defaultRichColors:v,duration:(pt=P==null?void 0:P.duration)!=null?pt:T,className:P==null?void 0:P.className,descriptionClassName:P==null?void 0:P.descriptionClassName,invert:r,visibleToasts:k,closeButton:(Pt=P==null?void 0:P.closeButton)!=null?Pt:c,interacting:Se,position:we,style:P==null?void 0:P.style,unstyled:P==null?void 0:P.unstyled,classNames:P==null?void 0:P.classNames,cancelButtonStyle:P==null?void 0:P.cancelButtonStyle,actionButtonStyle:P==null?void 0:P.actionButtonStyle,removeToast:Ee,toasts:W.filter(tr=>tr.position==vt.position),heights:Q.filter(tr=>tr.position==vt.position),setHeights:ee,expandByDefault:o,gap:D,loadingIcon:M,expanded:le,pauseWhenPageIsHidden:G,swipeDirections:t.swipeDirections})})):null}))});const NOe=({...t})=>{const{theme:e="system"}=rOe();return s.jsx(COe,{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 IOe=kG[" useId ".trim().toString()]||(()=>{}),POe=0;function Fl(t){const[e,r]=C.useState(IOe());return Do(()=>{r(n=>n??String(POe++))},[t]),e?`radix-${e}`:""}var p$="focusScope.autoFocusOnMount",g$="focusScope.autoFocusOnUnmount",Yee={bubbles:!1,cancelable:!0},ROe="FocusScope",EC=C.forwardRef((t,e)=>{const{loop:r=!1,trapped:n=!1,onMountAutoFocus:i,onUnmountAutoFocus:o,...c}=t,[a,f]=C.useState(null),p=vo(i),y=vo(o),v=C.useRef(null),T=Yn(e,P=>f(P)),E=C.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;C.useEffect(()=>{if(n){let P=function(B){if(E.paused||!a)return;const V=B.target;a.contains(V)?v.current=V:my(v.current,{select:!0})},R=function(B){if(E.paused||!a)return;const V=B.relatedTarget;V!==null&&(a.contains(V)||my(v.current,{select:!0}))},D=function(B){if(document.activeElement===document.body)for(const G of B)G.removedNodes.length>0&&my(a)};document.addEventListener("focusin",P),document.addEventListener("focusout",R);const M=new MutationObserver(D);return a&&M.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",P),document.removeEventListener("focusout",R),M.disconnect()}}},[n,a,E.paused]),C.useEffect(()=>{if(a){Xee.add(E);const P=document.activeElement;if(!a.contains(P)){const D=new CustomEvent(p$,Yee);a.addEventListener(p$,p),a.dispatchEvent(D),D.defaultPrevented||(LOe(BOe(Rme(a)),{select:!0}),document.activeElement===P&&my(a))}return()=>{a.removeEventListener(p$,p),setTimeout(()=>{const D=new CustomEvent(g$,Yee);a.addEventListener(g$,y),a.dispatchEvent(D),D.defaultPrevented||my(P??document.body,{select:!0}),a.removeEventListener(g$,y),Xee.remove(E)},0)}}},[a,p,y,E]);const k=C.useCallback(P=>{if(!r&&!n||E.paused)return;const R=P.key==="Tab"&&!P.altKey&&!P.ctrlKey&&!P.metaKey,D=document.activeElement;if(R&&D){const M=P.currentTarget,[B,V]=DOe(M);B&&V?!P.shiftKey&&D===V?(P.preventDefault(),r&&my(B,{select:!0})):P.shiftKey&&D===B&&(P.preventDefault(),r&&my(V,{select:!0})):D===M&&P.preventDefault()}},[r,n,E.paused]);return s.jsx(nn.div,{tabIndex:-1,...c,ref:T,onKeyDown:k})});EC.displayName=ROe;function LOe(t,{select:e=!1}={}){const r=document.activeElement;for(const n of t)if(my(n,{select:e}),document.activeElement!==r)return}function DOe(t){const e=Rme(t),r=Zee(e,t),n=Zee(e.reverse(),t);return[r,n]}function Rme(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 Zee(t,e){for(const r of t)if(!MOe(r,{upTo:e}))return r}function MOe(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 OOe(t){return t instanceof HTMLInputElement&&"select"in t}function my(t,{select:e=!1}={}){if(t&&t.focus){const r=document.activeElement;t.focus({preventScroll:!0}),t!==r&&OOe(t)&&e&&t.select()}}var Xee=FOe();function FOe(){let t=[];return{add(e){const r=t[0];e!==r&&(r==null||r.pause()),t=Qee(t,e),t.unshift(e)},remove(e){var r;t=Qee(t,e),(r=t[0])==null||r.resume()}}}function Qee(t,e){const r=[...t],n=r.indexOf(e);return n!==-1&&r.splice(n,1),r}function BOe(t){return t.filter(e=>e.tagName!=="A")}var y$=0;function e3(){C.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??Jee()),document.body.insertAdjacentElement("beforeend",t[1]??Jee()),y$++,()=>{y$===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),y$--}},[])}function Jee(){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 sm=function(){return sm=Object.assign||function(e){for(var r,n=1,i=arguments.length;n"u")return r3e;var e=n3e(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])}},s3e=Ome(),p1="data-scroll-locked",a3e=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(zOe,` { overflow: hidden `).concat(n,`; padding-right: `).concat(a,"px ").concat(n,`; } body[`).concat(p1,`] { 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(SL,` { right: `).concat(a,"px ").concat(n,`; } .`).concat(TL,` { margin-right: `).concat(a,"px ").concat(n,`; } .`).concat(SL," .").concat(SL,` { right: 0 `).concat(n,`; } .`).concat(TL," .").concat(TL,` { margin-right: 0 `).concat(n,`; } body[`).concat(p1,`] { `).concat(UOe,": ").concat(a,`px; } `)},tte=function(){var t=parseInt(document.body.getAttribute(p1)||"0",10);return isFinite(t)?t:0},o3e=function(){C.useEffect(function(){return document.body.setAttribute(p1,(tte()+1).toString()),function(){var t=tte()-1;t<=0?document.body.removeAttribute(p1):document.body.setAttribute(p1,t.toString())}},[])},l3e=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,i=n===void 0?"margin":n;o3e();var o=C.useMemo(function(){return i3e(i)},[i]);return C.createElement(s3e,{styles:a3e(o,!e,i,r?"":"!important")})},qU=!1;if(typeof window<"u")try{var eR=Object.defineProperty({},"passive",{get:function(){return qU=!0,!0}});window.addEventListener("test",eR,eR),window.removeEventListener("test",eR,eR)}catch{qU=!1}var lw=qU?{passive:!1}:!1,c3e=function(t){return t.tagName==="TEXTAREA"},Fme=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!c3e(t)&&r[e]==="visible")},u3e=function(t){return Fme(t,"overflowY")},d3e=function(t){return Fme(t,"overflowX")},rte=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var i=Bme(t,n);if(i){var o=$me(t,n),c=o[1],a=o[2];if(c>a)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},h3e=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},f3e=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},Bme=function(t,e){return t==="v"?u3e(e):d3e(e)},$me=function(t,e){return t==="v"?h3e(e):f3e(e)},m3e=function(t,e){return t==="h"&&e==="rtl"?-1:1},p3e=function(t,e,r,n,i){var o=m3e(t,window.getComputedStyle(e).direction),c=o*n,a=r.target,f=e.contains(a),p=!1,y=c>0,v=0,T=0;do{if(!a)break;var E=$me(t,a),k=E[0],P=E[1],R=E[2],D=P-R-o*k;(k||D)&&Bme(t,a)&&(v+=D,T+=k);var M=a.parentNode;a=M&&M.nodeType===Node.DOCUMENT_FRAGMENT_NODE?M.host:M}while(!f&&a!==document.body||f&&(e.contains(a)||e===a));return(y&&(Math.abs(v)<1||!i)||!y&&(Math.abs(T)<1||!i))&&(p=!0),p},tR=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},nte=function(t){return[t.deltaX,t.deltaY]},ite=function(t){return t&&"current"in t?t.current:t},g3e=function(t,e){return t[0]===e[0]&&t[1]===e[1]},y3e=function(t){return` .block-interactivity-`.concat(t,` {pointer-events: none;} .allow-interactivity-`).concat(t,` {pointer-events: all;} `)},x3e=0,cw=[];function v3e(t){var e=C.useRef([]),r=C.useRef([0,0]),n=C.useRef(),i=C.useState(x3e++)[0],o=C.useState(Ome)[0],c=C.useRef(t);C.useEffect(function(){c.current=t},[t]),C.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(i));var P=$Oe([t.lockRef.current],(t.shards||[]).map(ite),!0).filter(Boolean);return P.forEach(function(R){return R.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),P.forEach(function(R){return R.classList.remove("allow-interactivity-".concat(i))})}}},[t.inert,t.lockRef.current,t.shards]);var a=C.useCallback(function(P,R){if("touches"in P&&P.touches.length===2||P.type==="wheel"&&P.ctrlKey)return!c.current.allowPinchZoom;var D=tR(P),M=r.current,B="deltaX"in P?P.deltaX:M[0]-D[0],V="deltaY"in P?P.deltaY:M[1]-D[1],G,W=P.target,Y=Math.abs(B)>Math.abs(V)?"h":"v";if("touches"in P&&Y==="h"&&W.type==="range")return!1;var J=rte(Y,W);if(!J)return!0;if(J?G=Y:(G=Y==="v"?"h":"v",J=rte(Y,W)),!J)return!1;if(!n.current&&"changedTouches"in P&&(B||V)&&(n.current=G),!G)return!0;var Q=n.current||G;return p3e(Q,R,P,Q==="h"?B:V,!0)},[]),f=C.useCallback(function(P){var R=P;if(!(!cw.length||cw[cw.length-1]!==o)){var D="deltaY"in R?nte(R):tR(R),M=e.current.filter(function(G){return G.name===R.type&&(G.target===R.target||R.target===G.shadowParent)&&g3e(G.delta,D)})[0];if(M&&M.should){R.cancelable&&R.preventDefault();return}if(!M){var B=(c.current.shards||[]).map(ite).filter(Boolean).filter(function(G){return G.contains(R.target)}),V=B.length>0?a(R,B[0]):!c.current.noIsolation;V&&R.cancelable&&R.preventDefault()}}},[]),p=C.useCallback(function(P,R,D,M){var B={name:P,delta:R,target:D,should:M,shadowParent:_3e(D)};e.current.push(B),setTimeout(function(){e.current=e.current.filter(function(V){return V!==B})},1)},[]),y=C.useCallback(function(P){r.current=tR(P),n.current=void 0},[]),v=C.useCallback(function(P){p(P.type,nte(P),P.target,a(P,t.lockRef.current))},[]),T=C.useCallback(function(P){p(P.type,tR(P),P.target,a(P,t.lockRef.current))},[]);C.useEffect(function(){return cw.push(o),t.setCallbacks({onScrollCapture:v,onWheelCapture:v,onTouchMoveCapture:T}),document.addEventListener("wheel",f,lw),document.addEventListener("touchmove",f,lw),document.addEventListener("touchstart",y,lw),function(){cw=cw.filter(function(P){return P!==o}),document.removeEventListener("wheel",f,lw),document.removeEventListener("touchmove",f,lw),document.removeEventListener("touchstart",y,lw)}},[]);var E=t.removeScrollBar,k=t.inert;return C.createElement(C.Fragment,null,k?C.createElement(o,{styles:y3e(i)}):null,E?C.createElement(l3e,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function _3e(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}const b3e=YOe(Mme,v3e);var jC=C.forwardRef(function(t,e){return C.createElement(t3,sm({},t,{ref:e,sideCar:b3e}))});jC.classNames=t3.classNames;var w3e=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},uw=new WeakMap,rR=new WeakMap,nR={},b$=0,zme=function(t){return t&&(t.host||zme(t.parentNode))},S3e=function(t,e){return e.map(function(r){if(t.contains(r))return r;var n=zme(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})},T3e=function(t,e,r,n){var i=S3e(e,Array.isArray(t)?t:[t]);nR[r]||(nR[r]=new WeakMap);var o=nR[r],c=[],a=new Set,f=new Set(i),p=function(v){!v||a.has(v)||(a.add(v),p(v.parentNode))};i.forEach(p);var y=function(v){!v||f.has(v)||Array.prototype.forEach.call(v.children,function(T){if(a.has(T))y(T);else try{var E=T.getAttribute(n),k=E!==null&&E!=="false",P=(uw.get(T)||0)+1,R=(o.get(T)||0)+1;uw.set(T,P),o.set(T,R),c.push(T),P===1&&k&&rR.set(T,!0),R===1&&T.setAttribute(r,"true"),k||T.setAttribute(n,"true")}catch(D){console.error("aria-hidden: cannot operate on ",T,D)}})};return y(e),a.clear(),b$++,function(){c.forEach(function(v){var T=uw.get(v)-1,E=o.get(v)-1;uw.set(v,T),o.set(v,E),T||(rR.has(v)||v.removeAttribute(n),rR.delete(v)),E||v.removeAttribute(r)}),b$--,b$||(uw=new WeakMap,uw=new WeakMap,rR=new WeakMap,nR={})}},r3=function(t,e,r){r===void 0&&(r="data-aria-hidden");var n=Array.from(Array.isArray(t)?t:[t]),i=w3e(t);return i?(n.push.apply(n,Array.from(i.querySelectorAll("[aria-live]"))),T3e(n,i,r,"aria-hidden")):function(){return null}},n3="Dialog",[Ume,Vme]=Qo(n3),[E3e,vf]=Ume(n3),qme=t=>{const{__scopeDialog:e,children:r,open:n,defaultOpen:i,onOpenChange:o,modal:c=!0}=t,a=C.useRef(null),f=C.useRef(null),[p,y]=yd({prop:n,defaultProp:i??!1,onChange:o,caller:n3});return s.jsx(E3e,{scope:e,triggerRef:a,contentRef:f,contentId:Fl(),titleId:Fl(),descriptionId:Fl(),open:p,onOpenChange:y,onOpenToggle:C.useCallback(()=>y(v=>!v),[y]),modal:c,children:r})};qme.displayName=n3;var Gme="DialogTrigger",Hme=C.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=vf(Gme,r),o=Yn(e,i.triggerRef);return s.jsx(nn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":M9(i.open),...n,ref:o,onClick:Or(t.onClick,i.onOpenToggle)})});Hme.displayName=Gme;var L9="DialogPortal",[j3e,Wme]=Ume(L9,{forceMount:void 0}),Kme=t=>{const{__scopeDialog:e,forceMount:r,children:n,container:i}=t,o=vf(L9,e);return s.jsx(j3e,{scope:e,forceMount:r,children:C.Children.map(n,c=>s.jsx(vl,{present:r||o.open,children:s.jsx(YS,{asChild:!0,container:i,children:c})}))})};Kme.displayName=L9;var ID="DialogOverlay",Yme=C.forwardRef((t,e)=>{const r=Wme(ID,t.__scopeDialog),{forceMount:n=r.forceMount,...i}=t,o=vf(ID,t.__scopeDialog);return o.modal?s.jsx(vl,{present:n||o.open,children:s.jsx(k3e,{...i,ref:e})}):null});Yme.displayName=ID;var A3e=ux("DialogOverlay.RemoveScroll"),k3e=C.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=vf(ID,r);return s.jsx(jC,{as:A3e,allowPinchZoom:!0,shards:[i.contentRef],children:s.jsx(nn.div,{"data-state":M9(i.open),...n,ref:e,style:{pointerEvents:"auto",...n.style}})})}),r_="DialogContent",Zme=C.forwardRef((t,e)=>{const r=Wme(r_,t.__scopeDialog),{forceMount:n=r.forceMount,...i}=t,o=vf(r_,t.__scopeDialog);return s.jsx(vl,{present:n||o.open,children:o.modal?s.jsx(C3e,{...i,ref:e}):s.jsx(N3e,{...i,ref:e})})});Zme.displayName=r_;var C3e=C.forwardRef((t,e)=>{const r=vf(r_,t.__scopeDialog),n=C.useRef(null),i=Yn(e,r.contentRef,n);return C.useEffect(()=>{const o=n.current;if(o)return r3(o)},[]),s.jsx(Xme,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Or(t.onCloseAutoFocus,o=>{var c;o.preventDefault(),(c=r.triggerRef.current)==null||c.focus()}),onPointerDownOutside:Or(t.onPointerDownOutside,o=>{const c=o.detail.originalEvent,a=c.button===0&&c.ctrlKey===!0;(c.button===2||a)&&o.preventDefault()}),onFocusOutside:Or(t.onFocusOutside,o=>o.preventDefault())})}),N3e=C.forwardRef((t,e)=>{const r=vf(r_,t.__scopeDialog),n=C.useRef(!1),i=C.useRef(!1);return s.jsx(Xme,{...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,p;(f=t.onInteractOutside)==null||f.call(t,o),o.defaultPrevented||(n.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const c=o.target;((p=r.triggerRef.current)==null?void 0:p.contains(c))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),Xme=C.forwardRef((t,e)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:o,...c}=t,a=vf(r_,r),f=C.useRef(null),p=Yn(e,f);return e3(),s.jsxs(s.Fragment,{children:[s.jsx(EC,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:o,children:s.jsx(v_,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":M9(a.open),...c,ref:p,onDismiss:()=>a.onOpenChange(!1)})}),s.jsxs(s.Fragment,{children:[s.jsx(P3e,{titleId:a.titleId}),s.jsx(L3e,{contentRef:f,descriptionId:a.descriptionId})]})]})}),D9="DialogTitle",Qme=C.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=vf(D9,r);return s.jsx(nn.h2,{id:i.titleId,...n,ref:e})});Qme.displayName=D9;var Jme="DialogDescription",epe=C.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=vf(Jme,r);return s.jsx(nn.p,{id:i.descriptionId,...n,ref:e})});epe.displayName=Jme;var tpe="DialogClose",rpe=C.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=vf(tpe,r);return s.jsx(nn.button,{type:"button",...n,ref:e,onClick:Or(t.onClick,()=>i.onOpenChange(!1))})});rpe.displayName=tpe;function M9(t){return t?"open":"closed"}var npe="DialogTitleWarning",[I3e,ipe]=ILe(npe,{contentName:r_,titleName:D9,docsSlug:"dialog"}),P3e=({titleId:t})=>{const e=ipe(npe),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 C.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},R3e="DialogDescriptionWarning",L3e=({contentRef:t,descriptionId:e})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${ipe(R3e).contentName}}.`;return C.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},i3=qme,O9=Hme,s3=Kme,tT=Yme,rT=Zme,AC=Qme,kC=epe,CC=rpe,spe="AlertDialog",[D3e,aqt]=Qo(spe,[Vme]),hg=Vme(),ape=t=>{const{__scopeAlertDialog:e,...r}=t,n=hg(e);return s.jsx(i3,{...n,...r,modal:!0})};ape.displayName=spe;var M3e="AlertDialogTrigger",ope=C.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=hg(r);return s.jsx(O9,{...i,...n,ref:e})});ope.displayName=M3e;var O3e="AlertDialogPortal",lpe=t=>{const{__scopeAlertDialog:e,...r}=t,n=hg(e);return s.jsx(s3,{...n,...r})};lpe.displayName=O3e;var F3e="AlertDialogOverlay",cpe=C.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=hg(r);return s.jsx(tT,{...i,...n,ref:e})});cpe.displayName=F3e;var g1="AlertDialogContent",[B3e,$3e]=D3e(g1),z3e=Mfe("AlertDialogContent"),upe=C.forwardRef((t,e)=>{const{__scopeAlertDialog:r,children:n,...i}=t,o=hg(r),c=C.useRef(null),a=Yn(e,c),f=C.useRef(null);return s.jsx(I3e,{contentName:g1,titleName:dpe,docsSlug:"alert-dialog",children:s.jsx(B3e,{scope:r,cancelRef:f,children:s.jsxs(rT,{role:"alertdialog",...o,...i,ref:a,onOpenAutoFocus:Or(i.onOpenAutoFocus,p=>{var y;p.preventDefault(),(y=f.current)==null||y.focus({preventScroll:!0})}),onPointerDownOutside:p=>p.preventDefault(),onInteractOutside:p=>p.preventDefault(),children:[s.jsx(z3e,{children:n}),s.jsx(V3e,{contentRef:c})]})})})});upe.displayName=g1;var dpe="AlertDialogTitle",hpe=C.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=hg(r);return s.jsx(AC,{...i,...n,ref:e})});hpe.displayName=dpe;var fpe="AlertDialogDescription",mpe=C.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=hg(r);return s.jsx(kC,{...i,...n,ref:e})});mpe.displayName=fpe;var U3e="AlertDialogAction",ppe=C.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=hg(r);return s.jsx(CC,{...i,...n,ref:e})});ppe.displayName=U3e;var gpe="AlertDialogCancel",ype=C.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,{cancelRef:i}=$3e(gpe,r),o=hg(r),c=Yn(e,i);return s.jsx(CC,{...o,...n,ref:c})});ype.displayName=gpe;var V3e=({contentRef:t})=>{const e=`\`${g1}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${g1}\` by passing a \`${fpe}\` 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 \`${g1}\`. 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 C.useEffect(()=>{var n;document.getElementById((n=t.current)==null?void 0:n.getAttribute("aria-describedby"))||console.warn(e)},[e,t]),null},q3e=ape,G3e=ope,H3e=lpe,xpe=cpe,vpe=upe,_pe=ppe,bpe=ype,wpe=hpe,Spe=mpe;const YA=ZS("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"}}),Bt=C.forwardRef(({className:t,variant:e,size:r,asChild:n=!1,...i},o)=>{const c=n?Lfe:"button";return s.jsx(c,{className:qt(YA({variant:e,size:r,className:t})),ref:o,...i})});Bt.displayName="Button";const Tpe=q3e,oqt=G3e,W3e=H3e,Epe=C.forwardRef(({className:t,...e},r)=>s.jsx(xpe,{className:qt("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}));Epe.displayName=xpe.displayName;const F9=C.forwardRef(({className:t,...e},r)=>s.jsxs(W3e,{children:[s.jsx(Epe,{}),s.jsx(vpe,{ref:r,className:qt("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})]}));F9.displayName=vpe.displayName;const B9=({className:t,...e})=>s.jsx("div",{className:qt("flex flex-col space-y-2 text-center sm:text-left",t),...e});B9.displayName="AlertDialogHeader";const $9=({className:t,...e})=>s.jsx("div",{className:qt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});$9.displayName="AlertDialogFooter";const z9=C.forwardRef(({className:t,...e},r)=>s.jsx(wpe,{ref:r,className:qt("text-lg font-semibold",t),...e}));z9.displayName=wpe.displayName;const U9=C.forwardRef(({className:t,...e},r)=>s.jsx(Spe,{ref:r,className:qt("text-sm text-muted-foreground",t),...e}));U9.displayName=Spe.displayName;const V9=C.forwardRef(({className:t,...e},r)=>s.jsx(_pe,{ref:r,className:qt(YA(),t),...e}));V9.displayName=_pe.displayName;const q9=C.forwardRef(({className:t,...e},r)=>s.jsx(bpe,{ref:r,className:qt(YA({variant:"outline"}),"mt-2 sm:mt-0",t),...e}));q9.displayName=bpe.displayName;let PD=null;const K3e=["delete","remove","revoke","cannot be undone","permanently"];function lqt(t,e={}){const r=typeof t=="string"?{description:t,...e}:t,n=`${r.title??""} ${r.description??""}`.toLowerCase(),i=r.destructive??K3e.some(o=>n.includes(o));return new Promise(o=>{if(!PD){o(window.confirm(r.description??r.title??"Are you sure?"));return}PD({...r,destructive:i,resolve:o})})}function Y3e(){const[t,e]=C.useState(null);C.useEffect(()=>(PD=i=>e(i),()=>{PD=null}),[]);const r=i=>{t==null||t.resolve(i),e(null)},n=!!(t!=null&&t.destructive);return s.jsx(Tpe,{open:!!t,onOpenChange:i=>!i&&r(!1),children:s.jsxs(F9,{className:"sm:max-w-md",children:[s.jsx(B9,{children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:qt("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(JS,{className:"h-5 w-5"})}),s.jsxs("div",{className:"space-y-1.5 text-left",children:[s.jsx(z9,{children:(t==null?void 0:t.title)??(n?"Are you sure?":"Please confirm")}),(t==null?void 0:t.description)&&s.jsx(U9,{className:"leading-relaxed",children:t.description})]})]})}),s.jsxs($9,{className:"gap-2 sm:gap-2",children:[s.jsx(q9,{onClick:()=>r(!1),children:(t==null?void 0:t.cancelText)??"Cancel"}),s.jsx(V9,{onClick:()=>r(!0),className:qt(n&&"bg-destructive text-destructive-foreground hover:bg-destructive/90"),children:(t==null?void 0:t.confirmText)??(n?"Delete":"Continue")})]})]})})}const Z3e=["top","right","bottom","left"],fx=Math.min,ad=Math.max,RD=Math.round,iR=Math.floor,mx=t=>({x:t,y:t}),X3e={left:"right",right:"left",bottom:"top",top:"bottom"},Q3e={start:"end",end:"start"};function GU(t,e,r){return ad(t,fx(e,r))}function Jp(t,e){return typeof t=="function"?t(e):t}function eg(t){return t.split("-")[0]}function nT(t){return t.split("-")[1]}function G9(t){return t==="x"?"y":"x"}function H9(t){return t==="y"?"height":"width"}function px(t){return["top","bottom"].includes(eg(t))?"y":"x"}function W9(t){return G9(px(t))}function J3e(t,e,r){r===void 0&&(r=!1);const n=nT(t),i=W9(t),o=H9(i);let c=i==="x"?n===(r?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[o]>e.floating[o]&&(c=LD(c)),[c,LD(c)]}function eFe(t){const e=LD(t);return[HU(t),e,HU(e)]}function HU(t){return t.replace(/start|end/g,e=>Q3e[e])}function tFe(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 rFe(t,e,r,n){const i=nT(t);let o=tFe(eg(t),r==="start",n);return i&&(o=o.map(c=>c+"-"+i),e&&(o=o.concat(o.map(HU)))),o}function LD(t){return t.replace(/left|right|bottom|top/g,e=>X3e[e])}function nFe(t){return{top:0,right:0,bottom:0,left:0,...t}}function jpe(t){return typeof t!="number"?nFe(t):{top:t,right:t,bottom:t,left:t}}function DD(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 ste(t,e,r){let{reference:n,floating:i}=t;const o=px(e),c=W9(e),a=H9(c),f=eg(e),p=o==="y",y=n.x+n.width/2-i.width/2,v=n.y+n.height/2-i.height/2,T=n[a]/2-i[a]/2;let E;switch(f){case"top":E={x:y,y:n.y-i.height};break;case"bottom":E={x:y,y:n.y+n.height};break;case"right":E={x:n.x+n.width,y:v};break;case"left":E={x:n.x-i.width,y:v};break;default:E={x:n.x,y:n.y}}switch(nT(e)){case"start":E[c]-=T*(r&&p?-1:1);break;case"end":E[c]+=T*(r&&p?-1:1);break}return E}const iFe=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 p=await c.getElementRects({reference:t,floating:e,strategy:i}),{x:y,y:v}=ste(p,n,f),T=n,E={},k=0;for(let P=0;P({name:"arrow",options:t,async fn(e){const{x:r,y:n,placement:i,rects:o,platform:c,elements:a,middlewareData:f}=e,{element:p,padding:y=0}=Jp(t,e)||{};if(p==null)return{};const v=jpe(y),T={x:r,y:n},E=W9(i),k=H9(E),P=await c.getDimensions(p),R=E==="y",D=R?"top":"left",M=R?"bottom":"right",B=R?"clientHeight":"clientWidth",V=o.reference[k]+o.reference[E]-T[E]-o.floating[k],G=T[E]-o.reference[E],W=await(c.getOffsetParent==null?void 0:c.getOffsetParent(p));let Y=W?W[B]:0;(!Y||!await(c.isElement==null?void 0:c.isElement(W)))&&(Y=a.floating[B]||o.floating[k]);const J=V/2-G/2,Q=Y/2-P[k]/2-1,ee=fx(v[D],Q),le=fx(v[M],Q),pe=ee,Se=Y-P[k]-le,je=Y/2-P[k]/2+J,Le=GU(pe,je,Se),Ae=!f.arrow&&nT(i)!=null&&je!==Le&&o.reference[k]/2-(jeje<=0)){var le,pe;const je=(((le=o.flip)==null?void 0:le.index)||0)+1,Le=Y[je];if(Le)return{data:{index:je,overflows:ee},reset:{placement:Le}};let Ae=(pe=ee.filter(be=>be.overflows[0]<=0).sort((be,me)=>be.overflows[1]-me.overflows[1])[0])==null?void 0:pe.placement;if(!Ae)switch(E){case"bestFit":{var Se;const be=(Se=ee.filter(me=>{if(W){const Te=px(me.placement);return Te===M||Te==="y"}return!0}).map(me=>[me.placement,me.overflows.filter(Te=>Te>0).reduce((Te,Ne)=>Te+Ne,0)]).sort((me,Te)=>me[1]-Te[1])[0])==null?void 0:Se[0];be&&(Ae=be);break}case"initialPlacement":Ae=a;break}if(i!==Ae)return{reset:{placement:Ae}}}return{}}}};function ate(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function ote(t){return Z3e.some(e=>t[e]>=0)}const oFe=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:r}=e,{strategy:n="referenceHidden",...i}=Jp(t,e);switch(n){case"referenceHidden":{const o=await ZA(e,{...i,elementContext:"reference"}),c=ate(o,r.reference);return{data:{referenceHiddenOffsets:c,referenceHidden:ote(c)}}}case"escaped":{const o=await ZA(e,{...i,altBoundary:!0}),c=ate(o,r.floating);return{data:{escapedOffsets:c,escaped:ote(c)}}}default:return{}}}}};async function lFe(t,e){const{placement:r,platform:n,elements:i}=t,o=await(n.isRTL==null?void 0:n.isRTL(i.floating)),c=eg(r),a=nT(r),f=px(r)==="y",p=["left","top"].includes(c)?-1:1,y=o&&f?-1:1,v=Jp(e,t);let{mainAxis:T,crossAxis:E,alignmentAxis:k}=typeof v=="number"?{mainAxis:v,crossAxis:0,alignmentAxis:null}:{mainAxis:v.mainAxis||0,crossAxis:v.crossAxis||0,alignmentAxis:v.alignmentAxis};return a&&typeof k=="number"&&(E=a==="end"?k*-1:k),f?{x:E*y,y:T*p}:{x:T*p,y:E*y}}const cFe=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 lFe(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}}}}},uFe=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:R=>{let{x:D,y:M}=R;return{x:D,y:M}}},...f}=Jp(t,e),p={x:r,y:n},y=await ZA(e,f),v=px(eg(i)),T=G9(v);let E=p[T],k=p[v];if(o){const R=T==="y"?"top":"left",D=T==="y"?"bottom":"right",M=E+y[R],B=E-y[D];E=GU(M,E,B)}if(c){const R=v==="y"?"top":"left",D=v==="y"?"bottom":"right",M=k+y[R],B=k-y[D];k=GU(M,k,B)}const P=a.fn({...e,[T]:E,[v]:k});return{...P,data:{x:P.x-r,y:P.y-n,enabled:{[T]:o,[v]:c}}}}}},dFe=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:p=!0}=Jp(t,e),y={x:r,y:n},v=px(i),T=G9(v);let E=y[T],k=y[v];const P=Jp(a,e),R=typeof P=="number"?{mainAxis:P,crossAxis:0}:{mainAxis:0,crossAxis:0,...P};if(f){const B=T==="y"?"height":"width",V=o.reference[T]-o.floating[B]+R.mainAxis,G=o.reference[T]+o.reference[B]-R.mainAxis;EG&&(E=G)}if(p){var D,M;const B=T==="y"?"width":"height",V=["top","left"].includes(eg(i)),G=o.reference[v]-o.floating[B]+(V&&((D=c.offset)==null?void 0:D[v])||0)+(V?0:R.crossAxis),W=o.reference[v]+o.reference[B]+(V?0:((M=c.offset)==null?void 0:M[v])||0)-(V?R.crossAxis:0);kW&&(k=W)}return{[T]:E,[v]:k}}}},hFe=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=()=>{},...p}=Jp(t,e),y=await ZA(e,p),v=eg(i),T=nT(i),E=px(i)==="y",{width:k,height:P}=o.floating;let R,D;v==="top"||v==="bottom"?(R=v,D=T===(await(c.isRTL==null?void 0:c.isRTL(a.floating))?"start":"end")?"left":"right"):(D=v,R=T==="end"?"top":"bottom");const M=P-y.top-y.bottom,B=k-y.left-y.right,V=fx(P-y[R],M),G=fx(k-y[D],B),W=!e.middlewareData.shift;let Y=V,J=G;if((r=e.middlewareData.shift)!=null&&r.enabled.x&&(J=B),(n=e.middlewareData.shift)!=null&&n.enabled.y&&(Y=M),W&&!T){const ee=ad(y.left,0),le=ad(y.right,0),pe=ad(y.top,0),Se=ad(y.bottom,0);E?J=k-2*(ee!==0||le!==0?ee+le:ad(y.left,y.right)):Y=P-2*(pe!==0||Se!==0?pe+Se:ad(y.top,y.bottom))}await f({...e,availableWidth:J,availableHeight:Y});const Q=await c.getDimensions(a.floating);return k!==Q.width||P!==Q.height?{reset:{rects:!0}}:{}}}};function a3(){return typeof window<"u"}function iT(t){return Ape(t)?(t.nodeName||"").toLowerCase():"#document"}function fd(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function Nm(t){var e;return(e=(Ape(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function Ape(t){return a3()?t instanceof Node||t instanceof fd(t).Node:!1}function gf(t){return a3()?t instanceof Element||t instanceof fd(t).Element:!1}function wm(t){return a3()?t instanceof HTMLElement||t instanceof fd(t).HTMLElement:!1}function lte(t){return!a3()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof fd(t).ShadowRoot}function NC(t){const{overflow:e,overflowX:r,overflowY:n,display:i}=yf(t);return/auto|scroll|overlay|hidden|clip/.test(e+n+r)&&!["inline","contents"].includes(i)}function fFe(t){return["table","td","th"].includes(iT(t))}function o3(t){return[":popover-open",":modal"].some(e=>{try{return t.matches(e)}catch{return!1}})}function K9(t){const e=Y9(),r=gf(t)?yf(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 mFe(t){let e=gx(t);for(;wm(e)&&!tS(e);){if(K9(e))return e;if(o3(e))return null;e=gx(e)}return null}function Y9(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function tS(t){return["html","body","#document"].includes(iT(t))}function yf(t){return fd(t).getComputedStyle(t)}function l3(t){return gf(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function gx(t){if(iT(t)==="html")return t;const e=t.assignedSlot||t.parentNode||lte(t)&&t.host||Nm(t);return lte(e)?e.host:e}function kpe(t){const e=gx(t);return tS(e)?t.ownerDocument?t.ownerDocument.body:t.body:wm(e)&&NC(e)?e:kpe(e)}function XA(t,e,r){var n;e===void 0&&(e=[]),r===void 0&&(r=!0);const i=kpe(t),o=i===((n=t.ownerDocument)==null?void 0:n.body),c=fd(i);if(o){const a=WU(c);return e.concat(c,c.visualViewport||[],NC(i)?i:[],a&&r?XA(a):[])}return e.concat(i,XA(i,[],r))}function WU(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function Cpe(t){const e=yf(t);let r=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const i=wm(t),o=i?t.offsetWidth:r,c=i?t.offsetHeight:n,a=RD(r)!==o||RD(n)!==c;return a&&(r=o,n=c),{width:r,height:n,$:a}}function Z9(t){return gf(t)?t:t.contextElement}function y1(t){const e=Z9(t);if(!wm(e))return mx(1);const r=e.getBoundingClientRect(),{width:n,height:i,$:o}=Cpe(e);let c=(o?RD(r.width):r.width)/n,a=(o?RD(r.height):r.height)/i;return(!c||!Number.isFinite(c))&&(c=1),(!a||!Number.isFinite(a))&&(a=1),{x:c,y:a}}const pFe=mx(0);function Npe(t){const e=fd(t);return!Y9()||!e.visualViewport?pFe:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function gFe(t,e,r){return e===void 0&&(e=!1),!r||e&&r!==fd(t)?!1:e}function n_(t,e,r,n){e===void 0&&(e=!1),r===void 0&&(r=!1);const i=t.getBoundingClientRect(),o=Z9(t);let c=mx(1);e&&(n?gf(n)&&(c=y1(n)):c=y1(t));const a=gFe(o,r,n)?Npe(o):mx(0);let f=(i.left+a.x)/c.x,p=(i.top+a.y)/c.y,y=i.width/c.x,v=i.height/c.y;if(o){const T=fd(o),E=n&&gf(n)?fd(n):n;let k=T,P=WU(k);for(;P&&n&&E!==k;){const R=y1(P),D=P.getBoundingClientRect(),M=yf(P),B=D.left+(P.clientLeft+parseFloat(M.paddingLeft))*R.x,V=D.top+(P.clientTop+parseFloat(M.paddingTop))*R.y;f*=R.x,p*=R.y,y*=R.x,v*=R.y,f+=B,p+=V,k=fd(P),P=WU(k)}}return DD({width:y,height:v,x:f,y:p})}function yFe(t){let{elements:e,rect:r,offsetParent:n,strategy:i}=t;const o=i==="fixed",c=Nm(n),a=e?o3(e.floating):!1;if(n===c||a&&o)return r;let f={scrollLeft:0,scrollTop:0},p=mx(1);const y=mx(0),v=wm(n);if((v||!v&&!o)&&((iT(n)!=="body"||NC(c))&&(f=l3(n)),wm(n))){const T=n_(n);p=y1(n),y.x=T.x+n.clientLeft,y.y=T.y+n.clientTop}return{width:r.width*p.x,height:r.height*p.y,x:r.x*p.x-f.scrollLeft*p.x+y.x,y:r.y*p.y-f.scrollTop*p.y+y.y}}function xFe(t){return Array.from(t.getClientRects())}function KU(t,e){const r=l3(t).scrollLeft;return e?e.left+r:n_(Nm(t)).left+r}function vFe(t){const e=Nm(t),r=l3(t),n=t.ownerDocument.body,i=ad(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),o=ad(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let c=-r.scrollLeft+KU(t);const a=-r.scrollTop;return yf(n).direction==="rtl"&&(c+=ad(e.clientWidth,n.clientWidth)-i),{width:i,height:o,x:c,y:a}}function _Fe(t,e){const r=fd(t),n=Nm(t),i=r.visualViewport;let o=n.clientWidth,c=n.clientHeight,a=0,f=0;if(i){o=i.width,c=i.height;const p=Y9();(!p||p&&e==="fixed")&&(a=i.offsetLeft,f=i.offsetTop)}return{width:o,height:c,x:a,y:f}}function bFe(t,e){const r=n_(t,!0,e==="fixed"),n=r.top+t.clientTop,i=r.left+t.clientLeft,o=wm(t)?y1(t):mx(1),c=t.clientWidth*o.x,a=t.clientHeight*o.y,f=i*o.x,p=n*o.y;return{width:c,height:a,x:f,y:p}}function cte(t,e,r){let n;if(e==="viewport")n=_Fe(t,r);else if(e==="document")n=vFe(Nm(t));else if(gf(e))n=bFe(e,r);else{const i=Npe(t);n={...e,x:e.x-i.x,y:e.y-i.y}}return DD(n)}function Ipe(t,e){const r=gx(t);return r===e||!gf(r)||tS(r)?!1:yf(r).position==="fixed"||Ipe(r,e)}function wFe(t,e){const r=e.get(t);if(r)return r;let n=XA(t,[],!1).filter(a=>gf(a)&&iT(a)!=="body"),i=null;const o=yf(t).position==="fixed";let c=o?gx(t):t;for(;gf(c)&&!tS(c);){const a=yf(c),f=K9(c);!f&&a.position==="fixed"&&(i=null),(o?!f&&!i:!f&&a.position==="static"&&!!i&&["absolute","fixed"].includes(i.position)||NC(c)&&!f&&Ipe(t,c))?n=n.filter(y=>y!==c):i=a,c=gx(c)}return e.set(t,n),n}function SFe(t){let{element:e,boundary:r,rootBoundary:n,strategy:i}=t;const c=[...r==="clippingAncestors"?o3(e)?[]:wFe(e,this._c):[].concat(r),n],a=c[0],f=c.reduce((p,y)=>{const v=cte(e,y,i);return p.top=ad(v.top,p.top),p.right=fx(v.right,p.right),p.bottom=fx(v.bottom,p.bottom),p.left=ad(v.left,p.left),p},cte(e,a,i));return{width:f.right-f.left,height:f.bottom-f.top,x:f.left,y:f.top}}function TFe(t){const{width:e,height:r}=Cpe(t);return{width:e,height:r}}function EFe(t,e,r){const n=wm(e),i=Nm(e),o=r==="fixed",c=n_(t,!0,o,e);let a={scrollLeft:0,scrollTop:0};const f=mx(0);if(n||!n&&!o)if((iT(e)!=="body"||NC(i))&&(a=l3(e)),n){const E=n_(e,!0,o,e);f.x=E.x+e.clientLeft,f.y=E.y+e.clientTop}else i&&(f.x=KU(i));let p=0,y=0;if(i&&!n&&!o){const E=i.getBoundingClientRect();y=E.top+a.scrollTop,p=E.left+a.scrollLeft-KU(i,E)}const v=c.left+a.scrollLeft-f.x-p,T=c.top+a.scrollTop-f.y-y;return{x:v,y:T,width:c.width,height:c.height}}function w$(t){return yf(t).position==="static"}function ute(t,e){if(!wm(t)||yf(t).position==="fixed")return null;if(e)return e(t);let r=t.offsetParent;return Nm(t)===r&&(r=r.ownerDocument.body),r}function Ppe(t,e){const r=fd(t);if(o3(t))return r;if(!wm(t)){let i=gx(t);for(;i&&!tS(i);){if(gf(i)&&!w$(i))return i;i=gx(i)}return r}let n=ute(t,e);for(;n&&fFe(n)&&w$(n);)n=ute(n,e);return n&&tS(n)&&w$(n)&&!K9(n)?r:n||mFe(t)||r}const jFe=async function(t){const e=this.getOffsetParent||Ppe,r=this.getDimensions,n=await r(t.floating);return{reference:EFe(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function AFe(t){return yf(t).direction==="rtl"}const kFe={convertOffsetParentRelativeRectToViewportRelativeRect:yFe,getDocumentElement:Nm,getClippingRect:SFe,getOffsetParent:Ppe,getElementRects:jFe,getClientRects:xFe,getDimensions:TFe,getScale:y1,isElement:gf,isRTL:AFe};function CFe(t,e){let r=null,n;const i=Nm(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:p,top:y,width:v,height:T}=t.getBoundingClientRect();if(a||e(),!v||!T)return;const E=iR(y),k=iR(i.clientWidth-(p+v)),P=iR(i.clientHeight-(y+T)),R=iR(p),M={rootMargin:-E+"px "+-k+"px "+-P+"px "+-R+"px",threshold:ad(0,fx(1,f))||1};let B=!0;function V(G){const W=G[0].intersectionRatio;if(W!==f){if(!B)return c();W?c(!1,W):n=setTimeout(()=>{c(!1,1e-7)},1e3)}B=!1}try{r=new IntersectionObserver(V,{...M,root:i.ownerDocument})}catch{r=new IntersectionObserver(V,M)}r.observe(t)}return c(!0),o}function NFe(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,p=Z9(t),y=i||o?[...p?XA(p):[],...XA(e)]:[];y.forEach(D=>{i&&D.addEventListener("scroll",r,{passive:!0}),o&&D.addEventListener("resize",r)});const v=p&&a?CFe(p,r):null;let T=-1,E=null;c&&(E=new ResizeObserver(D=>{let[M]=D;M&&M.target===p&&E&&(E.unobserve(e),cancelAnimationFrame(T),T=requestAnimationFrame(()=>{var B;(B=E)==null||B.observe(e)})),r()}),p&&!f&&E.observe(p),E.observe(e));let k,P=f?n_(t):null;f&&R();function R(){const D=n_(t);P&&(D.x!==P.x||D.y!==P.y||D.width!==P.width||D.height!==P.height)&&r(),P=D,k=requestAnimationFrame(R)}return r(),()=>{var D;y.forEach(M=>{i&&M.removeEventListener("scroll",r),o&&M.removeEventListener("resize",r)}),v==null||v(),(D=E)==null||D.disconnect(),E=null,f&&cancelAnimationFrame(k)}}const IFe=cFe,PFe=uFe,RFe=aFe,LFe=hFe,DFe=oFe,dte=sFe,MFe=dFe,OFe=(t,e,r)=>{const n=new Map,i={platform:kFe,...r},o={...i.platform,_c:n};return iFe(t,e,{...i,platform:o})};var EL=typeof document<"u"?C.useLayoutEffect:C.useEffect;function MD(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(!MD(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)&&!MD(t[o],e[o]))return!1}return!0}return t!==t&&e!==e}function Rpe(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function hte(t,e){const r=Rpe(t);return Math.round(e*r)/r}function S$(t){const e=C.useRef(t);return EL(()=>{e.current=t}),e}function FFe(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:p}=t,[y,v]=C.useState({x:0,y:0,strategy:r,placement:e,middlewareData:{},isPositioned:!1}),[T,E]=C.useState(n);MD(T,n)||E(n);const[k,P]=C.useState(null),[R,D]=C.useState(null),M=C.useCallback(me=>{me!==W.current&&(W.current=me,P(me))},[]),B=C.useCallback(me=>{me!==Y.current&&(Y.current=me,D(me))},[]),V=o||k,G=c||R,W=C.useRef(null),Y=C.useRef(null),J=C.useRef(y),Q=f!=null,ee=S$(f),le=S$(i),pe=S$(p),Se=C.useCallback(()=>{if(!W.current||!Y.current)return;const me={placement:e,strategy:r,middleware:T};le.current&&(me.platform=le.current),OFe(W.current,Y.current,me).then(Te=>{const Ne={...Te,isPositioned:pe.current!==!1};je.current&&!MD(J.current,Ne)&&(J.current=Ne,dg.flushSync(()=>{v(Ne)}))})},[T,e,r,le,pe]);EL(()=>{p===!1&&J.current.isPositioned&&(J.current.isPositioned=!1,v(me=>({...me,isPositioned:!1})))},[p]);const je=C.useRef(!1);EL(()=>(je.current=!0,()=>{je.current=!1}),[]),EL(()=>{if(V&&(W.current=V),G&&(Y.current=G),V&&G){if(ee.current)return ee.current(V,G,Se);Se()}},[V,G,Se,ee,Q]);const Le=C.useMemo(()=>({reference:W,floating:Y,setReference:M,setFloating:B}),[M,B]),Ae=C.useMemo(()=>({reference:V,floating:G}),[V,G]),be=C.useMemo(()=>{const me={position:r,left:0,top:0};if(!Ae.floating)return me;const Te=hte(Ae.floating,y.x),Ne=hte(Ae.floating,y.y);return a?{...me,transform:"translate("+Te+"px, "+Ne+"px)",...Rpe(Ae.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:Te,top:Ne}},[r,a,Ae.floating,y.x,y.y]);return C.useMemo(()=>({...y,update:Se,refs:Le,elements:Ae,floatingStyles:be}),[y,Se,Le,Ae,be])}const BFe=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?dte({element:n.current,padding:i}).fn(r):{}:n?dte({element:n,padding:i}).fn(r):{}}}},$Fe=(t,e)=>({...IFe(t),options:[t,e]}),zFe=(t,e)=>({...PFe(t),options:[t,e]}),UFe=(t,e)=>({...MFe(t),options:[t,e]}),VFe=(t,e)=>({...RFe(t),options:[t,e]}),qFe=(t,e)=>({...LFe(t),options:[t,e]}),GFe=(t,e)=>({...DFe(t),options:[t,e]}),HFe=(t,e)=>({...BFe(t),options:[t,e]});var WFe="Arrow",Lpe=C.forwardRef((t,e)=>{const{children:r,width:n=10,height:i=5,...o}=t;return s.jsx(nn.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"})})});Lpe.displayName=WFe;var KFe=Lpe;function IC(t){const[e,r]=C.useState(void 0);return Do(()=>{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,p=Array.isArray(f)?f[0]:f;c=p.inlineSize,a=p.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 X9="Popper",[Dpe,Ix]=Qo(X9),[YFe,Mpe]=Dpe(X9),Ope=t=>{const{__scopePopper:e,children:r}=t,[n,i]=C.useState(null);return s.jsx(YFe,{scope:e,anchor:n,onAnchorChange:i,children:r})};Ope.displayName=X9;var Fpe="PopperAnchor",Bpe=C.forwardRef((t,e)=>{const{__scopePopper:r,virtualRef:n,...i}=t,o=Mpe(Fpe,r),c=C.useRef(null),a=Yn(e,c);return C.useEffect(()=>{o.onAnchorChange((n==null?void 0:n.current)||c.current)}),n?null:s.jsx(nn.div,{...i,ref:a})});Bpe.displayName=Fpe;var Q9="PopperContent",[ZFe,XFe]=Dpe(Q9),$pe=C.forwardRef((t,e)=>{var vt,Gt,pt,Pt,tr,_t;const{__scopePopper:r,side:n="bottom",sideOffset:i=0,align:o="center",alignOffset:c=0,arrowPadding:a=0,avoidCollisions:f=!0,collisionBoundary:p=[],collisionPadding:y=0,sticky:v="partial",hideWhenDetached:T=!1,updatePositionStrategy:E="optimized",onPlaced:k,...P}=t,R=Mpe(Q9,r),[D,M]=C.useState(null),B=Yn(e,cr=>M(cr)),[V,G]=C.useState(null),W=IC(V),Y=(W==null?void 0:W.width)??0,J=(W==null?void 0:W.height)??0,Q=n+(o!=="center"?"-"+o:""),ee=typeof y=="number"?y:{top:0,right:0,bottom:0,left:0,...y},le=Array.isArray(p)?p:[p],pe=le.length>0,Se={padding:ee,boundary:le.filter(JFe),altBoundary:pe},{refs:je,floatingStyles:Le,placement:Ae,isPositioned:be,middlewareData:me}=FFe({strategy:"fixed",placement:Q,whileElementsMounted:(...cr)=>NFe(...cr,{animationFrame:E==="always"}),elements:{reference:R.anchor},middleware:[$Fe({mainAxis:i+J,alignmentAxis:c}),f&&zFe({mainAxis:!0,crossAxis:!1,limiter:v==="partial"?UFe():void 0,...Se}),f&&VFe({...Se}),qFe({...Se,apply:({elements:cr,rects:Tr,availableWidth:sn,availableHeight:ur})=>{const{width:xr,height:rr}=Tr.reference,vn=cr.floating.style;vn.setProperty("--radix-popper-available-width",`${sn}px`),vn.setProperty("--radix-popper-available-height",`${ur}px`),vn.setProperty("--radix-popper-anchor-width",`${xr}px`),vn.setProperty("--radix-popper-anchor-height",`${rr}px`)}}),V&&HFe({element:V,padding:a}),e5e({arrowWidth:Y,arrowHeight:J}),T&&GFe({strategy:"referenceHidden",...Se})]}),[Te,Ne]=Vpe(Ae),Ee=vo(k);Do(()=>{be&&(Ee==null||Ee())},[be,Ee]);const we=(vt=me.arrow)==null?void 0:vt.x,He=(Gt=me.arrow)==null?void 0:Gt.y,tt=((pt=me.arrow)==null?void 0:pt.centerOffset)!==0,[at,Et]=C.useState();return Do(()=>{D&&Et(window.getComputedStyle(D).zIndex)},[D]),s.jsx("div",{ref:je.setFloating,"data-radix-popper-content-wrapper":"",style:{...Le,transform:be?Le.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:at,"--radix-popper-transform-origin":[(Pt=me.transformOrigin)==null?void 0:Pt.x,(tr=me.transformOrigin)==null?void 0:tr.y].join(" "),...((_t=me.hide)==null?void 0:_t.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:s.jsx(ZFe,{scope:r,placedSide:Te,onArrowChange:G,arrowX:we,arrowY:He,shouldHideArrow:tt,children:s.jsx(nn.div,{"data-side":Te,"data-align":Ne,...P,ref:B,style:{...P.style,animation:be?void 0:"none"}})})})});$pe.displayName=Q9;var zpe="PopperArrow",QFe={top:"bottom",right:"left",bottom:"top",left:"right"},Upe=C.forwardRef(function(e,r){const{__scopePopper:n,...i}=e,o=XFe(zpe,n),c=QFe[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(KFe,{...i,ref:r,style:{...i.style,display:"block"}})})});Upe.displayName=zpe;function JFe(t){return t!==null}var e5e=t=>({name:"transformOrigin",options:t,fn(e){var R,D,M;const{placement:r,rects:n,middlewareData:i}=e,c=((R=i.arrow)==null?void 0:R.centerOffset)!==0,a=c?0:t.arrowWidth,f=c?0:t.arrowHeight,[p,y]=Vpe(r),v={start:"0%",center:"50%",end:"100%"}[y],T=(((D=i.arrow)==null?void 0:D.x)??0)+a/2,E=(((M=i.arrow)==null?void 0:M.y)??0)+f/2;let k="",P="";return p==="bottom"?(k=c?v:`${T}px`,P=`${-f}px`):p==="top"?(k=c?v:`${T}px`,P=`${n.floating.height+f}px`):p==="right"?(k=`${-f}px`,P=c?v:`${E}px`):p==="left"&&(k=`${n.floating.width+f}px`,P=c?v:`${E}px`),{data:{x:k,y:P}}}});function Vpe(t){const[e,r="center"]=t.split("-");return[e,r]}var c3=Ope,PC=Bpe,u3=$pe,d3=Upe,[h3,cqt]=Qo("Tooltip",[Ix]),f3=Ix(),qpe="TooltipProvider",t5e=700,YU="tooltip.open",[r5e,J9]=h3(qpe),Gpe=t=>{const{__scopeTooltip:e,delayDuration:r=t5e,skipDelayDuration:n=300,disableHoverableContent:i=!1,children:o}=t,c=C.useRef(!0),a=C.useRef(!1),f=C.useRef(0);return C.useEffect(()=>{const p=f.current;return()=>window.clearTimeout(p)},[]),s.jsx(r5e,{scope:e,isOpenDelayedRef:c,delayDuration:r,onOpen:C.useCallback(()=>{window.clearTimeout(f.current),c.current=!1},[]),onClose:C.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>c.current=!0,n)},[n]),isPointerInTransitRef:a,onPointerInTransitChange:C.useCallback(p=>{a.current=p},[]),disableHoverableContent:i,children:o})};Gpe.displayName=qpe;var QA="Tooltip",[n5e,m3]=h3(QA),Hpe=t=>{const{__scopeTooltip:e,children:r,open:n,defaultOpen:i,onOpenChange:o,disableHoverableContent:c,delayDuration:a}=t,f=J9(QA,t.__scopeTooltip),p=f3(e),[y,v]=C.useState(null),T=Fl(),E=C.useRef(0),k=c??f.disableHoverableContent,P=a??f.delayDuration,R=C.useRef(!1),[D,M]=yd({prop:n,defaultProp:i??!1,onChange:Y=>{Y?(f.onOpen(),document.dispatchEvent(new CustomEvent(YU))):f.onClose(),o==null||o(Y)},caller:QA}),B=C.useMemo(()=>D?R.current?"delayed-open":"instant-open":"closed",[D]),V=C.useCallback(()=>{window.clearTimeout(E.current),E.current=0,R.current=!1,M(!0)},[M]),G=C.useCallback(()=>{window.clearTimeout(E.current),E.current=0,M(!1)},[M]),W=C.useCallback(()=>{window.clearTimeout(E.current),E.current=window.setTimeout(()=>{R.current=!0,M(!0),E.current=0},P)},[P,M]);return C.useEffect(()=>()=>{E.current&&(window.clearTimeout(E.current),E.current=0)},[]),s.jsx(c3,{...p,children:s.jsx(n5e,{scope:e,contentId:T,open:D,stateAttribute:B,trigger:y,onTriggerChange:v,onTriggerEnter:C.useCallback(()=>{f.isOpenDelayedRef.current?W():V()},[f.isOpenDelayedRef,W,V]),onTriggerLeave:C.useCallback(()=>{k?G():(window.clearTimeout(E.current),E.current=0)},[G,k]),onOpen:V,onClose:G,disableHoverableContent:k,children:r})})};Hpe.displayName=QA;var ZU="TooltipTrigger",Wpe=C.forwardRef((t,e)=>{const{__scopeTooltip:r,...n}=t,i=m3(ZU,r),o=J9(ZU,r),c=f3(r),a=C.useRef(null),f=Yn(e,a,i.onTriggerChange),p=C.useRef(!1),y=C.useRef(!1),v=C.useCallback(()=>p.current=!1,[]);return C.useEffect(()=>()=>document.removeEventListener("pointerup",v),[v]),s.jsx(PC,{asChild:!0,...c,children:s.jsx(nn.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...n,ref:f,onPointerMove:Or(t.onPointerMove,T=>{T.pointerType!=="touch"&&!y.current&&!o.isPointerInTransitRef.current&&(i.onTriggerEnter(),y.current=!0)}),onPointerLeave:Or(t.onPointerLeave,()=>{i.onTriggerLeave(),y.current=!1}),onPointerDown:Or(t.onPointerDown,()=>{i.open&&i.onClose(),p.current=!0,document.addEventListener("pointerup",v,{once:!0})}),onFocus:Or(t.onFocus,()=>{p.current||i.onOpen()}),onBlur:Or(t.onBlur,i.onClose),onClick:Or(t.onClick,i.onClose)})})});Wpe.displayName=ZU;var i5e="TooltipPortal",[uqt,s5e]=h3(i5e,{forceMount:void 0}),rS="TooltipContent",Kpe=C.forwardRef((t,e)=>{const r=s5e(rS,t.__scopeTooltip),{forceMount:n=r.forceMount,side:i="top",...o}=t,c=m3(rS,t.__scopeTooltip);return s.jsx(vl,{present:n||c.open,children:c.disableHoverableContent?s.jsx(Ype,{side:i,...o,ref:e}):s.jsx(a5e,{side:i,...o,ref:e})})}),a5e=C.forwardRef((t,e)=>{const r=m3(rS,t.__scopeTooltip),n=J9(rS,t.__scopeTooltip),i=C.useRef(null),o=Yn(e,i),[c,a]=C.useState(null),{trigger:f,onClose:p}=r,y=i.current,{onPointerInTransitChange:v}=n,T=C.useCallback(()=>{a(null),v(!1)},[v]),E=C.useCallback((k,P)=>{const R=k.currentTarget,D={x:k.clientX,y:k.clientY},M=d5e(D,R.getBoundingClientRect()),B=h5e(D,M),V=f5e(P.getBoundingClientRect()),G=p5e([...B,...V]);a(G),v(!0)},[v]);return C.useEffect(()=>()=>T(),[T]),C.useEffect(()=>{if(f&&y){const k=R=>E(R,y),P=R=>E(R,f);return f.addEventListener("pointerleave",k),y.addEventListener("pointerleave",P),()=>{f.removeEventListener("pointerleave",k),y.removeEventListener("pointerleave",P)}}},[f,y,E,T]),C.useEffect(()=>{if(c){const k=P=>{const R=P.target,D={x:P.clientX,y:P.clientY},M=(f==null?void 0:f.contains(R))||(y==null?void 0:y.contains(R)),B=!m5e(D,c);M?T():B&&(T(),p())};return document.addEventListener("pointermove",k),()=>document.removeEventListener("pointermove",k)}},[f,y,c,p,T]),s.jsx(Ype,{...t,ref:o})}),[o5e,l5e]=h3(QA,{isInside:!1}),c5e=Mfe("TooltipContent"),Ype=C.forwardRef((t,e)=>{const{__scopeTooltip:r,children:n,"aria-label":i,onEscapeKeyDown:o,onPointerDownOutside:c,...a}=t,f=m3(rS,r),p=f3(r),{onClose:y}=f;return C.useEffect(()=>(document.addEventListener(YU,y),()=>document.removeEventListener(YU,y)),[y]),C.useEffect(()=>{if(f.trigger){const v=T=>{const E=T.target;E!=null&&E.contains(f.trigger)&&y()};return window.addEventListener("scroll",v,{capture:!0}),()=>window.removeEventListener("scroll",v,{capture:!0})}},[f.trigger,y]),s.jsx(v_,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:v=>v.preventDefault(),onDismiss:y,children:s.jsxs(u3,{"data-state":f.stateAttribute,...p,...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(c5e,{children:n}),s.jsx(o5e,{scope:r,isInside:!0,children:s.jsx(tDe,{id:f.contentId,role:"tooltip",children:i||n})})]})})});Kpe.displayName=rS;var Zpe="TooltipArrow",u5e=C.forwardRef((t,e)=>{const{__scopeTooltip:r,...n}=t,i=f3(r);return l5e(Zpe,r).isInside?null:s.jsx(d3,{...i,...n,ref:e})});u5e.displayName=Zpe;function d5e(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 h5e(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 f5e(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 m5e(t,e){const{x:r,y:n}=t;let i=!1;for(let o=0,c=e.length-1;on!=T>n&&r<(v-p)*(n-y)/(T-y)+p&&(i=!i)}return i}function p5e(t){const e=t.slice();return e.sort((r,n)=>r.xn.x?1:r.yn.y?1:0),g5e(e)}function g5e(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 y5e=Gpe,x5e=Hpe,v5e=Wpe,Xpe=Kpe;const Qpe=y5e,_5e=x5e,b5e=v5e,Jpe=C.forwardRef(({className:t,sideOffset:e=4,...r},n)=>s.jsx(Xpe,{ref:n,sideOffset:e,className:qt("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}));Jpe.displayName=Xpe.displayName;var sT=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(){}},i_=typeof window>"u"||"Deno"in globalThis;function Kc(){}function w5e(t,e){return typeof t=="function"?t(e):t}function XU(t){return typeof t=="number"&&t>=0&&t!==1/0}function ege(t,e){return Math.max(t+(e||0)-Date.now(),0)}function tx(t,e){return typeof t=="function"?t(e):t}function Qd(t,e){return typeof t=="function"?t(e):t}function fte(t,e){const{type:r="all",exact:n,fetchStatus:i,predicate:o,queryKey:c,stale:a}=t;if(c){if(n){if(e.queryHash!==e7(c,e.options))return!1}else if(!JA(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 mte(t,e){const{exact:r,status:n,predicate:i,mutationKey:o}=t;if(o){if(!e.options.mutationKey)return!1;if(r){if(s_(e.options.mutationKey)!==s_(o))return!1}else if(!JA(e.options.mutationKey,o))return!1}return!(n&&e.state.status!==n||i&&!i(e))}function e7(t,e){return((e==null?void 0:e.queryKeyHashFn)||s_)(t)}function s_(t){return JSON.stringify(t,(e,r)=>QU(r)?Object.keys(r).sort().reduce((n,i)=>(n[i]=r[i],n),{}):r)}function JA(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(r=>JA(t[r],e[r])):!1}function tge(t,e){if(t===e)return t;const r=pte(t)&&pte(e);if(r||QU(t)&&QU(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 p=0;for(let y=0;y{setTimeout(e,t)})}function JU(t,e,r){return typeof r.structuralSharing=="function"?r.structuralSharing(t,e):r.structuralSharing!==!1?tge(t,e):e}function T5e(t,e,r=0){const n=[...t,e];return r&&n.length>r?n.slice(1):n}function E5e(t,e,r=0){const n=[e,...t];return r&&n.length>r?n.slice(0,-1):n}var t7=Symbol();function rge(t,e){return!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===t7?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function nge(t,e){return typeof t=="function"?t(...e):!!t}var Pv,Py,R1,ode,j5e=(ode=class extends sT{constructor(){super();Qn(this,Pv);Qn(this,Py);Qn(this,R1);_n(this,R1,e=>{if(!i_&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){Tt(this,Py)||this.setEventListener(Tt(this,R1))}onUnsubscribe(){var e;this.hasListeners()||((e=Tt(this,Py))==null||e.call(this),_n(this,Py,void 0))}setEventListener(e){var r;_n(this,R1,e),(r=Tt(this,Py))==null||r.call(this),_n(this,Py,e(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()}))}setFocused(e){Tt(this,Pv)!==e&&(_n(this,Pv,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){var e;return typeof Tt(this,Pv)=="boolean"?Tt(this,Pv):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},Pv=new WeakMap,Py=new WeakMap,R1=new WeakMap,ode),r7=new j5e,L1,Ry,D1,lde,A5e=(lde=class extends sT{constructor(){super();Qn(this,L1,!0);Qn(this,Ry);Qn(this,D1);_n(this,D1,e=>{if(!i_&&window.addEventListener){const r=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",n)}}})}onSubscribe(){Tt(this,Ry)||this.setEventListener(Tt(this,D1))}onUnsubscribe(){var e;this.hasListeners()||((e=Tt(this,Ry))==null||e.call(this),_n(this,Ry,void 0))}setEventListener(e){var r;_n(this,D1,e),(r=Tt(this,Ry))==null||r.call(this),_n(this,Ry,e(this.setOnline.bind(this)))}setOnline(e){Tt(this,L1)!==e&&(_n(this,L1,e),this.listeners.forEach(n=>{n(e)}))}isOnline(){return Tt(this,L1)}},L1=new WeakMap,Ry=new WeakMap,D1=new WeakMap,lde),FD=new A5e;function eV(){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 k5e(t){return Math.min(1e3*2**t,3e4)}function ige(t){return(t??"online")==="online"?FD.isOnline():!0}var sge=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function T$(t){return t instanceof sge}function age(t){let e=!1,r=0,n=!1,i;const o=eV(),c=P=>{var R;n||(T(new sge(P)),(R=t.abort)==null||R.call(t))},a=()=>{e=!0},f=()=>{e=!1},p=()=>r7.isFocused()&&(t.networkMode==="always"||FD.isOnline())&&t.canRun(),y=()=>ige(t.networkMode)&&t.canRun(),v=P=>{var R;n||(n=!0,(R=t.onSuccess)==null||R.call(t,P),i==null||i(),o.resolve(P))},T=P=>{var R;n||(n=!0,(R=t.onError)==null||R.call(t,P),i==null||i(),o.reject(P))},E=()=>new Promise(P=>{var R;i=D=>{(n||p())&&P(D)},(R=t.onPause)==null||R.call(t)}).then(()=>{var P;i=void 0,n||(P=t.onContinue)==null||P.call(t)}),k=()=>{if(n)return;let P;const R=r===0?t.initialPromise:void 0;try{P=R??t.fn()}catch(D){P=Promise.reject(D)}Promise.resolve(P).then(v).catch(D=>{var W;if(n)return;const M=t.retry??(i_?0:3),B=t.retryDelay??k5e,V=typeof B=="function"?B(r,D):B,G=M===!0||typeof M=="number"&&rp()?void 0:E()).then(()=>{e?T(D):k()})})};return{promise:o,cancel:c,continue:()=>(i==null||i(),o),cancelRetry:a,continueRetry:f,canStart:y,start:()=>(y()?k():E().then(k),o)}}var C5e=t=>setTimeout(t,0);function N5e(){let t=[],e=0,r=a=>{a()},n=a=>{a()},i=C5e;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 hl=N5e(),Rv,cde,oge=(cde=class{constructor(){Qn(this,Rv)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),XU(this.gcTime)&&_n(this,Rv,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(i_?1/0:5*60*1e3))}clearGcTimeout(){Tt(this,Rv)&&(clearTimeout(Tt(this,Rv)),_n(this,Rv,void 0))}},Rv=new WeakMap,cde),M1,Lv,Xd,Dv,_c,uC,Mv,Kh,wp,ude,I5e=(ude=class extends oge{constructor(e){super();Qn(this,Kh);Qn(this,M1);Qn(this,Lv);Qn(this,Xd);Qn(this,Dv);Qn(this,_c);Qn(this,uC);Qn(this,Mv);_n(this,Mv,!1),_n(this,uC,e.defaultOptions),this.setOptions(e.options),this.observers=[],_n(this,Dv,e.client),_n(this,Xd,Tt(this,Dv).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,_n(this,M1,P5e(this.options)),this.state=e.state??Tt(this,M1),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=Tt(this,_c))==null?void 0:e.promise}setOptions(e){this.options={...Tt(this,uC),...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Tt(this,Xd).remove(this)}setData(e,r){const n=JU(this.state.data,e,this.options);return qi(this,Kh,wp).call(this,{data:n,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),n}setState(e,r){qi(this,Kh,wp).call(this,{type:"setState",state:e,setStateOptions:r})}cancel(e){var n,i;const r=(n=Tt(this,_c))==null?void 0:n.promise;return(i=Tt(this,_c))==null||i.cancel(e),r?r.then(Kc).catch(Kc):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(Tt(this,M1))}isActive(){return this.observers.some(e=>Qd(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===t7||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>tx(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:!ege(this.state.dataUpdatedAt,e)}onFocus(){var r;const e=this.observers.find(n=>n.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(r=Tt(this,_c))==null||r.continue()}onOnline(){var r;const e=this.observers.find(n=>n.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(r=Tt(this,_c))==null||r.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),Tt(this,Xd).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(r=>r!==e),this.observers.length||(Tt(this,_c)&&(Tt(this,Mv)?Tt(this,_c).cancel({revert:!0}):Tt(this,_c).cancelRetry()),this.scheduleGc()),Tt(this,Xd).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||qi(this,Kh,wp).call(this,{type:"invalidate"})}fetch(e,r){var p,y,v;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(Tt(this,_c))return Tt(this,_c).continueRetry(),Tt(this,_c).promise}if(e&&this.setOptions(e),!this.options.queryFn){const T=this.observers.find(E=>E.options.queryFn);T&&this.setOptions(T.options)}const n=new AbortController,i=T=>{Object.defineProperty(T,"signal",{enumerable:!0,get:()=>(_n(this,Mv,!0),n.signal)})},o=()=>{const T=rge(this.options,r),k=(()=>{const P={client:Tt(this,Dv),queryKey:this.queryKey,meta:this.meta};return i(P),P})();return _n(this,Mv,!1),this.options.persister?this.options.persister(T,k,this):T(k)},a=(()=>{const T={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:Tt(this,Dv),state:this.state,fetchFn:o};return i(T),T})();(p=this.options.behavior)==null||p.onFetch(a,this),_n(this,Lv,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((y=a.fetchOptions)==null?void 0:y.meta))&&qi(this,Kh,wp).call(this,{type:"fetch",meta:(v=a.fetchOptions)==null?void 0:v.meta});const f=T=>{var E,k,P,R;T$(T)&&T.silent||qi(this,Kh,wp).call(this,{type:"error",error:T}),T$(T)||((k=(E=Tt(this,Xd).config).onError)==null||k.call(E,T,this),(R=(P=Tt(this,Xd).config).onSettled)==null||R.call(P,this.state.data,T,this)),this.scheduleGc()};return _n(this,_c,age({initialPromise:r==null?void 0:r.initialPromise,fn:a.fetchFn,abort:n.abort.bind(n),onSuccess:T=>{var E,k,P,R;if(T===void 0){f(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(T)}catch(D){f(D);return}(k=(E=Tt(this,Xd).config).onSuccess)==null||k.call(E,T,this),(R=(P=Tt(this,Xd).config).onSettled)==null||R.call(P,T,this.state.error,this),this.scheduleGc()},onError:f,onFail:(T,E)=>{qi(this,Kh,wp).call(this,{type:"failed",failureCount:T,error:E})},onPause:()=>{qi(this,Kh,wp).call(this,{type:"pause"})},onContinue:()=>{qi(this,Kh,wp).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0})),Tt(this,_c).start()}},M1=new WeakMap,Lv=new WeakMap,Xd=new WeakMap,Dv=new WeakMap,_c=new WeakMap,uC=new WeakMap,Mv=new WeakMap,Kh=new WeakSet,wp=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,...lge(n.data,this.options),fetchMeta:e.meta??null};case"success":return _n(this,Lv,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 T$(i)&&i.revert&&Tt(this,Lv)?{...Tt(this,Lv),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),hl.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),Tt(this,Xd).notify({query:this,type:"updated",action:e})})},ude);function lge(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ige(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function P5e(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 Jf,dde,R5e=(dde=class extends sT{constructor(e={}){super();Qn(this,Jf);this.config=e,_n(this,Jf,new Map)}build(e,r,n){const i=r.queryKey,o=r.queryHash??e7(i,r);let c=this.get(o);return c||(c=new I5e({client:e,queryKey:i,queryHash:o,options:e.defaultQueryOptions(r),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(c)),c}add(e){Tt(this,Jf).has(e.queryHash)||(Tt(this,Jf).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const r=Tt(this,Jf).get(e.queryHash);r&&(e.destroy(),r===e&&Tt(this,Jf).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){hl.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return Tt(this,Jf).get(e)}getAll(){return[...Tt(this,Jf).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(n=>fte(r,n))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(n=>fte(e,n)):r}notify(e){hl.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){hl.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){hl.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Jf=new WeakMap,dde),em,Gc,Ov,tm,py,hde,L5e=(hde=class extends oge{constructor(e){super();Qn(this,tm);Qn(this,em);Qn(this,Gc);Qn(this,Ov);this.mutationId=e.mutationId,_n(this,Gc,e.mutationCache),_n(this,em,[]),this.state=e.state||cge(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){Tt(this,em).includes(e)||(Tt(this,em).push(e),this.clearGcTimeout(),Tt(this,Gc).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){_n(this,em,Tt(this,em).filter(r=>r!==e)),this.scheduleGc(),Tt(this,Gc).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){Tt(this,em).length||(this.state.status==="pending"?this.scheduleGc():Tt(this,Gc).remove(this))}continue(){var e;return((e=Tt(this,Ov))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var o,c,a,f,p,y,v,T,E,k,P,R,D,M,B,V,G,W,Y,J;const r=()=>{qi(this,tm,py).call(this,{type:"continue"})};_n(this,Ov,age({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(Q,ee)=>{qi(this,tm,py).call(this,{type:"failed",failureCount:Q,error:ee})},onPause:()=>{qi(this,tm,py).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Tt(this,Gc).canRun(this)}));const n=this.state.status==="pending",i=!Tt(this,Ov).canStart();try{if(n)r();else{qi(this,tm,py).call(this,{type:"pending",variables:e,isPaused:i}),await((c=(o=Tt(this,Gc).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&&qi(this,tm,py).call(this,{type:"pending",context:ee,variables:e,isPaused:i})}const Q=await Tt(this,Ov).start();return await((y=(p=Tt(this,Gc).config).onSuccess)==null?void 0:y.call(p,Q,e,this.state.context,this)),await((T=(v=this.options).onSuccess)==null?void 0:T.call(v,Q,e,this.state.context)),await((k=(E=Tt(this,Gc).config).onSettled)==null?void 0:k.call(E,Q,null,this.state.variables,this.state.context,this)),await((R=(P=this.options).onSettled)==null?void 0:R.call(P,Q,null,e,this.state.context)),qi(this,tm,py).call(this,{type:"success",data:Q}),Q}catch(Q){try{throw await((M=(D=Tt(this,Gc).config).onError)==null?void 0:M.call(D,Q,e,this.state.context,this)),await((V=(B=this.options).onError)==null?void 0:V.call(B,Q,e,this.state.context)),await((W=(G=Tt(this,Gc).config).onSettled)==null?void 0:W.call(G,void 0,Q,this.state.variables,this.state.context,this)),await((J=(Y=this.options).onSettled)==null?void 0:J.call(Y,void 0,Q,e,this.state.context)),Q}finally{qi(this,tm,py).call(this,{type:"error",error:Q})}}finally{Tt(this,Gc).runNext(this)}}},em=new WeakMap,Gc=new WeakMap,Ov=new WeakMap,tm=new WeakSet,py=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),hl.batch(()=>{Tt(this,em).forEach(n=>{n.onMutationUpdate(e)}),Tt(this,Gc).notify({mutation:this,type:"updated",action:e})})},hde);function cge(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Np,Yh,dC,fde,D5e=(fde=class extends sT{constructor(e={}){super();Qn(this,Np);Qn(this,Yh);Qn(this,dC);this.config=e,_n(this,Np,new Set),_n(this,Yh,new Map),_n(this,dC,0)}build(e,r,n){const i=new L5e({mutationCache:this,mutationId:++RP(this,dC)._,options:e.defaultMutationOptions(r),state:n});return this.add(i),i}add(e){Tt(this,Np).add(e);const r=sR(e);if(typeof r=="string"){const n=Tt(this,Yh).get(r);n?n.push(e):Tt(this,Yh).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(Tt(this,Np).delete(e)){const r=sR(e);if(typeof r=="string"){const n=Tt(this,Yh).get(r);if(n)if(n.length>1){const i=n.indexOf(e);i!==-1&&n.splice(i,1)}else n[0]===e&&Tt(this,Yh).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){const r=sR(e);if(typeof r=="string"){const n=Tt(this,Yh).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=sR(e);if(typeof r=="string"){const i=(n=Tt(this,Yh).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(){hl.batch(()=>{Tt(this,Np).forEach(e=>{this.notify({type:"removed",mutation:e})}),Tt(this,Np).clear(),Tt(this,Yh).clear()})}getAll(){return Array.from(Tt(this,Np))}find(e){const r={exact:!0,...e};return this.getAll().find(n=>mte(r,n))}findAll(e={}){return this.getAll().filter(r=>mte(e,r))}notify(e){hl.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return hl.batch(()=>Promise.all(e.map(r=>r.continue().catch(Kc))))}},Np=new WeakMap,Yh=new WeakMap,dC=new WeakMap,fde);function sR(t){var e;return(e=t.options.scope)==null?void 0:e.id}function yte(t){return{onFetch:(e,r)=>{var y,v,T,E,k;const n=e.options,i=(T=(v=(y=e.fetchOptions)==null?void 0:y.meta)==null?void 0:v.fetchMore)==null?void 0:T.direction,o=((E=e.state.data)==null?void 0:E.pages)||[],c=((k=e.state.data)==null?void 0:k.pageParams)||[];let a={pages:[],pageParams:[]},f=0;const p=async()=>{let P=!1;const R=B=>{Object.defineProperty(B,"signal",{enumerable:!0,get:()=>(e.signal.aborted?P=!0:e.signal.addEventListener("abort",()=>{P=!0}),e.signal)})},D=rge(e.options,e.fetchOptions),M=async(B,V,G)=>{if(P)return Promise.reject();if(V==null&&B.pages.length)return Promise.resolve(B);const Y=(()=>{const le={client:e.client,queryKey:e.queryKey,pageParam:V,direction:G?"backward":"forward",meta:e.options.meta};return R(le),le})(),J=await D(Y),{maxPages:Q}=e.options,ee=G?E5e:T5e;return{pages:ee(B.pages,J,Q),pageParams:ee(B.pageParams,V,Q)}};if(i&&o.length){const B=i==="backward",V=B?uge:tV,G={pages:o,pageParams:c},W=V(n,G);a=await M(G,W,B)}else{const B=t??o.length;do{const V=f===0?c[0]??n.initialPageParam:tV(n,a);if(f>0&&V==null)break;a=await M(a,V),f++}while(f{var P,R;return(R=(P=e.options).persister)==null?void 0:R.call(P,p,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r)}:e.fetchFn=p}}}function tV(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 uge(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 dqt(t,e){return e?tV(t,e)!=null:!1}function hqt(t,e){return!e||!t.getPreviousPageParam?!1:uge(t,e)!=null}var go,Ly,Dy,O1,F1,My,B1,$1,mde,M5e=(mde=class{constructor(t={}){Qn(this,go);Qn(this,Ly);Qn(this,Dy);Qn(this,O1);Qn(this,F1);Qn(this,My);Qn(this,B1);Qn(this,$1);_n(this,go,t.queryCache||new R5e),_n(this,Ly,t.mutationCache||new D5e),_n(this,Dy,t.defaultOptions||{}),_n(this,O1,new Map),_n(this,F1,new Map),_n(this,My,0)}mount(){RP(this,My)._++,Tt(this,My)===1&&(_n(this,B1,r7.subscribe(async t=>{t&&(await this.resumePausedMutations(),Tt(this,go).onFocus())})),_n(this,$1,FD.subscribe(async t=>{t&&(await this.resumePausedMutations(),Tt(this,go).onOnline())})))}unmount(){var t,e;RP(this,My)._--,Tt(this,My)===0&&((t=Tt(this,B1))==null||t.call(this),_n(this,B1,void 0),(e=Tt(this,$1))==null||e.call(this),_n(this,$1,void 0))}isFetching(t){return Tt(this,go).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return Tt(this,Ly).findAll({...t,status:"pending"}).length}getQueryData(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=Tt(this,go).get(e.queryHash))==null?void 0:r.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=Tt(this,go).build(this,e),n=r.state.data;return n===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(tx(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(n))}getQueriesData(t){return Tt(this,go).findAll(t).map(({queryKey:e,state:r})=>{const n=r.data;return[e,n]})}setQueryData(t,e,r){const n=this.defaultQueryOptions({queryKey:t}),i=Tt(this,go).get(n.queryHash),o=i==null?void 0:i.state.data,c=w5e(e,o);if(c!==void 0)return Tt(this,go).build(this,n).setData(c,{...r,manual:!0})}setQueriesData(t,e,r){return hl.batch(()=>Tt(this,go).findAll(t).map(({queryKey:n})=>[n,this.setQueryData(n,e,r)]))}getQueryState(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=Tt(this,go).get(e.queryHash))==null?void 0:r.state}removeQueries(t){const e=Tt(this,go);hl.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=Tt(this,go);return hl.batch(()=>(r.findAll(t).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const r={revert:!0,...e},n=hl.batch(()=>Tt(this,go).findAll(t).map(i=>i.cancel(r)));return Promise.all(n).then(Kc).catch(Kc)}invalidateQueries(t,e={}){return hl.batch(()=>(Tt(this,go).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=hl.batch(()=>Tt(this,go).findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let o=i.fetch(void 0,r);return r.throwOnError||(o=o.catch(Kc)),i.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(n).then(Kc)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=Tt(this,go).build(this,e);return r.isStaleByTime(tx(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(Kc).catch(Kc)}fetchInfiniteQuery(t){return t.behavior=yte(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(Kc).catch(Kc)}ensureInfiniteQueryData(t){return t.behavior=yte(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return FD.isOnline()?Tt(this,Ly).resumePausedMutations():Promise.resolve()}getQueryCache(){return Tt(this,go)}getMutationCache(){return Tt(this,Ly)}getDefaultOptions(){return Tt(this,Dy)}setDefaultOptions(t){_n(this,Dy,t)}setQueryDefaults(t,e){Tt(this,O1).set(s_(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...Tt(this,O1).values()],r={};return e.forEach(n=>{JA(t,n.queryKey)&&Object.assign(r,n.defaultOptions)}),r}setMutationDefaults(t,e){Tt(this,F1).set(s_(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...Tt(this,F1).values()],r={};return e.forEach(n=>{JA(t,n.mutationKey)&&Object.assign(r,n.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={...Tt(this,Dy).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=e7(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===t7&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...Tt(this,Dy).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){Tt(this,go).clear(),Tt(this,Ly).clear()}},go=new WeakMap,Ly=new WeakMap,Dy=new WeakMap,O1=new WeakMap,F1=new WeakMap,My=new WeakMap,B1=new WeakMap,$1=new WeakMap,mde),Tu,is,hC,Hc,Fv,z1,Oy,Fy,fC,U1,V1,Bv,$v,By,q1,Ms,B2,rV,nV,iV,sV,aV,oV,lV,dge,pde,O5e=(pde=class extends sT{constructor(e,r){super();Qn(this,Ms);Qn(this,Tu);Qn(this,is);Qn(this,hC);Qn(this,Hc);Qn(this,Fv);Qn(this,z1);Qn(this,Oy);Qn(this,Fy);Qn(this,fC);Qn(this,U1);Qn(this,V1);Qn(this,Bv);Qn(this,$v);Qn(this,By);Qn(this,q1,new Set);this.options=r,_n(this,Tu,e),_n(this,Fy,null),_n(this,Oy,eV()),this.options.experimental_prefetchInRender||Tt(this,Oy).reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Tt(this,is).addObserver(this),xte(Tt(this,is),this.options)?qi(this,Ms,B2).call(this):this.updateResult(),qi(this,Ms,sV).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return cV(Tt(this,is),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return cV(Tt(this,is),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,qi(this,Ms,aV).call(this),qi(this,Ms,oV).call(this),Tt(this,is).removeObserver(this)}setOptions(e){const r=this.options,n=Tt(this,is);if(this.options=Tt(this,Tu).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Qd(this.options.enabled,Tt(this,is))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");qi(this,Ms,lV).call(this),Tt(this,is).setOptions(this.options),r._defaulted&&!OD(this.options,r)&&Tt(this,Tu).getQueryCache().notify({type:"observerOptionsUpdated",query:Tt(this,is),observer:this});const i=this.hasListeners();i&&vte(Tt(this,is),n,this.options,r)&&qi(this,Ms,B2).call(this),this.updateResult(),i&&(Tt(this,is)!==n||Qd(this.options.enabled,Tt(this,is))!==Qd(r.enabled,Tt(this,is))||tx(this.options.staleTime,Tt(this,is))!==tx(r.staleTime,Tt(this,is)))&&qi(this,Ms,rV).call(this);const o=qi(this,Ms,nV).call(this);i&&(Tt(this,is)!==n||Qd(this.options.enabled,Tt(this,is))!==Qd(r.enabled,Tt(this,is))||o!==Tt(this,By))&&qi(this,Ms,iV).call(this,o)}getOptimisticResult(e){const r=Tt(this,Tu).getQueryCache().build(Tt(this,Tu),e),n=this.createResult(r,e);return B5e(this,n)&&(_n(this,Hc,n),_n(this,z1,this.options),_n(this,Fv,Tt(this,is).state)),n}getCurrentResult(){return Tt(this,Hc)}trackResult(e,r){return new Proxy(e,{get:(n,i)=>(this.trackProp(i),r==null||r(i),Reflect.get(n,i))})}trackProp(e){Tt(this,q1).add(e)}getCurrentQuery(){return Tt(this,is)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const r=Tt(this,Tu).defaultQueryOptions(e),n=Tt(this,Tu).getQueryCache().build(Tt(this,Tu),r);return n.fetch().then(()=>this.createResult(n,r))}fetch(e){return qi(this,Ms,B2).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),Tt(this,Hc)))}createResult(e,r){var Q;const n=Tt(this,is),i=this.options,o=Tt(this,Hc),c=Tt(this,Fv),a=Tt(this,z1),p=e!==n?e.state:Tt(this,hC),{state:y}=e;let v={...y},T=!1,E;if(r._optimisticResults){const ee=this.hasListeners(),le=!ee&&xte(e,r),pe=ee&&vte(e,n,r,i);(le||pe)&&(v={...v,...lge(y.data,e.options)}),r._optimisticResults==="isRestoring"&&(v.fetchStatus="idle")}let{error:k,errorUpdatedAt:P,status:R}=v;E=v.data;let D=!1;if(r.placeholderData!==void 0&&E===void 0&&R==="pending"){let ee;o!=null&&o.isPlaceholderData&&r.placeholderData===(a==null?void 0:a.placeholderData)?(ee=o.data,D=!0):ee=typeof r.placeholderData=="function"?r.placeholderData((Q=Tt(this,V1))==null?void 0:Q.state.data,Tt(this,V1)):r.placeholderData,ee!==void 0&&(R="success",E=JU(o==null?void 0:o.data,ee,r),T=!0)}if(r.select&&E!==void 0&&!D)if(o&&E===(c==null?void 0:c.data)&&r.select===Tt(this,fC))E=Tt(this,U1);else try{_n(this,fC,r.select),E=r.select(E),E=JU(o==null?void 0:o.data,E,r),_n(this,U1,E),_n(this,Fy,null)}catch(ee){_n(this,Fy,ee)}Tt(this,Fy)&&(k=Tt(this,Fy),E=Tt(this,U1),P=Date.now(),R="error");const M=v.fetchStatus==="fetching",B=R==="pending",V=R==="error",G=B&&M,W=E!==void 0,J={status:R,fetchStatus:v.fetchStatus,isPending:B,isSuccess:R==="success",isError:V,isInitialLoading:G,isLoading:G,data:E,dataUpdatedAt:v.dataUpdatedAt,error:k,errorUpdatedAt:P,failureCount:v.fetchFailureCount,failureReason:v.fetchFailureReason,errorUpdateCount:v.errorUpdateCount,isFetched:v.dataUpdateCount>0||v.errorUpdateCount>0,isFetchedAfterMount:v.dataUpdateCount>p.dataUpdateCount||v.errorUpdateCount>p.errorUpdateCount,isFetching:M,isRefetching:M&&!B,isLoadingError:V&&!W,isPaused:v.fetchStatus==="paused",isPlaceholderData:T,isRefetchError:V&&W,isStale:n7(e,r),refetch:this.refetch,promise:Tt(this,Oy),isEnabled:Qd(r.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const ee=Se=>{J.status==="error"?Se.reject(J.error):J.data!==void 0&&Se.resolve(J.data)},le=()=>{const Se=_n(this,Oy,J.promise=eV());ee(Se)},pe=Tt(this,Oy);switch(pe.status){case"pending":e.queryHash===n.queryHash&&ee(pe);break;case"fulfilled":(J.status==="error"||J.data!==pe.value)&&le();break;case"rejected":(J.status!=="error"||J.error!==pe.reason)&&le();break}}return J}updateResult(){const e=Tt(this,Hc),r=this.createResult(Tt(this,is),this.options);if(_n(this,Fv,Tt(this,is).state),_n(this,z1,this.options),Tt(this,Fv).data!==void 0&&_n(this,V1,Tt(this,is)),OD(r,e))return;_n(this,Hc,r);const n=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,o=typeof i=="function"?i():i;if(o==="all"||!o&&!Tt(this,q1).size)return!0;const c=new Set(o??Tt(this,q1));return this.options.throwOnError&&c.add("error"),Object.keys(Tt(this,Hc)).some(a=>{const f=a;return Tt(this,Hc)[f]!==e[f]&&c.has(f)})};qi(this,Ms,dge).call(this,{listeners:n()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&qi(this,Ms,sV).call(this)}},Tu=new WeakMap,is=new WeakMap,hC=new WeakMap,Hc=new WeakMap,Fv=new WeakMap,z1=new WeakMap,Oy=new WeakMap,Fy=new WeakMap,fC=new WeakMap,U1=new WeakMap,V1=new WeakMap,Bv=new WeakMap,$v=new WeakMap,By=new WeakMap,q1=new WeakMap,Ms=new WeakSet,B2=function(e){qi(this,Ms,lV).call(this);let r=Tt(this,is).fetch(this.options,e);return e!=null&&e.throwOnError||(r=r.catch(Kc)),r},rV=function(){qi(this,Ms,aV).call(this);const e=tx(this.options.staleTime,Tt(this,is));if(i_||Tt(this,Hc).isStale||!XU(e))return;const n=ege(Tt(this,Hc).dataUpdatedAt,e)+1;_n(this,Bv,setTimeout(()=>{Tt(this,Hc).isStale||this.updateResult()},n))},nV=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Tt(this,is)):this.options.refetchInterval)??!1},iV=function(e){qi(this,Ms,oV).call(this),_n(this,By,e),!(i_||Qd(this.options.enabled,Tt(this,is))===!1||!XU(Tt(this,By))||Tt(this,By)===0)&&_n(this,$v,setInterval(()=>{(this.options.refetchIntervalInBackground||r7.isFocused())&&qi(this,Ms,B2).call(this)},Tt(this,By)))},sV=function(){qi(this,Ms,rV).call(this),qi(this,Ms,iV).call(this,qi(this,Ms,nV).call(this))},aV=function(){Tt(this,Bv)&&(clearTimeout(Tt(this,Bv)),_n(this,Bv,void 0))},oV=function(){Tt(this,$v)&&(clearInterval(Tt(this,$v)),_n(this,$v,void 0))},lV=function(){const e=Tt(this,Tu).getQueryCache().build(Tt(this,Tu),this.options);if(e===Tt(this,is))return;const r=Tt(this,is);_n(this,is,e),_n(this,hC,e.state),this.hasListeners()&&(r==null||r.removeObserver(this),e.addObserver(this))},dge=function(e){hl.batch(()=>{e.listeners&&this.listeners.forEach(r=>{r(Tt(this,Hc))}),Tt(this,Tu).getQueryCache().notify({query:Tt(this,is),type:"observerResultsUpdated"})})},pde);function F5e(t,e){return Qd(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function xte(t,e){return F5e(t,e)||t.state.data!==void 0&&cV(t,e,e.refetchOnMount)}function cV(t,e,r){if(Qd(e.enabled,t)!==!1&&tx(e.staleTime,t)!=="static"){const n=typeof r=="function"?r(t):r;return n==="always"||n!==!1&&n7(t,e)}return!1}function vte(t,e,r,n){return(t!==e||Qd(n.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&n7(t,r)}function n7(t,e){return Qd(e.enabled,t)!==!1&&t.isStaleByTime(tx(e.staleTime,t))}function B5e(t,e){return!OD(t.getCurrentResult(),e)}var $y,zy,Eu,Ip,Wp,jL,uV,gde,$5e=(gde=class extends sT{constructor(r,n){super();Qn(this,Wp);Qn(this,$y);Qn(this,zy);Qn(this,Eu);Qn(this,Ip);_n(this,$y,r),this.setOptions(n),this.bindMethods(),qi(this,Wp,jL).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(r){var i;const n=this.options;this.options=Tt(this,$y).defaultMutationOptions(r),OD(this.options,n)||Tt(this,$y).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Tt(this,Eu),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&s_(n.mutationKey)!==s_(this.options.mutationKey)?this.reset():((i=Tt(this,Eu))==null?void 0:i.state.status)==="pending"&&Tt(this,Eu).setOptions(this.options)}onUnsubscribe(){var r;this.hasListeners()||(r=Tt(this,Eu))==null||r.removeObserver(this)}onMutationUpdate(r){qi(this,Wp,jL).call(this),qi(this,Wp,uV).call(this,r)}getCurrentResult(){return Tt(this,zy)}reset(){var r;(r=Tt(this,Eu))==null||r.removeObserver(this),_n(this,Eu,void 0),qi(this,Wp,jL).call(this),qi(this,Wp,uV).call(this)}mutate(r,n){var i;return _n(this,Ip,n),(i=Tt(this,Eu))==null||i.removeObserver(this),_n(this,Eu,Tt(this,$y).getMutationCache().build(Tt(this,$y),this.options)),Tt(this,Eu).addObserver(this),Tt(this,Eu).execute(r)}},$y=new WeakMap,zy=new WeakMap,Eu=new WeakMap,Ip=new WeakMap,Wp=new WeakSet,jL=function(){var n;const r=((n=Tt(this,Eu))==null?void 0:n.state)??cge();_n(this,zy,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},uV=function(r){hl.batch(()=>{var n,i,o,c,a,f,p,y;if(Tt(this,Ip)&&this.hasListeners()){const v=Tt(this,zy).variables,T=Tt(this,zy).context;(r==null?void 0:r.type)==="success"?((i=(n=Tt(this,Ip)).onSuccess)==null||i.call(n,r.data,v,T),(c=(o=Tt(this,Ip)).onSettled)==null||c.call(o,r.data,null,v,T)):(r==null?void 0:r.type)==="error"&&((f=(a=Tt(this,Ip)).onError)==null||f.call(a,r.error,v,T),(y=(p=Tt(this,Ip)).onSettled)==null||y.call(p,void 0,r.error,v,T))}this.listeners.forEach(v=>{v(Tt(this,zy))})})},gde),hge=C.createContext(void 0),Ar=t=>{const e=C.useContext(hge);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},z5e=({client:t,children:e})=>(C.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),s.jsx(hge.Provider,{value:t,children:e})),fge=C.createContext(!1),U5e=()=>C.useContext(fge);fge.Provider;function V5e(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var q5e=C.createContext(V5e()),G5e=()=>C.useContext(q5e),H5e=(t,e)=>{(t.suspense||t.throwOnError||t.experimental_prefetchInRender)&&(e.isReset()||(t.retryOnMount=!1))},W5e=t=>{C.useEffect(()=>{t.clearReset()},[t])},K5e=({result:t,errorResetBoundary:e,throwOnError:r,query:n,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&n&&(i&&t.data===void 0||nge(r,[t.error,n])),Y5e=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))}},Z5e=(t,e)=>t.isLoading&&t.isFetching&&!e,X5e=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,_te=(t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()});function Q5e(t,e,r){var v,T,E,k,P;const n=U5e(),i=G5e(),o=Ar(),c=o.defaultQueryOptions(t);(T=(v=o.getDefaultOptions().queries)==null?void 0:v._experimental_beforeQuery)==null||T.call(v,c),c._optimisticResults=n?"isRestoring":"optimistic",Y5e(c),H5e(c,i),W5e(i);const a=!o.getQueryCache().get(c.queryHash),[f]=C.useState(()=>new e(o,c)),p=f.getOptimisticResult(c),y=!n&&t.subscribed!==!1;if(C.useSyncExternalStore(C.useCallback(R=>{const D=y?f.subscribe(hl.batchCalls(R)):Kc;return f.updateResult(),D},[f,y]),()=>f.getCurrentResult(),()=>f.getCurrentResult()),C.useEffect(()=>{f.setOptions(c)},[c,f]),X5e(c,p))throw _te(c,f,i);if(K5e({result:p,errorResetBoundary:i,throwOnError:c.throwOnError,query:o.getQueryCache().get(c.queryHash),suspense:c.suspense}))throw p.error;if((k=(E=o.getDefaultOptions().queries)==null?void 0:E._experimental_afterQuery)==null||k.call(E,c,p),c.experimental_prefetchInRender&&!i_&&Z5e(p,n)){const R=a?_te(c,f,i):(P=o.getQueryCache().get(c.queryHash))==null?void 0:P.promise;R==null||R.catch(Kc).finally(()=>{f.updateResult()})}return c.notifyOnChangeProps?p:f.trackResult(p)}function mr(t,e){return Q5e(t,O5e)}function Sr(t,e){const r=Ar(),[n]=C.useState(()=>new $5e(r,t));C.useEffect(()=>{n.setOptions(t)},[n,t]);const i=C.useSyncExternalStore(C.useCallback(c=>n.subscribe(hl.batchCalls(c)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),o=C.useCallback((c,a)=>{n.mutate(c,a).catch(Kc)},[n]);if(i.error&&nge(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 ek(){return ek=Object.assign?Object.assign.bind():function(t){for(var e=1;e"u")throw new Error(e)}function mge(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function e4e(){return Math.random().toString(36).substr(2,8)}function wte(t,e){return{usr:t.state,key:t.key,idx:e}}function dV(t,e,r,n){return r===void 0&&(r=null),ek({pathname:typeof t=="string"?t:t.pathname,search:"",hash:""},typeof e=="string"?aT(e):e,{state:r,key:e&&e.key||n||e4e()})}function BD(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 aT(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 t4e(t,e,r,n){n===void 0&&(n={});let{window:i=document.defaultView,v5Compat:o=!1}=n,c=i.history,a=qy.Pop,f=null,p=y();p==null&&(p=0,c.replaceState(ek({},c.state,{idx:p}),""));function y(){return(c.state||{idx:null}).idx}function v(){a=qy.Pop;let R=y(),D=R==null?null:R-p;p=R,f&&f({action:a,location:P.location,delta:D})}function T(R,D){a=qy.Push;let M=dV(P.location,R,D);p=y()+1;let B=wte(M,p),V=P.createHref(M);try{c.pushState(B,"",V)}catch(G){if(G instanceof DOMException&&G.name==="DataCloneError")throw G;i.location.assign(V)}o&&f&&f({action:a,location:P.location,delta:1})}function E(R,D){a=qy.Replace;let M=dV(P.location,R,D);p=y();let B=wte(M,p),V=P.createHref(M);c.replaceState(B,"",V),o&&f&&f({action:a,location:P.location,delta:0})}function k(R){let D=i.location.origin!=="null"?i.location.origin:i.location.href,M=typeof R=="string"?R:BD(R);return M=M.replace(/ $/,"%20"),so(D,"No window.location.(origin|href) available to create URL for href: "+M),new URL(M,D)}let P={get action(){return a},get location(){return t(i,c)},listen(R){if(f)throw new Error("A history only accepts one active listener");return i.addEventListener(bte,v),f=R,()=>{i.removeEventListener(bte,v),f=null}},createHref(R){return e(i,R)},createURL:k,encodeLocation(R){let D=k(R);return{pathname:D.pathname,search:D.search,hash:D.hash}},push:T,replace:E,go(R){return c.go(R)}};return P}var Ste;(function(t){t.data="data",t.deferred="deferred",t.redirect="redirect",t.error="error"})(Ste||(Ste={}));function r4e(t,e,r){return r===void 0&&(r="/"),n4e(t,e,r,!1)}function n4e(t,e,r,n){let i=typeof e=="string"?aT(e):e,o=nS(i.pathname||"/",r);if(o==null)return null;let c=pge(t);i4e(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("/")&&(so(f.relativePath.startsWith(n),'Absolute route path "'+f.relativePath+'" nested under path '+('"'+n+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),f.relativePath=f.relativePath.slice(n.length));let p=rx([n,f.relativePath]),y=r.concat(f);o.children&&o.children.length>0&&(so(o.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+p+'".')),pge(o.children,e,y,p)),!(o.path==null&&!o.index)&&e.push({path:p,score:d4e(p,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 gge(o.path))i(o,c,f)}),e}function gge(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=gge(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 i4e(t){t.sort((e,r)=>e.score!==r.score?r.score-e.score:h4e(e.routesMeta.map(n=>n.childrenIndex),r.routesMeta.map(n=>n.childrenIndex)))}const s4e=/^:[\w-]+$/,a4e=3,o4e=2,l4e=1,c4e=10,u4e=-2,Tte=t=>t==="*";function d4e(t,e){let r=t.split("/"),n=r.length;return r.some(Tte)&&(n+=u4e),e&&(n+=o4e),r.filter(i=>!Tte(i)).reduce((i,o)=>i+(s4e.test(o)?a4e:o===""?l4e:c4e),n)}function h4e(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 f4e(t,e,r){let{routesMeta:n}=t,i={},o="/",c=[];for(let a=0;a{let{paramName:T,isOptional:E}=y;if(T==="*"){let P=a[v]||"";c=o.slice(0,o.length-P.length).replace(/(.)\/+$/,"$1")}const k=a[v];return E&&!k?p[T]=void 0:p[T]=(k||"").replace(/%2F/g,"/"),p},{}),pathname:o,pathnameBase:c,pattern:t}}function m4e(t,e,r){e===void 0&&(e=!1),r===void 0&&(r=!0),mge(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 p4e(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return mge(!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 nS(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 g4e(t,e){e===void 0&&(e="/");let{pathname:r,search:n="",hash:i=""}=typeof t=="string"?aT(t):t;return{pathname:r?r.startsWith("/")?r:y4e(r,e):e,search:_4e(n),hash:b4e(i)}}function y4e(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 E$(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 x4e(t){return t.filter((e,r)=>r===0||e.route.path&&e.route.path.length>0)}function i7(t,e){let r=x4e(t);return e?r.map((n,i)=>i===r.length-1?n.pathname:n.pathnameBase):r.map(n=>n.pathnameBase)}function s7(t,e,r,n){n===void 0&&(n=!1);let i;typeof t=="string"?i=aT(t):(i=ek({},t),so(!i.pathname||!i.pathname.includes("?"),E$("?","pathname","search",i)),so(!i.pathname||!i.pathname.includes("#"),E$("#","pathname","hash",i)),so(!i.search||!i.search.includes("#"),E$("#","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 T=c.split("/");for(;T[0]==="..";)T.shift(),v-=1;i.pathname=T.join("/")}a=v>=0?e[v]:"/"}let f=g4e(i,a),p=c&&c!=="/"&&c.endsWith("/"),y=(o||c===".")&&r.endsWith("/");return!f.pathname.endsWith("/")&&(p||y)&&(f.pathname+="/"),f}const rx=t=>t.join("/").replace(/\/\/+/g,"/"),v4e=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),_4e=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,b4e=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function w4e(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}const yge=["post","put","patch","delete"];new Set(yge);const S4e=["get",...yge];new Set(S4e);/** * 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 tk(){return tk=Object.assign?Object.assign.bind():function(t){for(var e=1;e{a.current=!0}),C.useCallback(function(p,y){if(y===void 0&&(y={}),!a.current)return;if(typeof p=="number"){n.go(p);return}let v=s7(p,JSON.parse(c),o,y.relative==="path");t==null&&e!=="/"&&(v.pathname=v.pathname==="/"?e:rx([e,v.pathname])),(y.replace?n.replace:n.push)(v,y.state,y)},[e,n,c,o,t])}const j4e=C.createContext(null);function A4e(t){let e=C.useContext(Im).outlet;return e&&C.createElement(j4e.Provider,{value:t},e)}function Pm(){let{matches:t}=C.useContext(Im),e=t[t.length-1];return e?e.params:{}}function y3(t,e){let{relative:r}=e===void 0?{}:e,{future:n}=C.useContext(fg),{matches:i}=C.useContext(Im),{pathname:o}=ki(),c=JSON.stringify(i7(i,n.v7_relativeSplatPath));return C.useMemo(()=>s7(t,JSON.parse(c),o,r==="path"),[t,c,o,r])}function k4e(t,e){return C4e(t,e)}function C4e(t,e,r,n){oT()||so(!1);let{navigator:i}=C.useContext(fg),{matches:o}=C.useContext(Im),c=o[o.length-1],a=c?c.params:{};c&&c.pathname;let f=c?c.pathnameBase:"/";c&&c.route;let p=ki(),y;if(e){var v;let R=typeof e=="string"?aT(e):e;f==="/"||(v=R.pathname)!=null&&v.startsWith(f)||so(!1),y=R}else y=p;let T=y.pathname||"/",E=T;if(f!=="/"){let R=f.replace(/^\//,"").split("/");E="/"+T.replace(/^\//,"").split("/").slice(R.length).join("/")}let k=r4e(t,{pathname:E}),P=L4e(k&&k.map(R=>Object.assign({},R,{params:Object.assign({},a,R.params),pathname:rx([f,i.encodeLocation?i.encodeLocation(R.pathname).pathname:R.pathname]),pathnameBase:R.pathnameBase==="/"?f:rx([f,i.encodeLocation?i.encodeLocation(R.pathnameBase).pathname:R.pathnameBase])})),o,r,n);return e&&P?C.createElement(g3.Provider,{value:{location:tk({pathname:"/",search:"",hash:"",state:null,key:"default"},y),navigationType:qy.Pop}},P):P}function N4e(){let t=F4e(),e=w4e(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 C.createElement(C.Fragment,null,C.createElement("h2",null,"Unexpected Application Error!"),C.createElement("h3",{style:{fontStyle:"italic"}},e),r?C.createElement("pre",{style:i},r):null,null)}const I4e=C.createElement(N4e,null);class P4e extends C.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?C.createElement(Im.Provider,{value:this.props.routeContext},C.createElement(vge.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function R4e(t){let{routeContext:e,match:r,children:n}=t,i=C.useContext(p3);return i&&i.static&&i.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=r.route.id),C.createElement(Im.Provider,{value:e},n)}function L4e(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||so(!1),c=c.slice(0,Math.min(c.length,y+1))}let f=!1,p=-1;if(r&&n&&n.v7_partialHydration)for(let y=0;y=0?c=c.slice(0,p+1):c=[c[0]];break}}}return c.reduceRight((y,v,T)=>{let E,k=!1,P=null,R=null;r&&(E=a&&v.route.id?a[v.route.id]:void 0,P=v.route.errorElement||I4e,f&&(p<0&&T===0?(k=!0,R=null):p===T&&(k=!0,R=v.route.hydrateFallbackElement||null)));let D=e.concat(c.slice(0,T+1)),M=()=>{let B;return E?B=P:k?B=R:v.route.Component?B=C.createElement(v.route.Component,null):v.route.element?B=v.route.element:B=y,C.createElement(R4e,{match:v,routeContext:{outlet:y,matches:D,isDataRoute:r!=null},children:B})};return r&&(v.route.ErrorBoundary||v.route.errorElement||T===0)?C.createElement(P4e,{location:r.location,revalidation:r.revalidation,component:P,error:E,children:M(),routeContext:{outlet:null,matches:D,isDataRoute:!0}}):M()},null)}var bge=function(t){return t.UseBlocker="useBlocker",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t}(bge||{}),zD=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}(zD||{});function D4e(t){let e=C.useContext(p3);return e||so(!1),e}function M4e(t){let e=C.useContext(xge);return e||so(!1),e}function O4e(t){let e=C.useContext(Im);return e||so(!1),e}function wge(t){let e=O4e(),r=e.matches[e.matches.length-1];return r.route.id||so(!1),r.route.id}function F4e(){var t;let e=C.useContext(vge),r=M4e(zD.UseRouteError),n=wge(zD.UseRouteError);return e!==void 0?e:(t=r.errors)==null?void 0:t[n]}function B4e(){let{router:t}=D4e(bge.UseNavigateStable),e=wge(zD.UseNavigateStable),r=C.useRef(!1);return _ge(()=>{r.current=!0}),C.useCallback(function(i,o){o===void 0&&(o={}),r.current&&(typeof i=="number"?t.navigate(i):t.navigate(i,tk({fromRouteId:e},o)))},[t,e])}function $4e(t,e){t==null||t.v7_startTransition,t==null||t.v7_relativeSplatPath}function ci(t){let{to:e,replace:r,state:n,relative:i}=t;oT()||so(!1);let{future:o,static:c}=C.useContext(fg),{matches:a}=C.useContext(Im),{pathname:f}=ki(),p=Hs(),y=s7(e,i7(a,o.v7_relativeSplatPath),f,i==="path"),v=JSON.stringify(y);return C.useEffect(()=>p(JSON.parse(v),{replace:r,state:n,relative:i}),[p,v,i,r,n]),null}function mqt(t){return A4e(t.context)}function xe(t){so(!1)}function z4e(t){let{basename:e="/",children:r=null,location:n,navigationType:i=qy.Pop,navigator:o,static:c=!1,future:a}=t;oT()&&so(!1);let f=e.replace(/^\/*/,"/"),p=C.useMemo(()=>({basename:f,navigator:o,static:c,future:tk({v7_relativeSplatPath:!1},a)}),[f,a,o,c]);typeof n=="string"&&(n=aT(n));let{pathname:y="/",search:v="",hash:T="",state:E=null,key:k="default"}=n,P=C.useMemo(()=>{let R=nS(y,f);return R==null?null:{location:{pathname:R,search:v,hash:T,state:E,key:k},navigationType:i}},[f,y,v,T,E,k,i]);return P==null?null:C.createElement(fg.Provider,{value:p},C.createElement(g3.Provider,{children:r,value:P}))}function Cy(t){let{children:e,location:r}=t;return k4e(hV(e),r)}new Promise(()=>{});function hV(t,e){e===void 0&&(e=[]);let r=[];return C.Children.forEach(t,(n,i)=>{if(!C.isValidElement(n))return;let o=[...e,i];if(n.type===C.Fragment){r.push.apply(r,hV(n.props.children,o));return}n.type!==xe&&so(!1),!n.props.index||!n.props.children||so(!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=hV(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 UD(){return UD=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&(r[i]=t[i]);return r}function U4e(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function V4e(t,e){return t.button===0&&(!e||e==="_self")&&!U4e(t)}function fV(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 q4e(t,e){let r=fV(t);return e&&e.forEach((n,i)=>{r.has(i)||e.getAll(i).forEach(o=>{r.append(i,o)})}),r}const G4e=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],H4e=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],W4e="6";try{window.__reactRouterVersion=W4e}catch{}const K4e=C.createContext({isTransitioning:!1}),Y4e="startTransition",Ete=kG[Y4e];function Z4e(t){let{basename:e,children:r,future:n,window:i}=t,o=C.useRef();o.current==null&&(o.current=J5e({window:i,v5Compat:!0}));let c=o.current,[a,f]=C.useState({action:c.action,location:c.location}),{v7_startTransition:p}=n||{},y=C.useCallback(v=>{p&&Ete?Ete(()=>f(v)):f(v)},[f,p]);return C.useLayoutEffect(()=>c.listen(y),[c,y]),C.useEffect(()=>$4e(n),[n]),C.createElement(z4e,{basename:e,children:r,location:a.location,navigationType:a.action,navigator:c,future:n})}const X4e=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Q4e=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Wr=C.forwardRef(function(e,r){let{onClick:n,relative:i,reloadDocument:o,replace:c,state:a,target:f,to:p,preventScrollReset:y,viewTransition:v}=e,T=Sge(e,G4e),{basename:E}=C.useContext(fg),k,P=!1;if(typeof p=="string"&&Q4e.test(p)&&(k=p,X4e))try{let B=new URL(window.location.href),V=p.startsWith("//")?new URL(B.protocol+p):new URL(p),G=nS(V.pathname,E);V.origin===B.origin&&G!=null?p=G+V.search+V.hash:P=!0}catch{}let R=T4e(p,{relative:i}),D=eBe(p,{replace:c,state:a,target:f,preventScrollReset:y,relative:i,viewTransition:v});function M(B){n&&n(B),B.defaultPrevented||D(B)}return C.createElement("a",UD({},T,{href:k||R,onClick:P||o?n:M,ref:r,target:f}))}),pqt=C.forwardRef(function(e,r){let{"aria-current":n="page",caseSensitive:i=!1,className:o="",end:c=!1,style:a,to:f,viewTransition:p,children:y}=e,v=Sge(e,H4e),T=y3(f,{relative:v.relative}),E=ki(),k=C.useContext(xge),{navigator:P,basename:R}=C.useContext(fg),D=k!=null&&tBe(T)&&p===!0,M=P.encodeLocation?P.encodeLocation(T).pathname:T.pathname,B=E.pathname,V=k&&k.navigation&&k.navigation.location?k.navigation.location.pathname:null;i||(B=B.toLowerCase(),V=V?V.toLowerCase():null,M=M.toLowerCase()),V&&R&&(V=nS(V,R)||V);const G=M!=="/"&&M.endsWith("/")?M.length-1:M.length;let W=B===M||!c&&B.startsWith(M)&&B.charAt(G)==="/",Y=V!=null&&(V===M||!c&&V.startsWith(M)&&V.charAt(M.length)==="/"),J={isActive:W,isPending:Y,isTransitioning:D},Q=W?n:void 0,ee;typeof o=="function"?ee=o(J):ee=[o,W?"active":null,Y?"pending":null,D?"transitioning":null].filter(Boolean).join(" ");let le=typeof a=="function"?a(J):a;return C.createElement(Wr,UD({},v,{"aria-current":Q,className:ee,ref:r,style:le,to:f,viewTransition:p}),typeof y=="function"?y(J):y)});var mV;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(mV||(mV={}));var jte;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(jte||(jte={}));function J4e(t){let e=C.useContext(p3);return e||so(!1),e}function eBe(t,e){let{target:r,replace:n,state:i,preventScrollReset:o,relative:c,viewTransition:a}=e===void 0?{}:e,f=Hs(),p=ki(),y=y3(t,{relative:c});return C.useCallback(v=>{if(V4e(v,r)){v.preventDefault();let T=n!==void 0?n:BD(p)===BD(y);f(t,{replace:T,state:i,preventScrollReset:o,relative:c,viewTransition:a})}},[p,f,y,n,i,r,t,o,c,a])}function Px(t){let e=C.useRef(fV(t)),r=C.useRef(!1),n=ki(),i=C.useMemo(()=>q4e(n.search,r.current?null:e.current),[n.search]),o=Hs(),c=C.useCallback((a,f)=>{const p=fV(typeof a=="function"?a(i):a);r.current=!0,o("?"+p,f)},[o,i]);return[i,c]}function tBe(t,e){e===void 0&&(e={});let r=C.useContext(K4e);r==null&&so(!1);let{basename:n}=J4e(mV.useViewTransitionState),i=y3(t,{relative:e.relative});if(!r.isTransitioning)return!1;let o=nS(r.currentLocation.pathname,n)||r.currentLocation.pathname,c=nS(r.nextLocation.pathname,n)||r.nextLocation.pathname;return $D(i.pathname,c)!=null||$D(i.pathname,o)!=null}var rBe=typeof Element<"u",nBe=typeof Map=="function",iBe=typeof Set=="function",sBe=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function AL(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(t.constructor!==e.constructor)return!1;var r,n,i;if(Array.isArray(t)){if(r=t.length,r!=e.length)return!1;for(n=r;n--!==0;)if(!AL(t[n],e[n]))return!1;return!0}var o;if(nBe&&t instanceof Map&&e instanceof Map){if(t.size!==e.size)return!1;for(o=t.entries();!(n=o.next()).done;)if(!e.has(n.value[0]))return!1;for(o=t.entries();!(n=o.next()).done;)if(!AL(n.value[1],e.get(n.value[0])))return!1;return!0}if(iBe&&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(sBe&&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(rBe&&t instanceof Element)return!1;for(n=r;n--!==0;)if(!((i[n]==="_owner"||i[n]==="__v"||i[n]==="__o")&&t.$$typeof)&&!AL(t[i[n]],e[i[n]]))return!1;return!0}return t!==t&&e!==e}var aBe=function(e,r){try{return AL(e,r)}catch(n){if((n.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw n}};const oBe=ds(aBe);var lBe=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 p=[r,n,i,o,c,a],y=0;f=new Error(e.replace(/%s/g,function(){return p[y++]})),f.name="Invariant Violation"}throw f.framesToPop=1,f}},cBe=lBe;const Ate=ds(cBe);var uBe=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),p=0;p(t.BASE="base",t.BODY="body",t.HEAD="head",t.HTML="html",t.LINK="link",t.META="meta",t.NOSCRIPT="noscript",t.SCRIPT="script",t.STYLE="style",t.TITLE="title",t.FRAGMENT="Symbol(react.fragment)",t))(Tge||{}),j$={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"]}},kte=Object.values(Tge),a7={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},hBe=Object.entries(a7).reduce((t,[e,r])=>(t[r]=e,t),{}),of="data-rh",x1={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},v1=(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},fBe=t=>{let e=v1(t,"title");const r=v1(t,x1.TITLE_TEMPLATE);if(Array.isArray(e)&&(e=e.join("")),r&&e)return r.replace(/%s/g,()=>e);const n=v1(t,x1.DEFAULT_TITLE);return e||n||void 0},mBe=t=>v1(t,x1.ON_CHANGE_CLIENT_STATE)||(()=>{}),A$=(t,e)=>e.filter(r=>typeof r[t]<"u").map(r=>r[t]).reduce((r,n)=>({...r,...n}),{}),pBe=(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),r2=(t,e,r)=>{const n={};return r.filter(i=>Array.isArray(i[t])?!0:(typeof i[t]<"u"&&gBe(`Helmet: ${t} should be of type "Array". Instead found type "${typeof i[t]}"`),!1)).map(i=>i[t]).reverse().reduce((i,o)=>{const c={};o.filter(f=>{let p;const y=Object.keys(f);for(let T=0;Ti.push(f));const a=Object.keys(c);for(let f=0;f{if(Array.isArray(t)&&t.length){for(let r=0;r({baseTag:pBe(["href"],t),bodyAttributes:A$("bodyAttributes",t),defer:v1(t,x1.DEFER),encode:v1(t,x1.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:A$("htmlAttributes",t),linkTags:r2("link",["rel","href"],t),metaTags:r2("meta",["name","charset","http-equiv","property","itemprop"],t),noscriptTags:r2("noscript",["innerHTML"],t),onChangeClientState:mBe(t),scriptTags:r2("script",["src","innerHTML"],t),styleTags:r2("style",["cssText"],t),title:fBe(t),titleAttributes:A$("titleAttributes",t),prioritizeSeoTags:yBe(t,x1.PRIORITIZE_SEO_TAGS)}),Ege=t=>Array.isArray(t)?t.join(""):t,vBe=(t,e)=>{const r=Object.keys(t);for(let n=0;nArray.isArray(t)?t.reduce((r,n)=>(vBe(n,e)?r.priority.push(n):r.default.push(n),r),{priority:[],default:[]}):{default:t,priority:[]},Cte=(t,e)=>({...t,[e]:void 0}),_Be=["noscript","script","style"],pV=(t,e=!0)=>e===!1?String(t):String(t).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),jge=t=>Object.keys(t).reduce((e,r)=>{const n=typeof t[r]<"u"?`${r}="${t[r]}"`:`${r}`;return e?`${e} ${n}`:n},""),bBe=(t,e,r,n)=>{const i=jge(r),o=Ege(e);return i?`<${t} ${of}="true" ${i}>${pV(o,n)}`:`<${t} ${of}="true">${pV(o,n)}`},wBe=(t,e,r=!0)=>e.reduce((n,i)=>{const o=i,c=Object.keys(o).filter(p=>!(p==="innerHTML"||p==="cssText")).reduce((p,y)=>{const v=typeof o[y]>"u"?y:`${y}="${pV(o[y],r)}"`;return p?`${p} ${v}`:v},""),a=o.innerHTML||o.cssText||"",f=_Be.indexOf(t)===-1;return`${n}<${t} ${of}="true" ${c}${f?"/>":`>${a}`}`},""),Age=(t,e={})=>Object.keys(t).reduce((r,n)=>{const i=a7[n];return r[i||n]=t[n],r},e),SBe=(t,e,r)=>{const n={key:e,[of]:!0},i=Age(r,n);return[Xe.createElement("title",i,e)]},kL=(t,e)=>e.map((r,n)=>{const i={key:n,[of]:!0};return Object.keys(r).forEach(o=>{const a=a7[o]||o;if(a==="innerHTML"||a==="cssText"){const f=r.innerHTML||r.cssText;i.dangerouslySetInnerHTML={__html:f}}else i[a]=r[o]}),Xe.createElement(t,i)}),Zd=(t,e,r=!0)=>{switch(t){case"title":return{toComponent:()=>SBe(t,e.title,e.titleAttributes),toString:()=>bBe(t,e.title,e.titleAttributes,r)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>Age(e),toString:()=>jge(e)};default:return{toComponent:()=>kL(t,e),toString:()=>wBe(t,e,r)}}},TBe=({metaTags:t,linkTags:e,scriptTags:r,encode:n})=>{const i=k$(t,j$.meta),o=k$(e,j$.link),c=k$(r,j$.script);return{priorityMethods:{toComponent:()=>[...kL("meta",i.priority),...kL("link",o.priority),...kL("script",c.priority)],toString:()=>`${Zd("meta",i.priority,n)} ${Zd("link",o.priority,n)} ${Zd("script",c.priority,n)}`},metaTags:i.default,linkTags:o.default,scriptTags:c.default}},EBe=t=>{const{baseTag:e,bodyAttributes:r,encode:n=!0,htmlAttributes:i,noscriptTags:o,styleTags:c,title:a="",titleAttributes:f,prioritizeSeoTags:p}=t;let{linkTags:y,metaTags:v,scriptTags:T}=t,E={toComponent:()=>{},toString:()=>""};return p&&({priorityMethods:E,linkTags:y,metaTags:v,scriptTags:T}=TBe(t)),{priority:E,base:Zd("base",e,n),bodyAttributes:Zd("bodyAttributes",r,n),htmlAttributes:Zd("htmlAttributes",i,n),link:Zd("link",y,n),meta:Zd("meta",v,n),noscript:Zd("noscript",o,n),script:Zd("script",T,n),style:Zd("style",c,n),title:Zd("title",{title:a,titleAttributes:f},n)}},gV=EBe,aR=[],kge=!!(typeof window<"u"&&window.document&&window.document.createElement),yV=class{constructor(t,e){dn(this,"instances",[]);dn(this,"canUseDOM",kge);dn(this,"context");dn(this,"value",{setHelmet:t=>{this.context.helmet=t},helmetInstances:{get:()=>this.canUseDOM?aR:this.instances,add:t=>{(this.canUseDOM?aR:this.instances).push(t)},remove:t=>{const e=(this.canUseDOM?aR:this.instances).indexOf(t);(this.canUseDOM?aR:this.instances).splice(e,1)}}});this.context=t,this.canUseDOM=e||!1,e||(t.helmet=gV({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},jBe={},Cge=Xe.createContext(jBe),zv,Nge=(zv=class extends C.Component{constructor(r){super(r);dn(this,"helmetData");this.helmetData=new yV(this.props.context||{},zv.canUseDOM)}render(){return Xe.createElement(Cge.Provider,{value:this.helmetData.value},this.props.children)}},dn(zv,"canUseDOM",kge),zv),dw=(t,e)=>{const r=document.head||document.querySelector("head"),n=r.querySelectorAll(`${t}[${of}]`),i=[].slice.call(n),o=[];let c;return e&&e.length&&e.forEach(a=>{const f=document.createElement(t);for(const p in a)if(Object.prototype.hasOwnProperty.call(a,p))if(p==="innerHTML")f.innerHTML=a.innerHTML;else if(p==="cssText")f.styleSheet?f.styleSheet.cssText=a.cssText:f.appendChild(document.createTextNode(a.cssText));else{const y=p,v=typeof a[y]>"u"?"":a[y];f.setAttribute(p,v)}f.setAttribute(of,"true"),i.some((p,y)=>(c=y,f.isEqualNode(p)))?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}},xV=(t,e)=>{const r=document.getElementsByTagName(t)[0];if(!r)return;const n=r.getAttribute(of),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 p=o.indexOf(a);p!==-1&&o.splice(p,1)}for(let a=o.length-1;a>=0;a-=1)r.removeAttribute(o[a]);i.length===o.length?r.removeAttribute(of):r.getAttribute(of)!==c.join(",")&&r.setAttribute(of,c.join(","))},ABe=(t,e)=>{typeof t<"u"&&document.title!==t&&(document.title=Ege(t)),xV("title",e)},Nte=(t,e)=>{const{baseTag:r,bodyAttributes:n,htmlAttributes:i,linkTags:o,metaTags:c,noscriptTags:a,onChangeClientState:f,scriptTags:p,styleTags:y,title:v,titleAttributes:T}=t;xV("body",n),xV("html",i),ABe(v,T);const E={baseTag:dw("base",r),linkTags:dw("link",o),metaTags:dw("meta",c),noscriptTags:dw("noscript",a),scriptTags:dw("script",p),styleTags:dw("style",y)},k={},P={};Object.keys(E).forEach(R=>{const{newTags:D,oldTags:M}=E[R];D.length&&(k[R]=D),M.length&&(P[R]=E[R].oldTags)}),e&&e(),f(t,k,P)},n2=null,kBe=t=>{n2&&cancelAnimationFrame(n2),t.defer?n2=requestAnimationFrame(()=>{Nte(t,()=>{n2=null})}):(Nte(t),n2=null)},CBe=kBe,Ite=class extends C.Component{constructor(){super(...arguments);dn(this,"rendered",!1)}shouldComponentUpdate(e){return!dBe(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=xBe(e.get().map(o=>{const c={...o.props};return delete c.context,c}));Nge.canUseDOM?CBe(i):gV&&(n=gV(i)),r(n)}init(){if(this.rendered)return;this.rendered=!0;const{helmetInstances:e}=this.props.context;e.add(this),this.emitChange()}render(){return this.init(),null}},M6,Zo=(M6=class extends C.Component{shouldComponentUpdate(t){return!oBe(Cte(this.props,"helmetData"),Cte(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 Ate(kte.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 ${kte.join(", ")} are allowed. Helmet does not support rendering <${t.type}> elements. Refer to our API for more information.`),Ate(!e||typeof e=="string"||Array.isArray(e)&&!e.some(r=>typeof r!="string"),`Helmet expects a string as a child of <${t.type}>. Did you forget to wrap your children in braces? ( <${t.type}>{\`\`} ) Refer to our API for more information.`),!0}mapChildrenToProps(t,e){let r={};return Xe.Children.forEach(t,n=>{if(!n||!n.props)return;const{children:i,...o}=n.props,c=Object.keys(o).reduce((f,p)=>(f[hBe[p]||p]=o[p],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 yV)){const i=n;n=new yV(i.context,!0),delete r.helmetData}return n?Xe.createElement(Ite,{...r,context:n.value}):Xe.createElement(Cge.Consumer,null,i=>Xe.createElement(Ite,{...r,context:i}))}},dn(M6,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),M6);const NBe=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Fe(async()=>{const{default:n}=await Promise.resolve().then(()=>lT);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)};class o7 extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}}class IBe extends o7{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class PBe extends o7{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class RBe extends o7{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var vV;(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"})(vV||(vV={}));var LBe=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{p(n.next(y))}catch(v){c(v)}}function f(y){try{p(n.throw(y))}catch(v){c(v)}}function p(y){y.done?o(y.value):i(y.value).then(a,f)}p((n=n.apply(t,e||[])).next())})};class DBe{constructor(e,{headers:r={},customFetch:n,region:i=vV.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=NBe(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,r={}){var n;return LBe(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 p;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",p=c):typeof c=="string"?(a["Content-Type"]="text/plain",p=c):typeof FormData<"u"&&c instanceof FormData?p=c:(a["Content-Type"]="application/json",p=JSON.stringify(c)));const y=yield this.fetch(`${this.url}/${e}`,{method:o||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:p}).catch(k=>{throw new IBe(k)}),v=y.headers.get("x-relay-error");if(v&&v==="true")throw new PBe(y);if(!y.ok)throw new RBe(y);let T=((n=y.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),E;return T==="application/json"?E=yield y.json():T==="application/octet-stream"?E=yield y.blob():T==="text/event-stream"?E=y:T==="multipart/form-data"?E=yield y.formData():E=yield y.text(),{data:E,error:null}}catch(i){return{data:null,error:i}}})}}var Cu={},l7={},x3={},RC={},v3={},_3={},MBe=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")},iS=MBe();const OBe=iS.fetch,Ige=iS.fetch.bind(iS),Pge=iS.Headers,FBe=iS.Request,BBe=iS.Response,lT=Object.freeze(Object.defineProperty({__proto__:null,Headers:Pge,Request:FBe,Response:BBe,default:Ige,fetch:OBe},Symbol.toStringTag,{value:"Module"})),$Be=ZIe(lT);var b3={};Object.defineProperty(b3,"__esModule",{value:!0});let zBe=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};b3.default=zBe;var Rge=tc&&tc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(_3,"__esModule",{value:!0});const UBe=Rge($Be),VBe=Rge(b3);let qBe=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=UBe.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 p=null,y=null,v=null,T=o.status,E=o.statusText;if(o.ok){if(this.method!=="HEAD"){const D=await o.text();D===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?y=D:y=JSON.parse(D))}const P=(c=this.headers.Prefer)===null||c===void 0?void 0:c.match(/count=(exact|planned|estimated)/),R=(a=o.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");P&&R&&R.length>1&&(v=parseInt(R[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(y)&&(y.length>1?(p={code:"PGRST116",details:`Results contain ${y.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},y=null,v=null,T=406,E="Not Acceptable"):y.length===1?y=y[0]:y=null)}else{const P=await o.text();try{p=JSON.parse(P),Array.isArray(p)&&o.status===404&&(y=[],p=null,T=200,E="OK")}catch{o.status===404&&P===""?(T=204,E="No Content"):p={message:P}}if(p&&this.isMaybeSingle&&(!((f=p==null?void 0:p.details)===null||f===void 0)&&f.includes("0 rows"))&&(p=null,T=200,E="OK"),p&&this.shouldThrowOnError)throw new VBe.default(p)}return{error:p,data:y,count:v,status:T,statusText:E}});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}};_3.default=qBe;var GBe=tc&&tc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(v3,"__esModule",{value:!0});const HBe=GBe(_3);let WBe=class extends HBe.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("|"),p=(a=this.headers.Accept)!==null&&a!==void 0?a:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${c}; for="${p}"; options=${f};`,c==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};v3.default=WBe;var KBe=tc&&tc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(RC,"__esModule",{value:!0});const YBe=KBe(v3);let ZBe=class extends YBe.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}};RC.default=ZBe;var XBe=tc&&tc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(x3,"__esModule",{value:!0});const i2=XBe(RC);let QBe=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 i2.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 i2.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((p,y)=>p.concat(Object.keys(y)),[]);if(f.length>0){const p=[...new Set(f)].map(y=>`"${y}"`);this.url.searchParams.set("columns",p.join(","))}}return new i2.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 i2.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 i2.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};x3.default=QBe;var w3={},S3={};Object.defineProperty(S3,"__esModule",{value:!0});S3.version=void 0;S3.version="0.0.0-automated";Object.defineProperty(w3,"__esModule",{value:!0});w3.DEFAULT_HEADERS=void 0;const JBe=S3;w3.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${JBe.version}`};var Lge=tc&&tc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(l7,"__esModule",{value:!0});const e$e=Lge(x3),t$e=Lge(RC),r$e=w3;let n$e=class Dge{constructor(e,{headers:r={},schema:n,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},r$e.DEFAULT_HEADERS),r),this.schemaName=n,this.fetch=i}from(e){const r=new URL(`${this.url}/${e}`);return new e$e.default(r,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new Dge(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 p=Object.assign({},this.headers);return o&&(p.Prefer=`count=${o}`),new t$e.default({method:c,url:a,headers:p,schema:this.schemaName,body:f,fetch:this.fetch,allowEmpty:!1})}};l7.default=n$e;var cT=tc&&tc.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Cu,"__esModule",{value:!0});Cu.PostgrestError=Cu.PostgrestBuilder=Cu.PostgrestTransformBuilder=Cu.PostgrestFilterBuilder=Cu.PostgrestQueryBuilder=Cu.PostgrestClient=void 0;const Mge=cT(l7);Cu.PostgrestClient=Mge.default;const Oge=cT(x3);Cu.PostgrestQueryBuilder=Oge.default;const Fge=cT(RC);Cu.PostgrestFilterBuilder=Fge.default;const Bge=cT(v3);Cu.PostgrestTransformBuilder=Bge.default;const $ge=cT(_3);Cu.PostgrestBuilder=$ge.default;const zge=cT(b3);Cu.PostgrestError=zge.default;var i$e=Cu.default={PostgrestClient:Mge.default,PostgrestQueryBuilder:Oge.default,PostgrestFilterBuilder:Fge.default,PostgrestTransformBuilder:Bge.default,PostgrestBuilder:$ge.default,PostgrestError:zge.default};const{PostgrestClient:s$e,PostgrestQueryBuilder:bqt,PostgrestFilterBuilder:wqt,PostgrestTransformBuilder:Sqt,PostgrestBuilder:Tqt,PostgrestError:Eqt}=i$e;let _V;typeof window>"u"?_V=require("ws"):_V=window.WebSocket;const a$e=_V,o$e="2.11.10",l$e={"X-Client-Info":`realtime-js/${o$e}`},c$e="1.0.0",Uge=1e4,u$e=1e3;var _1;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(_1||(_1={}));var qc;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(qc||(qc={}));var Xh;(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"})(Xh||(Xh={}));var bV;(function(t){t.websocket="websocket"})(bV||(bV={}));var _v;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(_v||(_v={}));class d$e{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 p=JSON.parse(n.decode(e.slice(c,e.byteLength)));return{ref:null,topic:a,event:f,payload:p}}}class Vge{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 pa;(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"})(pa||(pa={}));const Pte=(t,e,r={})=>{var n;const i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(e).reduce((o,c)=>(o[c]=h$e(c,t,e,i),o),{})},h$e=(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)?qge(o,c):wV(c)},qge=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return g$e(e,r)}switch(t){case pa.bool:return f$e(e);case pa.float4:case pa.float8:case pa.int2:case pa.int4:case pa.int8:case pa.numeric:case pa.oid:return m$e(e);case pa.json:case pa.jsonb:return p$e(e);case pa.timestamp:return y$e(e);case pa.abstime:case pa.date:case pa.daterange:case pa.int4range:case pa.int8range:case pa.money:case pa.reltime:case pa.text:case pa.time:case pa.timestamptz:case pa.timetz:case pa.tsrange:case pa.tstzrange:return wV(e);default:return wV(e)}},wV=t=>t,f$e=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},m$e=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},p$e=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch(e){return console.log(`JSON parse error: ${e}`),t}return t},g$e=(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=>qge(e,a))}return t},y$e=t=>typeof t=="string"?t.replace(" ","T"):t,Gge=t=>{let e=t;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};class C${constructor(e,r,n={},i=Uge){this.channel=e,this.event=r,this.payload=n,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,r){var n;return this._hasReceived(e)&&r((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:e,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:r})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:r}){this.recHooks.filter(n=>n.status===e).forEach(n=>n.callback(r))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var Rte;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Rte||(Rte={}));class aA{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=aA.syncState(this.state,i,o,c),this.pendingDiffs.forEach(f=>{this.state=aA.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=aA.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,(p,y)=>{c[p]||(f[p]=y)}),this.map(c,(p,y)=>{const v=o[p];if(v){const T=y.map(R=>R.presence_ref),E=v.map(R=>R.presence_ref),k=y.filter(R=>E.indexOf(R.presence_ref)<0),P=v.filter(R=>T.indexOf(R.presence_ref)<0);k.length>0&&(a[p]=k),P.length>0&&(f[p]=P)}else a[p]=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 p;const y=(p=e[a])!==null&&p!==void 0?p:[];if(e[a]=this.cloneDeep(f),y.length>0){const v=e[a].map(E=>E.presence_ref),T=y.filter(E=>v.indexOf(E.presence_ref)<0);e[a].unshift(...T)}n(a,y,f)}),this.map(c,(a,f)=>{let p=e[a];if(!p)return;const y=f.map(v=>v.presence_ref);p=p.filter(v=>y.indexOf(v.presence_ref)<0),e[a]=p,i(a,p,f),p.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 Lte;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Lte||(Lte={}));var Dte;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Dte||(Dte={}));var Ep;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Ep||(Ep={}));class c7{constructor(e,r={config:{}},n){this.topic=e,this.params=r,this.socket=n,this.bindings={},this.state=qc.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 C$(this,Xh.join,this.params,this.timeout),this.rejoinTimer=new Vge(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=qc.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=qc.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=qc.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=qc.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Xh.reply,{},(i,o)=>{this._trigger(this._replyEventName(o),i)}),this.presence=new aA(this),this.broadcastEndpointURL=Gge(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(Ep.CHANNEL_ERROR,y)),this._onClose(()=>e==null?void 0:e(Ep.CLOSED));const f={},p={broadcast:o,presence:c,postgres_changes:(i=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(y=>y.filter))!==null&&i!==void 0?i:[],private:a};this.socket.accessTokenValue&&(f.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:p},f)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:y})=>{var v;if(this.socket.setAuth(),y===void 0){e==null||e(Ep.SUBSCRIBED);return}else{const T=this.bindings.postgres_changes,E=(v=T==null?void 0:T.length)!==null&&v!==void 0?v:0,k=[];for(let P=0;P{this.state=qc.errored,e==null||e(Ep.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(y).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(Ep.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){return this._on(e,r,n)}async send(e,r={}){var n,i;if(!this._canPush()&&e.type==="broadcast"){const{event:o,payload:c}=e,f={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:o,payload:c,private:this.private}]})};try{const p=await this._fetchWithTimeout(this.broadcastEndpointURL,f,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((i=p.body)===null||i===void 0?void 0:i.cancel()),p.ok?"ok":"error"}catch(p){return p.name==="AbortError"?"timed out":"error"}}else return new Promise(o=>{var c,a,f;const p=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"),p.receive("ok",()=>o("ok")),p.receive("error",()=>o("error")),p.receive("timeout",()=>o("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=qc.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Xh.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(n=>{const i=new C$(this,Xh.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 C$(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:p,join:y}=Xh;if(n&&[a,f,p,y].indexOf(c)>=0&&n!==this._joinRef())return;let T=this._onMessage(c,r,n);if(r&&!T)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(c)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(E=>{var k,P,R;return((k=E.filter)===null||k===void 0?void 0:k.event)==="*"||((R=(P=E.filter)===null||P===void 0?void 0:P.event)===null||R===void 0?void 0:R.toLocaleLowerCase())===c}).map(E=>E.callback(T,n)):(o=this.bindings[c])===null||o===void 0||o.filter(E=>{var k,P,R,D,M,B;if(["broadcast","presence","postgres_changes"].includes(c))if("id"in E){const V=E.id,G=(k=E.filter)===null||k===void 0?void 0:k.event;return V&&((P=r.ids)===null||P===void 0?void 0:P.includes(V))&&(G==="*"||(G==null?void 0:G.toLocaleLowerCase())===((R=r.data)===null||R===void 0?void 0:R.type.toLocaleLowerCase()))}else{const V=(M=(D=E==null?void 0:E.filter)===null||D===void 0?void 0:D.event)===null||M===void 0?void 0:M.toLocaleLowerCase();return V==="*"||V===((B=r==null?void 0:r.event)===null||B===void 0?void 0:B.toLocaleLowerCase())}else return E.type.toLocaleLowerCase()===c}).map(E=>{if(typeof T=="object"&&"ids"in T){const k=T.data,{schema:P,table:R,commit_timestamp:D,type:M,errors:B}=k;T=Object.assign(Object.assign({},{schema:P,table:R,commit_timestamp:D,eventType:M,new:{},old:{},errors:B}),this._getPayloadRecords(k))}E.callback(T,n)})}_isClosed(){return this.state===qc.closed}_isJoined(){return this.state===qc.joined}_isJoining(){return this.state===qc.joining}_isLeaving(){return this.state===qc.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&&c7.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(Xh.close,{},e)}_onError(e){this._on(Xh.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=qc.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Pte(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Pte(e.columns,e.old_record)),r}}const Mte=()=>{},x$e=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class v$e{constructor(e,r){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=l$e,this.params={},this.timeout=Uge,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Mte,this.ref=0,this.logger=Mte,this.conn=null,this.sendBuffer=[],this.serializer=new d$e,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=o=>{let c;return o?c=o:typeof fetch>"u"?c=(...a)=>Fe(async()=>{const{default:f}=await Promise.resolve().then(()=>lT);return{default:f}},void 0).then(({default:f})=>f(...a)):c=fetch,(...a)=>c(...a)},this.endPoint=`${e}/${bV.websocket}`,this.httpEndpoint=Gge(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 Vge(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=a$e),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 _$e(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:c$e}))}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 _1.connecting:return _v.Connecting;case _1.open:return _v.Open;case _1.closing:return _v.Closing;default:return _v.Closed}}isConnected(){return this.connectionState()===_v.Open}channel(e,r={config:{}}){const n=`realtime:${e}`,i=this.getChannels().find(o=>o.topic===n);if(i)return i;{const o=new c7(`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(Xh.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(u$e,"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(Xh.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([x$e],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}}class _$e{constructor(e,r,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=_1.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}}class u7 extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function Nl(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}class b$e extends u7{constructor(e,r){super(e),this.name="StorageApiError",this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class SV extends u7{constructor(e,r){super(e),this.name="StorageUnknownError",this.originalError=r}}var w$e=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function a(y){try{p(n.next(y))}catch(v){c(v)}}function f(y){try{p(n.throw(y))}catch(v){c(v)}}function p(y){y.done?o(y.value):i(y.value).then(a,f)}p((n=n.apply(t,e||[])).next())})};const Hge=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Fe(async()=>{const{default:n}=await Promise.resolve().then(()=>lT);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},S$e=()=>w$e(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Fe(()=>Promise.resolve().then(()=>lT),void 0)).Response:Response}),TV=t=>{if(Array.isArray(t))return t.map(r=>TV(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,n])=>{const i=r.replace(/([-_][a-z])/gi,o=>o.toUpperCase().replace(/[-_]/g,""));e[i]=TV(n)}),e};var w_=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{p(n.next(y))}catch(v){c(v)}}function f(y){try{p(n.throw(y))}catch(v){c(v)}}function p(y){y.done?o(y.value):i(y.value).then(a,f)}p((n=n.apply(t,e||[])).next())})};const N$=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),T$e=(t,e,r)=>w_(void 0,void 0,void 0,function*(){const n=yield S$e();t instanceof n&&!(r!=null&&r.noResolveJson)?t.json().then(i=>{e(new b$e(N$(i),t.status||500))}).catch(i=>{e(new SV(N$(i),i))}):e(new SV(N$(t),t))}),E$e=(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 LC(t,e,r,n,i,o){return w_(this,void 0,void 0,function*(){return new Promise((c,a)=>{t(r,E$e(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=>T$e(f,a,n))})})}function VD(t,e,r,n){return w_(this,void 0,void 0,function*(){return LC(t,"GET",e,r,n)})}function wy(t,e,r,n,i){return w_(this,void 0,void 0,function*(){return LC(t,"POST",e,n,i,r)})}function j$e(t,e,r,n,i){return w_(this,void 0,void 0,function*(){return LC(t,"PUT",e,n,i,r)})}function A$e(t,e,r,n){return w_(this,void 0,void 0,function*(){return LC(t,"HEAD",e,Object.assign(Object.assign({},r),{noResolveJson:!0}),n)})}function Wge(t,e,r,n,i){return w_(this,void 0,void 0,function*(){return LC(t,"DELETE",e,n,i,r)})}var wu=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{p(n.next(y))}catch(v){c(v)}}function f(y){try{p(n.throw(y))}catch(v){c(v)}}function p(y){y.done?o(y.value):i(y.value).then(a,f)}p((n=n.apply(t,e||[])).next())})};const k$e={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ote={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class C$e{constructor(e,r={},n,i){this.url=e,this.headers=r,this.bucketId=n,this.fetch=Hge(i)}uploadOrUpdate(e,r,n,i){return wu(this,void 0,void 0,function*(){try{let o;const c=Object.assign(Object.assign({},Ote),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 p=this._removeEmptyFolders(r),y=this._getFinalPath(p),v=yield this.fetch(`${this.url}/object/${y}`,Object.assign({method:e,body:o,headers:a},c!=null&&c.duplex?{duplex:c.duplex}:{})),T=yield v.json();return v.ok?{data:{path:p,id:T.Id,fullPath:T.Key},error:null}:{data:null,error:T}}catch(o){if(Nl(o))return{data:null,error:o};throw o}})}upload(e,r,n){return wu(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,r,n)})}uploadToSignedUrl(e,r,n,i){return wu(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 p=Object.assign({upsert:Ote.upsert},i),y=Object.assign(Object.assign({},this.headers),{"x-upsert":String(p.upsert)});typeof Blob<"u"&&n instanceof Blob?(f=new FormData,f.append("cacheControl",p.cacheControl),f.append("",n)):typeof FormData<"u"&&n instanceof FormData?(f=n,f.append("cacheControl",p.cacheControl)):(f=n,y["cache-control"]=`max-age=${p.cacheControl}`,y["content-type"]=p.contentType);const v=yield this.fetch(a.toString(),{method:"PUT",body:f,headers:y}),T=yield v.json();return v.ok?{data:{path:o,fullPath:T.Key},error:null}:{data:null,error:T}}catch(f){if(Nl(f))return{data:null,error:f};throw f}})}createSignedUploadUrl(e,r){return wu(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 wy(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 u7("No token returned by API");return{data:{signedUrl:c.toString(),path:e,token:a},error:null}}catch(n){if(Nl(n))return{data:null,error:n};throw n}})}update(e,r,n){return wu(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,r,n)})}move(e,r,n){return wu(this,void 0,void 0,function*(){try{return{data:yield wy(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(Nl(i))return{data:null,error:i};throw i}})}copy(e,r,n){return wu(this,void 0,void 0,function*(){try{return{data:{path:(yield wy(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(Nl(i))return{data:null,error:i};throw i}})}createSignedUrl(e,r,n){return wu(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),o=yield wy(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(Nl(i))return{data:null,error:i};throw i}})}createSignedUrls(e,r,n){return wu(this,void 0,void 0,function*(){try{const i=yield wy(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(Nl(i))return{data:null,error:i};throw i}})}download(e,r){return wu(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 VD(this.fetch,`${this.url}/${i}/${a}${c}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(a){if(Nl(a))return{data:null,error:a};throw a}})}info(e){return wu(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{const n=yield VD(this.fetch,`${this.url}/object/info/${r}`,{headers:this.headers});return{data:TV(n),error:null}}catch(n){if(Nl(n))return{data:null,error:n};throw n}})}exists(e){return wu(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{return yield A$e(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(Nl(n)&&n instanceof SV){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 p=i.join("&");return p!==""&&(p=`?${p}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${n}${p}`)}}}remove(e){return wu(this,void 0,void 0,function*(){try{return{data:yield Wge(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(r){if(Nl(r))return{data:null,error:r};throw r}})}list(e,r,n){return wu(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},k$e),r),{prefix:e||""});return{data:yield wy(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},n),error:null}}catch(i){if(Nl(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 N$e="2.7.1",I$e={"X-Client-Info":`storage-js/${N$e}`};var hw=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{p(n.next(y))}catch(v){c(v)}}function f(y){try{p(n.throw(y))}catch(v){c(v)}}function p(y){y.done?o(y.value):i(y.value).then(a,f)}p((n=n.apply(t,e||[])).next())})};class P$e{constructor(e,r={},n){this.url=e,this.headers=Object.assign(Object.assign({},I$e),r),this.fetch=Hge(n)}listBuckets(){return hw(this,void 0,void 0,function*(){try{return{data:yield VD(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(Nl(e))return{data:null,error:e};throw e}})}getBucket(e){return hw(this,void 0,void 0,function*(){try{return{data:yield VD(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(r){if(Nl(r))return{data:null,error:r};throw r}})}createBucket(e,r={public:!1}){return hw(this,void 0,void 0,function*(){try{return{data:yield wy(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(Nl(n))return{data:null,error:n};throw n}})}updateBucket(e,r){return hw(this,void 0,void 0,function*(){try{return{data:yield j$e(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(Nl(n))return{data:null,error:n};throw n}})}emptyBucket(e){return hw(this,void 0,void 0,function*(){try{return{data:yield wy(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(r){if(Nl(r))return{data:null,error:r};throw r}})}deleteBucket(e){return hw(this,void 0,void 0,function*(){try{return{data:yield Wge(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(r){if(Nl(r))return{data:null,error:r};throw r}})}}class R$e extends P$e{constructor(e,r={},n){super(e,r,n)}from(e){return new C$e(this.url,this.headers,e,this.fetch)}}const L$e="2.49.10";let $2="";typeof Deno<"u"?$2="deno":typeof document<"u"?$2="web":typeof navigator<"u"&&navigator.product==="ReactNative"?$2="react-native":$2="node";const D$e={"X-Client-Info":`supabase-js-${$2}/${L$e}`},M$e={headers:D$e},O$e={schema:"public"},F$e={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},B$e={};var $$e=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function a(y){try{p(n.next(y))}catch(v){c(v)}}function f(y){try{p(n.throw(y))}catch(v){c(v)}}function p(y){y.done?o(y.value):i(y.value).then(a,f)}p((n=n.apply(t,e||[])).next())})};const z$e=t=>{let e;return t?e=t:typeof fetch>"u"?e=Ige:e=fetch,(...r)=>e(...r)},U$e=()=>typeof Headers>"u"?Pge:Headers,V$e=(t,e,r)=>{const n=z$e(r),i=U$e();return(o,c)=>$$e(void 0,void 0,void 0,function*(){var a;const f=(a=yield e())!==null&&a!==void 0?a:t;let p=new i(c==null?void 0:c.headers);return p.has("apikey")||p.set("apikey",t),p.has("Authorization")||p.set("Authorization",`Bearer ${f}`),n(o,Object.assign(Object.assign({},c),{headers:p}))})};var q$e=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(c){c(o)})}return new(r||(r=Promise))(function(o,c){function a(y){try{p(n.next(y))}catch(v){c(v)}}function f(y){try{p(n.throw(y))}catch(v){c(v)}}function p(y){y.done?o(y.value):i(y.value).then(a,f)}p((n=n.apply(t,e||[])).next())})};function G$e(t){return t.endsWith("/")?t:t+"/"}function H$e(t,e){var r,n;const{db:i,auth:o,realtime:c,global:a}=t,{db:f,auth:p,realtime:y,global:v}=e,T={db:Object.assign(Object.assign({},f),i),auth:Object.assign(Object.assign({},p),o),realtime:Object.assign(Object.assign({},y),c),global:Object.assign(Object.assign(Object.assign({},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:()=>q$e(this,void 0,void 0,function*(){return""})};return t.accessToken?T.accessToken=t.accessToken:delete T.accessToken,T}const Kge="2.69.1",Pw=30*1e3,EV=3,I$=EV*Pw,W$e="http://localhost:9999",K$e="supabase.auth.token",Y$e={"X-Client-Info":`gotrue-js/${Kge}`},jV="X-Supabase-Api-Version",Yge={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Z$e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,X$e=6e5;class d7 extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}}function Bi(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class Q$e extends d7{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}}function J$e(t){return Bi(t)&&t.name==="AuthApiError"}class Zge extends d7{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class Rx extends d7{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n}}class gy extends Rx{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function eze(t){return Bi(t)&&t.name==="AuthSessionMissingError"}class P$ extends Rx{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class oR extends Rx{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class lR extends Rx{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 tze(t){return Bi(t)&&t.name==="AuthImplicitGrantRedirectError"}class Fte extends Rx{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 AV extends Rx{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function R$(t){return Bi(t)&&t.name==="AuthRetryableFetchError"}class Bte extends Rx{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}}class oA extends Rx{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const $te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),zte=` \r=`.split(""),rze=(()=>{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 Ute(t){const e=[],r=c=>{e.push(String.fromCodePoint(c))},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},o=c=>{sze(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 ize(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}nze(n,e)}}function sze(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 aze(t){const e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};for(let i=0;ie.push(r)),new Uint8Array(e)}function lze(t){return Math.round(Date.now()/1e3)+t}function cze(){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 Wf=()=>typeof window<"u"&&typeof document<"u",tv={tested:!1,writable:!1},lA=()=>{if(!Wf())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(tv.tested)return tv.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),tv.tested=!0,tv.writable=!0}catch{tv.tested=!0,tv.writable=!1}return tv.writable};function uze(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 Qge=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Fe(async()=>{const{default:n}=await Promise.resolve().then(()=>lT);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},dze=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Jge=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},cR=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},uR=async(t,e)=>{await t.removeItem(e)};class T3{constructor(){this.promise=new T3.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}T3.promiseConstructor=Promise;function L$(t){const e=t.split(".");if(e.length!==3)throw new oA("Invalid JWT structure");for(let n=0;n{setTimeout(()=>e(null),t)})}function fze(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 mze(t){return("0"+t.toString(16)).substr(-2)}function pze(){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,mze).join("")}async function gze(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 yze(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 gze(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function fw(t,e,r=!1){const n=pze();let i=n;r&&(i+="/PASSWORD_RECOVERY"),await Jge(t,`${e}-code-verifier`,i);const o=await yze(n);return[o,n===o?"plain":"s256"]}const xze=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function vze(t){const e=t.headers.get(jV);if(!e||!e.match(xze))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function _ze(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 bze(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 wze=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),Sze=[502,503,504];async function Vte(t){var e;if(!dze(t))throw new AV(fv(t),0);if(Sze.includes(t.status))throw new AV(fv(t),t.status);let r;try{r=await t.json()}catch(o){throw new Zge(fv(o),o)}let n;const i=vze(t);if(i&&i.getTime()>=Yge["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new Bte(fv(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new gy}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 Bte(fv(r),t.status,r.weak_password.reasons);throw new Q$e(fv(r),t.status||500,n)}const Tze=(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 Ji(t,e,r,n){var i;const o=Object.assign({},n==null?void 0:n.headers);o[jV]||(o[jV]=Yge["2024-01-01"].name),n!=null&&n.jwt&&(o.Authorization=`Bearer ${n.jwt}`);const c=(i=n==null?void 0:n.query)!==null&&i!==void 0?i:{};n!=null&&n.redirectTo&&(c.redirect_to=n.redirectTo);const a=Object.keys(c).length?"?"+new URLSearchParams(c).toString():"",f=await Eze(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 Eze(t,e,r,n,i,o){const c=Tze(e,n,i,o);let a;try{a=await t(r,Object.assign({},c))}catch(f){throw console.error(f),new AV(fv(f),0)}if(a.ok||await Vte(a),n!=null&&n.noResolveJson)return a;try{return await a.json()}catch(f){await Vte(f)}}function yy(t){var e;let r=null;Cze(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=lze(t.expires_in)));const n=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:n},error:null}}function qte(t){const e=yy(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Ny(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function jze(t){return{data:t,error:null}}function Aze(t){const{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:o}=t,c=wze(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 kze(t){return t}function Cze(t){return t.access_token&&t.refresh_token&&t.expires_in}var Nze=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i0&&(E.forEach(k=>{const P=parseInt(k.split(";")[0].split("=")[1].substring(0,1)),R=JSON.parse(k.split(";")[1].split("=")[1]);p[`${R}Page`]=P}),p.total=parseInt(T)),{data:Object.assign(Object.assign({},v),p),error:null}}catch(p){if(Bi(p))return{data:{users:[]},error:p};throw p}}async getUserById(e){try{return await Ji(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Ny})}catch(r){if(Bi(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){try{return await Ji(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Ny})}catch(n){if(Bi(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){try{return await Ji(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Ny})}catch(n){if(Bi(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){try{const{data:r,error:n}=await Ji(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(Bi(r))return{data:null,error:r};throw r}}async _deleteFactor(e){try{return{data:await Ji(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(Bi(r))return{data:null,error:r};throw r}}}const Pze={getItem:t=>lA()?globalThis.localStorage.getItem(t):null,setItem:(t,e)=>{lA()&&globalThis.localStorage.setItem(t,e)},removeItem:t=>{lA()&&globalThis.localStorage.removeItem(t)}};function Gte(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}function Rze(){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 mw={debug:!!(globalThis&&lA()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class eye extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Lze extends eye{}async function Dze(t,e,r){mw.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),mw.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){mw.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,i.name);try{return await r()}finally{mw.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,i.name)}}else{if(e===0)throw mw.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Lze(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(mw.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()}}))}Rze();const Mze={url:W$e,storageKey:K$e,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Y$e,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Hte(t,e,r){return await r()}class rk{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=rk.nextInstanceID,rk.nextInstanceID+=1,this.instanceID>0&&Wf()&&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({},Mze),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 Ize({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=Qge(i.fetch),this.lock=i.lock||Hte,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:Wf()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=Dze:this.lock=Hte,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:lA()?this.storage=Pze:(this.memoryStorage={},this.storage=Gte(this.memoryStorage)):(this.memoryStorage={},this.storage=Gte(this.memoryStorage)),Wf()&&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} (${Kge}) ${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=uze(window.location.href);let n="none";if(this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce"),Wf()&&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),tze(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 Bi(r)?{error:r}:{error:new Zge("Unexpected error during initialization",r)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,i;try{const o=await Ji(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:yy}),{data:c,error:a}=o;if(a||!c)return{data:{user:null,session:null},error:a};const f=c.session,p=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",f)),{data:{user:p,session:f},error:null}}catch(o){if(Bi(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:T}=e;let E=null,k=null;this.flowType==="pkce"&&([E,k]=await fw(this.storage,this.storageKey)),o=await Ji(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:T==null?void 0:T.emailRedirectTo,body:{email:y,password:v,data:(r=T==null?void 0:T.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:T==null?void 0:T.captchaToken},code_challenge:E,code_challenge_method:k},xform:yy})}else if("phone"in e){const{phone:y,password:v,options:T}=e;o=await Ji(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:y,password:v,data:(n=T==null?void 0:T.data)!==null&&n!==void 0?n:{},channel:(i=T==null?void 0:T.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:T==null?void 0:T.captchaToken}},xform:yy})}else throw new oR("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,p=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",f)),{data:{user:p,session:f},error:null}}catch(o){if(Bi(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 Ji(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:qte})}else if("phone"in e){const{phone:o,password:c,options:a}=e;r=await Ji(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:qte})}else throw new oR("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 P$}:(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(Bi(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 cR(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{const{data:o,error:c}=await Ji(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:yy});if(await uR(this.storage,`${this.storageKey}-code-verifier`),c)throw c;return!o||!o.session||!o.user?{data:{user:null,session:null,redirectType:null},error:new P$}:(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(Bi(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 Ji(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:yy}),{data:f,error:p}=a;return p?{data:{user:null,session:null},error:p}:!f||!f.session||!f.user?{data:{user:null,session:null},error:new P$}:(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("SIGNED_IN",f.session)),{data:f,error:p})}catch(r){if(Bi(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 p=null,y=null;this.flowType==="pkce"&&([p,y]=await fw(this.storage,this.storageKey));const{error:v}=await Ji(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:p,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:p,error:y}=await Ji(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:p==null?void 0:p.message_id},error:y}}throw new oR("You must provide either an email or phone number.")}catch(a){if(Bi(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 Ji(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:o}}),redirectTo:i,xform:yy});if(a)throw a;if(!c)throw new Error("An error occurred on token verification.");const f=c.session,p=c.user;return f!=null&&f.access_token&&(await this._saveSession(f),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",f)),{data:{user:p,session:f},error:null}}catch(i){if(Bi(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 fw(this.storage,this.storageKey)),await Ji(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:jze})}catch(o){if(Bi(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 gy;const{error:i}=await Ji(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(Bi(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 Ji(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 Ji(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 oR("You must provide either an email or phone number and a type")}catch(r){if(Bi(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 cR(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const n=e.expires_at?e.expires_at*1e3-Date.now()(!c&&p==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),c=!0,this.suppressGetSessionWarning=!0),Reflect.get(f,p,y))})}return{data:{session:e},error:null}}const{session:i,error:o}=await this._callRefreshToken(e.refresh_token);return o?{data:{session:null},error:o}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await Ji(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Ny}):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 gy}:await Ji(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:Ny})})}catch(r){if(Bi(r))return eze(r)&&(await this._removeSession(),await uR(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 gy;const c=i.session;let a=null,f=null;this.flowType==="pkce"&&e.email!=null&&([a,f]=await fw(this.storage,this.storageKey));const{data:p,error:y}=await Ji(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:Ny});if(y)throw y;return c.user=p.user,await this._saveSession(c),await this._notifyAllSubscribers("USER_UPDATED",c),{data:{user:c.user},error:null}})}catch(n){if(Bi(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 gy;const r=Date.now()/1e3;let n=r,i=!0,o=null;const{payload:c}=L$(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(Bi(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 gy;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(Bi(r))return{data:{user:null,session:null},error:r};throw r}}async _getSessionFromURL(e,r){try{if(!Wf())throw new lR("No browser detected.");if(e.error||e.error_description||e.error_code)throw new lR(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 Fte("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new lR("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 Fte("No code detected.");const{data:M,error:B}=await this._exchangeCodeForSession(e.code);if(B)throw B;const V=new URL(window.location.href);return V.searchParams.delete("code"),window.history.replaceState(window.history.state,"",V.toString()),{data:{session:M.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:i,access_token:o,refresh_token:c,expires_in:a,expires_at:f,token_type:p}=e;if(!o||!a||!c||!p)throw new lR("No session defined in URL");const y=Math.round(Date.now()/1e3),v=parseInt(a);let T=y+v;f&&(T=parseInt(f));const E=T-y;E*1e3<=Pw&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${E}s, should have been closer to ${v}s`);const k=T-v;y-k>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",k,T,y):y-k<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",k,T,y);const{data:P,error:R}=await this._getUser(o);if(R)throw R;const D={provider_token:n,provider_refresh_token:i,access_token:o,expires_in:v,expires_at:T,refresh_token:c,token_type:p,user:P.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:D,redirectType:e.type},error:null}}catch(n){if(Bi(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 cR(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&&!(J$e(a)&&(a.status===404||a.status===401||a.status===403)))return{error:a}}return e!=="others"&&(await this._removeSession(),await uR(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const r=cze(),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 fw(this.storage,this.storageKey,!0));try{return await Ji(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(Bi(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(Bi(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,p,y;const{data:v,error:T}=o;if(T)throw T;const E=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(c=e.options)===null||c===void 0?void 0:c.redirectTo,scopes:(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 Ji(this.fetch,"GET",E,{headers:this.headers,jwt:(y=(p=v.session)===null||p===void 0?void 0:p.access_token)!==null&&y!==void 0?y:void 0})});if(i)throw i;return Wf()&&!(!((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(Bi(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 Ji(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(Bi(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 fze(async i=>(i>0&&await hze(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await Ji(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:yy})),(i,o)=>{const c=200*Math.pow(2,i);return o&&R$(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(),Pw);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)/Pw);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Pw}ms, refresh threshold is ${EV} ticks`),i<=EV&&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 eye)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Wf()||!(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 fw(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 Ji(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(Bi(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:p}=await Ji(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 p?{data:null,error:p}:(e.factorType==="totp"&&(!((i=f==null?void 0:f.totp)===null||i===void 0)&&i.qr_code)&&(f.totp.qr_code=`data:image/svg+xml;utf-8,${f.totp.qr_code}`),{data:f,error:null})})}catch(r){if(Bi(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 Ji(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(Bi(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 Ji(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(Bi(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}=L$(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+X$e>Date.now()))return n;const{data:i,error:o}=await Ji(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;if(!i.keys||i.keys.length===0)throw new oA("JWKS is empty");if(this.jwks=i,this.jwks_cached_at=Date.now(),n=i.keys.find(c=>c.kid===e),!n)throw new oA("No matching signing key found in JWKS");return n}async getClaims(e,r={keys:[]}){try{let n=e;if(!n){const{data:E,error:k}=await this.getSession();if(k||!E.session)return{data:null,error:k};n=E.session.access_token}const{header:i,payload:o,signature:c,raw:{header:a,payload:f}}=L$(n);if(_ze(o.exp),!i.kid||i.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:E}=await this.getUser(n);if(E)throw E;return{data:{claims:o,header:i,signature:c},error:null}}const p=bze(i.alg),y=await this.fetchJwk(i.kid,r),v=await crypto.subtle.importKey("jwk",y,p,!0,["verify"]);if(!await crypto.subtle.verify(p,v,c,oze(`${a}.${f}`)))throw new oA("Invalid JWT signature");return{data:{claims:o,header:i,signature:c},error:null}}catch(n){if(Bi(n))return{data:null,error:n};throw n}}}rk.nextInstanceID=0;const Oze=rk;class Fze extends Oze{constructor(e){super(e)}}var Bze=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{p(n.next(y))}catch(v){c(v)}}function f(y){try{p(n.throw(y))}catch(v){c(v)}}function p(y){y.done?o(y.value):i(y.value).then(a,f)}p((n=n.apply(t,e||[])).next())})};class $ze{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=G$e(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 p=`sb-${f.hostname.split(".")[0]}-auth-token`,y={db:O$e,realtime:B$e,auth:Object.assign(Object.assign({},F$e),{storageKey:p}),global:M$e},v=H$e(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:(T,E)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(E)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((c=v.auth)!==null&&c!==void 0?c:{},this.headers,v.global.fetch),this.fetch=V$e(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 s$e(new URL("rest/v1",f).href,{headers:this.headers,schema:v.db.schema,fetch:this.fetch}),v.accessToken||this._listenForAuthEvents()}get functions(){return new DBe(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new R$e(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 Bze(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},p,y){const v={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Fze({url:this.authUrl.href,headers:Object.assign(Object.assign({},v),p),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 v$e(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 zze=(t,e,r)=>new $ze(t,e,r),Uze="lovable-preview-auth:result";function Vze(t,e){return typeof t!="object"||t===null||!("type"in t)||t.type!==Uze||!("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 qze(){var M,B,V;if(typeof window>"u")return;const t=location.hostname,r=["lovableproject.com","lovableproject-dev.com","lovable.app","gpt-eng.com","gptengineer.run"].some(G=>t===G||t.endsWith("."+G)),n="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",i=r?((M=new RegExp("^(?:id-preview(?:-[a-z0-9]+)?|project)--("+n+")(?:-dev)?(?=\\.|$)","i").exec(t))==null?void 0:M[1])??((B=new RegExp("^live--("+n+")(?:-thr_[a-z0-9]+)?(?=\\.|$)","i").exec(t))==null?void 0:B[1])??((V=new RegExp("^("+n+")(?=[.-])","i").exec(t))==null?void 0:V[1]):void 0,o=window.parent;if(!i||!(o!==null&&o!==window))return localStorage;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)$/,p=location.ancestorOrigins,y=(p==null?void 0:p[0])??(document.referrer?new URL(document.referrer).origin:""),v=y&&f.test(y)?[y]:a?["https://lovable.dev","http://localhost:3000"]:["https://lovable.dev"],T=2e3,E=()=>Math.random().toString(36).slice(2)+Date.now().toString(36),k=(G,W,Y)=>new Promise(J=>{const Q=E();let ee=!1;const le=Le=>{ee||(ee=!0,clearTimeout(Se),window.removeEventListener("message",pe),J(Le))},pe=Le=>{if(!v.includes(Le.origin))return;const Ae=Vze(Le.data,Q);Ae&&le(Ae)};window.addEventListener("message",pe);const Se=setTimeout(()=>{le(null)},T),je={type:G,requestId:Q,projectId:i,key:W};Y!==void 0&&(je.value=Y);for(const Le of v)window.parent.postMessage(je,Le)});let P=!0;const R=250,D=G=>{try{return localStorage.getItem(G)}catch{return}};return{getItem:async G=>{const W=D(G);let Y=await k("lovable-preview-auth:get",G,W??void 0);if(!Y&&P&&(await new Promise(J=>setTimeout(J,R)),Y=await k("lovable-preview-auth:get",G,W??void 0)),P=!1,Y!=null&&Y.ok&&Y.value!==null){if(Y.value==="")return W!==void 0&&D(G)===W&&localStorage.removeItem(G),null;if(W===null&&D(G)===null)try{localStorage.setItem(G,Y.value)}catch{}return Y.value}return localStorage.getItem(G)},setItem:(G,W)=>(localStorage.setItem(G,W),k("lovable-preview-auth:set",G,W).then(Y=>{Y!=null&&Y.ok&&Y.value!==null&&localStorage.getItem(G)===W&&(Y.value===""?localStorage.removeItem(G):localStorage.setItem(G,Y.value))})),removeItem:G=>{const W=D(G);return localStorage.removeItem(G),k("lovable-preview-auth:remove",G,W??void 0).then(()=>{})}}}const Gze="https://relzejiswnotikjgvjhz.supabase.co",Hze="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",Re=zze(Gze,Hze,{auth:{storage:qze(),persistSession:!0,autoRefreshToken:!0}}),jqt=Object.freeze(Object.defineProperty({__proto__:null,supabase:Re},Symbol.toStringTag,{value:"Module"})),tye=C.createContext(void 0),Wze=({children:t})=>{const[e,r]=C.useState(null),[n,i]=C.useState(null),[o,c]=C.useState(!0),[a,f]=C.useState(!0),[p,y]=C.useState(!1),[v,T]=C.useState(!1),[E,k]=C.useState(!1),[P,R]=C.useState(null),[D,M]=C.useState([]),[B,V]=C.useState(null),G=C.useRef(null),W=C.useRef(!1),Y=C.useRef(!1),J=Hs(),Q=()=>{y(!1),T(!1),k(!1),R(null),M([]),V(null),G.current=null,W.current=!1},ee=async je=>{if(W.current&&G.current===je||Y.current)return;Y.current=!0,f(!0);const Le=window.setTimeout(()=>{console.warn("Role check timeout reached — unblocking UI."),Y.current=!1,f(!1)},8e3);try{console.log("Checking roles via RPC for user:",je);const[{data:Ae,error:be},{data:me,error:Te},{data:Ne,error:Ee}]=await Promise.all([Re.rpc("has_role",{_user_id:je,_role:"admin"}),Re.rpc("has_role",{_user_id:je,_role:"brokerage_manager"}),Re.rpc("has_role",{_user_id:je,_role:"coach"})]);if(be||Te)console.error("Role RPC errors:",{isAdminError:be,isBrokerError:Te,isCoachError:Ee}),y(!1),T(!1),k(!1);else{const tt=!!Ae,at=!!me,Et=!!Ne;console.log("RPC roles result:",{adminValue:tt,brokerValue:at,coachValue:Et}),y(tt),T(at),k(Et)}G.current=je,W.current=!0,window.clearTimeout(Le),f(!1);const{data:we,error:He}=await Re.from("profiles").select("brokerage_id, is_paused, paused_reason").eq("id",je).single();if(!He&&(we!=null&&we.is_paused)){const tt=we.paused_reason;try{sessionStorage.setItem("accountPausedReason",tt||"")}catch{}await Re.auth.signOut(),Q(),J("/auth?paused=1",{replace:!0});return}if(R(!He&&we?we.brokerage_id:null),me){console.log("Fetching managed brokerages for user:",je);const{data:tt,error:at}=await Re.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",je);if(console.log("Managed brokerage assignments result:",{assignments:tt,assignmentsError:at}),at||!tt){console.error("Error fetching managed brokerage assignments:",at),M([]);return}const Et=Array.from(new Set(tt.map(Pt=>Pt.brokerage_id).filter(Boolean)));if(Et.length===0){M([]);return}const{data:vt,error:Gt}=await Re.from("brokerages").select("id, name").in("id",Et);if(console.log("Managed brokerages details result:",{brokeragesData:vt,brokeragesError:Gt}),Gt||!vt){console.error("Error fetching managed brokerages details:",Gt),M([]);return}const pt=vt.map(Pt=>({id:Pt.id,name:Pt.name})).sort((Pt,tr)=>Et.indexOf(Pt.id)-Et.indexOf(tr.id));console.log("Parsed managed brokerages:",pt),M(pt),pt.length>0&&V(Pt=>Pt??pt[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),M([]);G.current=je,W.current=!0}catch(Ae){console.error("Unexpected error in checkRoles:",Ae),Q()}finally{window.clearTimeout(Le),Y.current=!1,f(!1)}};C.useEffect(()=>{let je=!0,Le=!1;const Ae=()=>{!je||Le||(Le=!0,c(!1))},{data:{subscription:be}}=Re.auth.onAuthStateChange((Te,Ne)=>{console.log("Auth event:",Te),je&&(i(Ne),r((Ne==null?void 0:Ne.user)??null),Ae(),Te==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{J("/profile?reset=true")},100)),Ne!=null&&Ne.user?(!W.current||G.current!==Ne.user.id)&&setTimeout(()=>{ee(Ne.user.id)},0):(Q(),f(!1)))}),me=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),Ae()},8e3);return()=>{je=!1,window.clearTimeout(me),be.unsubscribe()}},[]);const le=async(je,Le)=>{var Te;const Ae=(je||"").trim().toLowerCase(),{data:be,error:me}=await Re.auth.signInWithPassword({email:Ae,password:Le});if(me)throw Vt.error(/invalid login credentials/i.test(me.message)?`That email and password don't match an account. Check the email address, or use "Forgot password" to set a new password.`:me.message),me;if((Te=be.user)!=null&&Te.id){const{data:Ne}=await Re.from("profiles").select("is_paused, paused_reason").eq("id",be.user.id).maybeSingle();if(Ne!=null&&Ne.is_paused){const Ee=Ne.paused_reason||"";try{sessionStorage.setItem("accountPausedReason",Ee)}catch{}await Re.auth.signOut(),Q(),r(null),i(null);const we=new Error(Ee?`Your account is paused. ${Ee}`:"Your account is paused. Please contact LevelUp support to reactivate it.");throw we.name="AccountPaused",Vt.error(we.message),we}}Vt.success("Welcome back!")},pe=async(je,Le,Ae)=>{var Ee;const be="https://dashboard.relevelup.com/dashboard",me=localStorage.getItem("levelup_referral_code")||null,{data:Te,error:Ne}=await Re.auth.signUp({email:je,password:Le,options:{emailRedirectTo:be,data:{name:Ae,referred_by_code:me}}});if(Ne)throw Vt.error(Ne.message),Ne;if(me&&((Ee=Te.user)!=null&&Ee.id))try{await Re.from("profiles").update({referred_by_code:me}).eq("id",Te.user.id),localStorage.removeItem("levelup_referral_code")}catch(we){console.warn("Failed to attach referral code to profile",we)}Vt.success("Account created! Welcome to LevelUp."),J("/dashboard")},Se=async()=>{try{const{data:{session:je}}=await Re.auth.getSession();if(je){const{error:Le}=await Re.auth.signOut();Le?Le.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",Le.message):(console.error("Sign out error:",Le),Vt.error(Le.message)):Vt.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");r(null),i(null),y(!1),T(!1),R(null),M([]),V(null),J("/auth")}catch(je){console.error("Unexpected sign out error:",je),J("/auth")}};return s.jsx(tye.Provider,{value:{user:e,session:n,loading:o,rolesLoading:a,signIn:le,signUp:pe,signOut:Se,isAdmin:p,isBrokerageManager:v,isCoach:E,brokerageId:P,managedBrokerages:D,selectedBrokerageId:B,setSelectedBrokerageId:V},children:t})},Hn=()=>{const t=C.useContext(tye);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t},rye=C.createContext({onlineUsers:[],totalOnline:0}),Kze=3*60*1e3,Yze=45*1e3,Zze=30*1e3,Xze=({children:t})=>{const{user:e,brokerageId:r,isAdmin:n}=Hn(),[i,o]=C.useState([]),c=C.useRef(new Date().toISOString()),a=C.useCallback(async()=>{e&&await Re.from("user_presence").upsert({user_id:e.id,last_seen_at:new Date().toISOString(),online_since:c.current,current_path:window.location.pathname},{onConflict:"user_id"})},[e==null?void 0:e.id]),f=C.useCallback(async()=>{if(!e)return;const y=new Date(Date.now()-Kze).toISOString(),{data:v}=await Re.from("user_presence").select("user_id, last_seen_at, online_since").gte("last_seen_at",y).order("last_seen_at",{ascending:!1}).limit(200);if(!(v!=null&&v.length)){o([]);return}const T=v.map(P=>P.user_id),{data:E}=await Re.from("profiles").select("id, name, email, avatar_url, brokerage_id").in("id",T),k=new Map((E||[]).map(P=>[P.id,P]));o(v.map(P=>{var D;const R=k.get(P.user_id);return{id:P.user_id,name:(R==null?void 0:R.name)||((D=R==null?void 0:R.email)==null?void 0:D.split("@")[0])||"Member",avatarUrl:(R==null?void 0:R.avatar_url)||void 0,brokerageId:(R==null?void 0:R.brokerage_id)||void 0,onlineSince:P.online_since||P.last_seen_at}}))},[e==null?void 0:e.id]);C.useEffect(()=>{if(!e){o([]);return}c.current=new Date().toISOString();let y=!1;const v=async()=>{y||(await a(),await f())};v();const T=window.setInterval(()=>{a()},Yze),E=window.setInterval(()=>{f()},Zze),k=()=>{document.visibilityState==="visible"&&v()};return document.addEventListener("visibilitychange",k),()=>{y=!0,window.clearInterval(T),window.clearInterval(E),document.removeEventListener("visibilitychange",k)}},[e==null?void 0:e.id,a,f]);const p=i.filter(y=>!!(y.id===(e==null?void 0:e.id)||n||r&&y.brokerageId===r||!r&&!y.brokerageId));return s.jsx(rye.Provider,{value:{onlineUsers:p,totalOnline:p.length},children:t})},Aqt=()=>C.useContext(rye),nye=C.createContext(void 0),rv="levelup_admin_session",ly="levelup_impersonation",D$="levelup_impersonation_return",Qze=({children:t})=>{const[e,r]=C.useState(!1),[n,i]=C.useState(null),[o,c]=C.useState(!1);C.useEffect(()=>{const p=sessionStorage.getItem(ly);if(p)try{const y=JSON.parse(p);r(!0),i(y)}catch{sessionStorage.removeItem(ly)}},[]);const a=async(p,y)=>{c(!0);try{const{data:{session:v}}=await Re.auth.getSession();if(!v)return Vt.error("No active session found"),!1;const T={access_token:v.access_token,refresh_token:v.refresh_token};sessionStorage.setItem(rv,JSON.stringify(T)),y&&sessionStorage.setItem(D$,y);const E=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:p})}),k=await E.json();if(!E.ok)throw new Error(k.error||"Failed to impersonate user");const P={id:k.targetUser.id,name:k.targetUser.name,email:k.targetUser.email};if(sessionStorage.setItem(ly,JSON.stringify(P)),k.method==="session"){const{error:R}=await Re.auth.setSession({access_token:k.access_token,refresh_token:k.refresh_token});if(R)throw console.error("Set session error:",R),sessionStorage.removeItem(rv),sessionStorage.removeItem(ly),new Error("Failed to establish impersonation session")}else{const R=k.type||"recovery",{error:D}=await Re.auth.verifyOtp({token_hash:k.token_hash,type:R});if(D)throw console.error("Verify OTP error:",D),sessionStorage.removeItem(rv),sessionStorage.removeItem(ly),new Error("Failed to establish impersonation session")}return r(!0),i(P),Vt.success(`Now viewing as ${P.name}`),window.location.href="/dashboard",!0}catch(v){return console.error("Impersonation error:",v),Vt.error(v.message||"Failed to impersonate user"),sessionStorage.removeItem(rv),sessionStorage.removeItem(ly),!1}finally{c(!1)}},f=async()=>{c(!0);try{const p=sessionStorage.getItem(rv);if(!p){await Re.auth.signOut(),window.location.href="/auth";return}const y=JSON.parse(p);await Re.auth.signOut();const{error:v}=await Re.auth.setSession({access_token:y.access_token,refresh_token:y.refresh_token});if(sessionStorage.removeItem(rv),sessionStorage.removeItem(ly),v){console.error("Failed to restore admin session:",v),Vt.error("Admin session expired, please sign in again"),window.location.href="/auth";return}r(!1),i(null),Vt.success("Returned to your account");const T=sessionStorage.getItem(D$)||"/admin/members";sessionStorage.removeItem(D$),window.location.href=T}catch(p){console.error("Stop impersonation error:",p),Vt.error("Failed to restore admin session"),sessionStorage.removeItem(rv),sessionStorage.removeItem(ly),window.location.href="/auth"}finally{c(!1)}};return s.jsx(nye.Provider,{value:{isImpersonating:e,impersonatedUser:n,startImpersonation:a,stopImpersonation:f,isLoading:o},children:t})},iye=()=>{const t=C.useContext(nye);if(t===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return t},Jze=()=>{const{isImpersonating:t,impersonatedUser:e,stopImpersonation:r,isLoading:n}=iye();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(JS,{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(Bt,{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(su,{className:"h-4 w-4 animate-spin"}):s.jsxs(s.Fragment,{children:[s.jsx(Os,{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"})]})})]})})},sye=C.createContext(void 0),pw="levelup_acting_as",dR="levelup_acting_as_self",e6e=({children:t})=>{const{user:e}=Hn(),[r,n]=C.useState(!1),[i,o]=C.useState([]),[c,a]=C.useState(null),[f,p]=C.useState({}),[y,v]=C.useState(!0),[T,E]=C.useState(()=>sessionStorage.getItem(dR)==="true");C.useEffect(()=>{if(!(e!=null&&e.id)){n(!1),o([]),a(null),p({}),v(!1);return}(async()=>{v(!0);try{const{data:B}=await Re.rpc("has_role",{_user_id:e.id,_role:"assistant"});if(!B){n(!1),o([]),a(null),p({}),v(!1);return}n(!0);const{data:V,error:G}=await Re.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",e.id);if(G||!V||V.length===0){o([]),v(!1);return}const W=V.map(Q=>Q.agent_id),{data:Y}=await Re.from("profiles").select("id, name, email, avatar_url").in("id",W),J=(Y||[]).map(Q=>({id:Q.id,name:Q.name||Q.email||"Unknown",email:Q.email||"",avatar_url:Q.avatar_url}));if(o(J),sessionStorage.getItem(dR)==="true")E(!0),a(null),p({});else{const Q=sessionStorage.getItem(pw);if(Q){const ee=J.find(le=>le.id===Q);if(ee){a(ee);const le=V.find(pe=>pe.agent_id===Q);p((le==null?void 0:le.permissions)||{})}else if(J.length>0){a(J[0]);const le=V.find(pe=>pe.agent_id===J[0].id);p((le==null?void 0:le.permissions)||{}),sessionStorage.setItem(pw,J[0].id)}}else if(J.length>0){a(J[0]);const ee=V.find(le=>le.agent_id===J[0].id);p((ee==null?void 0:ee.permissions)||{}),sessionStorage.setItem(pw,J[0].id)}}}catch(B){console.error("Error loading assistant data:",B)}finally{v(!1)}})()},[e==null?void 0:e.id]);const k=M=>{a(M),E(!1),sessionStorage.removeItem(dR),M?(sessionStorage.setItem(pw,M.id),Re.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(e==null?void 0:e.id)||"").eq("agent_id",M.id).single().then(({data:B})=>{p((B==null?void 0:B.permissions)||{})})):(sessionStorage.removeItem(pw),p({}))},P=()=>{E(!0),a(null),p({}),sessionStorage.setItem(dR,"true"),sessionStorage.removeItem(pw)},R=M=>!r||T?!0:f[M]===!0,D=r&&c&&!T?c.id:(e==null?void 0:e.id)||null;return s.jsx(sye.Provider,{value:{isAssistant:r,assignedAgents:i,actingAsAgent:c,setActingAsAgent:k,effectiveUserId:D,permissions:f,hasPermission:R,isLoading:y,isActingAsSelf:T,setActingAsSelf:P},children:t})},E3=()=>{const t=C.useContext(sye);if(t===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return t},Li=()=>{const{effectiveUserId:t}=E3();return t};var aye={exports:{}},oye={};/** * @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 sS=C;function t6e(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var r6e=typeof Object.is=="function"?Object.is:t6e,n6e=sS.useState,i6e=sS.useEffect,s6e=sS.useLayoutEffect,a6e=sS.useDebugValue;function o6e(t,e){var r=e(),n=n6e({inst:{value:r,getSnapshot:e}}),i=n[0].inst,o=n[1];return s6e(function(){i.value=r,i.getSnapshot=e,M$(i)&&o({inst:i})},[t,r,e]),i6e(function(){return M$(i)&&o({inst:i}),t(function(){M$(i)&&o({inst:i})})},[t]),a6e(r),r}function M$(t){var e=t.getSnapshot;t=t.value;try{var r=e();return!r6e(t,r)}catch{return!0}}function l6e(t,e){return e()}var c6e=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?l6e:o6e;oye.useSyncExternalStore=sS.useSyncExternalStore!==void 0?sS.useSyncExternalStore:c6e;aye.exports=oye;var u6e=aye.exports;function d6e(){return u6e.useSyncExternalStore(h6e,()=>!0,()=>!1)}function h6e(){return()=>{}}var h7="Avatar",[f6e,kqt]=Qo(h7),[m6e,lye]=f6e(h7),cye=C.forwardRef((t,e)=>{const{__scopeAvatar:r,...n}=t,[i,o]=C.useState("idle");return s.jsx(m6e,{scope:r,imageLoadingStatus:i,onImageLoadingStatusChange:o,children:s.jsx(nn.span,{...n,ref:e})})});cye.displayName=h7;var uye="AvatarImage",dye=C.forwardRef((t,e)=>{const{__scopeAvatar:r,src:n,onLoadingStatusChange:i=()=>{},...o}=t,c=lye(uye,r),a=p6e(n,o),f=vo(p=>{i(p),c.onImageLoadingStatusChange(p)});return Do(()=>{a!=="idle"&&f(a)},[a,f]),a==="loaded"?s.jsx(nn.img,{...o,ref:e,src:n}):null});dye.displayName=uye;var hye="AvatarFallback",fye=C.forwardRef((t,e)=>{const{__scopeAvatar:r,delayMs:n,...i}=t,o=lye(hye,r),[c,a]=C.useState(n===void 0);return C.useEffect(()=>{if(n!==void 0){const f=window.setTimeout(()=>a(!0),n);return()=>window.clearTimeout(f)}},[n]),c&&o.imageLoadingStatus!=="loaded"?s.jsx(nn.span,{...i,ref:e}):null});fye.displayName=hye;function Wte(t,e){return t?e?(t.src!==e&&(t.src=e),t.complete&&t.naturalWidth>0?"loaded":"loading"):"error":"idle"}function p6e(t,{referrerPolicy:e,crossOrigin:r}){const n=d6e(),i=C.useRef(null),o=n?(i.current||(i.current=new window.Image),i.current):null,[c,a]=C.useState(()=>Wte(o,t));return Do(()=>{a(Wte(o,t))},[o,t]),Do(()=>{const f=v=>()=>{a(v)};if(!o)return;const p=f("loaded"),y=f("error");return o.addEventListener("load",p),o.addEventListener("error",y),e&&(o.referrerPolicy=e),typeof r=="string"&&(o.crossOrigin=r),()=>{o.removeEventListener("load",p),o.removeEventListener("error",y)}},[o,r,e]),c}var mye=cye,pye=dye,gye=fye;const vd=C.forwardRef(({className:t,...e},r)=>s.jsx(mye,{ref:r,className:qt("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...e}));vd.displayName=mye.displayName;const _d=C.forwardRef(({className:t,...e},r)=>s.jsx(pye,{ref:r,className:qt("aspect-square h-full w-full",t),...e}));_d.displayName=pye.displayName;const bd=C.forwardRef(({className:t,...e},r)=>s.jsx(gye,{ref:r,className:qt("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...e}));bd.displayName=gye.displayName;const g6e=ZS("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 ss({className:t,variant:e,...r}){return s.jsx("div",{className:qt(g6e({variant:e}),t),...r})}var y6e=C.createContext(void 0);function S_(t){const e=C.useContext(y6e);return t||e||"ltr"}var O$="rovingFocusGroup.onEntryFocus",x6e={bubbles:!1,cancelable:!0},DC="RovingFocusGroup",[kV,yye,v6e]=vC(DC),[_6e,uT]=Qo(DC,[v6e]),[b6e,w6e]=_6e(DC),xye=C.forwardRef((t,e)=>s.jsx(kV.Provider,{scope:t.__scopeRovingFocusGroup,children:s.jsx(kV.Slot,{scope:t.__scopeRovingFocusGroup,children:s.jsx(S6e,{...t,ref:e})})}));xye.displayName=DC;var S6e=C.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:r,orientation:n,loop:i=!1,dir:o,currentTabStopId:c,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:f,onEntryFocus:p,preventScrollOnEntryFocus:y=!1,...v}=t,T=C.useRef(null),E=Yn(e,T),k=S_(o),[P,R]=yd({prop:c,defaultProp:a??null,onChange:f,caller:DC}),[D,M]=C.useState(!1),B=vo(p),V=yye(r),G=C.useRef(!1),[W,Y]=C.useState(0);return C.useEffect(()=>{const J=T.current;if(J)return J.addEventListener(O$,B),()=>J.removeEventListener(O$,B)},[B]),s.jsx(b6e,{scope:r,orientation:n,dir:k,loop:i,currentTabStopId:P,onItemFocus:C.useCallback(J=>R(J),[R]),onItemShiftTab:C.useCallback(()=>M(!0),[]),onFocusableItemAdd:C.useCallback(()=>Y(J=>J+1),[]),onFocusableItemRemove:C.useCallback(()=>Y(J=>J-1),[]),children:s.jsx(nn.div,{tabIndex:D||W===0?-1:0,"data-orientation":n,...v,ref:E,style:{outline:"none",...t.style},onMouseDown:Or(t.onMouseDown,()=>{G.current=!0}),onFocus:Or(t.onFocus,J=>{const Q=!G.current;if(J.target===J.currentTarget&&Q&&!D){const ee=new CustomEvent(O$,x6e);if(J.currentTarget.dispatchEvent(ee),!ee.defaultPrevented){const le=V().filter(Ae=>Ae.focusable),pe=le.find(Ae=>Ae.active),Se=le.find(Ae=>Ae.id===P),Le=[pe,Se,...le].filter(Boolean).map(Ae=>Ae.ref.current);bye(Le,y)}}G.current=!1}),onBlur:Or(t.onBlur,()=>M(!1))})})}),vye="RovingFocusGroupItem",_ye=C.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:r,focusable:n=!0,active:i=!1,tabStopId:o,children:c,...a}=t,f=Fl(),p=o||f,y=w6e(vye,r),v=y.currentTabStopId===p,T=yye(r),{onFocusableItemAdd:E,onFocusableItemRemove:k,currentTabStopId:P}=y;return C.useEffect(()=>{if(n)return E(),()=>k()},[n,E,k]),s.jsx(kV.ItemSlot,{scope:r,id:p,focusable:n,active:i,children:s.jsx(nn.span,{tabIndex:v?0:-1,"data-orientation":y.orientation,...a,ref:e,onMouseDown:Or(t.onMouseDown,R=>{n?y.onItemFocus(p):R.preventDefault()}),onFocus:Or(t.onFocus,()=>y.onItemFocus(p)),onKeyDown:Or(t.onKeyDown,R=>{if(R.key==="Tab"&&R.shiftKey){y.onItemShiftTab();return}if(R.target!==R.currentTarget)return;const D=j6e(R,y.orientation,y.dir);if(D!==void 0){if(R.metaKey||R.ctrlKey||R.altKey||R.shiftKey)return;R.preventDefault();let B=T().filter(V=>V.focusable).map(V=>V.ref.current);if(D==="last")B.reverse();else if(D==="prev"||D==="next"){D==="prev"&&B.reverse();const V=B.indexOf(R.currentTarget);B=y.loop?A6e(B,V+1):B.slice(V+1)}setTimeout(()=>bye(B))}}),children:typeof c=="function"?c({isCurrentTabStop:v,hasTabStop:P!=null}):c})})});_ye.displayName=vye;var T6e={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function E6e(t,e){return e!=="rtl"?t:t==="ArrowLeft"?"ArrowRight":t==="ArrowRight"?"ArrowLeft":t}function j6e(t,e,r){const n=E6e(t.key,r);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return T6e[n]}function bye(t,e=!1){const r=document.activeElement;for(const n of t)if(n===r||(n.focus({preventScroll:e}),document.activeElement!==r))return}function A6e(t,e){return t.map((r,n)=>t[(e+n)%t.length])}var f7=xye,m7=_ye,CV=["Enter"," "],k6e=["ArrowDown","PageUp","Home"],wye=["ArrowUp","PageDown","End"],C6e=[...k6e,...wye],N6e={ltr:[...CV,"ArrowRight"],rtl:[...CV,"ArrowLeft"]},I6e={ltr:["ArrowLeft"],rtl:["ArrowRight"]},MC="Menu",[nk,P6e,R6e]=vC(MC),[T_,Sye]=Qo(MC,[R6e,Ix,uT]),j3=Ix(),Tye=uT(),[L6e,E_]=T_(MC),[D6e,OC]=T_(MC),Eye=t=>{const{__scopeMenu:e,open:r=!1,children:n,dir:i,onOpenChange:o,modal:c=!0}=t,a=j3(e),[f,p]=C.useState(null),y=C.useRef(!1),v=vo(o),T=S_(i);return C.useEffect(()=>{const E=()=>{y.current=!0,document.addEventListener("pointerdown",k,{capture:!0,once:!0}),document.addEventListener("pointermove",k,{capture:!0,once:!0})},k=()=>y.current=!1;return document.addEventListener("keydown",E,{capture:!0}),()=>{document.removeEventListener("keydown",E,{capture:!0}),document.removeEventListener("pointerdown",k,{capture:!0}),document.removeEventListener("pointermove",k,{capture:!0})}},[]),s.jsx(c3,{...a,children:s.jsx(L6e,{scope:e,open:r,onOpenChange:v,content:f,onContentChange:p,children:s.jsx(D6e,{scope:e,onClose:C.useCallback(()=>v(!1),[v]),isUsingKeyboardRef:y,dir:T,modal:c,children:n})})})};Eye.displayName=MC;var M6e="MenuAnchor",p7=C.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t,i=j3(r);return s.jsx(PC,{...i,...n,ref:e})});p7.displayName=M6e;var g7="MenuPortal",[O6e,jye]=T_(g7,{forceMount:void 0}),Aye=t=>{const{__scopeMenu:e,forceMount:r,children:n,container:i}=t,o=E_(g7,e);return s.jsx(O6e,{scope:e,forceMount:r,children:s.jsx(vl,{present:r||o.open,children:s.jsx(YS,{asChild:!0,container:i,children:n})})})};Aye.displayName=g7;var oh="MenuContent",[F6e,y7]=T_(oh),kye=C.forwardRef((t,e)=>{const r=jye(oh,t.__scopeMenu),{forceMount:n=r.forceMount,...i}=t,o=E_(oh,t.__scopeMenu),c=OC(oh,t.__scopeMenu);return s.jsx(nk.Provider,{scope:t.__scopeMenu,children:s.jsx(vl,{present:n||o.open,children:s.jsx(nk.Slot,{scope:t.__scopeMenu,children:c.modal?s.jsx(B6e,{...i,ref:e}):s.jsx($6e,{...i,ref:e})})})})}),B6e=C.forwardRef((t,e)=>{const r=E_(oh,t.__scopeMenu),n=C.useRef(null),i=Yn(e,n);return C.useEffect(()=>{const o=n.current;if(o)return r3(o)},[]),s.jsx(x7,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:Or(t.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})}),$6e=C.forwardRef((t,e)=>{const r=E_(oh,t.__scopeMenu);return s.jsx(x7,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})}),z6e=ux("MenuContent.ScrollLock"),x7=C.forwardRef((t,e)=>{const{__scopeMenu:r,loop:n=!1,trapFocus:i,onOpenAutoFocus:o,onCloseAutoFocus:c,disableOutsidePointerEvents:a,onEntryFocus:f,onEscapeKeyDown:p,onPointerDownOutside:y,onFocusOutside:v,onInteractOutside:T,onDismiss:E,disableOutsideScroll:k,...P}=t,R=E_(oh,r),D=OC(oh,r),M=j3(r),B=Tye(r),V=P6e(r),[G,W]=C.useState(null),Y=C.useRef(null),J=Yn(e,Y,R.onContentChange),Q=C.useRef(0),ee=C.useRef(""),le=C.useRef(0),pe=C.useRef(null),Se=C.useRef("right"),je=C.useRef(0),Le=k?jC:C.Fragment,Ae=k?{as:z6e,allowPinchZoom:!0}:void 0,be=Te=>{var vt,Gt;const Ne=ee.current+Te,Ee=V().filter(pt=>!pt.disabled),we=document.activeElement,He=(vt=Ee.find(pt=>pt.ref.current===we))==null?void 0:vt.textValue,tt=Ee.map(pt=>pt.textValue),at=J6e(tt,Ne,He),Et=(Gt=Ee.find(pt=>pt.textValue===at))==null?void 0:Gt.ref.current;(function pt(Pt){ee.current=Pt,window.clearTimeout(Q.current),Pt!==""&&(Q.current=window.setTimeout(()=>pt(""),1e3))})(Ne),Et&&setTimeout(()=>Et.focus())};C.useEffect(()=>()=>window.clearTimeout(Q.current),[]),e3();const me=C.useCallback(Te=>{var Ee,we;return Se.current===((Ee=pe.current)==null?void 0:Ee.side)&&tUe(Te,(we=pe.current)==null?void 0:we.area)},[]);return s.jsx(F6e,{scope:r,searchRef:ee,onItemEnter:C.useCallback(Te=>{me(Te)&&Te.preventDefault()},[me]),onItemLeave:C.useCallback(Te=>{var Ne;me(Te)||((Ne=Y.current)==null||Ne.focus(),W(null))},[me]),onTriggerLeave:C.useCallback(Te=>{me(Te)&&Te.preventDefault()},[me]),pointerGraceTimerRef:le,onPointerGraceIntentChange:C.useCallback(Te=>{pe.current=Te},[]),children:s.jsx(Le,{...Ae,children:s.jsx(EC,{asChild:!0,trapped:i,onMountAutoFocus:Or(o,Te=>{var Ne;Te.preventDefault(),(Ne=Y.current)==null||Ne.focus({preventScroll:!0})}),onUnmountAutoFocus:c,children:s.jsx(v_,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:p,onPointerDownOutside:y,onFocusOutside:v,onInteractOutside:T,onDismiss:E,children:s.jsx(f7,{asChild:!0,...B,dir:D.dir,orientation:"vertical",loop:n,currentTabStopId:G,onCurrentTabStopIdChange:W,onEntryFocus:Or(f,Te=>{D.isUsingKeyboardRef.current||Te.preventDefault()}),preventScrollOnEntryFocus:!0,children:s.jsx(u3,{role:"menu","aria-orientation":"vertical","data-state":qye(R.open),"data-radix-menu-content":"",dir:D.dir,...M,...P,ref:J,style:{outline:"none",...P.style},onKeyDown:Or(P.onKeyDown,Te=>{const Ee=Te.target.closest("[data-radix-menu-content]")===Te.currentTarget,we=Te.ctrlKey||Te.altKey||Te.metaKey,He=Te.key.length===1;Ee&&(Te.key==="Tab"&&Te.preventDefault(),!we&&He&&be(Te.key));const tt=Y.current;if(Te.target!==tt||!C6e.includes(Te.key))return;Te.preventDefault();const Et=V().filter(vt=>!vt.disabled).map(vt=>vt.ref.current);wye.includes(Te.key)&&Et.reverse(),X6e(Et)}),onBlur:Or(t.onBlur,Te=>{Te.currentTarget.contains(Te.target)||(window.clearTimeout(Q.current),ee.current="")}),onPointerMove:Or(t.onPointerMove,ik(Te=>{const Ne=Te.target,Ee=je.current!==Te.clientX;if(Te.currentTarget.contains(Ne)&&Ee){const we=Te.clientX>je.current?"right":"left";Se.current=we,je.current=Te.clientX}}))})})})})})})});kye.displayName=oh;var U6e="MenuGroup",v7=C.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return s.jsx(nn.div,{role:"group",...n,ref:e})});v7.displayName=U6e;var V6e="MenuLabel",Cye=C.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return s.jsx(nn.div,{...n,ref:e})});Cye.displayName=V6e;var qD="MenuItem",Kte="menu.itemSelect",A3=C.forwardRef((t,e)=>{const{disabled:r=!1,onSelect:n,...i}=t,o=C.useRef(null),c=OC(qD,t.__scopeMenu),a=y7(qD,t.__scopeMenu),f=Yn(e,o),p=C.useRef(!1),y=()=>{const v=o.current;if(!r&&v){const T=new CustomEvent(Kte,{bubbles:!0,cancelable:!0});v.addEventListener(Kte,E=>n==null?void 0:n(E),{once:!0}),v9(v,T),T.defaultPrevented?p.current=!1:c.onClose()}};return s.jsx(Nye,{...i,ref:f,disabled:r,onClick:Or(t.onClick,y),onPointerDown:v=>{var T;(T=t.onPointerDown)==null||T.call(t,v),p.current=!0},onPointerUp:Or(t.onPointerUp,v=>{var T;p.current||(T=v.currentTarget)==null||T.click()}),onKeyDown:Or(t.onKeyDown,v=>{const T=a.searchRef.current!=="";r||T&&v.key===" "||CV.includes(v.key)&&(v.currentTarget.click(),v.preventDefault())})})});A3.displayName=qD;var Nye=C.forwardRef((t,e)=>{const{__scopeMenu:r,disabled:n=!1,textValue:i,...o}=t,c=y7(qD,r),a=Tye(r),f=C.useRef(null),p=Yn(e,f),[y,v]=C.useState(!1),[T,E]=C.useState("");return C.useEffect(()=>{const k=f.current;k&&E((k.textContent??"").trim())},[o.children]),s.jsx(nk.ItemSlot,{scope:r,disabled:n,textValue:i??T,children:s.jsx(m7,{asChild:!0,...a,focusable:!n,children:s.jsx(nn.div,{role:"menuitem","data-highlighted":y?"":void 0,"aria-disabled":n||void 0,"data-disabled":n?"":void 0,...o,ref:p,onPointerMove:Or(t.onPointerMove,ik(k=>{n?c.onItemLeave(k):(c.onItemEnter(k),k.defaultPrevented||k.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Or(t.onPointerLeave,ik(k=>c.onItemLeave(k))),onFocus:Or(t.onFocus,()=>v(!0)),onBlur:Or(t.onBlur,()=>v(!1))})})})}),q6e="MenuCheckboxItem",Iye=C.forwardRef((t,e)=>{const{checked:r=!1,onCheckedChange:n,...i}=t;return s.jsx(Mye,{scope:t.__scopeMenu,checked:r,children:s.jsx(A3,{role:"menuitemcheckbox","aria-checked":GD(r)?"mixed":r,...i,ref:e,"data-state":b7(r),onSelect:Or(i.onSelect,()=>n==null?void 0:n(GD(r)?!0:!r),{checkForDefaultPrevented:!1})})})});Iye.displayName=q6e;var Pye="MenuRadioGroup",[G6e,H6e]=T_(Pye,{value:void 0,onValueChange:()=>{}}),Rye=C.forwardRef((t,e)=>{const{value:r,onValueChange:n,...i}=t,o=vo(n);return s.jsx(G6e,{scope:t.__scopeMenu,value:r,onValueChange:o,children:s.jsx(v7,{...i,ref:e})})});Rye.displayName=Pye;var Lye="MenuRadioItem",Dye=C.forwardRef((t,e)=>{const{value:r,...n}=t,i=H6e(Lye,t.__scopeMenu),o=r===i.value;return s.jsx(Mye,{scope:t.__scopeMenu,checked:o,children:s.jsx(A3,{role:"menuitemradio","aria-checked":o,...n,ref:e,"data-state":b7(o),onSelect:Or(n.onSelect,()=>{var c;return(c=i.onValueChange)==null?void 0:c.call(i,r)},{checkForDefaultPrevented:!1})})})});Dye.displayName=Lye;var _7="MenuItemIndicator",[Mye,W6e]=T_(_7,{checked:!1}),Oye=C.forwardRef((t,e)=>{const{__scopeMenu:r,forceMount:n,...i}=t,o=W6e(_7,r);return s.jsx(vl,{present:n||GD(o.checked)||o.checked===!0,children:s.jsx(nn.span,{...i,ref:e,"data-state":b7(o.checked)})})});Oye.displayName=_7;var K6e="MenuSeparator",Fye=C.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return s.jsx(nn.div,{role:"separator","aria-orientation":"horizontal",...n,ref:e})});Fye.displayName=K6e;var Y6e="MenuArrow",Bye=C.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t,i=j3(r);return s.jsx(d3,{...i,...n,ref:e})});Bye.displayName=Y6e;var Z6e="MenuSub",[Cqt,$ye]=T_(Z6e),z2="MenuSubTrigger",zye=C.forwardRef((t,e)=>{const r=E_(z2,t.__scopeMenu),n=OC(z2,t.__scopeMenu),i=$ye(z2,t.__scopeMenu),o=y7(z2,t.__scopeMenu),c=C.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:f}=o,p={__scopeMenu:t.__scopeMenu},y=C.useCallback(()=>{c.current&&window.clearTimeout(c.current),c.current=null},[]);return C.useEffect(()=>y,[y]),C.useEffect(()=>{const v=a.current;return()=>{window.clearTimeout(v),f(null)}},[a,f]),s.jsx(p7,{asChild:!0,...p,children:s.jsx(Nye,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":i.contentId,"data-state":qye(r.open),...t,ref:Qp(e,i.onTriggerChange),onClick:v=>{var T;(T=t.onClick)==null||T.call(t,v),!(t.disabled||v.defaultPrevented)&&(v.currentTarget.focus(),r.open||r.onOpenChange(!0))},onPointerMove:Or(t.onPointerMove,ik(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:Or(t.onPointerLeave,ik(v=>{var E,k;y();const T=(E=r.content)==null?void 0:E.getBoundingClientRect();if(T){const P=(k=r.content)==null?void 0:k.dataset.side,R=P==="right",D=R?-5:5,M=T[R?"left":"right"],B=T[R?"right":"left"];o.onPointerGraceIntentChange({area:[{x:v.clientX+D,y:v.clientY},{x:M,y:T.top},{x:B,y:T.top},{x:B,y:T.bottom},{x:M,y:T.bottom}],side:P}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(v),v.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:Or(t.onKeyDown,v=>{var E;const T=o.searchRef.current!=="";t.disabled||T&&v.key===" "||N6e[n.dir].includes(v.key)&&(r.onOpenChange(!0),(E=r.content)==null||E.focus(),v.preventDefault())})})})});zye.displayName=z2;var Uye="MenuSubContent",Vye=C.forwardRef((t,e)=>{const r=jye(oh,t.__scopeMenu),{forceMount:n=r.forceMount,...i}=t,o=E_(oh,t.__scopeMenu),c=OC(oh,t.__scopeMenu),a=$ye(Uye,t.__scopeMenu),f=C.useRef(null),p=Yn(e,f);return s.jsx(nk.Provider,{scope:t.__scopeMenu,children:s.jsx(vl,{present:n||o.open,children:s.jsx(nk.Slot,{scope:t.__scopeMenu,children:s.jsx(x7,{id:a.contentId,"aria-labelledby":a.triggerId,...i,ref:p,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:Or(t.onFocusOutside,y=>{y.target!==a.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:Or(t.onEscapeKeyDown,y=>{c.onClose(),y.preventDefault()}),onKeyDown:Or(t.onKeyDown,y=>{var E;const v=y.currentTarget.contains(y.target),T=I6e[c.dir].includes(y.key);v&&T&&(o.onOpenChange(!1),(E=a.trigger)==null||E.focus(),y.preventDefault())})})})})})});Vye.displayName=Uye;function qye(t){return t?"open":"closed"}function GD(t){return t==="indeterminate"}function b7(t){return GD(t)?"indeterminate":t?"checked":"unchecked"}function X6e(t){const e=document.activeElement;for(const r of t)if(r===e||(r.focus(),document.activeElement!==e))return}function Q6e(t,e){return t.map((r,n)=>t[(e+n)%t.length])}function J6e(t,e,r){const i=e.length>1&&Array.from(e).every(p=>p===e[0])?e[0]:e,o=r?t.indexOf(r):-1;let c=Q6e(t,Math.max(o,0));i.length===1&&(c=c.filter(p=>p!==r));const f=c.find(p=>p.toLowerCase().startsWith(i.toLowerCase()));return f!==r?f:void 0}function eUe(t,e){const{x:r,y:n}=t;let i=!1;for(let o=0,c=e.length-1;on!=T>n&&r<(v-p)*(n-y)/(T-y)+p&&(i=!i)}return i}function tUe(t,e){if(!e)return!1;const r={x:t.clientX,y:t.clientY};return eUe(r,e)}function ik(t){return e=>e.pointerType==="mouse"?t(e):void 0}var rUe=Eye,nUe=p7,iUe=Aye,sUe=kye,aUe=v7,oUe=Cye,lUe=A3,cUe=Iye,uUe=Rye,dUe=Dye,hUe=Oye,fUe=Fye,mUe=Bye,pUe=zye,gUe=Vye,k3="DropdownMenu",[yUe,Nqt]=Qo(k3,[Sye]),lu=Sye(),[xUe,Gye]=yUe(k3),Hye=t=>{const{__scopeDropdownMenu:e,children:r,dir:n,open:i,defaultOpen:o,onOpenChange:c,modal:a=!0}=t,f=lu(e),p=C.useRef(null),[y,v]=yd({prop:i,defaultProp:o??!1,onChange:c,caller:k3});return s.jsx(xUe,{scope:e,triggerId:Fl(),triggerRef:p,contentId:Fl(),open:y,onOpenChange:v,onOpenToggle:C.useCallback(()=>v(T=>!T),[v]),modal:a,children:s.jsx(rUe,{...f,open:y,onOpenChange:v,dir:n,modal:a,children:r})})};Hye.displayName=k3;var Wye="DropdownMenuTrigger",Kye=C.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,disabled:n=!1,...i}=t,o=Gye(Wye,r),c=lu(r);return s.jsx(nUe,{asChild:!0,...c,children:s.jsx(nn.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:Qp(e,o.triggerRef),onPointerDown:Or(t.onPointerDown,a=>{!n&&a.button===0&&a.ctrlKey===!1&&(o.onOpenToggle(),o.open||a.preventDefault())}),onKeyDown:Or(t.onKeyDown,a=>{n||(["Enter"," "].includes(a.key)&&o.onOpenToggle(),a.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});Kye.displayName=Wye;var vUe="DropdownMenuPortal",Yye=t=>{const{__scopeDropdownMenu:e,...r}=t,n=lu(e);return s.jsx(iUe,{...n,...r})};Yye.displayName=vUe;var Zye="DropdownMenuContent",Xye=C.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=Gye(Zye,r),o=lu(r),c=C.useRef(!1);return s.jsx(sUe,{id:i.contentId,"aria-labelledby":i.triggerId,...o,...n,ref:e,onCloseAutoFocus:Or(t.onCloseAutoFocus,a=>{var f;c.current||(f=i.triggerRef.current)==null||f.focus(),c.current=!1,a.preventDefault()}),onInteractOutside:Or(t.onInteractOutside,a=>{const f=a.detail.originalEvent,p=f.button===0&&f.ctrlKey===!0,y=f.button===2||p;(!i.modal||y)&&(c.current=!0)}),style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Xye.displayName=Zye;var _Ue="DropdownMenuGroup",bUe=C.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=lu(r);return s.jsx(aUe,{...i,...n,ref:e})});bUe.displayName=_Ue;var wUe="DropdownMenuLabel",Qye=C.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=lu(r);return s.jsx(oUe,{...i,...n,ref:e})});Qye.displayName=wUe;var SUe="DropdownMenuItem",Jye=C.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=lu(r);return s.jsx(lUe,{...i,...n,ref:e})});Jye.displayName=SUe;var TUe="DropdownMenuCheckboxItem",exe=C.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=lu(r);return s.jsx(cUe,{...i,...n,ref:e})});exe.displayName=TUe;var EUe="DropdownMenuRadioGroup",jUe=C.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=lu(r);return s.jsx(uUe,{...i,...n,ref:e})});jUe.displayName=EUe;var AUe="DropdownMenuRadioItem",txe=C.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=lu(r);return s.jsx(dUe,{...i,...n,ref:e})});txe.displayName=AUe;var kUe="DropdownMenuItemIndicator",rxe=C.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=lu(r);return s.jsx(hUe,{...i,...n,ref:e})});rxe.displayName=kUe;var CUe="DropdownMenuSeparator",nxe=C.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=lu(r);return s.jsx(fUe,{...i,...n,ref:e})});nxe.displayName=CUe;var NUe="DropdownMenuArrow",IUe=C.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=lu(r);return s.jsx(mUe,{...i,...n,ref:e})});IUe.displayName=NUe;var PUe="DropdownMenuSubTrigger",ixe=C.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=lu(r);return s.jsx(pUe,{...i,...n,ref:e})});ixe.displayName=PUe;var RUe="DropdownMenuSubContent",sxe=C.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=lu(r);return s.jsx(gUe,{...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)"}})});sxe.displayName=RUe;var LUe=Hye,DUe=Kye,MUe=Yye,axe=Xye,oxe=Qye,lxe=Jye,cxe=exe,uxe=txe,dxe=rxe,hxe=nxe,fxe=ixe,mxe=sxe;const FC=LUe,BC=DUe,OUe=C.forwardRef(({className:t,inset:e,children:r,...n},i)=>s.jsxs(fxe,{ref:i,className:qt("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(jd,{className:"ml-auto h-4 w-4"})]}));OUe.displayName=fxe.displayName;const FUe=C.forwardRef(({className:t,...e},r)=>s.jsx(mxe,{ref:r,className:qt("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}));FUe.displayName=mxe.displayName;const dT=C.forwardRef(({className:t,sideOffset:e=4,...r},n)=>s.jsx(MUe,{children:s.jsx(axe,{ref:n,sideOffset:e,className:qt("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})}));dT.displayName=axe.displayName;const Nu=C.forwardRef(({className:t,inset:e,...r},n)=>s.jsx(lxe,{ref:n,className:qt("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}));Nu.displayName=lxe.displayName;const BUe=C.forwardRef(({className:t,children:e,checked:r,...n},i)=>s.jsxs(cxe,{ref:i,className:qt("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(dxe,{children:s.jsx(no,{className:"h-4 w-4"})})}),e]}));BUe.displayName=cxe.displayName;const $Ue=C.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(uxe,{ref:n,className:qt("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(dxe,{children:s.jsx(t_,{className:"h-2 w-2 fill-current"})})}),e]}));$Ue.displayName=uxe.displayName;const pxe=C.forwardRef(({className:t,inset:e,...r},n)=>s.jsx(oxe,{ref:n,className:qt("px-2 py-1.5 text-sm font-semibold",e&&"pl-8",t),...r}));pxe.displayName=oxe.displayName;const sk=C.forwardRef(({className:t,...e},r)=>s.jsx(hxe,{ref:r,className:qt("-mx-1 my-1 h-px bg-muted",t),...e}));sk.displayName=hxe.displayName;const zUe=()=>{const{isAssistant:t,actingAsAgent:e,assignedAgents:r,setActingAsAgent:n,isActingAsSelf:i,setActingAsSelf:o}=E3();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(Ml,{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(fl,{className:"h-4 w-4 flex-shrink-0"}),s.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),s.jsxs(FC,{children:[s.jsx(BC,{asChild:!0,children:s.jsxs(Bt,{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(Ml,{className:"h-4 w-4"}),s.jsx("strong",{children:"My Account"})]}):e?s.jsxs(s.Fragment,{children:[s.jsxs(vd,{className:"h-5 w-5",children:[s.jsx(_d,{src:e.avatar_url||void 0}),s.jsx(bd,{className:"text-[10px] bg-primary-foreground/30",children:c(e.name)})]}),s.jsx("strong",{children:e.name})]}):s.jsx("strong",{children:"Select..."}),s.jsx(yl,{className:"h-3 w-3"})]})}),s.jsxs(dT,{align:"start",className:"z-[2147483647]",children:[s.jsxs(Nu,{onClick:o,className:"gap-2",children:[s.jsx(Ml,{className:"h-4 w-4"}),s.jsx("span",{children:"My Account"}),i&&s.jsx(ss,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),s.jsx(sk,{}),r.map(a=>s.jsxs(Nu,{onClick:()=>n(a),className:"gap-2",children:[s.jsxs(vd,{className:"h-6 w-6",children:[s.jsx(_d,{src:a.avatar_url||void 0}),s.jsx(bd,{className:"text-[10px]",children:c(a.name)})]}),s.jsx("span",{children:a.name}),!i&&a.id===(e==null?void 0:e.id)&&s.jsx(ss,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},a.id))]})]})]}),s.jsx(ss,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:i?"Personal Mode":"Assistant Mode"})]})})};function gxe(){var f,p;const{user:t,isAdmin:e}=Hn(),{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 Re.from("partnership_memberships").select("id, status, package_id, program_id").eq("user_id",t.id).eq("status","active").maybeSingle();if(!y)return null;const[{data:v},{data:T}]=await Promise.all([Re.from("partnership_packages").select("*").eq("id",y.package_id).maybeSingle(),Re.from("partnership_programs").select("id, name, enabled, brokerage_id").eq("id",y.program_id).maybeSingle()]);return!v||!(T!=null&&T.enabled)?null:{membership:y,pkg:v,program:T}}}),i=C.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 E,k;const v=((E=r==null?void 0:r.pkg)==null?void 0:E.feature_limits)||{},T=(k=v==null?void 0:v[y])==null?void 0:k.monthly_limit;return typeof T=="number"?T:null};return{isLoading:n,isMember:o,membership:(r==null?void 0:r.membership)??null,pkg:(r==null?void 0:r.pkg)??null,program:(r==null?void 0:r.program)??null,packageKey:((f=r==null?void 0:r.pkg)==null?void 0:f.key)??null,packageName:((p=r==null?void 0:r.pkg)==null?void 0:p.name)??null,features:i,hasFeature:c,limitFor:a,isRestricted:o&&!e}}const w7={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"},Iqt=Object.keys(w7),UUe={home:null,crm:"crm",deals:"deals",listings:"listing_exchange",marketing:"marketing_studio",websites:"website",academy:"learn",events:"learn",apps:null,brokerage:"community",more:null},Yte={"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"},VUe={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 qUe(t){return t.id in Yte?Yte[t.id]:UUe[t.primaryCategory]??null}function Pqt(t){return VUe[t]??null}const GUe=[["/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 HUe(t){let e=null;for(const r of GUe){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 $n=C.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:qt("rounded-lg border bg-card text-card-foreground shadow-sm",t),...e}));$n.displayName="Card";const ud=C.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:qt("flex flex-col space-y-1.5 p-6",t),...e}));ud.displayName="CardHeader";const dd=C.forwardRef(({className:t,...e},r)=>s.jsx("h3",{ref:r,className:qt("text-2xl font-semibold leading-none tracking-tight",t),...e}));dd.displayName="CardTitle";const ak=C.forwardRef(({className:t,...e},r)=>s.jsx("p",{ref:r,className:qt("text-sm text-muted-foreground",t),...e}));ak.displayName="CardDescription";const Kn=C.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:qt("p-6 pt-0",t),...e}));Kn.displayName="CardContent";const NV=C.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:qt("flex items-center p-6 pt-0",t),...e}));NV.displayName="CardFooter";const Ad=C.forwardRef(({className:t,...e},r)=>s.jsx("textarea",{className:qt("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}));Ad.displayName="Textarea";const lo=i3,yxe=O9,WUe=s3,Rqt=CC,xxe=C.forwardRef(({className:t,...e},r)=>s.jsx(tT,{ref:r,className:qt("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}));xxe.displayName=tT.displayName;const qa=C.forwardRef(({className:t,children:e,overlayClassName:r,...n},i)=>s.jsxs(WUe,{children:[s.jsx(xxe,{className:r}),s.jsxs(rT,{ref:i,className:qt("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(CC,{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(Os,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));qa.displayName=rT.displayName;const xl=({className:t,...e})=>s.jsx("div",{className:qt("flex flex-col space-y-1.5 text-center sm:text-left",t),...e});xl.displayName="DialogHeader";const vxe=({className:t,...e})=>s.jsx("div",{className:qt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});vxe.displayName="DialogFooter";const Xo=C.forwardRef(({className:t,...e},r)=>s.jsx(AC,{ref:r,className:qt("text-lg font-semibold leading-none tracking-tight",t),...e}));Xo.displayName=AC.displayName;const wd=C.forwardRef(({className:t,...e},r)=>s.jsx(kC,{ref:r,className:qt("text-sm text-muted-foreground",t),...e}));wd.displayName=kC.displayName;function KUe({featureKey:t,open:e,onOpenChange:r}){const{user:n}=Hn(),i=Ar(),[o,c]=C.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 Re.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")),p=Sr({mutationFn:async()=>{const{error:v}=await Re.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"]}),Vt.success("Request sent — we'll be in touch shortly."),c(""),r(!1)},onError:v=>Vt.error((v==null?void 0:v.message)||"Could not send your request")}),y=w7[t]||t;return s.jsx(lo,{open:e,onOpenChange:r,children:s.jsxs(qa,{className:"sm:max-w-md",children:[s.jsxs(xl,{children:[s.jsxs(Xo,{className:"flex items-center gap-2",children:[s.jsx(xs,{className:"h-5 w-5 text-primary"}),"Request ",y]}),s.jsxs(wd,{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(no,{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(Ad,{placeholder:"Anything we should know? (optional)",value:o,onChange:v=>c(v.target.value),rows:4}),s.jsxs(vxe,{children:[s.jsx(Bt,{variant:"outline",onClick:()=>r(!1),children:"Close"}),!f&&s.jsx(Bt,{onClick:()=>p.mutate(),disabled:p.isPending,children:p.isPending?"Sending…":"Send request"})]})]})})}function YUe({featureKey:t}){const[e,r]=C.useState(!1),n=w7[t]||t;return s.jsxs("div",{className:"flex items-center justify-center py-16 px-4",children:[s.jsx($n,{className:"max-w-lg w-full border-border/60",children:s.jsxs(Kn,{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(hx,{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(Bt,{onClick:()=>r(!0),className:"gap-2",children:[s.jsx(xs,{className:"h-4 w-4"})," Request access"]})]})}),s.jsx(KUe,{featureKey:t,open:e,onOpenChange:r})]})}const ZUe=t=>{const[e,r]=C.useState(null),[n,i]=C.useState(!0);return C.useEffect(()=>{if(!t){i(!1);return}(async()=>{try{const{data:a}=await Re.storage.from("avatars").list(`${t}`);if(a&&a.length>0){const{data:f}=Re.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 Re.storage.from("avatars").list(`${t}`);if(c&&c.length>0){const{data:a}=Re.storage.from("avatars").getPublicUrl(`${t}/${c[0].name}`);r(`${a.publicUrl}?t=${Date.now()}`)}}catch(c){console.error("Error refreshing avatar:",c)}}}},Lqt=async t=>{const e=new Map;return await Promise.all(t.map(async r=>{try{const{data:n}=await Re.storage.from("avatars").list(`${r}`);if(n&&n.length>0){const{data:i}=Re.storage.from("avatars").getPublicUrl(`${r}/${n[0].name}`);e.set(r,i.publicUrl)}}catch{}})),e},XUe=t=>{const[e,r]=C.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return C.useEffect(()=>{if(!t){r(i=>({...i,loading:!1}));return}(async()=>{try{const{data:i,error:o}=await Re.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",t).single();if(o){console.error("Error fetching trial status:",o),r(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",p=c&&(i==null?void 0:i.subscription_end_date)||(i==null?void 0:i.trial_expires_at)||(i==null?void 0:i.subscription_end_date)||null;if((c||a||f)&&!!p&&p){const v=new Date().getTime(),T=new Date(p).getTime(),E=Math.ceil((T-v)/(1e3*60*60*24)),k=E<=0;r({isTrial:!0,isExpired:k,expiresAt:p,daysLeft:k?0:E,loading:!1})}else r({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(i){console.error("Error in useTrialStatus:",i),r(o=>({...o,loading:!1}))}})()},[t]),e},C3=()=>{const{data:t,isLoading:e}=mr({queryKey:["feature-flags"],queryFn:async()=>{const{data:n,error:i}=await Re.from("feature_flags").select("*");if(i)throw i;return n}}),r=n=>{if(!t)return!1;const i=t.find(o=>o.key===n);return(i==null?void 0:i.enabled)??!1};return{flags:t,isLoading:e,isFeatureEnabled:r,isAgentOSEnabled:r("agent_os_enabled"),isInnerCircleEnabled:r("innercircle_enabled"),isMarketplaceEnabled:r("marketplace")}},Zte="community_last_seen_post_at";function QUe(){const{user:t}=Hn(),e=ki(),[r,n]=C.useState(0),[i,o]=C.useState(null);C.useEffect(()=>{if(!t)return;const a=localStorage.getItem(`${Zte}_${t.id}`);o(a)},[t]),C.useEffect(()=>{if(!t)return;const a=`community_unread_count_${t.id}`,f=2*60*1e3;(async()=>{try{const E=sessionStorage.getItem(a);if(E){const k=JSON.parse(E);if(k.ts&&Date.now()-k.ts{if(!t)return;const a=Re.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async f=>{const p=f.new;if(p.user_id===t.id)return;const y=e.pathname==="/community";y||n(P=>P+1);const{data:v}=await Re.from("profiles").select("name").eq("id",p.user_id).single(),T=(v==null?void 0:v.name)||"Someone",E=p.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),k=E.length>50?E.substring(0,50)+"...":E;y||Vt("New Community Post",{description:`${T}: ${k}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{Re.removeChannel(a)}},[t,e.pathname]);const c=C.useCallback(()=>{if(!t)return;const a=new Date().toISOString();localStorage.setItem(`${Zte}_${t.id}`,a),o(a),n(0)},[t]);return C.useEffect(()=>{e.pathname==="/community"&&r>0&&c()},[e.pathname,r,c]),{unreadCount:r,markAsRead:c}}function JUe(){const{isAdmin:t}=Hn(),{data:e=0}=mr({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:r,error:n}=await Re.from("wishlist_items").select("*",{count:"exact",head:!0}).eq("status","open");if(n)throw n;return r||0},enabled:t,staleTime:6e4});return{openCount:t?e:0}}const F$=t=>`levelup:activeTeam:${t}`,eVe=()=>{const t=Li();return mr({queryKey:["user-teams",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("team_members").select("id, team_id, role").eq("user_id",t);if(r)throw r;if(!(e!=null&&e.length))return[];const{data:n,error:i}=await Re.from("teams").select("*").in("id",e.map(c=>c.team_id));if(i)throw i;const o=new Map((n||[]).map(c=>[c.id,c]));return e.filter(c=>o.has(c.team_id)).map(c=>({membershipId:c.id,teamId:c.team_id,role:c.role,team:o.get(c.team_id)})).sort((c,a)=>{var f,p;return c.role!==a.role?c.role==="team_leader"?-1:1:(((f=c.team)==null?void 0:f.name)||"").localeCompare(((p=a.team)==null?void 0:p.name)||"")})},enabled:!!t,staleTime:5*60*1e3})},hT=()=>{const t=Li(),e=eVe(),r=C.useMemo(()=>e.data||[],[e.data]),[n,i]=C.useState(()=>!t||typeof window>"u"?null:window.localStorage.getItem(F$(t)));C.useEffect(()=>{!t||typeof window>"u"||i(window.localStorage.getItem(F$(t)))},[t]);const o=C.useCallback(a=>{i(a),t&&typeof window<"u"&&window.localStorage.setItem(F$(t),a)},[t]),c=C.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}},Xte="weekly_reels";function S7(){const{user:t,loading:e,isAdmin:r}=Hn(),{data:n,isLoading:i}=mr({queryKey:["feature-entitlement",Xte,t==null?void 0:t.id],enabled:!!t&&!r,staleTime:5*60*1e3,queryFn:async()=>{const{data:o,error:c}=await Re.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",t.id).eq("feature_key",Xte).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 _xe=i3,tVe=O9,rVe=s3,bxe=C.forwardRef(({className:t,...e},r)=>s.jsx(tT,{className:qt("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}));bxe.displayName=tT.displayName;const nVe=ZS("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"}}),T7=C.forwardRef(({side:t="right",className:e,children:r,...n},i)=>s.jsxs(rVe,{children:[s.jsx(bxe,{}),s.jsxs(rT,{ref:i,className:qt(nVe({side:t}),e),...n,children:[r,s.jsxs(CC,{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(Os,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));T7.displayName=rT.displayName;const wxe=({className:t,...e})=>s.jsx("div",{className:qt("flex flex-col space-y-2 text-center sm:text-left",t),...e});wxe.displayName="SheetHeader";const iVe=({className:t,...e})=>s.jsx("div",{className:qt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});iVe.displayName="SheetFooter";const Sxe=C.forwardRef(({className:t,...e},r)=>s.jsx(AC,{ref:r,className:qt("text-lg font-semibold text-foreground",t),...e}));Sxe.displayName=AC.displayName;const Txe=C.forwardRef(({className:t,...e},r)=>s.jsx(kC,{ref:r,className:qt("text-sm text-muted-foreground",t),...e}));Txe.displayName=kC.displayName;function ok(t,[e,r]){return Math.min(r,Math.max(e,t))}function sVe(t,e){return C.useReducer((r,n)=>e[r][n]??r,t)}var E7="ScrollArea",[Exe,Dqt]=Qo(E7),[aVe,gh]=Exe(E7),jxe=C.forwardRef((t,e)=>{const{__scopeScrollArea:r,type:n="hover",dir:i,scrollHideDelay:o=600,...c}=t,[a,f]=C.useState(null),[p,y]=C.useState(null),[v,T]=C.useState(null),[E,k]=C.useState(null),[P,R]=C.useState(null),[D,M]=C.useState(0),[B,V]=C.useState(0),[G,W]=C.useState(!1),[Y,J]=C.useState(!1),Q=Yn(e,le=>f(le)),ee=S_(i);return s.jsx(aVe,{scope:r,type:n,dir:ee,scrollHideDelay:o,scrollArea:a,viewport:p,onViewportChange:y,content:v,onContentChange:T,scrollbarX:E,onScrollbarXChange:k,scrollbarXEnabled:G,onScrollbarXEnabledChange:W,scrollbarY:P,onScrollbarYChange:R,scrollbarYEnabled:Y,onScrollbarYEnabledChange:J,onCornerWidthChange:M,onCornerHeightChange:V,children:s.jsx(nn.div,{dir:ee,...c,ref:Q,style:{position:"relative","--radix-scroll-area-corner-width":D+"px","--radix-scroll-area-corner-height":B+"px",...t.style}})})});jxe.displayName=E7;var Axe="ScrollAreaViewport",kxe=C.forwardRef((t,e)=>{const{__scopeScrollArea:r,children:n,nonce:i,...o}=t,c=gh(Axe,r),a=C.useRef(null),f=Yn(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(nn.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})})]})});kxe.displayName=Axe;var Rm="ScrollAreaScrollbar",j7=C.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=gh(Rm,t.__scopeScrollArea),{onScrollbarXEnabledChange:o,onScrollbarYEnabledChange:c}=i,a=t.orientation==="horizontal";return C.useEffect(()=>(a?o(!0):c(!0),()=>{a?o(!1):c(!1)}),[a,o,c]),i.type==="hover"?s.jsx(oVe,{...n,ref:e,forceMount:r}):i.type==="scroll"?s.jsx(lVe,{...n,ref:e,forceMount:r}):i.type==="auto"?s.jsx(Cxe,{...n,ref:e,forceMount:r}):i.type==="always"?s.jsx(A7,{...n,ref:e}):null});j7.displayName=Rm;var oVe=C.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=gh(Rm,t.__scopeScrollArea),[o,c]=C.useState(!1);return C.useEffect(()=>{const a=i.scrollArea;let f=0;if(a){const p=()=>{window.clearTimeout(f),c(!0)},y=()=>{f=window.setTimeout(()=>c(!1),i.scrollHideDelay)};return a.addEventListener("pointerenter",p),a.addEventListener("pointerleave",y),()=>{window.clearTimeout(f),a.removeEventListener("pointerenter",p),a.removeEventListener("pointerleave",y)}}},[i.scrollArea,i.scrollHideDelay]),s.jsx(vl,{present:r||o,children:s.jsx(Cxe,{"data-state":o?"visible":"hidden",...n,ref:e})})}),lVe=C.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=gh(Rm,t.__scopeScrollArea),o=t.orientation==="horizontal",c=I3(()=>f("SCROLL_END"),100),[a,f]=sVe("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 C.useEffect(()=>{if(a==="idle"){const p=window.setTimeout(()=>f("HIDE"),i.scrollHideDelay);return()=>window.clearTimeout(p)}},[a,i.scrollHideDelay,f]),C.useEffect(()=>{const p=i.viewport,y=o?"scrollLeft":"scrollTop";if(p){let v=p[y];const T=()=>{const E=p[y];v!==E&&(f("SCROLL"),c()),v=E};return p.addEventListener("scroll",T),()=>p.removeEventListener("scroll",T)}},[i.viewport,o,f,c]),s.jsx(vl,{present:r||a!=="hidden",children:s.jsx(A7,{"data-state":a==="hidden"?"hidden":"visible",...n,ref:e,onPointerEnter:Or(t.onPointerEnter,()=>f("POINTER_ENTER")),onPointerLeave:Or(t.onPointerLeave,()=>f("POINTER_LEAVE"))})})}),Cxe=C.forwardRef((t,e)=>{const r=gh(Rm,t.__scopeScrollArea),{forceMount:n,...i}=t,[o,c]=C.useState(!1),a=t.orientation==="horizontal",f=I3(()=>{if(r.viewport){const p=r.viewport.offsetWidth{const{orientation:r="vertical",...n}=t,i=gh(Rm,t.__scopeScrollArea),o=C.useRef(null),c=C.useRef(0),[a,f]=C.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),p=Lxe(a.viewport,a.content),y={...n,sizes:a,onSizesChange:f,hasThumb:p>0&&p<1,onThumbChange:T=>o.current=T,onThumbPointerUp:()=>c.current=0,onThumbPointerDown:T=>c.current=T};function v(T,E){return mVe(T,c.current,a,E)}return r==="horizontal"?s.jsx(cVe,{...y,ref:e,onThumbPositionChange:()=>{if(i.viewport&&o.current){const T=i.viewport.scrollLeft,E=Qte(T,a,i.dir);o.current.style.transform=`translate3d(${E}px, 0, 0)`}},onWheelScroll:T=>{i.viewport&&(i.viewport.scrollLeft=T)},onDragScroll:T=>{i.viewport&&(i.viewport.scrollLeft=v(T,i.dir))}}):r==="vertical"?s.jsx(uVe,{...y,ref:e,onThumbPositionChange:()=>{if(i.viewport&&o.current){const T=i.viewport.scrollTop,E=Qte(T,a);o.current.style.transform=`translate3d(0, ${E}px, 0)`}},onWheelScroll:T=>{i.viewport&&(i.viewport.scrollTop=T)},onDragScroll:T=>{i.viewport&&(i.viewport.scrollTop=v(T))}}):null}),cVe=C.forwardRef((t,e)=>{const{sizes:r,onSizesChange:n,...i}=t,o=gh(Rm,t.__scopeScrollArea),[c,a]=C.useState(),f=C.useRef(null),p=Yn(e,f,o.onScrollbarXChange);return C.useEffect(()=>{f.current&&a(getComputedStyle(f.current))},[f]),s.jsx(Ixe,{"data-orientation":"horizontal",...i,ref:p,sizes:r,style:{bottom:0,left:o.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:o.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":N3(r)+"px",...t.style},onThumbPointerDown:y=>t.onThumbPointerDown(y.x),onDragScroll:y=>t.onDragScroll(y.x),onWheelScroll:(y,v)=>{if(o.viewport){const T=o.viewport.scrollLeft+y.deltaX;t.onWheelScroll(T),Mxe(T,v)&&y.preventDefault()}},onResize:()=>{f.current&&o.viewport&&c&&n({content:o.viewport.scrollWidth,viewport:o.viewport.offsetWidth,scrollbar:{size:f.current.clientWidth,paddingStart:WD(c.paddingLeft),paddingEnd:WD(c.paddingRight)}})}})}),uVe=C.forwardRef((t,e)=>{const{sizes:r,onSizesChange:n,...i}=t,o=gh(Rm,t.__scopeScrollArea),[c,a]=C.useState(),f=C.useRef(null),p=Yn(e,f,o.onScrollbarYChange);return C.useEffect(()=>{f.current&&a(getComputedStyle(f.current))},[f]),s.jsx(Ixe,{"data-orientation":"vertical",...i,ref:p,sizes:r,style:{top:0,right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":N3(r)+"px",...t.style},onThumbPointerDown:y=>t.onThumbPointerDown(y.y),onDragScroll:y=>t.onDragScroll(y.y),onWheelScroll:(y,v)=>{if(o.viewport){const T=o.viewport.scrollTop+y.deltaY;t.onWheelScroll(T),Mxe(T,v)&&y.preventDefault()}},onResize:()=>{f.current&&o.viewport&&c&&n({content:o.viewport.scrollHeight,viewport:o.viewport.offsetHeight,scrollbar:{size:f.current.clientHeight,paddingStart:WD(c.paddingTop),paddingEnd:WD(c.paddingBottom)}})}})}),[dVe,Nxe]=Exe(Rm),Ixe=C.forwardRef((t,e)=>{const{__scopeScrollArea:r,sizes:n,hasThumb:i,onThumbChange:o,onThumbPointerUp:c,onThumbPointerDown:a,onThumbPositionChange:f,onDragScroll:p,onWheelScroll:y,onResize:v,...T}=t,E=gh(Rm,r),[k,P]=C.useState(null),R=Yn(e,Q=>P(Q)),D=C.useRef(null),M=C.useRef(""),B=E.viewport,V=n.content-n.viewport,G=vo(y),W=vo(f),Y=I3(v,10);function J(Q){if(D.current){const ee=Q.clientX-D.current.left,le=Q.clientY-D.current.top;p({x:ee,y:le})}}return C.useEffect(()=>{const Q=ee=>{const le=ee.target;(k==null?void 0:k.contains(le))&&G(ee,V)};return document.addEventListener("wheel",Q,{passive:!1}),()=>document.removeEventListener("wheel",Q,{passive:!1})},[B,k,V,G]),C.useEffect(W,[n,W]),aS(k,Y),aS(E.content,Y),s.jsx(dVe,{scope:r,scrollbar:k,hasThumb:i,onThumbChange:vo(o),onThumbPointerUp:vo(c),onThumbPositionChange:W,onThumbPointerDown:vo(a),children:s.jsx(nn.div,{...T,ref:R,style:{position:"absolute",...T.style},onPointerDown:Or(t.onPointerDown,Q=>{Q.button===0&&(Q.target.setPointerCapture(Q.pointerId),D.current=k.getBoundingClientRect(),M.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",E.viewport&&(E.viewport.style.scrollBehavior="auto"),J(Q))}),onPointerMove:Or(t.onPointerMove,J),onPointerUp:Or(t.onPointerUp,Q=>{const ee=Q.target;ee.hasPointerCapture(Q.pointerId)&&ee.releasePointerCapture(Q.pointerId),document.body.style.webkitUserSelect=M.current,E.viewport&&(E.viewport.style.scrollBehavior=""),D.current=null})})})}),HD="ScrollAreaThumb",Pxe=C.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=Nxe(HD,t.__scopeScrollArea);return s.jsx(vl,{present:r||i.hasThumb,children:s.jsx(hVe,{ref:e,...n})})}),hVe=C.forwardRef((t,e)=>{const{__scopeScrollArea:r,style:n,...i}=t,o=gh(HD,r),c=Nxe(HD,r),{onThumbPositionChange:a}=c,f=Yn(e,v=>c.onThumbChange(v)),p=C.useRef(void 0),y=I3(()=>{p.current&&(p.current(),p.current=void 0)},100);return C.useEffect(()=>{const v=o.viewport;if(v){const T=()=>{if(y(),!p.current){const E=pVe(v,a);p.current=E,a()}};return a(),v.addEventListener("scroll",T),()=>v.removeEventListener("scroll",T)}},[o.viewport,y,a]),s.jsx(nn.div,{"data-state":c.hasThumb?"visible":"hidden",...i,ref:f,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...n},onPointerDownCapture:Or(t.onPointerDownCapture,v=>{const E=v.target.getBoundingClientRect(),k=v.clientX-E.left,P=v.clientY-E.top;c.onThumbPointerDown({x:k,y:P})}),onPointerUp:Or(t.onPointerUp,c.onThumbPointerUp)})});Pxe.displayName=HD;var k7="ScrollAreaCorner",Rxe=C.forwardRef((t,e)=>{const r=gh(k7,t.__scopeScrollArea),n=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&n?s.jsx(fVe,{...t,ref:e}):null});Rxe.displayName=k7;var fVe=C.forwardRef((t,e)=>{const{__scopeScrollArea:r,...n}=t,i=gh(k7,r),[o,c]=C.useState(0),[a,f]=C.useState(0),p=!!(o&&a);return aS(i.scrollbarX,()=>{var v;const y=((v=i.scrollbarX)==null?void 0:v.offsetHeight)||0;i.onCornerHeightChange(y),f(y)}),aS(i.scrollbarY,()=>{var v;const y=((v=i.scrollbarY)==null?void 0:v.offsetWidth)||0;i.onCornerWidthChange(y),c(y)}),p?s.jsx(nn.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 WD(t){return t?parseInt(t,10):0}function Lxe(t,e){const r=t/e;return isNaN(r)?0:r}function N3(t){const e=Lxe(t.viewport,t.content),r=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,n=(t.scrollbar.size-r)*e;return Math.max(n,18)}function mVe(t,e,r,n="ltr"){const i=N3(r),o=i/2,c=e||o,a=i-c,f=r.scrollbar.paddingStart+c,p=r.scrollbar.size-r.scrollbar.paddingEnd-a,y=r.content-r.viewport,v=n==="ltr"?[0,y]:[y*-1,0];return Dxe([f,p],v)(t)}function Qte(t,e,r="ltr"){const n=N3(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],p=ok(t,f);return Dxe([0,c],[0,a])(p)}function Dxe(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 Mxe(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 I3(t,e){const r=vo(t),n=C.useRef(0);return C.useEffect(()=>()=>window.clearTimeout(n.current),[]),C.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(r,e)},[r,e])}function aS(t,e){const r=vo(e);Do(()=>{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 Oxe=jxe,gVe=kxe,yVe=Rxe;const Lm=C.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(Oxe,{ref:n,className:qt("relative overflow-hidden",t),...r,children:[s.jsx(gVe,{className:"h-full w-full rounded-[inherit]",children:e}),s.jsx(Fxe,{}),s.jsx(yVe,{})]}));Lm.displayName=Oxe.displayName;const Fxe=C.forwardRef(({className:t,orientation:e="vertical",...r},n)=>s.jsx(j7,{ref:n,orientation:e,className:qt("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(Pxe,{className:"relative flex-1 rounded-full bg-border"})}));Fxe.displayName=j7.displayName;const xVe="/assets/levelup-logo-Eif24dqY.png",vVe="/assets/levelup-logo-icon-C-7iromj.png",_Ve="/assets/levelup-logo-mobile-B9skSjUG.png";var $C=t=>t.type==="checkbox",Ev=t=>t instanceof Date,Yc=t=>t==null;const Bxe=t=>typeof t=="object";var Lo=t=>!Yc(t)&&!Array.isArray(t)&&Bxe(t)&&!Ev(t),$xe=t=>Lo(t)&&t.target?$C(t.target)?t.target.checked:t.target.value:t,bVe=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,zxe=(t,e)=>t.has(bVe(e)),wVe=t=>{const e=t.constructor&&t.constructor.prototype;return Lo(e)&&e.hasOwnProperty("isPrototypeOf")},C7=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function al(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(!(C7&&(t instanceof Blob||n))&&(r||Lo(t)))if(e=r?[]:{},!r&&!wVe(t))e=t;else for(const i in t)t.hasOwnProperty(i)&&(e[i]=al(t[i]));else return t;return e}var P3=t=>/^\w*$/.test(t),ko=t=>t===void 0,N7=t=>Array.isArray(t)?t.filter(Boolean):[],I7=t=>N7(t.replace(/["|']|\]/g,"").split(/\.|\[/)),hn=(t,e,r)=>{if(!e||!Lo(t))return r;const n=(P3(e)?[e]:I7(e)).reduce((i,o)=>Yc(i)?i:i[o],t);return ko(n)||n===t?ko(t[e])?r:t[e]:n},sd=t=>typeof t=="boolean",$s=(t,e,r)=>{let n=-1;const i=P3(e)?[e]:I7(e),o=i.length,c=o-1;for(;++nXe.useContext(P7),SVe=t=>{const{children:e,...r}=t;return Xe.createElement(P7.Provider,{value:r},e)};var Uxe=(t,e,r,n=!0)=>{const i={defaultValues:e._defaultValues};for(const o in t)Object.defineProperty(i,o,{get:()=>{const c=o;return e._proxyFormState[c]!==tf.all&&(e._proxyFormState[c]=!n||tf.all),r&&(r[c]=!0),t[c]}});return i};const R7=typeof window<"u"?Xe.useLayoutEffect:Xe.useEffect;function TVe(t){const e=R3(),{control:r=e.control,disabled:n,name:i,exact:o}=t||{},[c,a]=Xe.useState(r._formState),f=Xe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return R7(()=>r._subscribe({name:i,formState:f.current,exact:o,callback:p=>{!n&&a({...r._formState,...p})}}),[i,n,o]),Xe.useEffect(()=>{f.current.isValid&&r._setValid(!0)},[r]),Xe.useMemo(()=>Uxe(c,r,f.current,!1),[c,r])}var cm=t=>typeof t=="string",Vxe=(t,e,r,n,i)=>cm(t)?(n&&e.watch.add(t),hn(r,t,i)):Array.isArray(t)?t.map(o=>(n&&e.watch.add(o),hn(r,o))):(n&&(e.watchAll=!0),r),IV=t=>Yc(t)||!Bxe(t);function Pp(t,e,r=new WeakSet){if(IV(t)||IV(e))return t===e;if(Ev(t)&&Ev(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(Ev(c)&&Ev(a)||Lo(c)&&Lo(a)||Array.isArray(c)&&Array.isArray(a)?!Pp(c,a,r):c!==a)return!1}}return!0}function EVe(t){const e=R3(),{control:r=e.control,name:n,defaultValue:i,disabled:o,exact:c,compute:a}=t||{},f=Xe.useRef(i),p=Xe.useRef(a),y=Xe.useRef(void 0);p.current=a;const v=Xe.useMemo(()=>r._getWatch(n,f.current),[r,n]),[T,E]=Xe.useState(p.current?p.current(v):v);return R7(()=>r._subscribe({name:n,formState:{values:!0},exact:c,callback:k=>{if(!o){const P=Vxe(n,r._names,k.values||r._formValues,!1,f.current);if(p.current){const R=p.current(P);Pp(R,y.current)||(E(R),y.current=R)}else E(P)}}}),[r,o,n,c]),Xe.useEffect(()=>r._removeUnmounted()),T}function jVe(t){const e=R3(),{name:r,disabled:n,control:i=e.control,shouldUnregister:o,defaultValue:c}=t,a=zxe(i._names.array,r),f=Xe.useMemo(()=>hn(i._formValues,r,hn(i._defaultValues,r,c)),[i,r,c]),p=EVe({control:i,name:r,defaultValue:f,exact:!0}),y=TVe({control:i,name:r,exact:!0}),v=Xe.useRef(t),T=Xe.useRef(i.register(r,{...t.rules,value:p,...sd(t.disabled)?{disabled:t.disabled}:{}}));v.current=t;const E=Xe.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!hn(y.errors,r)},isDirty:{enumerable:!0,get:()=>!!hn(y.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!hn(y.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!hn(y.validatingFields,r)},error:{enumerable:!0,get:()=>hn(y.errors,r)}}),[y,r]),k=Xe.useCallback(M=>T.current.onChange({target:{value:$xe(M),name:r},type:KD.CHANGE}),[r]),P=Xe.useCallback(()=>T.current.onBlur({target:{value:hn(i._formValues,r),name:r},type:KD.BLUR}),[r,i._formValues]),R=Xe.useCallback(M=>{const B=hn(i._fields,r);B&&M&&(B._f.ref={focus:()=>M.focus&&M.focus(),select:()=>M.select&&M.select(),setCustomValidity:V=>M.setCustomValidity(V),reportValidity:()=>M.reportValidity()})},[i._fields,r]),D=Xe.useMemo(()=>({name:r,value:p,...sd(n)||y.disabled?{disabled:y.disabled||n}:{},onChange:k,onBlur:P,ref:R}),[r,n,y.disabled,k,P,R,p]);return Xe.useEffect(()=>{const M=i._options.shouldUnregister||o;i.register(r,{...v.current.rules,...sd(v.current.disabled)?{disabled:v.current.disabled}:{}});const B=(V,G)=>{const W=hn(i._fields,V);W&&W._f&&(W._f.mount=G)};if(B(r,!0),M){const V=al(hn(i._options.defaultValues,r));$s(i._defaultValues,r,V),ko(hn(i._formValues,r))&&$s(i._formValues,r,V)}return!a&&i.register(r),()=>{(a?M&&!i._state.action:M)?i.unregister(r):B(r,!1)}},[r,i,a,o]),Xe.useEffect(()=>{i._setDisabledField({disabled:n,name:r})},[n,r,i]),Xe.useMemo(()=>({field:D,formState:y,fieldState:E}),[D,y,E])}const AVe=t=>t.render(jVe(t));var qxe=(t,e,r,n,i)=>e?{...r[t],types:{...r[t]&&r[t].types?r[t].types:{},[n]:i||!0}}:{},cA=t=>Array.isArray(t)?t:[t],Jte=()=>{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=[]}}},ju=t=>Lo(t)&&!Object.keys(t).length,L7=t=>t.type==="file",rf=t=>typeof t=="function",YD=t=>{if(!C7)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},Gxe=t=>t.type==="select-multiple",D7=t=>t.type==="radio",kVe=t=>D7(t)||$C(t),B$=t=>YD(t)&&t.isConnected;function CVe(t,e){const r=e.slice(0,-1).length;let n=0;for(;n{for(const e in t)if(rf(t[e]))return!0;return!1};function ZD(t,e={}){const r=Array.isArray(t);if(Lo(t)||r)for(const n in t)Array.isArray(t[n])||Lo(t[n])&&!Hxe(t[n])?(e[n]=Array.isArray(t[n])?[]:{},ZD(t[n],e[n])):Yc(t[n])||(e[n]=!0);return e}function Wxe(t,e,r){const n=Array.isArray(t);if(Lo(t)||n)for(const i in t)Array.isArray(t[i])||Lo(t[i])&&!Hxe(t[i])?ko(e)||IV(r[i])?r[i]=Array.isArray(t[i])?ZD(t[i],[]):{...ZD(t[i])}:Wxe(t[i],Yc(e)?{}:e[i],r[i]):r[i]=!Pp(t[i],e[i]);return r}var s2=(t,e)=>Wxe(t,e,ZD(e));const ere={value:!1,isValid:!1},tre={value:!0,isValid:!0};var Kxe=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&&!ko(t[0].attributes.value)?ko(t[0].value)||t[0].value===""?tre:{value:t[0].value,isValid:!0}:tre:ere}return ere},Yxe=(t,{valueAsNumber:e,valueAsDate:r,setValueAs:n})=>ko(t)?t:e?t===""?NaN:t&&+t:r&&cm(t)?new Date(t):n?n(t):t;const rre={isValid:!1,value:null};var Zxe=t=>Array.isArray(t)?t.reduce((e,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:e,rre):rre;function nre(t){const e=t.ref;return L7(e)?e.files:D7(e)?Zxe(t.refs).value:Gxe(e)?[...e.selectedOptions].map(({value:r})=>r):$C(e)?Kxe(t.refs).value:Yxe(ko(e.value)?t.ref.value:e.value,t)}var IVe=(t,e,r,n)=>{const i={};for(const o of t){const c=hn(e,o);c&&$s(i,o,c._f)}return{criteriaMode:r,names:[...t],fields:i,shouldUseNativeValidation:n}},XD=t=>t instanceof RegExp,a2=t=>ko(t)?t:XD(t)?t.source:Lo(t)?XD(t.value)?t.value.source:t.value:t,ire=t=>({isOnSubmit:!t||t===tf.onSubmit,isOnBlur:t===tf.onBlur,isOnChange:t===tf.onChange,isOnAll:t===tf.all,isOnTouch:t===tf.onTouched});const sre="AsyncFunction";var PVe=t=>!!t&&!!t.validate&&!!(rf(t.validate)&&t.validate.constructor.name===sre||Lo(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===sre)),RVe=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate),are=(t,e,r)=>!r&&(e.watchAll||e.watch.has(t)||[...e.watch].some(n=>t.startsWith(n)&&/^\.\w+/.test(t.slice(n.length))));const uA=(t,e,r,n)=>{for(const i of r||Object.keys(t)){const o=hn(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(uA(a,e))break}else if(Lo(a)&&uA(a,e))break}}};function ore(t,e,r){const n=hn(t,r);if(n||P3(r))return{error:n,name:r};const i=r.split(".");for(;i.length;){const o=i.join("."),c=hn(e,o),a=hn(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 LVe=(t,e,r,n)=>{r(t);const{name:i,...o}=t;return ju(o)||Object.keys(o).length>=Object.keys(e).length||Object.keys(o).find(c=>e[c]===(!n||tf.all))},DVe=(t,e,r)=>!t||!e||t===e||cA(t).some(n=>n&&(r?n===e:n.startsWith(e)||e.startsWith(n))),MVe=(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,OVe=(t,e)=>!N7(hn(t,e)).length&&zo(t,e),FVe=(t,e,r)=>{const n=cA(hn(t,r));return $s(n,"root",e[r]),$s(t,r,n),t},CL=t=>cm(t);function lre(t,e,r="validate"){if(CL(t)||Array.isArray(t)&&t.every(CL)||sd(t)&&!t)return{type:r,message:CL(t)?t:"",ref:e}}var gw=t=>Lo(t)&&!XD(t)?t:{value:t,message:""},cre=async(t,e,r,n,i,o)=>{const{ref:c,refs:a,required:f,maxLength:p,minLength:y,min:v,max:T,pattern:E,validate:k,name:P,valueAsNumber:R,mount:D}=t._f,M=hn(r,P);if(!D||e.has(P))return{};const B=a?a[0]:c,V=pe=>{i&&B.reportValidity&&(B.setCustomValidity(sd(pe)?"":pe||""),B.reportValidity())},G={},W=D7(c),Y=$C(c),J=W||Y,Q=(R||L7(c))&&ko(c.value)&&ko(M)||YD(c)&&c.value===""||M===""||Array.isArray(M)&&!M.length,ee=qxe.bind(null,P,n,G),le=(pe,Se,je,Le=gp.maxLength,Ae=gp.minLength)=>{const be=pe?Se:je;G[P]={type:pe?Le:Ae,message:be,ref:c,...ee(pe?Le:Ae,be)}};if(o?!Array.isArray(M)||!M.length:f&&(!J&&(Q||Yc(M))||sd(M)&&!M||Y&&!Kxe(a).isValid||W&&!Zxe(a).isValid)){const{value:pe,message:Se}=CL(f)?{value:!!f,message:f}:gw(f);if(pe&&(G[P]={type:gp.required,message:Se,ref:B,...ee(gp.required,Se)},!n))return V(Se),G}if(!Q&&(!Yc(v)||!Yc(T))){let pe,Se;const je=gw(T),Le=gw(v);if(!Yc(M)&&!isNaN(M)){const Ae=c.valueAsNumber||M&&+M;Yc(je.value)||(pe=Ae>je.value),Yc(Le.value)||(Se=Aenew Date(new Date().toDateString()+" "+Ne),me=c.type=="time",Te=c.type=="week";cm(je.value)&&M&&(pe=me?be(M)>be(je.value):Te?M>je.value:Ae>new Date(je.value)),cm(Le.value)&&M&&(Se=me?be(M)+pe.value,Le=!Yc(Se.value)&&M.length<+Se.value;if((je||Le)&&(le(je,pe.message,Se.message),!n))return V(G[P].message),G}if(E&&!Q&&cm(M)){const{value:pe,message:Se}=gw(E);if(XD(pe)&&!M.match(pe)&&(G[P]={type:gp.pattern,message:Se,ref:c,...ee(gp.pattern,Se)},!n))return V(Se),G}if(k){if(rf(k)){const pe=await k(M,r),Se=lre(pe,B);if(Se&&(G[P]={...Se,...ee(gp.validate,Se.message)},!n))return V(Se.message),G}else if(Lo(k)){let pe={};for(const Se in k){if(!ju(pe)&&!n)break;const je=lre(await k[Se](M,r),B,Se);je&&(pe={...je,...ee(Se,je.message)},V(je.message),n&&(G[P]=pe))}if(!ju(pe)&&(G[P]={ref:B,...pe},!n))return G}}return V(!0),G};const BVe={mode:tf.onSubmit,reValidateMode:tf.onChange,shouldFocusError:!0};function $Ve(t={}){let e={...BVe,...t},r={submitCount:0,isDirty:!1,isReady:!1,isLoading:rf(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1},n={},i=Lo(e.defaultValues)||Lo(e.values)?al(e.defaultValues||e.values)||{}:{},o=e.shouldUnregister?{}:al(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,p=0;const y={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let v={...y};const T={array:Jte(),state:Jte()},E=e.criteriaMode===tf.all,k=ct=>jt=>{clearTimeout(p),p=setTimeout(ct,jt)},P=async ct=>{if(!e.disabled&&(y.isValid||v.isValid||ct)){const jt=e.resolver?ju((await Y()).errors):await Q(n,!0);jt!==r.isValid&&T.state.next({isValid:jt})}},R=(ct,jt)=>{!e.disabled&&(y.isValidating||y.validatingFields||v.isValidating||v.validatingFields)&&((ct||Array.from(a.mount)).forEach(er=>{er&&(jt?$s(r.validatingFields,er,jt):zo(r.validatingFields,er))}),T.state.next({validatingFields:r.validatingFields,isValidating:!ju(r.validatingFields)}))},D=(ct,jt=[],er,Pr,dr=!0,ar=!0)=>{if(Pr&&er&&!e.disabled){if(c.action=!0,ar&&Array.isArray(hn(n,ct))){const Nt=er(hn(n,ct),Pr.argA,Pr.argB);dr&&$s(n,ct,Nt)}if(ar&&Array.isArray(hn(r.errors,ct))){const Nt=er(hn(r.errors,ct),Pr.argA,Pr.argB);dr&&$s(r.errors,ct,Nt),OVe(r.errors,ct)}if((y.touchedFields||v.touchedFields)&&ar&&Array.isArray(hn(r.touchedFields,ct))){const Nt=er(hn(r.touchedFields,ct),Pr.argA,Pr.argB);dr&&$s(r.touchedFields,ct,Nt)}(y.dirtyFields||v.dirtyFields)&&(r.dirtyFields=s2(i,o)),T.state.next({name:ct,isDirty:le(ct,jt),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else $s(o,ct,jt)},M=(ct,jt)=>{$s(r.errors,ct,jt),T.state.next({errors:r.errors})},B=ct=>{r.errors=ct,T.state.next({errors:r.errors,isValid:!1})},V=(ct,jt,er,Pr)=>{const dr=hn(n,ct);if(dr){const ar=hn(o,ct,ko(er)?hn(i,ct):er);ko(ar)||Pr&&Pr.defaultChecked||jt?$s(o,ct,jt?ar:nre(dr._f)):je(ct,ar),c.mount&&P()}},G=(ct,jt,er,Pr,dr)=>{let ar=!1,Nt=!1;const gr={name:ct};if(!e.disabled){if(!er||Pr){(y.isDirty||v.isDirty)&&(Nt=r.isDirty,r.isDirty=gr.isDirty=le(),ar=Nt!==gr.isDirty);const En=Pp(hn(i,ct),jt);Nt=!!hn(r.dirtyFields,ct),En?zo(r.dirtyFields,ct):$s(r.dirtyFields,ct,!0),gr.dirtyFields=r.dirtyFields,ar=ar||(y.dirtyFields||v.dirtyFields)&&Nt!==!En}if(er){const En=hn(r.touchedFields,ct);En||($s(r.touchedFields,ct,er),gr.touchedFields=r.touchedFields,ar=ar||(y.touchedFields||v.touchedFields)&&En!==er)}ar&&dr&&T.state.next(gr)}return ar?gr:{}},W=(ct,jt,er,Pr)=>{const dr=hn(r.errors,ct),ar=(y.isValid||v.isValid)&&sd(jt)&&r.isValid!==jt;if(e.delayError&&er?(f=k(()=>M(ct,er)),f(e.delayError)):(clearTimeout(p),f=null,er?$s(r.errors,ct,er):zo(r.errors,ct)),(er?!Pp(dr,er):dr)||!ju(Pr)||ar){const Nt={...Pr,...ar&&sd(jt)?{isValid:jt}:{},errors:r.errors,name:ct};r={...r,...Nt},T.state.next(Nt)}},Y=async ct=>{R(ct,!0);const jt=await e.resolver(o,e.context,IVe(ct||a.mount,n,e.criteriaMode,e.shouldUseNativeValidation));return R(ct),jt},J=async ct=>{const{errors:jt}=await Y(ct);if(ct)for(const er of ct){const Pr=hn(jt,er);Pr?$s(r.errors,er,Pr):zo(r.errors,er)}else r.errors=jt;return jt},Q=async(ct,jt,er={valid:!0})=>{for(const Pr in ct){const dr=ct[Pr];if(dr){const{_f:ar,...Nt}=dr;if(ar){const gr=a.array.has(ar.name),En=dr._f&&PVe(dr._f);En&&y.validatingFields&&R([Pr],!0);const ni=await cre(dr,a.disabled,o,E,e.shouldUseNativeValidation&&!jt,gr);if(En&&y.validatingFields&&R([Pr]),ni[ar.name]&&(er.valid=!1,jt))break;!jt&&(hn(ni,ar.name)?gr?FVe(r.errors,ni,ar.name):$s(r.errors,ar.name,ni[ar.name]):zo(r.errors,ar.name))}!ju(Nt)&&await Q(Nt,jt,er)}}return er.valid},ee=()=>{for(const ct of a.unMount){const jt=hn(n,ct);jt&&(jt._f.refs?jt._f.refs.every(er=>!B$(er)):!B$(jt._f.ref))&&vt(ct)}a.unMount=new Set},le=(ct,jt)=>!e.disabled&&(ct&&jt&&$s(o,ct,jt),!Pp(Ne(),i)),pe=(ct,jt,er)=>Vxe(ct,a,{...c.mount?o:ko(jt)?i:cm(ct)?{[ct]:jt}:jt},er,jt),Se=ct=>N7(hn(c.mount?o:i,ct,e.shouldUnregister?hn(i,ct,[]):[])),je=(ct,jt,er={})=>{const Pr=hn(n,ct);let dr=jt;if(Pr){const ar=Pr._f;ar&&(!ar.disabled&&$s(o,ct,Yxe(jt,ar)),dr=YD(ar.ref)&&Yc(jt)?"":jt,Gxe(ar.ref)?[...ar.ref.options].forEach(Nt=>Nt.selected=dr.includes(Nt.value)):ar.refs?$C(ar.ref)?ar.refs.forEach(Nt=>{(!Nt.defaultChecked||!Nt.disabled)&&(Array.isArray(dr)?Nt.checked=!!dr.find(gr=>gr===Nt.value):Nt.checked=dr===Nt.value||!!dr)}):ar.refs.forEach(Nt=>Nt.checked=Nt.value===dr):L7(ar.ref)?ar.ref.value="":(ar.ref.value=dr,ar.ref.type||T.state.next({name:ct,values:al(o)})))}(er.shouldDirty||er.shouldTouch)&&G(ct,dr,er.shouldTouch,er.shouldDirty,!0),er.shouldValidate&&Te(ct)},Le=(ct,jt,er)=>{for(const Pr in jt){if(!jt.hasOwnProperty(Pr))return;const dr=jt[Pr],ar=ct+"."+Pr,Nt=hn(n,ar);(a.array.has(ct)||Lo(dr)||Nt&&!Nt._f)&&!Ev(dr)?Le(ar,dr,er):je(ar,dr,er)}},Ae=(ct,jt,er={})=>{const Pr=hn(n,ct),dr=a.array.has(ct),ar=al(jt);$s(o,ct,ar),dr?(T.array.next({name:ct,values:al(o)}),(y.isDirty||y.dirtyFields||v.isDirty||v.dirtyFields)&&er.shouldDirty&&T.state.next({name:ct,dirtyFields:s2(i,o),isDirty:le(ct,ar)})):Pr&&!Pr._f&&!Yc(ar)?Le(ct,ar,er):je(ct,ar,er),are(ct,a)&&T.state.next({...r,name:ct}),T.state.next({name:c.mount?ct:void 0,values:al(o)})},be=async ct=>{c.mount=!0;const jt=ct.target;let er=jt.name,Pr=!0;const dr=hn(n,er),ar=En=>{Pr=Number.isNaN(En)||Ev(En)&&isNaN(En.getTime())||Pp(En,hn(o,er,En))},Nt=ire(e.mode),gr=ire(e.reValidateMode);if(dr){let En,ni;const ii=jt.type?nre(dr._f):$xe(ct),Ui=ct.type===KD.BLUR||ct.type===KD.FOCUS_OUT,Ta=!RVe(dr._f)&&!e.resolver&&!hn(r.errors,er)&&!dr._f.deps||MVe(Ui,hn(r.touchedFields,er),r.isSubmitted,gr,Nt),vi=are(er,a,Ui);$s(o,er,ii),Ui?(dr._f.onBlur&&dr._f.onBlur(ct),f&&f(0)):dr._f.onChange&&dr._f.onChange(ct);const ca=G(er,ii,Ui),Nr=!ju(ca)||vi;if(!Ui&&T.state.next({name:er,type:ct.type,values:al(o)}),Ta)return(y.isValid||v.isValid)&&(e.mode==="onBlur"?Ui&&P():Ui||P()),Nr&&T.state.next({name:er,...vi?{}:ca});if(!Ui&&vi&&T.state.next({...r}),e.resolver){const{errors:Vn}=await Y([er]);if(ar(ii),Pr){const Ks=ore(r.errors,n,er),Ea=ore(Vn,n,Ks.name||er);En=Ea.error,er=Ea.name,ni=ju(Vn)}}else R([er],!0),En=(await cre(dr,a.disabled,o,E,e.shouldUseNativeValidation))[er],R([er]),ar(ii),Pr&&(En?ni=!1:(y.isValid||v.isValid)&&(ni=await Q(n,!0)));Pr&&(dr._f.deps&&Te(dr._f.deps),W(er,ni,En,ca))}},me=(ct,jt)=>{if(hn(r.errors,jt)&&ct.focus)return ct.focus(),1},Te=async(ct,jt={})=>{let er,Pr;const dr=cA(ct);if(e.resolver){const ar=await J(ko(ct)?ct:dr);er=ju(ar),Pr=ct?!dr.some(Nt=>hn(ar,Nt)):er}else ct?(Pr=(await Promise.all(dr.map(async ar=>{const Nt=hn(n,ar);return await Q(Nt&&Nt._f?{[ar]:Nt}:Nt)}))).every(Boolean),!(!Pr&&!r.isValid)&&P()):Pr=er=await Q(n);return T.state.next({...!cm(ct)||(y.isValid||v.isValid)&&er!==r.isValid?{}:{name:ct},...e.resolver||!ct?{isValid:er}:{},errors:r.errors}),jt.shouldFocus&&!Pr&&uA(n,me,ct?dr:a.mount),Pr},Ne=ct=>{const jt={...c.mount?o:i};return ko(ct)?jt:cm(ct)?hn(jt,ct):ct.map(er=>hn(jt,er))},Ee=(ct,jt)=>({invalid:!!hn((jt||r).errors,ct),isDirty:!!hn((jt||r).dirtyFields,ct),error:hn((jt||r).errors,ct),isValidating:!!hn(r.validatingFields,ct),isTouched:!!hn((jt||r).touchedFields,ct)}),we=ct=>{ct&&cA(ct).forEach(jt=>zo(r.errors,jt)),T.state.next({errors:ct?r.errors:{}})},He=(ct,jt,er)=>{const Pr=(hn(n,ct,{_f:{}})._f||{}).ref,dr=hn(r.errors,ct)||{},{ref:ar,message:Nt,type:gr,...En}=dr;$s(r.errors,ct,{...En,...jt,ref:Pr}),T.state.next({name:ct,errors:r.errors,isValid:!1}),er&&er.shouldFocus&&Pr&&Pr.focus&&Pr.focus()},tt=(ct,jt)=>rf(ct)?T.state.subscribe({next:er=>"values"in er&&ct(pe(void 0,jt),er)}):pe(ct,jt,!0),at=ct=>T.state.subscribe({next:jt=>{DVe(ct.name,jt.name,ct.exact)&&LVe(jt,ct.formState||y,xr,ct.reRenderRoot)&&ct.callback({values:{...o},...r,...jt,defaultValues:i})}}).unsubscribe,Et=ct=>(c.mount=!0,v={...v,...ct.formState},at({...ct,formState:v})),vt=(ct,jt={})=>{for(const er of ct?cA(ct):a.mount)a.mount.delete(er),a.array.delete(er),jt.keepValue||(zo(n,er),zo(o,er)),!jt.keepError&&zo(r.errors,er),!jt.keepDirty&&zo(r.dirtyFields,er),!jt.keepTouched&&zo(r.touchedFields,er),!jt.keepIsValidating&&zo(r.validatingFields,er),!e.shouldUnregister&&!jt.keepDefaultValue&&zo(i,er);T.state.next({values:al(o)}),T.state.next({...r,...jt.keepDirty?{isDirty:le()}:{}}),!jt.keepIsValid&&P()},Gt=({disabled:ct,name:jt})=>{(sd(ct)&&c.mount||ct||a.disabled.has(jt))&&(ct?a.disabled.add(jt):a.disabled.delete(jt))},pt=(ct,jt={})=>{let er=hn(n,ct);const Pr=sd(jt.disabled)||sd(e.disabled);return $s(n,ct,{...er||{},_f:{...er&&er._f?er._f:{ref:{name:ct}},name:ct,mount:!0,...jt}}),a.mount.add(ct),er?Gt({disabled:sd(jt.disabled)?jt.disabled:e.disabled,name:ct}):V(ct,!0,jt.value),{...Pr?{disabled:jt.disabled||e.disabled}:{},...e.progressive?{required:!!jt.required,min:a2(jt.min),max:a2(jt.max),minLength:a2(jt.minLength),maxLength:a2(jt.maxLength),pattern:a2(jt.pattern)}:{},name:ct,onChange:be,onBlur:be,ref:dr=>{if(dr){pt(ct,jt),er=hn(n,ct);const ar=ko(dr.value)&&dr.querySelectorAll&&dr.querySelectorAll("input,select,textarea")[0]||dr,Nt=kVe(ar),gr=er._f.refs||[];if(Nt?gr.find(En=>En===ar):ar===er._f.ref)return;$s(n,ct,{_f:{...er._f,...Nt?{refs:[...gr.filter(B$),ar,...Array.isArray(hn(i,ct))?[{}]:[]],ref:{type:ar.type,name:ct}}:{ref:ar}}}),V(ct,!1,void 0,ar)}else er=hn(n,ct,{}),er._f&&(er._f.mount=!1),(e.shouldUnregister||jt.shouldUnregister)&&!(zxe(a.array,ct)&&c.action)&&a.unMount.add(ct)}}},Pt=()=>e.shouldFocusError&&uA(n,me,a.mount),tr=ct=>{sd(ct)&&(T.state.next({disabled:ct}),uA(n,(jt,er)=>{const Pr=hn(n,er);Pr&&(jt.disabled=Pr._f.disabled||ct,Array.isArray(Pr._f.refs)&&Pr._f.refs.forEach(dr=>{dr.disabled=Pr._f.disabled||ct}))},0,!1))},_t=(ct,jt)=>async er=>{let Pr;er&&(er.preventDefault&&er.preventDefault(),er.persist&&er.persist());let dr=al(o);if(T.state.next({isSubmitting:!0}),e.resolver){const{errors:ar,values:Nt}=await Y();r.errors=ar,dr=al(Nt)}else await Q(n);if(a.disabled.size)for(const ar of a.disabled)zo(dr,ar);if(zo(r.errors,"root"),ju(r.errors)){T.state.next({errors:{}});try{await ct(dr,er)}catch(ar){Pr=ar}}else jt&&await jt({...r.errors},er),Pt(),setTimeout(Pt);if(T.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:ju(r.errors)&&!Pr,submitCount:r.submitCount+1,errors:r.errors}),Pr)throw Pr},cr=(ct,jt={})=>{hn(n,ct)&&(ko(jt.defaultValue)?Ae(ct,al(hn(i,ct))):(Ae(ct,jt.defaultValue),$s(i,ct,al(jt.defaultValue))),jt.keepTouched||zo(r.touchedFields,ct),jt.keepDirty||(zo(r.dirtyFields,ct),r.isDirty=jt.defaultValue?le(ct,al(hn(i,ct))):le()),jt.keepError||(zo(r.errors,ct),y.isValid&&P()),T.state.next({...r}))},Tr=(ct,jt={})=>{const er=ct?al(ct):i,Pr=al(er),dr=ju(ct),ar=dr?i:Pr;if(jt.keepDefaultValues||(i=er),!jt.keepValues){if(jt.keepDirtyValues){const Nt=new Set([...a.mount,...Object.keys(s2(i,o))]);for(const gr of Array.from(Nt))hn(r.dirtyFields,gr)?$s(ar,gr,hn(o,gr)):Ae(gr,hn(ar,gr))}else{if(C7&&ko(ct))for(const Nt of a.mount){const gr=hn(n,Nt);if(gr&&gr._f){const En=Array.isArray(gr._f.refs)?gr._f.refs[0]:gr._f.ref;if(YD(En)){const ni=En.closest("form");if(ni){ni.reset();break}}}}if(jt.keepFieldsRef)for(const Nt of a.mount)Ae(Nt,hn(ar,Nt));else n={}}o=e.shouldUnregister?jt.keepDefaultValues?al(i):{}:al(ar),T.array.next({values:{...ar}}),T.state.next({values:{...ar}})}a={mount:jt.keepDirtyValues?a.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},c.mount=!y.isValid||!!jt.keepIsValid||!!jt.keepDirtyValues,c.watch=!!e.shouldUnregister,T.state.next({submitCount:jt.keepSubmitCount?r.submitCount:0,isDirty:dr?!1:jt.keepDirty?r.isDirty:!!(jt.keepDefaultValues&&!Pp(ct,i)),isSubmitted:jt.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:dr?{}:jt.keepDirtyValues?jt.keepDefaultValues&&o?s2(i,o):r.dirtyFields:jt.keepDefaultValues&&ct?s2(i,ct):jt.keepDirty?r.dirtyFields:{},touchedFields:jt.keepTouched?r.touchedFields:{},errors:jt.keepErrors?r.errors:{},isSubmitSuccessful:jt.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},sn=(ct,jt)=>Tr(rf(ct)?ct(o):ct,jt),ur=(ct,jt={})=>{const er=hn(n,ct),Pr=er&&er._f;if(Pr){const dr=Pr.refs?Pr.refs[0]:Pr.ref;dr.focus&&(dr.focus(),jt.shouldSelect&&rf(dr.select)&&dr.select())}},xr=ct=>{r={...r,...ct}},vn={control:{register:pt,unregister:vt,getFieldState:Ee,handleSubmit:_t,setError:He,_subscribe:at,_runSchema:Y,_focusError:Pt,_getWatch:pe,_getDirty:le,_setValid:P,_setFieldArray:D,_setDisabledField:Gt,_setErrors:B,_getFieldArray:Se,_reset:Tr,_resetDefaultValues:()=>rf(e.defaultValues)&&e.defaultValues().then(ct=>{sn(ct,e.resetOptions),T.state.next({isLoading:!1})}),_removeUnmounted:ee,_disableForm:tr,_subjects:T,_proxyFormState:y,get _fields(){return n},get _formValues(){return o},get _state(){return c},set _state(ct){c=ct},get _defaultValues(){return i},get _names(){return a},set _names(ct){a=ct},get _formState(){return r},get _options(){return e},set _options(ct){e={...e,...ct}}},subscribe:Et,trigger:Te,register:pt,handleSubmit:_t,watch:tt,setValue:Ae,getValues:Ne,reset:sn,resetField:cr,clearErrors:we,unregister:vt,setError:He,setFocus:ur,getFieldState:Ee};return{...vn,formControl:vn}}function M7(t={}){const e=Xe.useRef(void 0),r=Xe.useRef(void 0),[n,i]=Xe.useState({isDirty:!1,isValidating:!1,isLoading:rf(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:rf(t.defaultValues)?void 0:t.defaultValues});if(!e.current)if(t.formControl)e.current={...t.formControl,formState:n},t.defaultValues&&!rf(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions);else{const{formControl:c,...a}=$Ve(t);e.current={...a,formState:n}}const o=e.current.control;return o._options=t,R7(()=>{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]),Xe.useEffect(()=>o._disableForm(t.disabled),[o,t.disabled]),Xe.useEffect(()=>{t.mode&&(o._options.mode=t.mode),t.reValidateMode&&(o._options.reValidateMode=t.reValidateMode)},[o,t.mode,t.reValidateMode]),Xe.useEffect(()=>{t.errors&&(o._setErrors(t.errors),o._focusError())},[o,t.errors]),Xe.useEffect(()=>{t.shouldUnregister&&o._subjects.state.next({values:o._getWatch()})},[o,t.shouldUnregister]),Xe.useEffect(()=>{if(o._proxyFormState.isDirty){const c=o._getDirty();c!==n.isDirty&&o._subjects.state.next({isDirty:c})}},[o,n.isDirty]),Xe.useEffect(()=>{t.values&&!Pp(t.values,r.current)?(o._reset(t.values,{keepFieldsRef:!0,...o._options.resetOptions}),r.current=t.values,i(c=>({...c}))):o._resetDefaultValues()},[o,t.values]),Xe.useEffect(()=>{o._state.mount||(o._setValid(),o._state.mount=!0),o._state.watch&&(o._state.watch=!1,o._subjects.state.next({...o._formState})),o._removeUnmounted()}),e.current.formState=Uxe(n,o),e.current}const ure=(t,e,r)=>{if(t&&"reportValidity"in t){const n=hn(r,e);t.setCustomValidity(n&&n.message||""),t.reportValidity()}},Xxe=(t,e)=>{for(const r in e.fields){const n=e.fields[r];n&&n.ref&&"reportValidity"in n.ref?ure(n.ref,r,t):n.refs&&n.refs.forEach(i=>ure(i,r,t))}},zVe=(t,e)=>{e.shouldUseNativeValidation&&Xxe(t,e);const r={};for(const n in t){const i=hn(e.fields,n),o=Object.assign(t[n]||{},{ref:i&&i.ref});if(UVe(e.names||Object.keys(t),n)){const c=Object.assign({},hn(r,n));$s(c,"root",o),$s(r,n,c)}else $s(r,n,o)}return r},UVe=(t,e)=>t.some(r=>r.startsWith(e+"."));var VVe=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,p=f&&f[n.code];r[c]=qxe(c,e,r,i,p?[].concat(p,n.message):n.message)}t.shift()}return r},O7=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(p){return o.shouldUseNativeValidation&&Xxe({},o),{errors:{},values:r.raw?n:p}})}catch(p){return a(p)}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:zVe(VVe(c.errors,!o.shouldUseNativeValidation&&o.criteriaMode==="all"),o)};throw c}))}catch(c){return Promise.reject(c)}}},dre;function jr(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 p=c.prototype,y=Object.keys(p);for(let v=0;v{var f,p;return r!=null&&r.Parent&&a instanceof r.Parent?!0:(p=(f=a==null?void 0:a._zod)==null?void 0:f.traits)==null?void 0:p.has(t)}}),Object.defineProperty(c,"name",{value:t}),c}class b1 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Qxe extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(dre=globalThis).__zod_globalConfig??(dre.__zod_globalConfig={});const F7=globalThis.__zod_globalConfig;function tg(t){return F7}function Jxe(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 PV(t,e){return typeof e=="bigint"?e.toString():e}function B7(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function $7(t){return t==null}function z7(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function qVe(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 QD(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const HVe=B7(()=>{var t;if(F7.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 oS(t){if(QD(t)===!1)return!1;const e=t.constructor;if(e===void 0||typeof e!="function")return!0;const r=e.prototype;return!(QD(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function t0e(t){return oS(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}const WVe=new Set(["string","number","symbol"]);function lS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Dx(t,e,r){const n=new t._zod.constr(e??t._zod.def);return(!e||r!=null&&r.parent)&&(n._zod.parent=t),n}function Un(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function KVe(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const YVe={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 ZVe(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=Lx(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 j_(this,"shape",c),c},checks:[]});return Dx(t,o)}function XVe(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=Lx(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 j_(this,"shape",c),c},checks:[]});return Dx(t,o)}function QVe(t,e){if(!oS(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=Lx(t._zod.def,{get shape(){const o={...t._zod.def.shape,...e};return j_(this,"shape",o),o}});return Dx(t,i)}function JVe(t,e){if(!oS(e))throw new Error("Invalid input to safeExtend: expected a plain object");const r=Lx(t._zod.def,{get shape(){const n={...t._zod.def.shape,...e};return j_(this,"shape",n),n}});return Dx(t,r)}function e8e(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=Lx(t._zod.def,{get shape(){const i={...t._zod.def.shape,...e._zod.def.shape};return j_(this,"shape",i),i},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return Dx(t,r)}function t8e(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=Lx(e._zod.def,{get shape(){const a=e._zod.def.shape,f={...a};if(r)for(const p in r){if(!(p in a))throw new Error(`Unrecognized key: "${p}"`);r[p]&&(f[p]=t?new t({type:"optional",innerType:a[p]}):a[p])}else for(const p in a)f[p]=t?new t({type:"optional",innerType:a[p]}):a[p];return j_(this,"shape",f),f},checks:[]});return Dx(e,c)}function r8e(t,e,r){const n=Lx(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 j_(this,"shape",o),o}});return Dx(e,n)}function Zw(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 hR(t){return typeof t=="string"?t:t==null?void 0:t.message}function rg(t,e,r){var f,p,y,v,T,E;const n=t.message?t.message:hR((y=(p=(f=t.inst)==null?void 0:f._zod.def)==null?void 0:p.error)==null?void 0:y.call(p,t))??hR((v=e==null?void 0:e.error)==null?void 0:v.call(e,t))??hR((T=r.customError)==null?void 0:T.call(r,t))??hR((E=r.localeError)==null?void 0:E.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 U7(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function lk(...t){const[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}const r0e=(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,PV,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},n0e=jr("$ZodError",r0e),i0e=jr("$ZodError",r0e,{Parent:Error});function i8e(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 s8e(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,p=0;for(;p(e,r,n,i)=>{const o=n?{...n,async:!1}:{async:!1},c=e._zod.run({value:r,issues:[]},o);if(c instanceof Promise)throw new b1;if(c.issues.length){const a=new((i==null?void 0:i.Err)??t)(c.issues.map(f=>rg(f,o,tg())));throw e0e(a,i==null?void 0:i.callee),a}return c.value},q7=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=>rg(f,o,tg())));throw e0e(a,i==null?void 0:i.callee),a}return c.value},L3=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 b1;return o.issues.length?{success:!1,error:new(t??n0e)(o.issues.map(c=>rg(c,i,tg())))}:{success:!0,data:o.value}},a8e=L3(i0e),D3=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=>rg(c,i,tg())))}:{success:!0,data:o.value}},o8e=D3(i0e),l8e=t=>(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return V7(t)(e,r,i)},c8e=t=>(e,r,n)=>V7(t)(e,r,n),u8e=t=>async(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return q7(t)(e,r,i)},d8e=t=>async(e,r,n)=>q7(t)(e,r,n),h8e=t=>(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return L3(t)(e,r,i)},f8e=t=>(e,r,n)=>L3(t)(e,r,n),m8e=t=>async(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return D3(t)(e,r,i)},p8e=t=>async(e,r,n)=>D3(t)(e,r,n),g8e=/^[cC][0-9a-z]{6,}$/,y8e=/^[0-9a-z]+$/,x8e=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,v8e=/^[0-9a-vA-V]{20}$/,_8e=/^[A-Za-z0-9]{27}$/,b8e=/^[a-zA-Z0-9_-]{21}$/,w8e=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,S8e=/^([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})$/,mre=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)$/,T8e=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,E8e="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function j8e(){return new RegExp(E8e,"u")}const A8e=/^(?:(?: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])$/,k8e=/^(([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}|:))$/,C8e=/^((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])$/,N8e=/^(([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])$/,I8e=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,s0e=/^[A-Za-z0-9_-]*$/,P8e=/^https?$/,R8e=/^\+[1-9]\d{6,14}$/,a0e="(?:(?:\\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])))",L8e=new RegExp(`^${a0e}$`);function o0e(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 D8e(t){return new RegExp(`^${o0e(t)}$`)}function M8e(t){const e=o0e({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(`^${a0e}T(?:${n})$`)}const O8e=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}$`)},F8e=/^-?\d+$/,l0e=/^-?\d+(?:\.\d+)?$/,B8e=/^(?:true|false)$/i,$8e=/^[^A-Z]*$/,z8e=/^[^a-z]*$/,Fu=jr("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),c0e={number:"number",bigint:"bigint",object:"date"},u0e=jr("$ZodCheckLessThan",(t,e)=>{Fu.init(t,e);const r=c0e[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{Fu.init(t,e);const r=c0e[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})}}),U8e=jr("$ZodCheckMultipleOf",(t,e)=>{Fu.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):qVe(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})}}),V8e=jr("$ZodCheckNumberFormat",(t,e)=>{var c;Fu.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]=YVe[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=F8e)}),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})}}),q8e=jr("$ZodCheckMaxLength",(t,e)=>{var r;Fu.init(t,e),(r=t._zod.def).when??(r.when=n=>{const i=n.value;return!$7(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=U7(i);n.issues.push({origin:c,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),G8e=jr("$ZodCheckMinLength",(t,e)=>{var r;Fu.init(t,e),(r=t._zod.def).when??(r.when=n=>{const i=n.value;return!$7(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=U7(i);n.issues.push({origin:c,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),H8e=jr("$ZodCheckLengthEquals",(t,e)=>{var r;Fu.init(t,e),(r=t._zod.def).when??(r.when=n=>{const i=n.value;return!$7(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=U7(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})}}),M3=jr("$ZodCheckStringFormat",(t,e)=>{var r,n;Fu.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=()=>{})}),W8e=jr("$ZodCheckRegex",(t,e)=>{M3.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})}}),K8e=jr("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=$8e),M3.init(t,e)}),Y8e=jr("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=z8e),M3.init(t,e)}),Z8e=jr("$ZodCheckIncludes",(t,e)=>{Fu.init(t,e);const r=lS(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})}}),X8e=jr("$ZodCheckStartsWith",(t,e)=>{Fu.init(t,e);const r=new RegExp(`^${lS(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})}}),Q8e=jr("$ZodCheckEndsWith",(t,e)=>{Fu.init(t,e);const r=new RegExp(`.*${lS(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})}}),J8e=jr("$ZodCheckOverwrite",(t,e)=>{Fu.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class eqe{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 tqe={major:4,minor:4,patch:3},co=jr("$ZodType",(t,e)=>{var i;var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=tqe;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,p)=>{let y=Zw(a),v;for(const T of f){if(T._zod.def.when){if(n8e(a)||!T._zod.def.when(a))continue}else if(y)continue;const E=a.issues.length,k=T._zod.check(a);if(k instanceof Promise&&(p==null?void 0:p.async)===!1)throw new b1;if(v||k instanceof Promise)v=(v??Promise.resolve()).then(async()=>{await k,a.issues.length!==E&&(y||(y=Zw(a,E)))});else{if(a.issues.length===E)continue;y||(y=Zw(a,E))}}return v?v.then(()=>a):a},c=(a,f,p)=>{if(Zw(a))return a.aborted=!0,a;const y=o(f,n,p);if(y instanceof Promise){if(p.async===!1)throw new b1;return y.then(v=>t._zod.parse(v,p))}return t._zod.parse(y,p)};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 p=t._zod.parse(a,f);if(p instanceof Promise){if(f.async===!1)throw new b1;return p.then(y=>o(y,n,f))}return o(p,n,f)}}Qs(t,"~standard",()=>({validate:o=>{var c;try{const a=a8e(t,o);return a.success?{value:a.data}:{issues:(c=a.error)==null?void 0:c.issues}}catch{return o8e(t,o).then(f=>{var p;return f.success?{value:f.data}:{issues:(p=f.error)==null?void 0:p.issues}})}},vendor:"zod",version:1}))}),G7=jr("$ZodString",(t,e)=>{var r;co.init(t,e),t._zod.pattern=[...((r=t==null?void 0:t._zod.bag)==null?void 0:r.patterns)??[]].pop()??O8e(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}}),Ga=jr("$ZodStringFormat",(t,e)=>{M3.init(t,e),G7.init(t,e)}),rqe=jr("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=S8e),Ga.init(t,e)}),nqe=jr("$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=mre(n))}else e.pattern??(e.pattern=mre());Ga.init(t,e)}),iqe=jr("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=T8e),Ga.init(t,e)}),sqe=jr("$ZodURL",(t,e)=>{Ga.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)===P8e.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})}}}),aqe=jr("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=j8e()),Ga.init(t,e)}),oqe=jr("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=b8e),Ga.init(t,e)}),lqe=jr("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=g8e),Ga.init(t,e)}),cqe=jr("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=y8e),Ga.init(t,e)}),uqe=jr("$ZodULID",(t,e)=>{e.pattern??(e.pattern=x8e),Ga.init(t,e)}),dqe=jr("$ZodXID",(t,e)=>{e.pattern??(e.pattern=v8e),Ga.init(t,e)}),hqe=jr("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=_8e),Ga.init(t,e)}),fqe=jr("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=M8e(e)),Ga.init(t,e)}),mqe=jr("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=L8e),Ga.init(t,e)}),pqe=jr("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=D8e(e)),Ga.init(t,e)}),gqe=jr("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=w8e),Ga.init(t,e)}),yqe=jr("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=A8e),Ga.init(t,e),t._zod.bag.format="ipv4"}),xqe=jr("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=k8e),Ga.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})}}}),vqe=jr("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=C8e),Ga.init(t,e)}),_qe=jr("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=N8e),Ga.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 h0e(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const bqe=jr("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=I8e),Ga.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{h0e(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function wqe(t){if(!s0e.test(t))return!1;const e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return h0e(r)}const Sqe=jr("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=s0e),Ga.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{wqe(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Tqe=jr("$ZodE164",(t,e)=>{e.pattern??(e.pattern=R8e),Ga.init(t,e)});function Eqe(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 jqe=jr("$ZodJWT",(t,e)=>{Ga.init(t,e),t._zod.check=r=>{Eqe(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),f0e=jr("$ZodNumber",(t,e)=>{co.init(t,e),t._zod.pattern=t._zod.bag.pattern??l0e,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}}),Aqe=jr("$ZodNumberFormat",(t,e)=>{V8e.init(t,e),f0e.init(t,e)}),kqe=jr("$ZodBoolean",(t,e)=>{co.init(t,e),t._zod.pattern=B8e,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}}),Cqe=jr("$ZodUnknown",(t,e)=>{co.init(t,e),t._zod.parse=r=>r}),Nqe=jr("$ZodNever",(t,e)=>{co.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function pre(t,e,r){t.issues.length&&e.issues.push(...Xw(r,t.issues)),e.value[r]=t.value}const Iqe=jr("$ZodArray",(t,e)=>{co.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;cpre(p,r,c))):pre(f,r,c)}return o.length?Promise.all(o).then(()=>r):r}});function JD(t,e,r,n,i,o){const c=r in n;if(t.issues.length){if(i&&o&&!c)return;e.issues.push(...Xw(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 m0e(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=KVe(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function p0e(t,e,r,n,i,o){const c=[],a=i.keySet,f=i.catchall._zod,p=f.def.type,y=f.optin==="optional",v=f.optout==="optional";for(const T in e){if(T==="__proto__"||a.has(T))continue;if(p==="never"){c.push(T);continue}const E=f.run({value:e[T],issues:[]},n);E instanceof Promise?t.push(E.then(k=>JD(k,r,T,e,y,v))):JD(E,r,T,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 Pqe=jr("$ZodObject",(t,e)=>{co.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=B7(()=>m0e(e));Qs(t._zod,"propValues",()=>{const a=e.shape,f={};for(const p in a){const y=a[p]._zod;if(y.values){f[p]??(f[p]=new Set);for(const v of y.values)f[p].add(v)}}return f});const i=QD,o=e.catchall;let c;t._zod.parse=(a,f)=>{c??(c=n.value);const p=a.value;if(!i(p))return a.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),a;a.value={};const y=[],v=c.shape;for(const T of c.keys){const E=v[T],k=E._zod.optin==="optional",P=E._zod.optout==="optional",R=E._zod.run({value:p[T],issues:[]},f);R instanceof Promise?y.push(R.then(D=>JD(D,a,T,p,k,P))):JD(R,a,T,p,k,P)}return o?p0e(y,p,a,f,n.value,t):y.length?Promise.all(y).then(()=>a):a}}),Rqe=jr("$ZodObjectJIT",(t,e)=>{Pqe.init(t,e);const r=t._zod.parse,n=B7(()=>m0e(e)),i=T=>{var B,V;const E=new eqe(["shape","payload","ctx"]),k=n.value,P=G=>{const W=fre(G);return`shape[${W}]._zod.run({ value: input[${W}], issues: [] }, ctx)`};E.write("const input = payload.value;");const R=Object.create(null);let D=0;for(const G of k.keys)R[G]=`key_${D++}`;E.write("const newResult = {};");for(const G of k.keys){const W=R[G],Y=fre(G),J=T[G],Q=((B=J==null?void 0:J._zod)==null?void 0:B.optin)==="optional",ee=((V=J==null?void 0:J._zod)==null?void 0:V.optout)==="optional";E.write(`const ${W} = ${P(G)};`),Q&&ee?E.write(` if (${W}.issues.length) { if (${Y} in input) { payload.issues = payload.issues.concat(${W}.issues.map(iss => ({ ...iss, path: iss.path ? [${Y}, ...iss.path] : [${Y}] }))); } } if (${W}.value === undefined) { if (${Y} in input) { newResult[${Y}] = undefined; } } else { newResult[${Y}] = ${W}.value; } `):Q?E.write(` if (${W}.issues.length) { payload.issues = payload.issues.concat(${W}.issues.map(iss => ({ ...iss, path: iss.path ? [${Y}, ...iss.path] : [${Y}] }))); } if (${W}.value === undefined) { if (${Y} in input) { newResult[${Y}] = undefined; } } else { newResult[${Y}] = ${W}.value; } `):E.write(` const ${W}_present = ${Y} in input; if (${W}.issues.length) { payload.issues = payload.issues.concat(${W}.issues.map(iss => ({ ...iss, path: iss.path ? [${Y}, ...iss.path] : [${Y}] }))); } if (!${W}_present && !${W}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${Y}] }); } if (${W}_present) { if (${W}.value === undefined) { newResult[${Y}] = undefined; } else { newResult[${Y}] = ${W}.value; } } `)}E.write("payload.value = newResult;"),E.write("return payload;");const M=E.compile();return(G,W)=>M(T,G,W)};let o;const c=QD,a=!F7.jitless,p=a&&HVe.value,y=e.catchall;let v;t._zod.parse=(T,E)=>{v??(v=n.value);const k=T.value;return c(k)?a&&p&&(E==null?void 0:E.async)===!1&&E.jitless!==!0?(o||(o=i(e.shape)),T=o(T,E),y?p0e([],k,T,E,v,t):T):r(T,E):(T.issues.push({expected:"object",code:"invalid_type",input:k,inst:t}),T)}});function gre(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=>!Zw(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=>rg(c,n,tg())))}),e)}const Lqe=jr("$ZodUnion",(t,e)=>{co.init(t,e),Qs(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Qs(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Qs(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Qs(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=>z7(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=>gre(a,n,t,i)):gre(c,n,t,i)}}),Dqe=jr("$ZodIntersection",(t,e)=>{co.init(t,e),t._zod.parse=(r,n)=>{const i=r.value,o=e.left._zod.run({value:i,issues:[]},n),c=e.right._zod.run({value:i,issues:[]},n);return o instanceof Promise||c instanceof Promise?Promise.all([o,c]).then(([f,p])=>yre(r,f,p)):yre(r,o,c)}});function RV(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(oS(t)&&oS(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=RV(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}),Zw(t))return t;const c=RV(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 Mqe=jr("$ZodRecord",(t,e)=>{co.init(t,e),t._zod.parse=(r,n)=>{const i=r.value;if(!oS(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 p of c)if(typeof p=="string"||typeof p=="number"||typeof p=="symbol"){a.add(typeof p=="number"?p.toString():p);const y=e.keyType._zod.run({value:p,issues:[]},n);if(y instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(y.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:y.issues.map(E=>rg(E,n,tg())),input:p,path:[p],inst:t});continue}const v=y.value,T=e.valueType._zod.run({value:i[p],issues:[]},n);T instanceof Promise?o.push(T.then(E=>{E.issues.length&&r.issues.push(...Xw(p,E.issues)),r.value[v]=E.value})):(T.issues.length&&r.issues.push(...Xw(p,T.issues)),r.value[v]=T.value)}let f;for(const p in i)a.has(p)||(f=f??[],f.push(p));f&&f.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:f})}else{r.value={};for(const 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"&&l0e.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=>rg(v,n,tg())),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(...Xw(a,v.issues)),r.value[f.value]=v.value})):(y.issues.length&&r.issues.push(...Xw(a,y.issues)),r.value[f.value]=y.value)}}return o.length?Promise.all(o).then(()=>r):r}}),Oqe=jr("$ZodEnum",(t,e)=>{co.init(t,e);const r=Jxe(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(i=>WVe.has(typeof i)).map(i=>typeof i=="string"?lS(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}}),Fqe=jr("$ZodLiteral",(t,e)=>{if(co.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"?lS(n):n?lS(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}}),Bqe=jr("$ZodTransform",(t,e)=>{co.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Qxe(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 b1;return r.value=i,r.fallback=!0,r}});function xre(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}const g0e=jr("$ZodOptional",(t,e)=>{co.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Qs(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Qs(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${z7(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=>xre(c,i)):xre(o,i)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),$qe=jr("$ZodExactOptional",(t,e)=>{g0e.init(t,e),Qs(t._zod,"values",()=>e.innerType._zod.values),Qs(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),zqe=jr("$ZodNullable",(t,e)=>{co.init(t,e),Qs(t._zod,"optin",()=>e.innerType._zod.optin),Qs(t._zod,"optout",()=>e.innerType._zod.optout),Qs(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${z7(r.source)}|null)$`):void 0}),Qs(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)}),Uqe=jr("$ZodDefault",(t,e)=>{co.init(t,e),t._zod.optin="optional",Qs(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=>vre(o,e)):vre(i,e)}});function vre(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const Vqe=jr("$ZodPrefault",(t,e)=>{co.init(t,e),t._zod.optin="optional",Qs(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))}),qqe=jr("$ZodNonOptional",(t,e)=>{co.init(t,e),Qs(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=>_re(o,t)):_re(i,t)}});function _re(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 Gqe=jr("$ZodCatch",(t,e)=>{co.init(t,e),t._zod.optin="optional",Qs(t._zod,"optout",()=>e.innerType._zod.optout),Qs(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=>rg(c,n,tg()))},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=>rg(o,n,tg()))},input:r.value}),r.issues=[],r.fallback=!0),r)}}),Hqe=jr("$ZodPipe",(t,e)=>{co.init(t,e),Qs(t._zod,"values",()=>e.in._zod.values),Qs(t._zod,"optin",()=>e.in._zod.optin),Qs(t._zod,"optout",()=>e.out._zod.optout),Qs(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=>fR(c,e.in,n)):fR(o,e.in,n)}const i=e.in._zod.run(r,n);return i instanceof Promise?i.then(o=>fR(o,e.out,n)):fR(i,e.out,n)}});function fR(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 Wqe=jr("$ZodReadonly",(t,e)=>{co.init(t,e),Qs(t._zod,"propValues",()=>e.innerType._zod.propValues),Qs(t._zod,"values",()=>e.innerType._zod.values),Qs(t._zod,"optin",()=>{var r,n;return(n=(r=e.innerType)==null?void 0:r._zod)==null?void 0:n.optin}),Qs(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(bre):bre(i)}});function bre(t){return t.value=Object.freeze(t.value),t}const Kqe=jr("$ZodCustom",(t,e)=>{Fu.init(t,e),co.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=>wre(o,r,n,t));wre(i,r,n,t)}});function wre(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(lk(i))}}var Sre;class Yqe{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 Zqe(){return new Yqe}(Sre=globalThis).__zod_globalRegistry??(Sre.__zod_globalRegistry=Zqe());const U2=globalThis.__zod_globalRegistry;function Xqe(t,e){return new t({type:"string",...Un(e)})}function Qqe(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Un(e)})}function Tre(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Un(e)})}function Jqe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Un(e)})}function eGe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Un(e)})}function tGe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Un(e)})}function rGe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Un(e)})}function nGe(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Un(e)})}function iGe(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Un(e)})}function sGe(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Un(e)})}function aGe(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Un(e)})}function oGe(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Un(e)})}function lGe(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Un(e)})}function cGe(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Un(e)})}function uGe(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Un(e)})}function dGe(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Un(e)})}function hGe(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Un(e)})}function fGe(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Un(e)})}function mGe(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Un(e)})}function pGe(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Un(e)})}function gGe(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Un(e)})}function yGe(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Un(e)})}function xGe(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Un(e)})}function vGe(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Un(e)})}function _Ge(t,e){return new t({type:"string",format:"date",check:"string_format",...Un(e)})}function bGe(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Un(e)})}function wGe(t,e){return new t({type:"string",format:"duration",check:"string_format",...Un(e)})}function SGe(t,e){return new t({type:"number",checks:[],...Un(e)})}function TGe(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Un(e)})}function EGe(t,e){return new t({type:"boolean",...Un(e)})}function jGe(t){return new t({type:"unknown"})}function AGe(t,e){return new t({type:"never",...Un(e)})}function Ere(t,e){return new u0e({check:"less_than",...Un(e),value:t,inclusive:!1})}function $$(t,e){return new u0e({check:"less_than",...Un(e),value:t,inclusive:!0})}function jre(t,e){return new d0e({check:"greater_than",...Un(e),value:t,inclusive:!1})}function z$(t,e){return new d0e({check:"greater_than",...Un(e),value:t,inclusive:!0})}function Are(t,e){return new U8e({check:"multiple_of",...Un(e),value:t})}function y0e(t,e){return new q8e({check:"max_length",...Un(e),maximum:t})}function eM(t,e){return new G8e({check:"min_length",...Un(e),minimum:t})}function x0e(t,e){return new H8e({check:"length_equals",...Un(e),length:t})}function kGe(t,e){return new W8e({check:"string_format",format:"regex",...Un(e),pattern:t})}function CGe(t){return new K8e({check:"string_format",format:"lowercase",...Un(t)})}function NGe(t){return new Y8e({check:"string_format",format:"uppercase",...Un(t)})}function IGe(t,e){return new Z8e({check:"string_format",format:"includes",...Un(e),includes:t})}function PGe(t,e){return new X8e({check:"string_format",format:"starts_with",...Un(e),prefix:t})}function RGe(t,e){return new Q8e({check:"string_format",format:"ends_with",...Un(e),suffix:t})}function fT(t){return new J8e({check:"overwrite",tx:t})}function LGe(t){return fT(e=>e.normalize(t))}function DGe(){return fT(t=>t.trim())}function MGe(){return fT(t=>t.toLowerCase())}function OGe(){return fT(t=>t.toUpperCase())}function FGe(){return fT(t=>GVe(t))}function BGe(t,e,r){return new t({type:"array",element:e,...Un(r)})}function $Ge(t,e,r){return new t({type:"custom",check:"custom",fn:e,...Un(r)})}function zGe(t,e){const r=UGe(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(lk(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(lk(o))}},t(n.value,n)),e);return r}function UGe(t,e){const r=new Fu({check:"custom",...Un(e)});return r._zod.check=t,r}function v0e(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)??U2,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 Ko(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 T={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,c.schema,T);else{const k=c.schema,P=e.processors[i.type];if(!P)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);P(t,e,k,T)}const E=t._zod.parent;E&&(c.ref||(c.ref=E),Ko(E,e,T),e.seen.get(E).isParent=!0)}const f=e.metadataRegistry.get(t);return f&&Object.assign(c.schema,f),e.io==="input"&&Vc(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 _0e(t,e){var c,a,f,p;const r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const y of t.seen.entries()){const v=(c=t.metadataRegistry.get(y[0]))==null?void 0:c.id;if(v){const T=n.get(v);if(T&&T!==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 P;const v=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){const R=(P=t.external.registry.get(y[0]))==null?void 0:P.id,D=t.external.uri??(B=>B);if(R)return{ref:D(R)};const M=y[1].defId??y[1].schema.id??`schema${t.counter++}`;return y[1].defId=M,{defId:M,ref:`${D("__shared")}#/${v}/${M}`}}if(y[1]===r)return{ref:"#"};const E=`#/${v}/`,k=y[1].schema.id??`__schema${t.counter++}`;return{defId:k,ref:E+k}},o=y=>{if(y[1].schema.$ref)return;const v=y[1],{ref:T,defId:E}=i(y);v.def={...v.schema},E&&(v.defId=E);const k=v.schema;for(const P in k)delete k[P];k.$ref=T};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 E=(f=t.external.registry.get(y[0]))==null?void 0:f.id;if(e!==y[0]&&E){o(y);continue}}if((p=t.metadataRegistry.get(y[0]))==null?void 0:p.id){o(y);continue}if(v.cycle){o(y);continue}if(v.count>1&&t.reused==="ref"){o(y);continue}}}function b0e(t,e){var a,f,p,y;const r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=v=>{const T=t.seen.get(v);if(T.ref===null)return;const E=T.def??T.schema,k={...E},P=T.ref;if(T.ref=null,P){n(P);const D=t.seen.get(P),M=D.schema;if(M.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(E.allOf=E.allOf??[],E.allOf.push(M)):Object.assign(E,M),Object.assign(E,k),v._zod.parent===P)for(const V in E)V==="$ref"||V==="allOf"||V in k||delete E[V];if(M.$ref&&D.def)for(const V in E)V==="$ref"||V==="allOf"||V in D.def&&JSON.stringify(E[V])===JSON.stringify(D.def[V])&&delete E[V]}const R=v._zod.parent;if(R&&R!==P){n(R);const D=t.seen.get(R);if(D!=null&&D.schema.$ref&&(E.$ref=D.schema.$ref,D.def))for(const M in E)M==="$ref"||M==="allOf"||M in D.def&&JSON.stringify(E[M])===JSON.stringify(D.def[M])&&delete E[M]}t.override({zodSchema:v,jsonSchema:E,path:T.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=(p=t.metadataRegistry.get(e))==null?void 0:p.id;o!==void 0&&i.id===o&&delete i.id;const c=((y=t.external)==null?void 0:y.defs)??{};for(const v of t.seen.entries()){const T=v[1];T.def&&T.defId&&(T.def.id===T.defId&&delete T.def.id,c[T.defId]=T.def)}t.external||Object.keys(c).length>0&&(t.target==="draft-2020-12"?i.$defs=c:i.definitions=c);try{const v=JSON.parse(JSON.stringify(i));return Object.defineProperty(v,"~standard",{value:{...e["~standard"],jsonSchema:{input:tM(e,"input",t.processors),output:tM(e,"output",t.processors)}},enumerable:!1,writable:!1}),v}catch{throw new Error("Error converting schema to JSON.")}}function Vc(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 Vc(n.element,r);if(n.type==="set")return Vc(n.valueType,r);if(n.type==="lazy")return Vc(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 Vc(n.innerType,r);if(n.type==="intersection")return Vc(n.left,r)||Vc(n.right,r);if(n.type==="record"||n.type==="map")return Vc(n.keyType,r)||Vc(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Vc(n.in,r)||Vc(n.out,r);if(n.type==="object"){for(const i in n.shape)if(Vc(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(const i of n.options)if(Vc(i,r))return!0;return!1}if(n.type==="tuple"){for(const i of n.items)if(Vc(i,r))return!0;return!!(n.rest&&Vc(n.rest,r))}return!1}const VGe=(t,e={})=>r=>{const n=v0e({...r,processors:e});return Ko(t,n),_0e(n,t),b0e(n,t)},tM=(t,e,r={})=>n=>{const{libraryOptions:i,target:o}=n??{},c=v0e({...i??{},target:o,io:e,processors:r});return Ko(t,c),_0e(c,t),b0e(c,t)},qGe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},GGe=(t,e,r,n)=>{const i=r;i.type="string";const{minimum:o,maximum:c,format:a,patterns:f,contentEncoding:p}=t._zod.bag;if(typeof o=="number"&&(i.minLength=o),typeof c=="number"&&(i.maxLength=c),a&&(i.format=qGe[a]??a,i.format===""&&delete i.format,a==="time"&&delete i.format),p&&(i.contentEncoding=p),f&&f.size>0){const y=[...f];y.length===1?i.pattern=y[0].source:y.length>1&&(i.allOf=[...y.map(v=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:v.source}))])}},HGe=(t,e,r,n)=>{const i=r,{minimum:o,maximum:c,format:a,multipleOf:f,exclusiveMaximum:p,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),T=typeof p=="number"&&p<=(c??Number.POSITIVE_INFINITY),E=e.target==="draft-04"||e.target==="openapi-3.0";v?E?(i.minimum=y,i.exclusiveMinimum=!0):i.exclusiveMinimum=y:typeof o=="number"&&(i.minimum=o),T?E?(i.maximum=p,i.exclusiveMaximum=!0):i.exclusiveMaximum=p:typeof c=="number"&&(i.maximum=c),typeof f=="number"&&(i.multipleOf=f)},WGe=(t,e,r,n)=>{r.type="boolean"},KGe=(t,e,r,n)=>{r.not={}},YGe=(t,e,r,n)=>{},ZGe=(t,e,r,n)=>{const i=t._zod.def,o=Jxe(i.entries);o.every(c=>typeof c=="number")&&(r.type="number"),o.every(c=>typeof c=="string")&&(r.type="string"),r.enum=o},XGe=(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},QGe=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},JGe=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},e9e=(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=Ko(o.element,e,{...n,path:[...n.path,"items"]})},t9e=(t,e,r,n)=>{var p;const i=r,o=t._zod.def;i.type="object",i.properties={};const c=o.shape;for(const y in c)i.properties[y]=Ko(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)),((p=o.catchall)==null?void 0:p._zod.def.type)==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=Ko(o.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},r9e=(t,e,r,n)=>{const i=t._zod.def,o=i.inclusive===!1,c=i.options.map((a,f)=>Ko(a,e,{...n,path:[...n.path,o?"oneOf":"anyOf",f]}));o?r.oneOf=c:r.anyOf=c},n9e=(t,e,r,n)=>{const i=t._zod.def,o=Ko(i.left,e,{...n,path:[...n.path,"allOf",0]}),c=Ko(i.right,e,{...n,path:[...n.path,"allOf",1]}),a=p=>"allOf"in p&&Object.keys(p).length===1,f=[...a(o)?o.allOf:[o],...a(c)?c.allOf:[c]];r.allOf=f},i9e=(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=Ko(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=Ko(o.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=Ko(o.valueType,e,{...n,path:[...n.path,"additionalProperties"]});const p=c._zod.values;if(p){const y=[...p].filter(v=>typeof v=="string"||typeof v=="number");y.length>0&&(i.required=y)}},s9e=(t,e,r,n)=>{const i=t._zod.def,o=Ko(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"}]},a9e=(t,e,r,n)=>{const i=t._zod.def;Ko(i.innerType,e,n);const o=e.seen.get(t);o.ref=i.innerType},o9e=(t,e,r,n)=>{const i=t._zod.def;Ko(i.innerType,e,n);const o=e.seen.get(t);o.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},l9e=(t,e,r,n)=>{const i=t._zod.def;Ko(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)))},c9e=(t,e,r,n)=>{const i=t._zod.def;Ko(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},u9e=(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;Ko(c,e,n);const a=e.seen.get(t);a.ref=c},d9e=(t,e,r,n)=>{const i=t._zod.def;Ko(i.innerType,e,n);const o=e.seen.get(t);o.ref=i.innerType,r.readOnly=!0},w0e=(t,e,r,n)=>{const i=t._zod.def;Ko(i.innerType,e,n);const o=e.seen.get(t);o.ref=i.innerType},h9e=jr("ZodISODateTime",(t,e)=>{fqe.init(t,e),ho.init(t,e)});function f9e(t){return vGe(h9e,t)}const m9e=jr("ZodISODate",(t,e)=>{mqe.init(t,e),ho.init(t,e)});function p9e(t){return _Ge(m9e,t)}const g9e=jr("ZodISOTime",(t,e)=>{pqe.init(t,e),ho.init(t,e)});function y9e(t){return bGe(g9e,t)}const x9e=jr("ZodISODuration",(t,e)=>{gqe.init(t,e),ho.init(t,e)});function v9e(t){return wGe(x9e,t)}const S0e=(t,e)=>{n0e.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>s8e(t,r)},flatten:{value:r=>i8e(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,PV,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,PV,2)}},isEmpty:{get(){return t.issues.length===0}}})},_9e=jr("ZodError",S0e),yh=jr("ZodError",S0e,{Parent:Error}),b9e=V7(yh),w9e=q7(yh),S9e=L3(yh),T9e=D3(yh),E9e=l8e(yh),j9e=c8e(yh),A9e=u8e(yh),k9e=d8e(yh),C9e=h8e(yh),N9e=f8e(yh),I9e=m8e(yh),P9e=p8e(yh),kre=new WeakMap;function zC(t,e,r){const n=Object.getPrototypeOf(t);let i=kre.get(n);if(i||(i=new Set,kre.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 uo=jr("ZodType",(t,e)=>(co.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:tM(t,"input"),output:tM(t,"output")}}),t.toJSONSchema=VGe(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>b9e(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>S9e(t,r,n),t.parseAsync=async(r,n)=>w9e(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>T9e(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>E9e(t,r,n),t.decode=(r,n)=>j9e(t,r,n),t.encodeAsync=async(r,n)=>A9e(t,r,n),t.decodeAsync=async(r,n)=>k9e(t,r,n),t.safeEncode=(r,n)=>C9e(t,r,n),t.safeDecode=(r,n)=>N9e(t,r,n),t.safeEncodeAsync=async(r,n)=>I9e(t,r,n),t.safeDecodeAsync=async(r,n)=>P9e(t,r,n),zC(t,"ZodType",{check(...r){const n=this.def;return this.clone(Lx(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 Dx(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(k7e(r,n))},superRefine(r,n){return this.check(C7e(r,n))},overwrite(r){return this.check(fT(r))},optional(){return Pre(this)},exactOptional(){return p7e(this)},nullable(){return Rre(this)},nullish(){return Pre(Rre(this))},nonoptional(r){return b7e(this,r)},array(){return i7e(this)},or(r){return o7e([this,r])},and(r){return c7e(this,r)},transform(r){return Lre(this,f7e(r))},default(r){return x7e(this,r)},prefault(r){return _7e(this,r)},catch(r){return S7e(this,r)},pipe(r){return Lre(this,r)},readonly(){return j7e(this)},describe(r){const n=this.clone();return U2.add(n,{description:r}),n},meta(...r){if(r.length===0)return U2.get(this);const n=this.clone();return U2.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=U2.get(t))==null?void 0:r.description},configurable:!0}),t)),T0e=jr("_ZodString",(t,e)=>{G7.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(n,i,o)=>GGe(t,n,i);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,zC(t,"_ZodString",{regex(...n){return this.check(kGe(...n))},includes(...n){return this.check(IGe(...n))},startsWith(...n){return this.check(PGe(...n))},endsWith(...n){return this.check(RGe(...n))},min(...n){return this.check(eM(...n))},max(...n){return this.check(y0e(...n))},length(...n){return this.check(x0e(...n))},nonempty(...n){return this.check(eM(1,...n))},lowercase(n){return this.check(CGe(n))},uppercase(n){return this.check(NGe(n))},trim(){return this.check(DGe())},normalize(...n){return this.check(LGe(...n))},toLowerCase(){return this.check(MGe())},toUpperCase(){return this.check(OGe())},slugify(){return this.check(FGe())}})}),R9e=jr("ZodString",(t,e)=>{G7.init(t,e),T0e.init(t,e),t.email=r=>t.check(Qqe(L9e,r)),t.url=r=>t.check(nGe(D9e,r)),t.jwt=r=>t.check(xGe(Z9e,r)),t.emoji=r=>t.check(iGe(M9e,r)),t.guid=r=>t.check(Tre(Cre,r)),t.uuid=r=>t.check(Jqe(mR,r)),t.uuidv4=r=>t.check(eGe(mR,r)),t.uuidv6=r=>t.check(tGe(mR,r)),t.uuidv7=r=>t.check(rGe(mR,r)),t.nanoid=r=>t.check(sGe(O9e,r)),t.guid=r=>t.check(Tre(Cre,r)),t.cuid=r=>t.check(aGe(F9e,r)),t.cuid2=r=>t.check(oGe(B9e,r)),t.ulid=r=>t.check(lGe($9e,r)),t.base64=r=>t.check(pGe(W9e,r)),t.base64url=r=>t.check(gGe(K9e,r)),t.xid=r=>t.check(cGe(z9e,r)),t.ksuid=r=>t.check(uGe(U9e,r)),t.ipv4=r=>t.check(dGe(V9e,r)),t.ipv6=r=>t.check(hGe(q9e,r)),t.cidrv4=r=>t.check(fGe(G9e,r)),t.cidrv6=r=>t.check(mGe(H9e,r)),t.e164=r=>t.check(yGe(Y9e,r)),t.datetime=r=>t.check(f9e(r)),t.date=r=>t.check(p9e(r)),t.time=r=>t.check(y9e(r)),t.duration=r=>t.check(v9e(r))});function Ai(t){return Xqe(R9e,t)}const ho=jr("ZodStringFormat",(t,e)=>{Ga.init(t,e),T0e.init(t,e)}),L9e=jr("ZodEmail",(t,e)=>{iqe.init(t,e),ho.init(t,e)}),Cre=jr("ZodGUID",(t,e)=>{rqe.init(t,e),ho.init(t,e)}),mR=jr("ZodUUID",(t,e)=>{nqe.init(t,e),ho.init(t,e)}),D9e=jr("ZodURL",(t,e)=>{sqe.init(t,e),ho.init(t,e)}),M9e=jr("ZodEmoji",(t,e)=>{aqe.init(t,e),ho.init(t,e)}),O9e=jr("ZodNanoID",(t,e)=>{oqe.init(t,e),ho.init(t,e)}),F9e=jr("ZodCUID",(t,e)=>{lqe.init(t,e),ho.init(t,e)}),B9e=jr("ZodCUID2",(t,e)=>{cqe.init(t,e),ho.init(t,e)}),$9e=jr("ZodULID",(t,e)=>{uqe.init(t,e),ho.init(t,e)}),z9e=jr("ZodXID",(t,e)=>{dqe.init(t,e),ho.init(t,e)}),U9e=jr("ZodKSUID",(t,e)=>{hqe.init(t,e),ho.init(t,e)}),V9e=jr("ZodIPv4",(t,e)=>{yqe.init(t,e),ho.init(t,e)}),q9e=jr("ZodIPv6",(t,e)=>{xqe.init(t,e),ho.init(t,e)}),G9e=jr("ZodCIDRv4",(t,e)=>{vqe.init(t,e),ho.init(t,e)}),H9e=jr("ZodCIDRv6",(t,e)=>{_qe.init(t,e),ho.init(t,e)}),W9e=jr("ZodBase64",(t,e)=>{bqe.init(t,e),ho.init(t,e)}),K9e=jr("ZodBase64URL",(t,e)=>{Sqe.init(t,e),ho.init(t,e)}),Y9e=jr("ZodE164",(t,e)=>{Tqe.init(t,e),ho.init(t,e)}),Z9e=jr("ZodJWT",(t,e)=>{jqe.init(t,e),ho.init(t,e)}),E0e=jr("ZodNumber",(t,e)=>{f0e.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(n,i,o)=>HGe(t,n,i),zC(t,"ZodNumber",{gt(n,i){return this.check(jre(n,i))},gte(n,i){return this.check(z$(n,i))},min(n,i){return this.check(z$(n,i))},lt(n,i){return this.check(Ere(n,i))},lte(n,i){return this.check($$(n,i))},max(n,i){return this.check($$(n,i))},int(n){return this.check(Nre(n))},safe(n){return this.check(Nre(n))},positive(n){return this.check(jre(0,n))},nonnegative(n){return this.check(z$(0,n))},negative(n){return this.check(Ere(0,n))},nonpositive(n){return this.check($$(0,n))},multipleOf(n,i){return this.check(Are(n,i))},step(n,i){return this.check(Are(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 dA(t){return SGe(E0e,t)}const X9e=jr("ZodNumberFormat",(t,e)=>{Aqe.init(t,e),E0e.init(t,e)});function Nre(t){return TGe(X9e,t)}const Q9e=jr("ZodBoolean",(t,e)=>{kqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>WGe(t,r,n)});function J9e(t){return EGe(Q9e,t)}const e7e=jr("ZodUnknown",(t,e)=>{Cqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>YGe()});function LV(){return jGe(e7e)}const t7e=jr("ZodNever",(t,e)=>{Nqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>KGe(t,r,n)});function r7e(t){return AGe(t7e,t)}const n7e=jr("ZodArray",(t,e)=>{Iqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>e9e(t,r,n,i),t.element=e.element,zC(t,"ZodArray",{min(r,n){return this.check(eM(r,n))},nonempty(r){return this.check(eM(1,r))},max(r,n){return this.check(y0e(r,n))},length(r,n){return this.check(x0e(r,n))},unwrap(){return this.element}})});function i7e(t,e){return BGe(n7e,t,e)}const s7e=jr("ZodObject",(t,e)=>{Rqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>t9e(t,r,n,i),Qs(t,"shape",()=>e.shape),zC(t,"ZodObject",{keyof(){return cS(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:LV()})},loose(){return this.clone({...this._zod.def,catchall:LV()})},strict(){return this.clone({...this._zod.def,catchall:r7e()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return QVe(this,r)},safeExtend(r){return JVe(this,r)},merge(r){return e8e(this,r)},pick(r){return ZVe(this,r)},omit(r){return XVe(this,r)},partial(...r){return t8e(j0e,this,r[0])},required(...r){return r8e(A0e,this,r[0])}})});function mg(t,e){const r={type:"object",shape:t??{},...Un(e)};return new s7e(r)}const a7e=jr("ZodUnion",(t,e)=>{Lqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>r9e(t,r,n,i),t.options=e.options});function o7e(t,e){return new a7e({type:"union",options:t,...Un(e)})}const l7e=jr("ZodIntersection",(t,e)=>{Dqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>n9e(t,r,n,i)});function c7e(t,e){return new l7e({type:"intersection",left:t,right:e})}const Ire=jr("ZodRecord",(t,e)=>{Mqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>i9e(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function u7e(t,e,r){return!e||!e._zod?new Ire({type:"record",keyType:Ai(),valueType:t,...Un(e)}):new Ire({type:"record",keyType:t,valueType:e,...Un(r)})}const DV=jr("ZodEnum",(t,e)=>{Oqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(n,i,o)=>ZGe(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 DV({...e,checks:[],...Un(i),entries:o})},t.exclude=(n,i)=>{const o={...e.entries};for(const c of n)if(r.has(c))delete o[c];else throw new Error(`Key ${c} not found in enum`);return new DV({...e,checks:[],...Un(i),entries:o})}});function cS(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new DV({type:"enum",entries:r,...Un(e)})}const d7e=jr("ZodLiteral",(t,e)=>{Fqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>XGe(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 rM(t,e){return new d7e({type:"literal",values:Array.isArray(t)?t:[t],...Un(e)})}const h7e=jr("ZodTransform",(t,e)=>{Bqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>JGe(t,r),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Qxe(t.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(lk(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(lk(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 f7e(t){return new h7e({type:"transform",transform:t})}const j0e=jr("ZodOptional",(t,e)=>{g0e.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>w0e(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Pre(t){return new j0e({type:"optional",innerType:t})}const m7e=jr("ZodExactOptional",(t,e)=>{$qe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>w0e(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function p7e(t){return new m7e({type:"optional",innerType:t})}const g7e=jr("ZodNullable",(t,e)=>{zqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>s9e(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Rre(t){return new g7e({type:"nullable",innerType:t})}const y7e=jr("ZodDefault",(t,e)=>{Uqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>o9e(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function x7e(t,e){return new y7e({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():t0e(e)}})}const v7e=jr("ZodPrefault",(t,e)=>{Vqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>l9e(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function _7e(t,e){return new v7e({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():t0e(e)}})}const A0e=jr("ZodNonOptional",(t,e)=>{qqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>a9e(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function b7e(t,e){return new A0e({type:"nonoptional",innerType:t,...Un(e)})}const w7e=jr("ZodCatch",(t,e)=>{Gqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>c9e(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function S7e(t,e){return new w7e({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const T7e=jr("ZodPipe",(t,e)=>{Hqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>u9e(t,r,n,i),t.in=e.in,t.out=e.out});function Lre(t,e){return new T7e({type:"pipe",in:t,out:e})}const E7e=jr("ZodReadonly",(t,e)=>{Wqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>d9e(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function j7e(t){return new E7e({type:"readonly",innerType:t})}const A7e=jr("ZodCustom",(t,e)=>{Kqe.init(t,e),uo.init(t,e),t._zod.processJSONSchema=(r,n,i)=>QGe(t,r)});function k7e(t,e={}){return $Ge(A7e,t,e)}function C7e(t,e){return zGe(t,e)}var N7e="Label",k0e=C.forwardRef((t,e)=>s.jsx(nn.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())}}));k0e.displayName=N7e;var C0e=k0e;const I7e=ZS("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Mr=C.forwardRef(({className:t,...e},r)=>s.jsx(C0e,{ref:r,className:qt(I7e(),t),...e}));Mr.displayName=C0e.displayName;const H7=SVe,N0e=C.createContext({}),ll=({...t})=>s.jsx(N0e.Provider,{value:{name:t.name},children:s.jsx(AVe,{...t})}),O3=()=>{const t=C.useContext(N0e),e=C.useContext(I0e),{getFieldState:r,formState:n}=R3(),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}},I0e=C.createContext({}),Vo=C.forwardRef(({className:t,...e},r)=>{const n=C.useId();return s.jsx(I0e.Provider,{value:{id:n},children:s.jsx("div",{ref:r,className:qt("space-y-2",t),...e})})});Vo.displayName="FormItem";const qo=C.forwardRef(({className:t,...e},r)=>{const{error:n,formItemId:i}=O3();return s.jsx(Mr,{ref:r,className:qt(n&&"text-destructive",t),htmlFor:i,...e})});qo.displayName="FormLabel";const Go=C.forwardRef(({...t},e)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:o}=O3();return s.jsx(Lfe,{ref:e,id:n,"aria-describedby":r?`${i} ${o}`:`${i}`,"aria-invalid":!!r,...t})});Go.displayName="FormControl";const NL=C.forwardRef(({className:t,...e},r)=>{const{formDescriptionId:n}=O3();return s.jsx("p",{ref:r,id:n,className:qt("text-sm text-muted-foreground",t),...e})});NL.displayName="FormDescription";const lf=C.forwardRef(({className:t,children:e,...r},n)=>{const{error:i,formMessageId:o}=O3(),c=i?String(i==null?void 0:i.message):e;return c?s.jsx("p",{ref:n,id:o,className:qt("text-sm font-medium text-destructive",t),...r,children:c}):null});lf.displayName="FormMessage";const Br=C.forwardRef(({className:t,type:e,...r},n)=>s.jsx("input",{type:e,className:qt("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}));Br.displayName="Input";function UC(t){const e=C.useRef({value:t,previous:t});return C.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var P7e=[" ","Enter","ArrowUp","ArrowDown"],R7e=[" ","Enter"],a_="Select",[F3,B3,L7e]=vC(a_),[mT,Mqt]=Qo(a_,[L7e,Ix]),$3=Ix(),[D7e,Mx]=mT(a_),[M7e,O7e]=mT(a_),P0e=t=>{const{__scopeSelect:e,children:r,open:n,defaultOpen:i,onOpenChange:o,value:c,defaultValue:a,onValueChange:f,dir:p,name:y,autoComplete:v,disabled:T,required:E,form:k}=t,P=$3(e),[R,D]=C.useState(null),[M,B]=C.useState(null),[V,G]=C.useState(!1),W=S_(p),[Y,J]=yd({prop:n,defaultProp:i??!1,onChange:o,caller:a_}),[Q,ee]=yd({prop:c,defaultProp:a,onChange:f,caller:a_}),le=C.useRef(null),pe=R?k||!!R.closest("form"):!0,[Se,je]=C.useState(new Set),Le=Array.from(Se).map(Ae=>Ae.props.value).join(";");return s.jsx(c3,{...P,children:s.jsxs(D7e,{required:E,scope:e,trigger:R,onTriggerChange:D,valueNode:M,onValueNodeChange:B,valueNodeHasChildren:V,onValueNodeHasChildrenChange:G,contentId:Fl(),value:Q,onValueChange:ee,open:Y,onOpenChange:J,dir:W,triggerPointerDownPosRef:le,disabled:T,children:[s.jsx(F3.Provider,{scope:e,children:s.jsx(M7e,{scope:t.__scopeSelect,onNativeOptionAdd:C.useCallback(Ae=>{je(be=>new Set(be).add(Ae))},[]),onNativeOptionRemove:C.useCallback(Ae=>{je(be=>{const me=new Set(be);return me.delete(Ae),me})},[]),children:r})}),pe?s.jsxs(nve,{"aria-hidden":!0,required:E,tabIndex:-1,name:y,autoComplete:v,value:Q,onChange:Ae=>ee(Ae.target.value),disabled:T,form:k,children:[Q===void 0?s.jsx("option",{value:""}):null,Array.from(Se)]},Le):null]})})};P0e.displayName=a_;var R0e="SelectTrigger",L0e=C.forwardRef((t,e)=>{const{__scopeSelect:r,disabled:n=!1,...i}=t,o=$3(r),c=Mx(R0e,r),a=c.disabled||n,f=Yn(e,c.onTriggerChange),p=B3(r),y=C.useRef("touch"),[v,T,E]=sve(P=>{const R=p().filter(B=>!B.disabled),D=R.find(B=>B.value===c.value),M=ave(R,P,D);M!==void 0&&c.onValueChange(M.value)}),k=P=>{a||(c.onOpenChange(!0),E()),P&&(c.triggerPointerDownPosRef.current={x:Math.round(P.pageX),y:Math.round(P.pageY)})};return s.jsx(PC,{asChild:!0,...o,children:s.jsx(nn.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":ive(c.value)?"":void 0,...i,ref:f,onClick:Or(i.onClick,P=>{P.currentTarget.focus(),y.current!=="mouse"&&k(P)}),onPointerDown:Or(i.onPointerDown,P=>{y.current=P.pointerType;const R=P.target;R.hasPointerCapture(P.pointerId)&&R.releasePointerCapture(P.pointerId),P.button===0&&P.ctrlKey===!1&&P.pointerType==="mouse"&&(k(P),P.preventDefault())}),onKeyDown:Or(i.onKeyDown,P=>{const R=v.current!=="";!(P.ctrlKey||P.altKey||P.metaKey)&&P.key.length===1&&T(P.key),!(R&&P.key===" ")&&P7e.includes(P.key)&&(k(),P.preventDefault())})})})});L0e.displayName=R0e;var D0e="SelectValue",M0e=C.forwardRef((t,e)=>{const{__scopeSelect:r,className:n,style:i,children:o,placeholder:c="",...a}=t,f=Mx(D0e,r),{onValueNodeHasChildrenChange:p}=f,y=o!==void 0,v=Yn(e,f.onValueNodeChange);return Do(()=>{p(y)},[p,y]),s.jsx(nn.span,{...a,ref:v,style:{pointerEvents:"none"},children:ive(f.value)?s.jsx(s.Fragment,{children:c}):o})});M0e.displayName=D0e;var F7e="SelectIcon",O0e=C.forwardRef((t,e)=>{const{__scopeSelect:r,children:n,...i}=t;return s.jsx(nn.span,{"aria-hidden":!0,...i,ref:e,children:n||"▼"})});O0e.displayName=F7e;var B7e="SelectPortal",F0e=t=>s.jsx(YS,{asChild:!0,...t});F0e.displayName=B7e;var o_="SelectContent",B0e=C.forwardRef((t,e)=>{const r=Mx(o_,t.__scopeSelect),[n,i]=C.useState();if(Do(()=>{i(new DocumentFragment)},[]),!r.open){const o=n;return o?dg.createPortal(s.jsx($0e,{scope:t.__scopeSelect,children:s.jsx(F3.Slot,{scope:t.__scopeSelect,children:s.jsx("div",{children:t.children})})}),o):null}return s.jsx(z0e,{...t,ref:e})});B0e.displayName=o_;var qh=10,[$0e,Ox]=mT(o_),$7e="SelectContentImpl",z7e=ux("SelectContent.RemoveScroll"),z0e=C.forwardRef((t,e)=>{const{__scopeSelect:r,position:n="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:o,onPointerDownOutside:c,side:a,sideOffset:f,align:p,alignOffset:y,arrowPadding:v,collisionBoundary:T,collisionPadding:E,sticky:k,hideWhenDetached:P,avoidCollisions:R,...D}=t,M=Mx(o_,r),[B,V]=C.useState(null),[G,W]=C.useState(null),Y=Yn(e,vt=>V(vt)),[J,Q]=C.useState(null),[ee,le]=C.useState(null),pe=B3(r),[Se,je]=C.useState(!1),Le=C.useRef(!1);C.useEffect(()=>{if(B)return r3(B)},[B]),e3();const Ae=C.useCallback(vt=>{const[Gt,...pt]=pe().map(_t=>_t.ref.current),[Pt]=pt.slice(-1),tr=document.activeElement;for(const _t of vt)if(_t===tr||(_t==null||_t.scrollIntoView({block:"nearest"}),_t===Gt&&G&&(G.scrollTop=0),_t===Pt&&G&&(G.scrollTop=G.scrollHeight),_t==null||_t.focus(),document.activeElement!==tr))return},[pe,G]),be=C.useCallback(()=>Ae([J,B]),[Ae,J,B]);C.useEffect(()=>{Se&&be()},[Se,be]);const{onOpenChange:me,triggerPointerDownPosRef:Te}=M;C.useEffect(()=>{if(B){let vt={x:0,y:0};const Gt=Pt=>{var tr,_t;vt={x:Math.abs(Math.round(Pt.pageX)-(((tr=Te.current)==null?void 0:tr.x)??0)),y:Math.abs(Math.round(Pt.pageY)-(((_t=Te.current)==null?void 0:_t.y)??0))}},pt=Pt=>{vt.x<=10&&vt.y<=10?Pt.preventDefault():B.contains(Pt.target)||me(!1),document.removeEventListener("pointermove",Gt),Te.current=null};return Te.current!==null&&(document.addEventListener("pointermove",Gt),document.addEventListener("pointerup",pt,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Gt),document.removeEventListener("pointerup",pt,{capture:!0})}}},[B,me,Te]),C.useEffect(()=>{const vt=()=>me(!1);return window.addEventListener("blur",vt),window.addEventListener("resize",vt),()=>{window.removeEventListener("blur",vt),window.removeEventListener("resize",vt)}},[me]);const[Ne,Ee]=sve(vt=>{const Gt=pe().filter(tr=>!tr.disabled),pt=Gt.find(tr=>tr.ref.current===document.activeElement),Pt=ave(Gt,vt,pt);Pt&&setTimeout(()=>Pt.ref.current.focus())}),we=C.useCallback((vt,Gt,pt)=>{const Pt=!Le.current&&!pt;(M.value!==void 0&&M.value===Gt||Pt)&&(Q(vt),Pt&&(Le.current=!0))},[M.value]),He=C.useCallback(()=>B==null?void 0:B.focus(),[B]),tt=C.useCallback((vt,Gt,pt)=>{const Pt=!Le.current&&!pt;(M.value!==void 0&&M.value===Gt||Pt)&&le(vt)},[M.value]),at=n==="popper"?MV:U0e,Et=at===MV?{side:a,sideOffset:f,align:p,alignOffset:y,arrowPadding:v,collisionBoundary:T,collisionPadding:E,sticky:k,hideWhenDetached:P,avoidCollisions:R}:{};return s.jsx($0e,{scope:r,content:B,viewport:G,onViewportChange:W,itemRefCallback:we,selectedItem:J,onItemLeave:He,itemTextRefCallback:tt,focusSelectedItem:be,selectedItemText:ee,position:n,isPositioned:Se,searchRef:Ne,children:s.jsx(jC,{as:z7e,allowPinchZoom:!0,children:s.jsx(EC,{asChild:!0,trapped:M.open,onMountAutoFocus:vt=>{vt.preventDefault()},onUnmountAutoFocus:Or(i,vt=>{var Gt;(Gt=M.trigger)==null||Gt.focus({preventScroll:!0}),vt.preventDefault()}),children:s.jsx(v_,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:vt=>vt.preventDefault(),onDismiss:()=>M.onOpenChange(!1),children:s.jsx(at,{role:"listbox",id:M.contentId,"data-state":M.open?"open":"closed",dir:M.dir,onContextMenu:vt=>vt.preventDefault(),...D,...Et,onPlaced:()=>je(!0),ref:Y,style:{display:"flex",flexDirection:"column",outline:"none",...D.style},onKeyDown:Or(D.onKeyDown,vt=>{const Gt=vt.ctrlKey||vt.altKey||vt.metaKey;if(vt.key==="Tab"&&vt.preventDefault(),!Gt&&vt.key.length===1&&Ee(vt.key),["ArrowUp","ArrowDown","Home","End"].includes(vt.key)){let Pt=pe().filter(tr=>!tr.disabled).map(tr=>tr.ref.current);if(["ArrowUp","End"].includes(vt.key)&&(Pt=Pt.slice().reverse()),["ArrowUp","ArrowDown"].includes(vt.key)){const tr=vt.target,_t=Pt.indexOf(tr);Pt=Pt.slice(_t+1)}setTimeout(()=>Ae(Pt)),vt.preventDefault()}})})})})})})});z0e.displayName=$7e;var U7e="SelectItemAlignedPosition",U0e=C.forwardRef((t,e)=>{const{__scopeSelect:r,onPlaced:n,...i}=t,o=Mx(o_,r),c=Ox(o_,r),[a,f]=C.useState(null),[p,y]=C.useState(null),v=Yn(e,Y=>y(Y)),T=B3(r),E=C.useRef(!1),k=C.useRef(!0),{viewport:P,selectedItem:R,selectedItemText:D,focusSelectedItem:M}=c,B=C.useCallback(()=>{if(o.trigger&&o.valueNode&&a&&p&&P&&R&&D){const Y=o.trigger.getBoundingClientRect(),J=p.getBoundingClientRect(),Q=o.valueNode.getBoundingClientRect(),ee=D.getBoundingClientRect();if(o.dir!=="rtl"){const tr=ee.left-J.left,_t=Q.left-tr,cr=Y.left-_t,Tr=Y.width+cr,sn=Math.max(Tr,J.width),ur=window.innerWidth-qh,xr=ok(_t,[qh,Math.max(qh,ur-sn)]);a.style.minWidth=Tr+"px",a.style.left=xr+"px"}else{const tr=J.right-ee.right,_t=window.innerWidth-Q.right-tr,cr=window.innerWidth-Y.right-_t,Tr=Y.width+cr,sn=Math.max(Tr,J.width),ur=window.innerWidth-qh,xr=ok(_t,[qh,Math.max(qh,ur-sn)]);a.style.minWidth=Tr+"px",a.style.right=xr+"px"}const le=T(),pe=window.innerHeight-qh*2,Se=P.scrollHeight,je=window.getComputedStyle(p),Le=parseInt(je.borderTopWidth,10),Ae=parseInt(je.paddingTop,10),be=parseInt(je.borderBottomWidth,10),me=parseInt(je.paddingBottom,10),Te=Le+Ae+Se+me+be,Ne=Math.min(R.offsetHeight*5,Te),Ee=window.getComputedStyle(P),we=parseInt(Ee.paddingTop,10),He=parseInt(Ee.paddingBottom,10),tt=Y.top+Y.height/2-qh,at=pe-tt,Et=R.offsetHeight/2,vt=R.offsetTop+Et,Gt=Le+Ae+vt,pt=Te-Gt;if(Gt<=tt){const tr=le.length>0&&R===le[le.length-1].ref.current;a.style.bottom="0px";const _t=p.clientHeight-P.offsetTop-P.offsetHeight,cr=Math.max(at,Et+(tr?He:0)+_t+be),Tr=Gt+cr;a.style.height=Tr+"px"}else{const tr=le.length>0&&R===le[0].ref.current;a.style.top="0px";const cr=Math.max(tt,Le+P.offsetTop+(tr?we:0)+Et)+pt;a.style.height=cr+"px",P.scrollTop=Gt-tt+P.offsetTop}a.style.margin=`${qh}px 0`,a.style.minHeight=Ne+"px",a.style.maxHeight=pe+"px",n==null||n(),requestAnimationFrame(()=>E.current=!0)}},[T,o.trigger,o.valueNode,a,p,P,R,D,o.dir,n]);Do(()=>B(),[B]);const[V,G]=C.useState();Do(()=>{p&&G(window.getComputedStyle(p).zIndex)},[p]);const W=C.useCallback(Y=>{Y&&k.current===!0&&(B(),M==null||M(),k.current=!1)},[B,M]);return s.jsx(q7e,{scope:r,contentWrapper:a,shouldExpandOnScrollRef:E,onScrollButtonChange:W,children:s.jsx("div",{ref:f,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:V},children:s.jsx(nn.div,{...i,ref:v,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});U0e.displayName=U7e;var V7e="SelectPopperPosition",MV=C.forwardRef((t,e)=>{const{__scopeSelect:r,align:n="start",collisionPadding:i=qh,...o}=t,c=$3(r);return s.jsx(u3,{...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)"}})});MV.displayName=V7e;var[q7e,W7]=mT(o_,{}),OV="SelectViewport",V0e=C.forwardRef((t,e)=>{const{__scopeSelect:r,nonce:n,...i}=t,o=Ox(OV,r),c=W7(OV,r),a=Yn(e,o.onViewportChange),f=C.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(F3.Slot,{scope:r,children:s.jsx(nn.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:Or(i.onScroll,p=>{const y=p.currentTarget,{contentWrapper:v,shouldExpandOnScrollRef:T}=c;if(T!=null&&T.current&&v){const E=Math.abs(f.current-y.scrollTop);if(E>0){const k=window.innerHeight-qh*2,P=parseFloat(v.style.minHeight),R=parseFloat(v.style.height),D=Math.max(P,R);if(D0?V:0,v.style.justifyContent="flex-end")}}}f.current=y.scrollTop})})})]})});V0e.displayName=OV;var q0e="SelectGroup",[G7e,H7e]=mT(q0e),G0e=C.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=Fl();return s.jsx(G7e,{scope:r,id:i,children:s.jsx(nn.div,{role:"group","aria-labelledby":i,...n,ref:e})})});G0e.displayName=q0e;var H0e="SelectLabel",W0e=C.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=H7e(H0e,r);return s.jsx(nn.div,{id:i.id,...n,ref:e})});W0e.displayName=H0e;var nM="SelectItem",[W7e,K0e]=mT(nM),Y0e=C.forwardRef((t,e)=>{const{__scopeSelect:r,value:n,disabled:i=!1,textValue:o,...c}=t,a=Mx(nM,r),f=Ox(nM,r),p=a.value===n,[y,v]=C.useState(o??""),[T,E]=C.useState(!1),k=Yn(e,M=>{var B;return(B=f.itemRefCallback)==null?void 0:B.call(f,M,n,i)}),P=Fl(),R=C.useRef("touch"),D=()=>{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(W7e,{scope:r,value:n,disabled:i,textId:P,isSelected:p,onItemTextChange:C.useCallback(M=>{v(B=>B||((M==null?void 0:M.textContent)??"").trim())},[]),children:s.jsx(F3.ItemSlot,{scope:r,value:n,disabled:i,textValue:y,children:s.jsx(nn.div,{role:"option","aria-labelledby":P,"data-highlighted":T?"":void 0,"aria-selected":p&&T,"data-state":p?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...c,ref:k,onFocus:Or(c.onFocus,()=>E(!0)),onBlur:Or(c.onBlur,()=>E(!1)),onClick:Or(c.onClick,()=>{R.current!=="mouse"&&D()}),onPointerUp:Or(c.onPointerUp,()=>{R.current==="mouse"&&D()}),onPointerDown:Or(c.onPointerDown,M=>{R.current=M.pointerType}),onPointerMove:Or(c.onPointerMove,M=>{var B;R.current=M.pointerType,i?(B=f.onItemLeave)==null||B.call(f):R.current==="mouse"&&M.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Or(c.onPointerLeave,M=>{var B;M.currentTarget===document.activeElement&&((B=f.onItemLeave)==null||B.call(f))}),onKeyDown:Or(c.onKeyDown,M=>{var V;((V=f.searchRef)==null?void 0:V.current)!==""&&M.key===" "||(R7e.includes(M.key)&&D(),M.key===" "&&M.preventDefault())})})})})});Y0e.displayName=nM;var V2="SelectItemText",Z0e=C.forwardRef((t,e)=>{const{__scopeSelect:r,className:n,style:i,...o}=t,c=Mx(V2,r),a=Ox(V2,r),f=K0e(V2,r),p=O7e(V2,r),[y,v]=C.useState(null),T=Yn(e,D=>v(D),f.onItemTextChange,D=>{var M;return(M=a.itemTextRefCallback)==null?void 0:M.call(a,D,f.value,f.disabled)}),E=y==null?void 0:y.textContent,k=C.useMemo(()=>s.jsx("option",{value:f.value,disabled:f.disabled,children:E},f.value),[f.disabled,f.value,E]),{onNativeOptionAdd:P,onNativeOptionRemove:R}=p;return Do(()=>(P(k),()=>R(k)),[P,R,k]),s.jsxs(s.Fragment,{children:[s.jsx(nn.span,{id:f.textId,...o,ref:T}),f.isSelected&&c.valueNode&&!c.valueNodeHasChildren?dg.createPortal(o.children,c.valueNode):null]})});Z0e.displayName=V2;var X0e="SelectItemIndicator",Q0e=C.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t;return K0e(X0e,r).isSelected?s.jsx(nn.span,{"aria-hidden":!0,...n,ref:e}):null});Q0e.displayName=X0e;var FV="SelectScrollUpButton",J0e=C.forwardRef((t,e)=>{const r=Ox(FV,t.__scopeSelect),n=W7(FV,t.__scopeSelect),[i,o]=C.useState(!1),c=Yn(e,n.onScrollButtonChange);return Do(()=>{if(r.viewport&&r.isPositioned){let a=function(){const p=f.scrollTop>0;o(p)};const f=r.viewport;return a(),f.addEventListener("scroll",a),()=>f.removeEventListener("scroll",a)}},[r.viewport,r.isPositioned]),i?s.jsx(tve,{...t,ref:c,onAutoScroll:()=>{const{viewport:a,selectedItem:f}=r;a&&f&&(a.scrollTop=a.scrollTop-f.offsetHeight)}}):null});J0e.displayName=FV;var BV="SelectScrollDownButton",eve=C.forwardRef((t,e)=>{const r=Ox(BV,t.__scopeSelect),n=W7(BV,t.__scopeSelect),[i,o]=C.useState(!1),c=Yn(e,n.onScrollButtonChange);return Do(()=>{if(r.viewport&&r.isPositioned){let a=function(){const p=f.scrollHeight-f.clientHeight,y=Math.ceil(f.scrollTop)f.removeEventListener("scroll",a)}},[r.viewport,r.isPositioned]),i?s.jsx(tve,{...t,ref:c,onAutoScroll:()=>{const{viewport:a,selectedItem:f}=r;a&&f&&(a.scrollTop=a.scrollTop+f.offsetHeight)}}):null});eve.displayName=BV;var tve=C.forwardRef((t,e)=>{const{__scopeSelect:r,onAutoScroll:n,...i}=t,o=Ox("SelectScrollButton",r),c=C.useRef(null),a=B3(r),f=C.useCallback(()=>{c.current!==null&&(window.clearInterval(c.current),c.current=null)},[]);return C.useEffect(()=>()=>f(),[f]),Do(()=>{var y;const p=a().find(v=>v.ref.current===document.activeElement);(y=p==null?void 0:p.ref.current)==null||y.scrollIntoView({block:"nearest"})},[a]),s.jsx(nn.div,{"aria-hidden":!0,...i,ref:e,style:{flexShrink:0,...i.style},onPointerDown:Or(i.onPointerDown,()=>{c.current===null&&(c.current=window.setInterval(n,50))}),onPointerMove:Or(i.onPointerMove,()=>{var p;(p=o.onItemLeave)==null||p.call(o),c.current===null&&(c.current=window.setInterval(n,50))}),onPointerLeave:Or(i.onPointerLeave,()=>{f()})})}),K7e="SelectSeparator",rve=C.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t;return s.jsx(nn.div,{"aria-hidden":!0,...n,ref:e})});rve.displayName=K7e;var $V="SelectArrow",Y7e=C.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=$3(r),o=Mx($V,r),c=Ox($V,r);return o.open&&c.position==="popper"?s.jsx(d3,{...i,...n,ref:e}):null});Y7e.displayName=$V;var Z7e="SelectBubbleInput",nve=C.forwardRef(({__scopeSelect:t,value:e,...r},n)=>{const i=C.useRef(null),o=Yn(n,i),c=UC(e);return C.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(nn.select,{...r,style:{...$fe,...r.style},ref:o,defaultValue:e})});nve.displayName=Z7e;function ive(t){return t===""||t===void 0}function sve(t){const e=vo(t),r=C.useRef(""),n=C.useRef(0),i=C.useCallback(c=>{const a=r.current+c;e(a),function f(p){r.current=p,window.clearTimeout(n.current),p!==""&&(n.current=window.setTimeout(()=>f(""),1e3))}(a)},[e]),o=C.useCallback(()=>{r.current="",window.clearTimeout(n.current)},[]);return C.useEffect(()=>()=>window.clearTimeout(n.current),[]),[r,i,o]}function ave(t,e,r){const i=e.length>1&&Array.from(e).every(p=>p===e[0])?e[0]:e,o=r?t.indexOf(r):-1;let c=X7e(t,Math.max(o,0));i.length===1&&(c=c.filter(p=>p!==r));const f=c.find(p=>p.textValue.toLowerCase().startsWith(i.toLowerCase()));return f!==r?f:void 0}function X7e(t,e){return t.map((r,n)=>t[(e+n)%t.length])}var Q7e=P0e,ove=L0e,J7e=M0e,eHe=O0e,tHe=F0e,lve=B0e,rHe=V0e,nHe=G0e,cve=W0e,uve=Y0e,iHe=Z0e,sHe=Q0e,dve=J0e,hve=eve,fve=rve;const ba=Q7e,Oqt=nHe,wa=J7e,oa=C.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(ove,{ref:n,className:qt("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(eHe,{asChild:!0,children:s.jsx(yl,{className:"h-4 w-4 opacity-50"})})]}));oa.displayName=ove.displayName;const mve=C.forwardRef(({className:t,...e},r)=>s.jsx(dve,{ref:r,className:qt("flex cursor-default items-center justify-center py-1",t),...e,children:s.jsx(ume,{className:"h-4 w-4"})}));mve.displayName=dve.displayName;const pve=C.forwardRef(({className:t,...e},r)=>s.jsx(hve,{ref:r,className:qt("flex cursor-default items-center justify-center py-1",t),...e,children:s.jsx(yl,{className:"h-4 w-4"})}));pve.displayName=hve.displayName;const la=C.forwardRef(({className:t,children:e,position:r="popper",...n},i)=>s.jsx(tHe,{children:s.jsxs(lve,{ref:i,className:qt("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(mve,{}),s.jsx(rHe,{className:qt("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),s.jsx(pve,{})]})}));la.displayName=lve.displayName;const aHe=C.forwardRef(({className:t,...e},r)=>s.jsx(cve,{ref:r,className:qt("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...e}));aHe.displayName=cve.displayName;const mn=C.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(uve,{ref:n,className:qt("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(sHe,{children:s.jsx(no,{className:"h-4 w-4"})})}),s.jsx(iHe,{children:e})]}));mn.displayName=uve.displayName;const oHe=C.forwardRef(({className:t,...e},r)=>s.jsx(fve,{ref:r,className:qt("-mx-1 my-1 h-px bg-muted",t),...e}));oHe.displayName=fve.displayName;const lHe=mg({category:cS(["general","technology","crm","marketing"]),subject:Ai().min(5,"Subject must be at least 5 characters").max(200),description:Ai().min(20,"Please provide more details (at least 20 characters)").max(1e4,"Please keep the description under 10,000 characters")}),cHe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function uHe({trigger:t}){const[e,r]=C.useState(!1),[n,i]=C.useState(!1),{user:o}=Hn(),c=M7({resolver:O7(lHe),defaultValues:{category:"general",subject:"",description:""}}),a=async f=>{if(!o){Vt.error("You must be logged in to submit a ticket");return}i(!0);try{const{error:p}=await Re.from("support_tickets").insert({user_id:o.id,category:f.category,subject:f.subject,description:f.description});if(p)throw p;try{await Re.functions.invoke("support-ticket-notify",{body:{category:cHe[f.category],subject:f.subject}})}catch(y){console.log("Notification send attempted:",y)}Vt.success("Support ticket submitted successfully!"),c.reset(),r(!1)}catch(p){console.error("Error submitting ticket:",p),Vt.error("Failed to submit ticket. Please try again.")}finally{i(!1)}};return s.jsxs(lo,{open:e,onOpenChange:r,children:[s.jsx(yxe,{asChild:!0,children:t||s.jsxs(Bt,{variant:"ghost",size:"icon",className:"relative",children:[s.jsx(GDe,{className:"h-5 w-5"}),s.jsx("span",{className:"sr-only",children:"Support"})]})}),s.jsxs(qa,{className:"sm:max-w-[500px]",children:[s.jsxs(xl,{children:[s.jsx(Xo,{children:"Need Help?"}),s.jsx(wd,{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(ri,{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(H7,{...c,children:s.jsxs("form",{onSubmit:c.handleSubmit(a),className:"space-y-4",children:[s.jsx(ll,{control:c.control,name:"category",render:({field:f})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"Category"}),s.jsxs(ba,{onValueChange:f.onChange,defaultValue:f.value,children:[s.jsx(Go,{children:s.jsx(oa,{children:s.jsx(wa,{placeholder:"Select a category"})})}),s.jsxs(la,{children:[s.jsx(mn,{value:"general",children:"General Support"}),s.jsx(mn,{value:"technology",children:"Technology Support"}),s.jsx(mn,{value:"crm",children:"CRM Support"}),s.jsx(mn,{value:"marketing",children:"Marketing Support"})]})]}),s.jsx(lf,{})]})}),s.jsx(ll,{control:c.control,name:"subject",render:({field:f})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"Subject"}),s.jsx(Go,{children:s.jsx(Br,{placeholder:"Brief description of your issue",...f})}),s.jsx(lf,{})]})}),s.jsx(ll,{control:c.control,name:"description",render:({field:f})=>{var p;return s.jsxs(Vo,{children:[s.jsx(qo,{children:"Description"}),s.jsx(Go,{children:s.jsx(Ad,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...f})}),s.jsxs("p",{className:"text-right text-xs text-muted-foreground",children:[(((p=f.value)==null?void 0:p.length)??0).toLocaleString()," / 10,000"]}),s.jsx(lf,{})]})}}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(Bt,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),s.jsx(Bt,{type:"submit",disabled:n,children:n?"Submitting...":"Submit Ticket"})]})]})})]})]})}function On(t){const e=Object.prototype.toString.call(t);return t instanceof Date||typeof t=="object"&&e==="[object Date]"?new t.constructor(+t):typeof t=="number"||e==="[object Number]"||typeof t=="string"||e==="[object String]"?new Date(t):new Date(NaN)}function Xs(t,e){return t instanceof Date?new t.constructor(e):new Date(e)}function Rl(t,e){const r=On(t);return isNaN(e)?Xs(t,NaN):(e&&r.setDate(r.getDate()+e),r)}function Sd(t,e){const r=On(t);if(isNaN(e))return Xs(t,NaN);if(!e)return r;const n=r.getDate(),i=Xs(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 K7=6048e5,dHe=864e5,Y7=6e4,Z7=36e5,hHe=1e3,pR=43200,Dre=1440;let fHe={};function Fx(){return fHe}function jc(t,e){var a,f,p,y;const r=Fx(),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=(p=r.locale)==null?void 0:p.options)==null?void 0:y.weekStartsOn)??0,i=On(t),o=i.getDay(),c=(o=i.getTime()?r+1:e.getTime()>=c.getTime()?r:r-1}function yx(t){const e=On(t);return e.setHours(0,0,0,0),e}function xx(t){const e=On(t),r=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return r.setUTCFullYear(e.getFullYear()),+t-+r}function cf(t,e){const r=yx(t),n=yx(e),i=+r-xx(r),o=+n-xx(n);return Math.round((i-o)/dHe)}function mHe(t){const e=gve(t),r=Xs(t,0);return r.setFullYear(e,0,4),r.setHours(0,0,0,0),ng(r)}function zV(t,e){const r=e*7;return Rl(t,r)}function pHe(t,e){return Sd(t,e*12)}function gHe(t){let e;return t.forEach(function(r){const n=On(r);(e===void 0||e{const n=On(r);(!e||e>n||isNaN(+n))&&(e=n)}),e||new Date(NaN)}function IL(t,e){const r=On(t),n=On(e),i=r.getTime()-n.getTime();return i<0?-1:i>0?1:i}function X7(t){return Xs(t,Date.now())}function rc(t,e){const r=yx(t),n=yx(e);return+r==+n}function Q7(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function UV(t){if(!Q7(t)&&typeof t!="number")return!1;const e=On(t);return!isNaN(Number(e))}function uS(t,e){const r=On(t),n=On(e),i=r.getFullYear()-n.getFullYear(),o=r.getMonth()-n.getMonth();return i*12+o}function xHe(t,e,r){const n=jc(t,r),i=jc(e,r),o=+n-xx(n),c=+i-xx(i);return Math.round((o-c)/K7)}function vHe(t,e){const r=On(t),n=On(e),i=Mre(r,n),o=Math.abs(cf(r,n));r.setDate(r.getDate()-i*o);const c=+(Mre(r,n)===-i),a=i*(o-c);return a===0?0:a}function Mre(t,e){const r=t.getFullYear()-e.getFullYear()||t.getMonth()-e.getMonth()||t.getDate()-e.getDate()||t.getHours()-e.getHours()||t.getMinutes()-e.getMinutes()||t.getSeconds()-e.getSeconds()||t.getMilliseconds()-e.getMilliseconds();return r<0?-1:r>0?1:r}function _He(t){return e=>{const n=(t?Math[t]:Math.trunc)(e);return n===0?0:n}}function bHe(t,e){return+On(t)-+On(e)}function wHe(t){const e=On(t);return e.setHours(23,59,59,999),e}function VC(t){const e=On(t),r=e.getMonth();return e.setFullYear(e.getFullYear(),r+1,0),e.setHours(23,59,59,999),e}function SHe(t){const e=On(t);return+wHe(e)==+VC(e)}function THe(t,e){const r=On(t),n=On(e),i=IL(r,n),o=Math.abs(uS(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=IL(r,n)===-i;SHe(On(t))&&o===1&&IL(t,n)===1&&(a=!1),c=i*(o-Number(a))}return c===0?0:c}function EHe(t,e,r){const n=bHe(t,e)/1e3;return _He(r==null?void 0:r.roundingMethod)(n)}function jHe(t,e){const r=On(t.start),n=On(t.end);let i=+r>+n;const o=i?+r:+n,c=i?n:r;c.setHours(0,0,0,0);let a=1;const f=[];for(;+c<=o;)f.push(On(c)),c.setDate(c.getDate()+a),c.setHours(0,0,0,0);return i?f.reverse():f}function iu(t){const e=On(t);return e.setDate(1),e.setHours(0,0,0,0),e}function yve(t){const e=On(t),r=Xs(t,0);return r.setFullYear(e.getFullYear(),0,1),r.setHours(0,0,0,0),r}function z3(t,e){var a,f,p,y;const r=Fx(),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=(p=r.locale)==null?void 0:p.options)==null?void 0:y.weekStartsOn)??0,i=On(t),o=i.getDay(),c=(o{let n;const i=AHe[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 U$(t){return(e={})=>{const r=e.width?String(e.width):t.defaultWidth;return t.formats[r]||t.formats[t.defaultWidth]}}const CHe={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},NHe={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},IHe={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},PHe={date:U$({formats:CHe,defaultWidth:"full"}),time:U$({formats:NHe,defaultWidth:"full"}),dateTime:U$({formats:IHe,defaultWidth:"full"})},RHe={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},LHe=(t,e,r,n)=>RHe[t];function o2(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 DHe={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},MHe={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},OHe={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"]},FHe={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"]},BHe={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"}},$He={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"}},zHe=(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"},UHe={ordinalNumber:zHe,era:o2({values:DHe,defaultWidth:"wide"}),quarter:o2({values:MHe,defaultWidth:"wide",argumentCallback:t=>t-1}),month:o2({values:OHe,defaultWidth:"wide"}),day:o2({values:FHe,defaultWidth:"wide"}),dayPeriod:o2({values:BHe,defaultWidth:"wide",formattingValues:$He,defaultFormattingWidth:"wide"})};function l2(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)?qHe(a,v=>v.test(c)):VHe(a,v=>v.test(c));let p;p=t.valueCallback?t.valueCallback(f):f,p=r.valueCallback?r.valueCallback(p):p;const y=e.slice(c.length);return{value:p,rest:y}}}function VHe(t,e){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&e(t[r]))return r}function qHe(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 HHe=/^(\d+)(th|st|nd|rd)?/i,WHe=/\d+/i,KHe={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},YHe={any:[/^b/i,/^(a|c)/i]},ZHe={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},XHe={any:[/1/i,/2/i,/3/i,/4/i]},QHe={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},JHe={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]},eWe={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},tWe={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]},rWe={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},nWe={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}},iWe={ordinalNumber:GHe({matchPattern:HHe,parsePattern:WHe,valueCallback:t=>parseInt(t,10)}),era:l2({matchPatterns:KHe,defaultMatchWidth:"wide",parsePatterns:YHe,defaultParseWidth:"any"}),quarter:l2({matchPatterns:ZHe,defaultMatchWidth:"wide",parsePatterns:XHe,defaultParseWidth:"any",valueCallback:t=>t+1}),month:l2({matchPatterns:QHe,defaultMatchWidth:"wide",parsePatterns:JHe,defaultParseWidth:"any"}),day:l2({matchPatterns:eWe,defaultMatchWidth:"wide",parsePatterns:tWe,defaultParseWidth:"any"}),dayPeriod:l2({matchPatterns:rWe,defaultMatchWidth:"any",parsePatterns:nWe,defaultParseWidth:"any"})},U3={code:"en-US",formatDistance:kHe,formatLong:PHe,formatRelative:LHe,localize:UHe,match:iWe,options:{weekStartsOn:0,firstWeekContainsDate:1}};function sWe(t){const e=On(t);return cf(e,yve(e))+1}function J7(t){const e=On(t),r=+ng(e)-+mHe(e);return Math.round(r/K7)+1}function eH(t,e){var y,v,T,E;const r=On(t),n=r.getFullYear(),i=Fx(),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??((E=(T=i.locale)==null?void 0:T.options)==null?void 0:E.firstWeekContainsDate)??1,c=Xs(t,0);c.setFullYear(n+1,0,o),c.setHours(0,0,0,0);const a=jc(c,e),f=Xs(t,0);f.setFullYear(n,0,o),f.setHours(0,0,0,0);const p=jc(f,e);return r.getTime()>=a.getTime()?n+1:r.getTime()>=p.getTime()?n:n-1}function aWe(t,e){var a,f,p,y;const r=Fx(),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=(p=r.locale)==null?void 0:p.options)==null?void 0:y.firstWeekContainsDate)??1,i=eH(t,e),o=Xs(t,0);return o.setFullYear(i,0,n),o.setHours(0,0,0,0),jc(o,e)}function tH(t,e){const r=On(t),n=+jc(r,e)-+aWe(r,e);return Math.round(n/K7)+1}function zs(t,e){const r=t<0?"-":"",n=Math.abs(t).toString().padStart(e,"0");return r+n}const cy={y(t,e){const r=t.getFullYear(),n=r>0?r:1-r;return zs(e==="yy"?n%100:n,e.length)},M(t,e){const r=t.getMonth();return e==="M"?String(r+1):zs(r+1,2)},d(t,e){return zs(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 zs(t.getHours()%12||12,e.length)},H(t,e){return zs(t.getHours(),e.length)},m(t,e){return zs(t.getMinutes(),e.length)},s(t,e){return zs(t.getSeconds(),e.length)},S(t,e){const r=e.length,n=t.getMilliseconds(),i=Math.trunc(n*Math.pow(10,r-3));return zs(i,e.length)}},yw={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Ore={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 cy.y(t,e)},Y:function(t,e,r,n){const i=eH(t,n),o=i>0?i:1-i;if(e==="YY"){const c=o%100;return zs(c,2)}return e==="Yo"?r.ordinalNumber(o,{unit:"year"}):zs(o,e.length)},R:function(t,e){const r=gve(t);return zs(r,e.length)},u:function(t,e){const r=t.getFullYear();return zs(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 zs(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 zs(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 cy.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 zs(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=tH(t,n);return e==="wo"?r.ordinalNumber(i,{unit:"week"}):zs(i,e.length)},I:function(t,e,r){const n=J7(t);return e==="Io"?r.ordinalNumber(n,{unit:"week"}):zs(n,e.length)},d:function(t,e,r){return e==="do"?r.ordinalNumber(t.getDate(),{unit:"date"}):cy.d(t,e)},D:function(t,e,r){const n=sWe(t);return e==="Do"?r.ordinalNumber(n,{unit:"dayOfYear"}):zs(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 zs(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 zs(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 zs(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=yw.noon:n===0?i=yw.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=yw.evening:n>=12?i=yw.afternoon:n>=4?i=yw.morning:i=yw.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 cy.h(t,e)},H:function(t,e,r){return e==="Ho"?r.ordinalNumber(t.getHours(),{unit:"hour"}):cy.H(t,e)},K:function(t,e,r){const n=t.getHours()%12;return e==="Ko"?r.ordinalNumber(n,{unit:"hour"}):zs(n,e.length)},k:function(t,e,r){let n=t.getHours();return n===0&&(n=24),e==="ko"?r.ordinalNumber(n,{unit:"hour"}):zs(n,e.length)},m:function(t,e,r){return e==="mo"?r.ordinalNumber(t.getMinutes(),{unit:"minute"}):cy.m(t,e)},s:function(t,e,r){return e==="so"?r.ordinalNumber(t.getSeconds(),{unit:"second"}):cy.s(t,e)},S:function(t,e){return cy.S(t,e)},X:function(t,e,r){const n=t.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return Bre(n);case"XXXX":case"XX":return mv(n);case"XXXXX":case"XXX":default:return mv(n,":")}},x:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"x":return Bre(n);case"xxxx":case"xx":return mv(n);case"xxxxx":case"xxx":default:return mv(n,":")}},O:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+Fre(n,":");case"OOOO":default:return"GMT"+mv(n,":")}},z:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+Fre(n,":");case"zzzz":default:return"GMT"+mv(n,":")}},t:function(t,e,r){const n=Math.trunc(t.getTime()/1e3);return zs(n,e.length)},T:function(t,e,r){const n=t.getTime();return zs(n,e.length)}};function Fre(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+zs(o,2)}function Bre(t,e){return t%60===0?(t>0?"-":"+")+zs(Math.abs(t)/60,2):mv(t,e)}function mv(t,e=""){const r=t>0?"-":"+",n=Math.abs(t),i=zs(Math.trunc(n/60),2),o=zs(n%60,2);return r+i+e+o}const $re=(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"})}},vve=(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"})}},oWe=(t,e)=>{const r=t.match(/(P+)(p+)?/)||[],n=r[1],i=r[2];if(!i)return $re(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}}",$re(n,e)).replace("{{time}}",vve(i,e))},VV={p:vve,P:oWe},lWe=/^D+$/,cWe=/^Y+$/,uWe=["D","DD","YY","YYYY"];function _ve(t){return lWe.test(t)}function bve(t){return cWe.test(t)}function qV(t,e,r){const n=dWe(t,e,r);if(console.warn(n),uWe.includes(t))throw new RangeError(n)}function dWe(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 hWe=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,fWe=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,mWe=/^'([^]*?)'?$/,pWe=/''/g,gWe=/[a-zA-Z]/;function Ri(t,e,r){var y,v,T,E,k,P,R,D;const n=Fx(),i=(r==null?void 0:r.locale)??n.locale??U3,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??((E=(T=n.locale)==null?void 0:T.options)==null?void 0:E.firstWeekContainsDate)??1,c=(r==null?void 0:r.weekStartsOn)??((P=(k=r==null?void 0:r.locale)==null?void 0:k.options)==null?void 0:P.weekStartsOn)??n.weekStartsOn??((D=(R=n.locale)==null?void 0:R.options)==null?void 0:D.weekStartsOn)??0,a=On(t);if(!UV(a))throw new RangeError("Invalid time value");let f=e.match(fWe).map(M=>{const B=M[0];if(B==="p"||B==="P"){const V=VV[B];return V(M,i.formatLong)}return M}).join("").match(hWe).map(M=>{if(M==="''")return{isToken:!1,value:"'"};const B=M[0];if(B==="'")return{isToken:!1,value:yWe(M)};if(Ore[B])return{isToken:!0,value:M};if(B.match(gWe))throw new RangeError("Format string contains an unescaped latin alphabet character `"+B+"`");return{isToken:!1,value:M}});i.localize.preprocessor&&(f=i.localize.preprocessor(a,f));const p={firstWeekContainsDate:o,weekStartsOn:c,locale:i};return f.map(M=>{if(!M.isToken)return M.value;const B=M.value;(!(r!=null&&r.useAdditionalWeekYearTokens)&&bve(B)||!(r!=null&&r.useAdditionalDayOfYearTokens)&&_ve(B))&&qV(B,e,String(t));const V=Ore[B[0]];return V(a,B,i.localize,p)}).join("")}function yWe(t){const e=t.match(mWe);return e?e[1].replace(pWe,"'"):t}function xWe(t,e,r){const n=Fx(),i=(r==null?void 0:r.locale)??n.locale??U3,o=2520,c=IL(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,p;c>0?(f=On(e),p=On(t)):(f=On(t),p=On(e));const y=EHe(p,f),v=(xx(p)-xx(f))/1e3,T=Math.round((y-v)/60);let E;if(T<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):T===0?i.formatDistance("lessThanXMinutes",1,a):i.formatDistance("xMinutes",T,a);if(T<45)return i.formatDistance("xMinutes",T,a);if(T<90)return i.formatDistance("aboutXHours",1,a);if(Tn.getTime()}function rH(t,e){const r=On(t),n=On(e);return+r<+n}function EWe(t,e){const r=e instanceof Date?Xs(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 jWe=10;class Sve{constructor(){dn(this,"subPriority",0)}validate(e,r){return!0}}class AWe extends Sve{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 kWe extends Sve{constructor(){super(...arguments);dn(this,"priority",jWe);dn(this,"subPriority",-1)}set(r,n){return n.timestampIsSet?r:Xs(r,EWe(r,Date))}}class js{run(e,r,n,i){const o=this.parse(e,r,n,i);return o?{setter:new AWe(o.value,this.validate,this.set,this.priority,this.subPriority),rest:o.rest}:null}validate(e,r,n){return!0}}class CWe extends js{constructor(){super(...arguments);dn(this,"priority",140);dn(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 Po={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}/},am={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 Ro(t,e){return t&&{value:e(t.value),rest:t.rest}}function ro(t,e){const r=e.match(t);return r?{value:parseInt(r[0],10),rest:e.slice(r[0].length)}:null}function om(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*Z7+o*Y7+c*hHe),rest:e.slice(r[0].length)}}function Tve(t){return ro(Po.anyDigitsSigned,t)}function bo(t,e){switch(t){case 1:return ro(Po.singleDigit,e);case 2:return ro(Po.twoDigits,e);case 3:return ro(Po.threeDigits,e);case 4:return ro(Po.fourDigits,e);default:return ro(new RegExp("^\\d{1,"+t+"}"),e)}}function iM(t,e){switch(t){case 1:return ro(Po.singleDigitSigned,e);case 2:return ro(Po.twoDigitsSigned,e);case 3:return ro(Po.threeDigitsSigned,e);case 4:return ro(Po.fourDigitsSigned,e);default:return ro(new RegExp("^-?\\d{1,"+t+"}"),e)}}function nH(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 Eve(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 jve(t){return t%400===0||t%4===0&&t%100!==0}class NWe extends js{constructor(){super(...arguments);dn(this,"priority",130);dn(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 Ro(bo(4,r),o);case"yo":return Ro(i.ordinalNumber(r,{unit:"year"}),o);default:return Ro(bo(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=Eve(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 IWe extends js{constructor(){super(...arguments);dn(this,"priority",130);dn(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 Ro(bo(4,r),o);case"Yo":return Ro(i.ordinalNumber(r,{unit:"year"}),o);default:return Ro(bo(n.length,r),o)}}validate(r,n){return n.isTwoDigitYear||n.year>0}set(r,n,i,o){const c=eH(r,o);if(i.isTwoDigitYear){const f=Eve(i.year,c);return r.setFullYear(f,0,o.firstWeekContainsDate),r.setHours(0,0,0,0),jc(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),jc(r,o)}}class PWe extends js{constructor(){super(...arguments);dn(this,"priority",130);dn(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(r,n){return iM(n==="R"?4:n.length,r)}set(r,n,i){const o=Xs(r,0);return o.setFullYear(i,0,4),o.setHours(0,0,0,0),ng(o)}}class RWe extends js{constructor(){super(...arguments);dn(this,"priority",130);dn(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(r,n){return iM(n==="u"?4:n.length,r)}set(r,n,i){return r.setFullYear(i,0,1),r.setHours(0,0,0,0),r}}class LWe extends js{constructor(){super(...arguments);dn(this,"priority",120);dn(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 bo(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 DWe extends js{constructor(){super(...arguments);dn(this,"priority",120);dn(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 bo(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 MWe extends js{constructor(){super(...arguments);dn(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);dn(this,"priority",110)}parse(r,n,i){const o=c=>c-1;switch(n){case"M":return Ro(ro(Po.month,r),o);case"MM":return Ro(bo(2,r),o);case"Mo":return Ro(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 OWe extends js{constructor(){super(...arguments);dn(this,"priority",110);dn(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 Ro(ro(Po.month,r),o);case"LL":return Ro(bo(2,r),o);case"Lo":return Ro(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 FWe(t,e,r){const n=On(t),i=tH(n,r)-e;return n.setDate(n.getDate()-i*7),n}class BWe extends js{constructor(){super(...arguments);dn(this,"priority",100);dn(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(r,n,i){switch(n){case"w":return ro(Po.week,r);case"wo":return i.ordinalNumber(r,{unit:"week"});default:return bo(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,i,o){return jc(FWe(r,i,o),o)}}function $We(t,e){const r=On(t),n=J7(r)-e;return r.setDate(r.getDate()-n*7),r}class zWe extends js{constructor(){super(...arguments);dn(this,"priority",100);dn(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 ro(Po.week,r);case"Io":return i.ordinalNumber(r,{unit:"week"});default:return bo(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,i){return ng($We(r,i))}}const UWe=[31,28,31,30,31,30,31,31,30,31,30,31],VWe=[31,29,31,30,31,30,31,31,30,31,30,31];class qWe extends js{constructor(){super(...arguments);dn(this,"priority",90);dn(this,"subPriority",1);dn(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(r,n,i){switch(n){case"d":return ro(Po.date,r);case"do":return i.ordinalNumber(r,{unit:"date"});default:return bo(n.length,r)}}validate(r,n){const i=r.getFullYear(),o=jve(i),c=r.getMonth();return o?n>=1&&n<=VWe[c]:n>=1&&n<=UWe[c]}set(r,n,i){return r.setDate(i),r.setHours(0,0,0,0),r}}class GWe extends js{constructor(){super(...arguments);dn(this,"priority",90);dn(this,"subpriority",1);dn(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 ro(Po.dayOfYear,r);case"Do":return i.ordinalNumber(r,{unit:"date"});default:return bo(n.length,r)}}validate(r,n){const i=r.getFullYear();return jve(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 iH(t,e,r){var v,T,E,k;const n=Fx(),i=(r==null?void 0:r.weekStartsOn)??((T=(v=r==null?void 0:r.locale)==null?void 0:v.options)==null?void 0:T.weekStartsOn)??n.weekStartsOn??((k=(E=n.locale)==null?void 0:E.options)==null?void 0:k.weekStartsOn)??0,o=On(t),c=o.getDay(),f=(e%7+7)%7,p=7-i,y=e<0||e>6?e-(c+p)%7:(f+p)%7-(c+p)%7;return Rl(o,y)}class HWe extends js{constructor(){super(...arguments);dn(this,"priority",90);dn(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=iH(r,i,o),r.setHours(0,0,0,0),r}}class WWe extends js{constructor(){super(...arguments);dn(this,"priority",90);dn(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 Ro(bo(n.length,r),c);case"eo":return Ro(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=iH(r,i,o),r.setHours(0,0,0,0),r}}class KWe extends js{constructor(){super(...arguments);dn(this,"priority",90);dn(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 Ro(bo(n.length,r),c);case"co":return Ro(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=iH(r,i,o),r.setHours(0,0,0,0),r}}function YWe(t,e){const r=On(t),n=bWe(r),i=e-n;return Rl(r,i)}class ZWe extends js{constructor(){super(...arguments);dn(this,"priority",90);dn(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 bo(n.length,r);case"io":return i.ordinalNumber(r,{unit:"day"});case"iii":return Ro(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 Ro(i.day(r,{width:"narrow",context:"formatting"}),o);case"iiiiii":return Ro(i.day(r,{width:"short",context:"formatting"})||i.day(r,{width:"narrow",context:"formatting"}),o);case"iiii":default:return Ro(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=YWe(r,i),r.setHours(0,0,0,0),r}}class XWe extends js{constructor(){super(...arguments);dn(this,"priority",80);dn(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(nH(i),0,0,0),r}}class QWe extends js{constructor(){super(...arguments);dn(this,"priority",80);dn(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(nH(i),0,0,0),r}}class JWe extends js{constructor(){super(...arguments);dn(this,"priority",80);dn(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(nH(i),0,0,0),r}}class eKe extends js{constructor(){super(...arguments);dn(this,"priority",70);dn(this,"incompatibleTokens",["H","K","k","t","T"])}parse(r,n,i){switch(n){case"h":return ro(Po.hour12h,r);case"ho":return i.ordinalNumber(r,{unit:"hour"});default:return bo(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 tKe extends js{constructor(){super(...arguments);dn(this,"priority",70);dn(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(r,n,i){switch(n){case"H":return ro(Po.hour23h,r);case"Ho":return i.ordinalNumber(r,{unit:"hour"});default:return bo(n.length,r)}}validate(r,n){return n>=0&&n<=23}set(r,n,i){return r.setHours(i,0,0,0),r}}class rKe extends js{constructor(){super(...arguments);dn(this,"priority",70);dn(this,"incompatibleTokens",["h","H","k","t","T"])}parse(r,n,i){switch(n){case"K":return ro(Po.hour11h,r);case"Ko":return i.ordinalNumber(r,{unit:"hour"});default:return bo(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 nKe extends js{constructor(){super(...arguments);dn(this,"priority",70);dn(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(r,n,i){switch(n){case"k":return ro(Po.hour24h,r);case"ko":return i.ordinalNumber(r,{unit:"hour"});default:return bo(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 iKe extends js{constructor(){super(...arguments);dn(this,"priority",60);dn(this,"incompatibleTokens",["t","T"])}parse(r,n,i){switch(n){case"m":return ro(Po.minute,r);case"mo":return i.ordinalNumber(r,{unit:"minute"});default:return bo(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,i){return r.setMinutes(i,0,0),r}}class sKe extends js{constructor(){super(...arguments);dn(this,"priority",50);dn(this,"incompatibleTokens",["t","T"])}parse(r,n,i){switch(n){case"s":return ro(Po.second,r);case"so":return i.ordinalNumber(r,{unit:"second"});default:return bo(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,i){return r.setSeconds(i,0),r}}class aKe extends js{constructor(){super(...arguments);dn(this,"priority",30);dn(this,"incompatibleTokens",["t","T"])}parse(r,n){const i=o=>Math.trunc(o*Math.pow(10,-n.length+3));return Ro(bo(n.length,r),i)}set(r,n,i){return r.setMilliseconds(i),r}}class oKe extends js{constructor(){super(...arguments);dn(this,"priority",10);dn(this,"incompatibleTokens",["t","T","x"])}parse(r,n){switch(n){case"X":return om(am.basicOptionalMinutes,r);case"XX":return om(am.basic,r);case"XXXX":return om(am.basicOptionalSeconds,r);case"XXXXX":return om(am.extendedOptionalSeconds,r);case"XXX":default:return om(am.extended,r)}}set(r,n,i){return n.timestampIsSet?r:Xs(r,r.getTime()-xx(r)-i)}}class lKe extends js{constructor(){super(...arguments);dn(this,"priority",10);dn(this,"incompatibleTokens",["t","T","X"])}parse(r,n){switch(n){case"x":return om(am.basicOptionalMinutes,r);case"xx":return om(am.basic,r);case"xxxx":return om(am.basicOptionalSeconds,r);case"xxxxx":return om(am.extendedOptionalSeconds,r);case"xxx":default:return om(am.extended,r)}}set(r,n,i){return n.timestampIsSet?r:Xs(r,r.getTime()-xx(r)-i)}}class cKe extends js{constructor(){super(...arguments);dn(this,"priority",40);dn(this,"incompatibleTokens","*")}parse(r){return Tve(r)}set(r,n,i){return[Xs(r,i*1e3),{timestampIsSet:!0}]}}class uKe extends js{constructor(){super(...arguments);dn(this,"priority",20);dn(this,"incompatibleTokens","*")}parse(r){return Tve(r)}set(r,n,i){return[Xs(r,i),{timestampIsSet:!0}]}}const dKe={G:new CWe,y:new NWe,Y:new IWe,R:new PWe,u:new RWe,Q:new LWe,q:new DWe,M:new MWe,L:new OWe,w:new BWe,I:new zWe,d:new qWe,D:new GWe,E:new HWe,e:new WWe,c:new KWe,i:new ZWe,a:new XWe,b:new QWe,B:new JWe,h:new eKe,H:new tKe,K:new rKe,k:new nKe,m:new iKe,s:new sKe,S:new aKe,X:new oKe,x:new lKe,t:new cKe,T:new uKe},hKe=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,fKe=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,mKe=/^'([^]*?)'?$/,pKe=/''/g,gKe=/\S/,yKe=/[a-zA-Z]/;function xKe(t,e,r,n){var P,R,D,M;const i=_We(),o=i.locale??U3,c=i.firstWeekContainsDate??((R=(P=i.locale)==null?void 0:P.options)==null?void 0:R.firstWeekContainsDate)??1,a=i.weekStartsOn??((M=(D=i.locale)==null?void 0:D.options)==null?void 0:M.weekStartsOn)??0;if(e==="")return t===""?On(r):Xs(r,NaN);const f={firstWeekContainsDate:c,weekStartsOn:a,locale:o},p=[new kWe],y=e.match(fKe).map(B=>{const V=B[0];if(V in VV){const G=VV[V];return G(B,o.formatLong)}return B}).join("").match(hKe),v=[];for(let B of y){bve(B)&&qV(B,e,t),_ve(B)&&qV(B,e,t);const V=B[0],G=dKe[V];if(G){const{incompatibleTokens:W}=G;if(Array.isArray(W)){const J=v.find(Q=>W.includes(Q.token)||Q.token===V);if(J)throw new RangeError(`The format string mustn't contain \`${J.fullToken}\` and \`${B}\` at the same time`)}else if(G.incompatibleTokens==="*"&&v.length>0)throw new RangeError(`The format string mustn't contain \`${B}\` and any other token at the same time`);v.push({token:V,fullToken:B});const Y=G.run(t,B,o.match,f);if(!Y)return Xs(r,NaN);p.push(Y.setter),t=Y.rest}else{if(V.match(yKe))throw new RangeError("Format string contains an unescaped latin alphabet character `"+V+"`");if(B==="''"?B="'":V==="'"&&(B=vKe(B)),t.indexOf(B)===0)t=t.slice(B.length);else return Xs(r,NaN)}}if(t.length>0&&gKe.test(t))return Xs(r,NaN);const T=p.map(B=>B.priority).sort((B,V)=>V-B).filter((B,V,G)=>G.indexOf(B)===V).map(B=>p.filter(V=>V.priority===B).sort((V,G)=>G.subPriority-V.subPriority)).map(B=>B[0]);let E=On(r);if(isNaN(E.getTime()))return Xs(r,NaN);const k={};for(const B of T){if(!B.validate(E,f))return Xs(r,NaN);const V=B.set(E,k,f);Array.isArray(V)?(E=V[0],Object.assign(k,V[1])):E=V}return Xs(r,E)}function vKe(t){return t.match(mKe)[1].replace(pKe,"'")}function dS(t){return+On(t)2)return e;if(/:/.test(r[0])?n=r[0]:(e.date=r[0],n=r[1],gR.timeZoneDelimiter.test(e.date)&&(e.date=t.split(gR.timeZoneDelimiter)[0],n=t.substr(e.date.length,t.length))),n){const i=gR.timezone.exec(n);i?(e.time=n.replace(i[1],""),e.timezone=i[1]):e.time=n}return e}function AKe(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 kKe(t,e){if(e===null)return new Date(NaN);const r=t.match(SKe);if(!r)return new Date(NaN);const n=!!r[4],i=c2(r[1]),o=c2(r[2])-1,c=c2(r[3]),a=c2(r[4]),f=c2(r[5])-1;if(n)return DKe(e,a,f)?IKe(e,a,f):new Date(NaN);{const p=new Date(0);return!RKe(e,o,c)||!LKe(e,i)?new Date(NaN):(p.setUTCFullYear(e,o,Math.max(i,c)),p)}}function c2(t){return t?parseInt(t):1}function CKe(t){const e=t.match(TKe);if(!e)return NaN;const r=q$(e[1]),n=q$(e[2]),i=q$(e[3]);return MKe(r,n,i)?r*Z7+n*Y7+i*1e3:NaN}function q$(t){return t&&parseFloat(t.replace(",","."))||0}function NKe(t){if(t==="Z")return 0;const e=t.match(EKe);if(!e)return 0;const r=e[1]==="+"?-1:1,n=parseInt(e[2]),i=e[3]&&parseInt(e[3])||0;return OKe(n,i)?r*(n*Z7+i*Y7):NaN}function IKe(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 PKe=[31,null,31,30,31,30,31,31,30,31,30,31];function Ave(t){return t%400===0||t%4===0&&t%100!==0}function RKe(t,e,r){return e>=0&&e<=11&&r>=1&&r<=(PKe[e]||(Ave(t)?29:28))}function LKe(t,e){return e>=1&&e<=(Ave(t)?366:365)}function DKe(t,e,r){return e>=1&&e<=53&&r>=0&&r<=6}function MKe(t,e,r){return t===24?e===0&&r===0:r>=0&&r<60&&e>=0&&e<60&&t>=0&&t<25}function OKe(t,e){return e>=0&&e<=59}function G$(t,e){const r=On(t),n=r.getFullYear(),i=r.getDate(),o=Xs(t,0);o.setFullYear(n,e,15),o.setHours(0,0,0,0);const c=vWe(o);return r.setMonth(e,Math.min(i,c)),r}function zre(t,e){const r=On(t);return isNaN(+r)?Xs(t,NaN):(r.setFullYear(e),r)}function FKe(t,e){return Sd(t,-e)}const BKe=()=>{const{user:t}=Hn(),e=Hs(),[r,n]=C.useState([]),[i,o]=C.useState(0),[c,a]=C.useState(!1),[f,p]=C.useState(null),y=C.useRef(null);C.useEffect(()=>{y.current=f},[f]),C.useEffect(()=>{if(!t)return;const P=`notification_last_read_${t.id}`,R=localStorage.getItem(P);R&&!y.current&&(y.current=R,p(R));const D=`nb_cache_${t.id}`,M=60*1e3,B=async()=>{try{const J=sessionStorage.getItem(D);if(J){const Q=JSON.parse(J);if(Q.ts&&Date.now()-Q.ts{n(W);const Y=y.current?new Date(y.current):null,J=W.filter(Q=>Y?new Date(Q.created_at)>Y:!0);o(J.length)};B();const G=Re.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},W=>{const Y=W.new;n(Q=>{const ee=[Y,...Q].slice(0,20);try{sessionStorage.setItem(D,JSON.stringify({ts:Date.now(),data:ee}))}catch{}return ee});const J=y.current?new Date(y.current):null;(!J||new Date(Y.created_at)>J)&&o(Q=>Q+1),Notification.permission==="granted"&&new Notification(Y.title,{body:Y.body,icon:"/favicon.ico"})}).subscribe();return()=>{Re.removeChannel(G)}},[t]);const v=P=>{const R=P.toLowerCase();return R.includes("community")||R.includes("post")?fh:R.includes("academy")||R.includes("video")?sA:R.includes("template")?XO:R.includes("event")?oo:R.includes("newsletter")?xme:R.includes("brokerage")?lme:R.includes("swag")||R.includes("social")?hf:R.includes("toolbox")||R.includes("tool")?P9:R.includes("brief")?xs:fh},T=P=>{a(!1),P.url&&P.url!=="/"&&e(P.url)},E=()=>{if(!t)return;const P=new Date().toISOString(),R=`notification_last_read_${t.id}`;localStorage.setItem(R,P),p(P),o(0)},k=P=>{a(P),P&&i>0&&E()};return s.jsxs(FC,{open:c,onOpenChange:k,children:[s.jsx(BC,{asChild:!0,children:s.jsxs(Bt,{variant:"ghost",size:"icon",className:"relative",children:[s.jsx(bC,{className:"h-5 w-5"}),i>0&&s.jsx(ss,{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(dT,{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(Bt,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:E,children:"Mark all read"})]}),s.jsx(Lm,{className:"h-[300px]",children:r.length===0?s.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"No notifications yet"}):r.map(P=>{const R=v(P.title);return s.jsxs(Nu,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>T(P),children:[s.jsx("div",{className:"flex-shrink-0 mt-0.5",children:s.jsx(R,{className:"h-4 w-4 text-primary"})}),s.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[s.jsx("span",{className:"font-medium text-sm",children:P.title}),s.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:P.body}),s.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:wve(new Date(P.created_at),{addSuffix:!0})})]})]},P.id)})})]})]})};function $Ke(t){return t!=null&&t.length?t.find(e=>e.is_active&&e.mls_provider_id&&!e.no_mls_mode)||t[0]:null}function kve(){const{user:t}=Hn(),{data:e,isLoading:r}=mr({queryKey:["agent-lead-site",t==null?void 0:t.id],queryFn:async()=>{const{data:n,error:i}=await Re.from("lead_sites").select("id, subdomain_slug, custom_domain, site_title, is_active, plan_tier, mls_provider_id, no_mls_mode, mls_agent_id, mls_agent_key, mls_office_id, mls_service_cities, mls_disclaimer_text, brokerage_legal_name").eq("agent_id",t.id).eq("is_active",!0).order("created_at",{ascending:!0}).limit(10);if(i)throw i;return $Ke(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 Cve(t=!0){const{user:e}=Hn(),{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 Re.from("profiles").select("brokerage_id").eq("id",e.id).maybeSingle();if(!(i!=null&&i.brokerage_id))return null;const{data:o}=await Re.from("lead_site_brokerage_offers").select("*").eq("brokerage_id",i.brokerage_id).eq("enabled",!0).maybeSingle();return o??null}});return{offer:r??null,hasOffer:!!r,isLoading:n}}const zKe="coaching_access";function UKe(){const{user:t,loading:e,isAdmin:r,isCoach:n}=Hn(),{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([Re.from("coaching_assignments").select("id").eq("agent_id",t.id).eq("status","active").limit(1),Re.from("feature_entitlements").select("enabled, expires_at").eq("user_id",t.id).eq("feature_key",zKe).maybeSingle()]),f=(c.data||[]).length>0,p=a.data,y=!!(p!=null&&p.enabled)&&(!p.expires_at||new Date(p.expires_at).getTime()>Date.now());return{hasAssignment:f,entitled:y}}});return{hasAccess:!!(r||n||i!=null&&i.hasAssignment||i!=null&&i.entitled),hasAssignment:!!(i!=null&&i.hasAssignment),isLoading:e||o}}const Ki=Re,Fqt=[{value:"contract",label:"Under contract"},{value:"inspection",label:"Inspection / due diligence"},{value:"closing",label:"Closing"},{value:"closed",label:"Closed"}];function Bqt(t){return t.total_items===0?"not_started":t.rejected_items>0?"changes_requested":t.approved_items>=t.total_items?"compliant":"in_review"}const $qt={not_started:"Not started",in_review:"In review",changes_requested:"Changes requested",compliant:"Compliant"};function VKe(){return mr({queryKey:["transaction-admin-seats"],queryFn:async()=>{const{data:t}=await Re.auth.getUser();if(!t.user)return[];const{data:e,error:r}=await Ki.from("brokerage_transaction_admins").select("brokerage_id").eq("user_id",t.user.id);if(r)throw r;return e||[]}})}function zqt(t){return mr({queryKey:["transaction-admins",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ki.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 Ki.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 Uqt(){const t=Ar();return Sr({mutationFn:async({brokerageId:e,userId:r})=>{const{error:n}=await Ki.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 Vqt(){const t=Ar();return Sr({mutationFn:async({id:e})=>{const{error:r}=await Ki.from("brokerage_transaction_admins").delete().eq("id",e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["transaction-admins",r.brokerageId]})})}function qqt(t){return mr({queryKey:["compliance-settings",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ki.from("brokerage_compliance_settings").select("*").eq("brokerage_id",t).maybeSingle();if(r)throw r;return e}})}function Gqt(){const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Ki.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 Hqt(t){return mr({queryKey:["compliance-templates",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ki.from("brokerage_checklist_templates").select("*").eq("brokerage_id",t).order("created_at",{ascending:!0});if(r)throw r;return e||[]}})}function Wqt(t){return mr({queryKey:["compliance-template-items",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ki.from("brokerage_checklist_template_items").select("*").eq("template_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]}})}function Kqt(){const t=Ar();return Sr({mutationFn:async e=>{if(e.id){const{error:i}=await Ki.from("brokerage_checklist_templates").update(e).eq("id",e.id);if(i)throw i;return e.id}const{data:r,error:n}=await Ki.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 Yqt(){const t=Ar();return Sr({mutationFn:async({id:e})=>{const{error:r}=await Ki.from("brokerage_checklist_templates").delete().eq("id",e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["compliance-templates",r.brokerageId]})})}function Zqt(){const t=Ar();return Sr({mutationFn:async e=>{if(e.id){const{error:n}=await Ki.from("brokerage_checklist_template_items").update(e).eq("id",e.id);if(n)throw n;return}const{error:r}=await Ki.from("brokerage_checklist_template_items").insert(e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["compliance-template-items",r.template_id]})})}function Xqt(){const t=Ar();return Sr({mutationFn:async({id:e})=>{const{error:r}=await Ki.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 Qqt(t){return mr({queryKey:["compliance-deals",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ki.rpc("get_brokerage_compliance_deals",{_brokerage_id:t});if(r)throw r;return e||[]}})}function Jqt(t){return mr({queryKey:["deal-compliance-items",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ki.from("deal_compliance_items").select("*").eq("deal_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]}})}function eGt(t){return mr({queryKey:["deal-compliance-events",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ki.from("deal_compliance_events").select("*").eq("deal_id",t).order("created_at",{ascending:!1}).limit(200);if(r)throw r;return e||[]}})}async function qC(t){var r;const{data:e}=await Re.auth.getUser();await Ki.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 tGt(){const t=Ar();return Sr({mutationFn:async({item:e,status:r,note:n})=>{var c;const{data:i}=await Re.auth.getUser(),{error:o}=await Ki.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 qC({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 rGt(){const t=Ar();return Sr({mutationFn:async({dealId:e,brokerageId:r,templateId:n,deal:i})=>{const{data:o,error:c}=await Ki.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[T,E,k]=y.split(/[-/T]/).map(Number);return new Date(Date.UTC(T,E-1,k+(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:p}=await Ki.from("deal_compliance_items").insert(f);if(p)throw p;await qC({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 nGt(t){return mr({queryKey:["deal-compliance-files",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ki.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 iGt(){const t=Ar();return Sr({mutationFn:async({item:e,file:r})=>{var v,T;const{data:n}=await Re.auth.getUser(),i=(v=n.user)==null?void 0:v.id;if(!i)throw new Error("Not signed in");const{data:o}=await Ki.from("deal_files").select("id, version_no").eq("compliance_item_id",e.id).order("version_no",{ascending:!1}).limit(1),c=(((T=o==null?void 0:o[0])==null?void 0:T.version_no)||0)+1,a=r.name.split(".").pop(),f=`${i}/${e.deal_id}/${crypto.randomUUID()}.${a}`,{error:p}=await Re.storage.from("deal-files").upload(f,r);if(p)throw p;o!=null&&o.length&&await Ki.from("deal_files").update({is_current:!1}).eq("compliance_item_id",e.id);const{error:y}=await Ki.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 Ki.from("deal_compliance_items").update({status:"submitted",review_note:null,reviewed_at:null,reviewed_by:null}).eq("id",e.id),await qC({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 sGt(t){const{data:e,error:r}=await Re.storage.from("deal-files").createSignedUrl(t,3600);if(r)throw r;window.open(e.signedUrl,"_blank","noopener,noreferrer")}function aGt(t){return mr({queryKey:["deal-compliance-messages",t],enabled:!!t,refetchInterval:3e4,queryFn:async()=>{const{data:e,error:r}=await Ki.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 Ki.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 oGt(){const t=Ar();return Sr({mutationFn:async({dealId:e,brokerageId:r,body:n,senderRole:i,itemId:o})=>{var y;const{data:c}=await Re.auth.getUser(),a=(y=c.user)==null?void 0:y.id;if(!a)throw new Error("Not signed in");const{data:f,error:p}=await Ki.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(p)throw p;try{await Re.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 lGt(){const t=Ar();return Sr({mutationFn:async({dealId:e,senderRole:r})=>{const{error:n}=await Ki.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 cGt(t){return mr({queryKey:["brokerage-agent-roster",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ki.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",t).order("name",{ascending:!0});if(r)throw r;return e||[]}})}function uGt(t){return mr({queryKey:["agent-pipeline-stages",t],enabled:!!t,queryFn:async()=>{const e=async()=>{const{data:n,error:i}=await Ki.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 Ki.rpc("initialize_deal_pipeline_stages",{p_user_id:t});n||(r=await e())}return r}})}function dGt(){const t=Ar();return Sr({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 Ki.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 Ki.rpc("ensure_deal_compliance",{_deal_id:o})}catch(c){console.error("ensure_deal_compliance failed",c)}return await qC({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 hGt(t){return mr({queryKey:["staff-deal-detail",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ki.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 fGt(){const t=Ar();return Sr({mutationFn:async e=>{const r=e.price!=null&&e.commissionPercentage!=null?Math.round(e.price*(e.commissionPercentage/100)*100)/100:null,{error:n}=await Ki.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 qC({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 q3=[{id:"home",label:"Home",icon:gme,route:"/dashboard",accent:"nav-home"},{id:"crm",label:"CRM",icon:bm,description:"Contacts and follow-up",accent:"nav-crm"},{id:"deals",label:"Deals",icon:j9,description:"Pipeline, transactions and tasks",accent:"nav-deals"},{id:"listings",label:"Listings",icon:_o,description:"Win and market listings",accent:"nav-listings"},{id:"marketing",label:"Marketing",icon:wC,description:"Content, email and video",accent:"nav-marketing"},{id:"websites",label:"Websites",icon:qv,description:"Your site and add-ons",accent:"nav-websites"},{id:"academy",label:"Learn",icon:WA,description:"Training, programs and coaching",accent:"nav-academy"},{id:"mainstage",label:"Main Stage",icon:vme,route:"/main-stage",accent:"nav-mainstage"},{id:"events",label:"Events",icon:bme,route:"/events",accent:"nav-events"},{id:"apps",label:"Apps",icon:DDe,route:"/apps",accent:"nav-apps"},{id:"team",label:"Team",icon:fl,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:YO,description:"Your brokerage, teams and recruiting",accent:"nav-brokerage",visible:t=>!t.isAdmin&&(!!t.brokerageId||t.isBrokerageManager||t.isOnTeam)},{id:"more",label:"More",icon:CDe,description:"Community, marketplace and help",accent:"nav-more"}],kl=t=>e=>e.hasPermission(t),qKe=[{id:"mission-control",label:"Mission Control",route:"/mission-control",icon:EDe,description:"Your daily relationship command center",primaryCategory:"crm",section:"Overview",visible:kl("contacts"),searchKeywords:["agent os","mission control","dashboard"],displayOrder:10},{id:"client-portals",label:"Client Portals",route:"/mission-control/client-portals",icon:xs,description:"Private portals for buyers and sellers",primaryCategory:"crm",section:"Overview",searchKeywords:["portal","client portal"],displayOrder:20},{id:"net-sheets",label:"Seller Net Sheets",route:"/mission-control/net-sheets",icon:RU,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:fl,description:"Every contact in your database",primaryCategory:"crm",section:"Contacts",visible:kl("contacts"),searchKeywords:["contacts","database","sphere","people"],displayOrder:30},{id:"contact-map",label:"Contact Map",route:"/mission-control/sphere-map",icon:Es,iconTone:"red",description:"See your sphere on a map — boundaries, farms and prospects",primaryCategory:"crm",section:"Contacts",visible:kl("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:Lee,description:"See who needs attention next",primaryCategory:"crm",section:"Contacts",visible:kl("contacts"),searchKeywords:["relationship","scorecard","report"],displayOrder:40},{id:"sphere-gaps",label:"Sphere Gaps",route:"/mission-control/sphere-gaps",icon:aMe,description:"Find missing info across your sphere",primaryCategory:"crm",section:"Contacts",visible:kl("contacts"),searchKeywords:["gaps","missing data"],displayOrder:50},{id:"sent-emails",label:"Sent Emails",route:"/mission-control/sent-emails",icon:kD,description:"History of everything you have sent",primaryCategory:"crm",section:"Contacts",visible:kl("contacts"),searchKeywords:["sent","email history"],displayOrder:60},{id:"connect-page",label:"Connect Page",route:"/mission-control/connect-page",icon:Bee,description:"Your shareable intake and link page",primaryCategory:"crm",section:"Contacts",visible:kl("contacts"),searchKeywords:["connect","link in bio","intake"],displayOrder:70},{id:"property-intelligence",label:"Property Intelligence",route:"/mission-control/property-intelligence",icon:_o,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:pm,description:"Structured touch plans for your people",primaryCategory:"crm",section:"Follow-Up",visible:kl("contacts"),searchKeywords:["touch plan","follow up plan"],displayOrder:80},{id:"smart-drips",label:"Smart Drips",route:"/mission-control/smart-drips",icon:eS,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:mi,description:"Reusable email templates",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["email template"],displayOrder:100},{id:"signals",label:"Signals",route:"/mission-control/signals",icon:rMe,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:hf,description:"Plan and log in-person pop-bys",primaryCategory:"crm",section:"Follow-Up",visible:kl("popbys"),searchKeywords:["pop by","gifts","drop off"],displayOrder:120},{id:"pipeline",label:"Deal Pipeline",route:"/mission-control/pipeline",icon:j9,description:"Track every deal from lead to close",primaryCategory:"deals",section:"Pipeline",visible:kl("pipeline"),searchKeywords:["pipeline","deals","kanban"],displayOrder:130},{id:"lending-partners",label:"Lending Partners",route:"/mission-control/lenders",icon:YO,description:"Loan officers, loan milestones and lead exchange",primaryCategory:"deals",section:"Pipeline",visible:kl("pipeline"),searchKeywords:["lender","loan officer","mortgage","pre-approval","referral"],displayOrder:135},{id:"transactions",label:"Transactions",route:"/mission-control/transactions",icon:DU,description:"Closed and in-progress transactions",primaryCategory:"deals",section:"Pipeline",visible:kl("pipeline"),searchKeywords:["transactions","closings"],displayOrder:140},{id:"forms",label:"Forms Library",route:"/mission-control/forms",icon:NDe,description:"Your PDF form templates, filled from any deal",primaryCategory:"deals",section:"Pipeline",visible:kl("pipeline"),searchKeywords:["forms","pdf","templates","contracts","documents"],displayOrder:145},{id:"tasks",label:"Tasks",route:"/mission-control/tasks",icon:uMe,description:"Everything on your plate today",primaryCategory:"deals",section:"Pipeline",visible:kl("pipeline"),searchKeywords:["tasks","to do"],displayOrder:150},{id:"scorecard",label:"Scorecard",route:"/mission-control/scorecard",icon:HA,description:"Your production numbers at a glance",primaryCategory:"deals",section:"Pipeline",visible:kl("scorecard"),searchKeywords:["scorecard","production","goals"],displayOrder:160},{id:"my-calendar",label:"My Calendar",route:"/mission-control/calendar",icon:pm,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:pm,description:"Share your booking link and sync your calendar",primaryCategory:"crm",section:"Overview",toolId:"scheduler",visible:()=>!0,searchKeywords:["scheduler","booking","calendar","appointments"],displayOrder:25},{id:"listing-exchange",label:"Listing Exchange",route:"/mission-control/listings",icon:_o,description:"Publish and browse member listings",primaryCategory:"listings",section:"Manage Listings",visible:kl("listings"),searchKeywords:["listings","exchange","my listings"],displayOrder:10},{id:"listing-presentation-studio",label:"Listing Presentation Studio",route:"/apps/listing-presentation-studio",icon:JDe,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:fme,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:va,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:RU,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:DU,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:Fee,description:"Marketing assets for a listing",primaryCategory:"listings",section:"Market the Listing",toolId:"listing-studio",searchKeywords:["listing marketing","flyer","just listed"],displayOrder:70},{id:"templates",label:"Templates",route:"/templates",icon:XO,description:"Ready-to-edit Canva templates",primaryCategory:"marketing",section:"Create",searchKeywords:["templates","canva","graphics"],displayOrder:10},{id:"staging-studio",label:"Staging Studio",route:"/apps/staging-studio",icon:cMe,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:lc,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:Fee,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:f$,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:f$,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:Oee,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:xme,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:mi,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:kD,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:hf,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:sA,description:"All of your recorded videos",primaryCategory:"marketing",section:"Video",visible:kl("videos"),searchKeywords:["videos","library"],displayOrder:90},{id:"video-studio",label:"Video Studio",route:"/video-studio",icon:sA,description:"Record vertical or horizontal videos with a scrolling teleprompter",primaryCategory:"marketing",section:"Video",visible:kl("videos"),searchKeywords:["teleprompter","studio","reels","record video","social video"],displayOrder:95},{id:"quickvid",label:"Video Messages",route:"/video-studio",icon:sA,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:Oee,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:zee,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:OU,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:Bee,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:BDe,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:LDe,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:"Get My Website",route:"/get-my-website",icon:qv,description:"Claim the free site your brokerage offers",primaryCategory:"websites",section:"My Website",visible:t=>!t.hasLeadSite&&t.hasFreeSiteOffer,searchKeywords:["website","claim site","free site"],displayOrder:5},{id:"need-a-website",label:"Need a Website",route:"/need-a-website",icon:qv,description:"Request your free beta agent website",primaryCategory:"websites",section:"My Website",badge:"beta",visible:t=>!t.hasLeadSite&&!t.hasFreeSiteOffer,searchKeywords:["website","need a website","beta site","free website"],displayOrder:6},{id:"view-site",label:"View Site",route:t=>t.siteUrl||"#",icon:KO,description:"Open your live website",primaryCategory:"websites",section:"My Website",external:!0,openInNewTab:!0,visible:t=>t.hasLeadSite&&!!t.siteUrl,searchKeywords:["view site","live site"],displayOrder:10},{id:"edit-website",label:"Edit My Site",route:t=>`/my-website/${t.leadSiteId}/edit`,icon:YDe,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:_o,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:fl,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:va,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:HA,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:Lee,description:"See who is browsing your site",primaryCategory:"websites",section:"My Website",visible:t=>t.hasLeadSite,searchKeywords:["website activity","visitors","analytics"],displayOrder:50},{id:"mobile-command",label:"Mobile Command",route:"/m",icon:f$,description:"The mobile-first agent console",primaryCategory:"websites",section:"My Website",visible:t=>t.hasLeadSite,searchKeywords:["mobile","command"],displayOrder:60},{id:"website-apps",label:"Website Apps",route:"/website-apps",icon:xs,description:"Lead magnets, video greeter and more",primaryCategory:"websites",section:"Website Add-Ons",toolId:"website-apps",searchKeywords:["widgets","lead magnet","video greeter"],displayOrder:70},{id:"levelup-u",label:"LevelUp U",route:"/levelup-u",icon:WA,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:Q1,description:"On-demand training videos",primaryCategory:"academy",section:"Learn",searchKeywords:["academy","videos","training"],displayOrder:20},{id:"toolbox",label:"Toolbox",route:"/toolbox",icon:P9,description:"Scripts, checklists and downloads",primaryCategory:"academy",section:"Learn",searchKeywords:["toolbox","scripts","downloads"],displayOrder:30},{id:"events",label:"Events",route:"/events",icon:bme,description:"Live trainings and member events",primaryCategory:"events",section:"Events",searchKeywords:["events","live","webinar"],displayOrder:10},{id:"programs",label:"Programs",route:"/programs",icon:zee,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:WA,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:bm,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:fh,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:zDe,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:b_,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:N9,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:ND,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:hf,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:$De,description:"Get help from the LevelUp team",primaryCategory:"more",section:"Help & Services",searchKeywords:["support","help","ticket"],displayOrder:70},{id:"additional-services",label:"Additional Services",route:"/additional-services",icon:xs,description:"Done-for-you services from LevelUp",primaryCategory:"more",section:"Help & Services",searchKeywords:["services","done for you"],displayOrder:80},{id:"integrations",label:"Integrations",route:"/mission-control/integrations",icon:AD,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:AD,description:"Install the LevelUp Chrome extension",primaryCategory:"more",section:"Help & Services",searchKeywords:["extension","chrome"],displayOrder:100},{id:"attract",label:"LevelUp Attract",route:"/attract",icon:xs,description:"Relationship-first attraction coach",primaryCategory:"more",section:"Help & Services",badge:"beta",visible:t=>t.email==="jeremy@relevelup.com",searchKeywords:["attract","recruiting"],displayOrder:110},{id:"admin-dashboard",label:"Admin Dashboard",route:"/admin",icon:hx,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:eS,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:_o,description:"Your brokerage hub",primaryCategory:"brokerage",section:"My Brokerage",visible:t=>!!t.brokerageId&&!t.isAdmin,searchKeywords:["brokerage"],displayOrder:130},{id:"help-board",label:"Help Board",route:"/brokerage/help-board",icon:MDe,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:Q1,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:fl,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:fl,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:A9,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:fl,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:wC,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:h$,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:qv,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:gme,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:ZDe,description:"Commission plans, company dollar and fee statements",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:t=>(t.isBrokerageManager||t.isTransactionAdmin)&&!t.isAdmin,searchKeywords:["commission","split","cap","fees","agent plans"],displayOrder:195},{id:"brokerage-transactions",label:"Transactions & Compliance",route:"/brokerage/transactions",icon:h$,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:OU,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:_m,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:lme,description:"Documents and links for your agents",primaryCategory:"brokerage",section:"Manage Brokerage",visible:t=>t.isBrokerageManager&&!t.isAdmin,searchKeywords:["resources"],displayOrder:210},{id:"my-partnership",label:"My Package",route:"/my-partnership",icon:xs,description:"What is included in your partnership package",primaryCategory:"more",section:"Account",visible:t=>t.isPartnershipMember,searchKeywords:["partnership","package","upgrade","exp luxury"],displayOrder:5},{id:"coaching-onboarding",label:"Coaching Onboarding",route:"/coaching/onboarding",icon:h$,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 Nve(t,e){return typeof t.route=="function"?t.route(e):t.route}function Ive(){const{user:t,isAdmin:e,isBrokerageManager:r,isCoach:n,brokerageId:i}=Hn(),{hasPermission:o}=E3(),{isInnerCircleEnabled:c,isMarketplaceEnabled:a,isFeatureEnabled:f}=C3(),{hasAccess:p}=S7(),{data:y,teams:v}=hT(),{leadSite:T,hasLeadSite:E,siteUrl:k}=kve(),{hasOffer:P}=Cve(!E),R=gxe(),{hasAccess:D}=UKe(),{data:M}=VKe(),B=Ar(),{data:V}=mr({queryKey:["my-coach-nav",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:be}=await Re.from("coaching_assignments").select("id").eq("agent_id",t.id).eq("status","active").limit(1);return(be||[]).length>0}}),{data:G}=mr({queryKey:["user-tool-favorites",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),staleTime:60*1e3,queryFn:async()=>{const{data:be}=await Re.from("user_tool_favorites").select("tool_id").eq("user_id",t.id);return(be||[]).map(me=>me.tool_id)}}),W=C.useMemo(()=>new Set(G||[]),[G]),Y=Sr({mutationFn:async be=>{t!=null&&t.id&&(W.has(be)?await Re.from("user_tool_favorites").delete().eq("user_id",t.id).eq("tool_id",be):await Re.from("user_tool_favorites").insert({user_id:t.id,tool_id:be}))},onSuccess:()=>{B.invalidateQueries({queryKey:["user-tool-favorites"]}),B.invalidateQueries({queryKey:["app-catalog"]})}}),J=C.useMemo(()=>{var be,me;return{isAdmin:!!e,isBrokerageManager:!!r,isTransactionAdmin:((M==null?void 0:M.length)||0)>0,isCoach:!!n,isOnTeam:!!y,isTeamLeader:(v||[]).some(Te=>Te.role==="team_leader"),hasCoach:!!V,brokerageId:i??null,hasPermission:o,isInnerCircleEnabled:!!c,stagingStudioEnabled:f("staging_studio_enabled"),isMarketplaceEnabled:!!a,hasWeeklyReels:!!p,hasLeadSite:!!E,hasLeadSiteMLS:!!(T!=null&&T.mls_provider_id),hasFreeSiteOffer:!!P,leadSiteId:(T==null?void 0:T.id)??null,siteUrl:k??null,email:(t==null?void 0:t.email)??null,isPartnershipMember:R.isMember,hasCoachingOnboarding:R.isMember&&!!((be=R.pkg)!=null&&be.includes_coaching),hasCoachingAccess:!!D||R.isMember&&!!((me=R.pkg)!=null&&me.includes_coaching)}},[e,r,M,n,y,v,V,i,o,c,a,f,p,E,T,P,k,t==null?void 0:t.email,R.isMember,R.pkg,D]),Q=C.useMemo(()=>qKe.filter(be=>be.visible?be.visible(J):!0).map(be=>{if(!R.isRestricted)return be;const me=qUe(be);return!me||R.hasFeature(me)?be:{...be,locked:!0,route:`/upgrade/${me}`}}).sort((be,me)=>be.displayOrder-me.displayOrder),[J,R.isRestricted,R.features]),ee=C.useMemo(()=>q3.filter(be=>be.visible?be.visible(J):!0),[J]),le=C.useMemo(()=>ee.filter(be=>!be.route).map(be=>{const me=Q.filter(Ee=>Ee.primaryCategory===be.id),Te=[],Ne=new Map;for(const Ee of me)Ne.has(Ee.section)||(Ne.set(Ee.section,[]),Te.push(Ee.section)),Ne.get(Ee.section).push(Ee);return{id:be.id,label:be.label,sections:Te.map(Ee=>({title:Ee,items:Ne.get(Ee)}))}}),[Q,ee]),pe=C.useMemo(()=>new Map(le.map(be=>[be.id,be])),[le]),Se=be=>be.toolId||`nav:${be.id}`,je=be=>W.has(Se(be));return{ctx:J,categories:le,railCategories:ee,categoryMap:pe,destinations:Q,favorites:W,isFavorite:je,favoritesFor:be=>Q.filter(me=>me.primaryCategory===be&&je(me)),favoriteKey:Se,toggleFavorite:be=>Y.mutate(be),searchDestinations:be=>{const me=be.trim().toLowerCase();return me?Q.map(Ne=>{const Ee=Ne.label.toLowerCase(),we=(Ne.description||"").toLowerCase(),He=(Ne.searchKeywords||[]).join(" ").toLowerCase();let tt=0;return Ee===me?tt=100:Ee.startsWith(me)?tt=80:Ee.includes(me)?tt=60:He.includes(me)?tt=40:we.includes(me)?tt=20:Ne.section.toLowerCase().includes(me)&&(tt=10),tt&&je(Ne)&&(tt+=5),{d:Ne,score:tt}}).filter(Ne=>Ne.score>0).sort((Ne,Ee)=>Ee.score-Ne.score).map(Ne=>Ne.d):[]},routeFor:be=>Nve(be,J)}}var Ure=1,GKe=.9,HKe=.8,WKe=.17,H$=.1,W$=.999,KKe=.9999,YKe=.99,ZKe=/[\\\/_+.#"@\[\(\{&]/,XKe=/[\\\/_+.#"@\[\(\{&]/g,QKe=/[\s-]/,Pve=/[\s-]/g;function GV(t,e,r,n,i,o,c){if(o===e.length)return i===t.length?Ure:YKe;var a=`${i},${o}`;if(c[a]!==void 0)return c[a];for(var f=n.charAt(o),p=r.indexOf(f,i),y=0,v,T,E,k;p>=0;)v=GV(t,e,r,n,p+1,o+1,c),v>y&&(p===i?v*=Ure:ZKe.test(t.charAt(p-1))?(v*=HKe,E=t.slice(i,p-1).match(XKe),E&&i>0&&(v*=Math.pow(W$,E.length))):QKe.test(t.charAt(p-1))?(v*=GKe,k=t.slice(i,p-1).match(Pve),k&&i>0&&(v*=Math.pow(W$,k.length))):(v*=WKe,i>0&&(v*=Math.pow(W$,p-i))),t.charAt(p)!==e.charAt(o)&&(v*=KKe)),(vv&&(v=T*H$)),v>y&&(y=v),p=r.indexOf(f,p+1);return c[a]=y,y}function Vre(t){return t.toLowerCase().replace(Pve," ")}function JKe(t,e,r){return t=r&&r.length>0?`${t+" "+r.join(" ")}`:t,GV(t,e,Vre(t),Vre(e),0,0,{})}var u2='[cmdk-group=""]',K$='[cmdk-group-items=""]',eYe='[cmdk-group-heading=""]',Rve='[cmdk-item=""]',qre=`${Rve}:not([aria-disabled="true"])`,HV="cmdk-item-select",Rw="data-value",tYe=(t,e,r)=>JKe(t,e,r),Lve=C.createContext(void 0),GC=()=>C.useContext(Lve),Dve=C.createContext(void 0),sH=()=>C.useContext(Dve),Mve=C.createContext(void 0),Ove=C.forwardRef((t,e)=>{let r=Lw(()=>{var we,He;return{search:"",value:(He=(we=t.value)!=null?we:t.defaultValue)!=null?He:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=Lw(()=>new Set),i=Lw(()=>new Map),o=Lw(()=>new Map),c=Lw(()=>new Set),a=Fve(t),{label:f,children:p,value:y,onValueChange:v,filter:T,shouldFilter:E,loop:k,disablePointerSelection:P=!1,vimBindings:R=!0,...D}=t,M=Fl(),B=Fl(),V=Fl(),G=C.useRef(null),W=hYe();l_(()=>{if(y!==void 0){let we=y.trim();r.current.value=we,Y.emit()}},[y]),l_(()=>{W(6,Se)},[]);let Y=C.useMemo(()=>({subscribe:we=>(c.current.add(we),()=>c.current.delete(we)),snapshot:()=>r.current,setState:(we,He,tt)=>{var at,Et,vt,Gt;if(!Object.is(r.current[we],He)){if(r.current[we]=He,we==="search")pe(),ee(),W(1,le);else if(we==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let pt=document.getElementById(V);pt?pt.focus():(at=document.getElementById(M))==null||at.focus()}if(W(7,()=>{var pt;r.current.selectedItemId=(pt=je())==null?void 0:pt.id,Y.emit()}),tt||W(5,Se),((Et=a.current)==null?void 0:Et.value)!==void 0){let pt=He??"";(Gt=(vt=a.current).onValueChange)==null||Gt.call(vt,pt);return}}Y.emit()}},emit:()=>{c.current.forEach(we=>we())}}),[]),J=C.useMemo(()=>({value:(we,He,tt)=>{var at;He!==((at=o.current.get(we))==null?void 0:at.value)&&(o.current.set(we,{value:He,keywords:tt}),r.current.filtered.items.set(we,Q(He,tt)),W(2,()=>{ee(),Y.emit()}))},item:(we,He)=>(n.current.add(we),He&&(i.current.has(He)?i.current.get(He).add(we):i.current.set(He,new Set([we]))),W(3,()=>{pe(),ee(),r.current.value||le(),Y.emit()}),()=>{o.current.delete(we),n.current.delete(we),r.current.filtered.items.delete(we);let tt=je();W(4,()=>{pe(),(tt==null?void 0:tt.getAttribute("id"))===we&&le(),Y.emit()})}),group:we=>(i.current.has(we)||i.current.set(we,new Set),()=>{o.current.delete(we),i.current.delete(we)}),filter:()=>a.current.shouldFilter,label:f||t["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:M,inputId:V,labelId:B,listInnerRef:G}),[]);function Q(we,He){var tt,at;let Et=(at=(tt=a.current)==null?void 0:tt.filter)!=null?at:tYe;return we?Et(we,r.current.search,He):0}function ee(){if(!r.current.search||a.current.shouldFilter===!1)return;let we=r.current.filtered.items,He=[];r.current.filtered.groups.forEach(at=>{let Et=i.current.get(at),vt=0;Et.forEach(Gt=>{let pt=we.get(Gt);vt=Math.max(pt,vt)}),He.push([at,vt])});let tt=G.current;Le().sort((at,Et)=>{var vt,Gt;let pt=at.getAttribute("id"),Pt=Et.getAttribute("id");return((vt=we.get(Pt))!=null?vt:0)-((Gt=we.get(pt))!=null?Gt:0)}).forEach(at=>{let Et=at.closest(K$);Et?Et.appendChild(at.parentElement===Et?at:at.closest(`${K$} > *`)):tt.appendChild(at.parentElement===tt?at:at.closest(`${K$} > *`))}),He.sort((at,Et)=>Et[1]-at[1]).forEach(at=>{var Et;let vt=(Et=G.current)==null?void 0:Et.querySelector(`${u2}[${Rw}="${encodeURIComponent(at[0])}"]`);vt==null||vt.parentElement.appendChild(vt)})}function le(){let we=Le().find(tt=>tt.getAttribute("aria-disabled")!=="true"),He=we==null?void 0:we.getAttribute(Rw);Y.setState("value",He||void 0)}function pe(){var we,He,tt,at;if(!r.current.search||a.current.shouldFilter===!1){r.current.filtered.count=n.current.size;return}r.current.filtered.groups=new Set;let Et=0;for(let vt of n.current){let Gt=(He=(we=o.current.get(vt))==null?void 0:we.value)!=null?He:"",pt=(at=(tt=o.current.get(vt))==null?void 0:tt.keywords)!=null?at:[],Pt=Q(Gt,pt);r.current.filtered.items.set(vt,Pt),Pt>0&&Et++}for(let[vt,Gt]of i.current)for(let pt of Gt)if(r.current.filtered.items.get(pt)>0){r.current.filtered.groups.add(vt);break}r.current.filtered.count=Et}function Se(){var we,He,tt;let at=je();at&&(((we=at.parentElement)==null?void 0:we.firstChild)===at&&((tt=(He=at.closest(u2))==null?void 0:He.querySelector(eYe))==null||tt.scrollIntoView({block:"nearest"})),at.scrollIntoView({block:"nearest"}))}function je(){var we;return(we=G.current)==null?void 0:we.querySelector(`${Rve}[aria-selected="true"]`)}function Le(){var we;return Array.from(((we=G.current)==null?void 0:we.querySelectorAll(qre))||[])}function Ae(we){let He=Le()[we];He&&Y.setState("value",He.getAttribute(Rw))}function be(we){var He;let tt=je(),at=Le(),Et=at.findIndex(Gt=>Gt===tt),vt=at[Et+we];(He=a.current)!=null&&He.loop&&(vt=Et+we<0?at[at.length-1]:Et+we===at.length?at[0]:at[Et+we]),vt&&Y.setState("value",vt.getAttribute(Rw))}function me(we){let He=je(),tt=He==null?void 0:He.closest(u2),at;for(;tt&&!at;)tt=we>0?uYe(tt,u2):dYe(tt,u2),at=tt==null?void 0:tt.querySelector(qre);at?Y.setState("value",at.getAttribute(Rw)):be(we)}let Te=()=>Ae(Le().length-1),Ne=we=>{we.preventDefault(),we.metaKey?Te():we.altKey?me(1):be(1)},Ee=we=>{we.preventDefault(),we.metaKey?Ae(0):we.altKey?me(-1):be(-1)};return C.createElement(nn.div,{ref:e,tabIndex:-1,...D,"cmdk-root":"",onKeyDown:we=>{var He;(He=D.onKeyDown)==null||He.call(D,we);let tt=we.nativeEvent.isComposing||we.keyCode===229;if(!(we.defaultPrevented||tt))switch(we.key){case"n":case"j":{R&&we.ctrlKey&&Ne(we);break}case"ArrowDown":{Ne(we);break}case"p":case"k":{R&&we.ctrlKey&&Ee(we);break}case"ArrowUp":{Ee(we);break}case"Home":{we.preventDefault(),Ae(0);break}case"End":{we.preventDefault(),Te();break}case"Enter":{we.preventDefault();let at=je();if(at){let Et=new Event(HV);at.dispatchEvent(Et)}}}}},C.createElement("label",{"cmdk-label":"",htmlFor:J.inputId,id:J.labelId,style:mYe},f),G3(t,we=>C.createElement(Dve.Provider,{value:Y},C.createElement(Lve.Provider,{value:J},we))))}),rYe=C.forwardRef((t,e)=>{var r,n;let i=Fl(),o=C.useRef(null),c=C.useContext(Mve),a=GC(),f=Fve(t),p=(n=(r=f.current)==null?void 0:r.forceMount)!=null?n:c==null?void 0:c.forceMount;l_(()=>{if(!p)return a.item(i,c==null?void 0:c.id)},[p]);let y=Bve(i,o,[t.value,t.children,o],t.keywords),v=sH(),T=vx(W=>W.value&&W.value===y.current),E=vx(W=>p||a.filter()===!1?!0:W.search?W.filtered.items.get(i)>0:!0);C.useEffect(()=>{let W=o.current;if(!(!W||t.disabled))return W.addEventListener(HV,k),()=>W.removeEventListener(HV,k)},[E,t.onSelect,t.disabled]);function k(){var W,Y;P(),(Y=(W=f.current).onSelect)==null||Y.call(W,y.current)}function P(){v.setState("value",y.current,!0)}if(!E)return null;let{disabled:R,value:D,onSelect:M,forceMount:B,keywords:V,...G}=t;return C.createElement(nn.div,{ref:Qp(o,e),...G,id:i,"cmdk-item":"",role:"option","aria-disabled":!!R,"aria-selected":!!T,"data-disabled":!!R,"data-selected":!!T,onPointerMove:R||a.getDisablePointerSelection()?void 0:P,onClick:R?void 0:k},t.children)}),nYe=C.forwardRef((t,e)=>{let{heading:r,children:n,forceMount:i,...o}=t,c=Fl(),a=C.useRef(null),f=C.useRef(null),p=Fl(),y=GC(),v=vx(E=>i||y.filter()===!1?!0:E.search?E.filtered.groups.has(c):!0);l_(()=>y.group(c),[]),Bve(c,a,[t.value,t.heading,f]);let T=C.useMemo(()=>({id:c,forceMount:i}),[i]);return C.createElement(nn.div,{ref:Qp(a,e),...o,"cmdk-group":"",role:"presentation",hidden:v?void 0:!0},r&&C.createElement("div",{ref:f,"cmdk-group-heading":"","aria-hidden":!0,id:p},r),G3(t,E=>C.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?p:void 0},C.createElement(Mve.Provider,{value:T},E))))}),iYe=C.forwardRef((t,e)=>{let{alwaysRender:r,...n}=t,i=C.useRef(null),o=vx(c=>!c.search);return!r&&!o?null:C.createElement(nn.div,{ref:Qp(i,e),...n,"cmdk-separator":"",role:"separator"})}),sYe=C.forwardRef((t,e)=>{let{onValueChange:r,...n}=t,i=t.value!=null,o=sH(),c=vx(p=>p.search),a=vx(p=>p.selectedItemId),f=GC();return C.useEffect(()=>{t.value!=null&&o.setState("search",t.value)},[t.value]),C.createElement(nn.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:p=>{i||o.setState("search",p.target.value),r==null||r(p.target.value)}})}),aYe=C.forwardRef((t,e)=>{let{children:r,label:n="Suggestions",...i}=t,o=C.useRef(null),c=C.useRef(null),a=vx(p=>p.selectedItemId),f=GC();return C.useEffect(()=>{if(c.current&&o.current){let p=c.current,y=o.current,v,T=new ResizeObserver(()=>{v=requestAnimationFrame(()=>{let E=p.offsetHeight;y.style.setProperty("--cmdk-list-height",E.toFixed(1)+"px")})});return T.observe(p),()=>{cancelAnimationFrame(v),T.unobserve(p)}}},[]),C.createElement(nn.div,{ref:Qp(o,e),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":n,id:f.listId},G3(t,p=>C.createElement("div",{ref:Qp(c,f.listInnerRef),"cmdk-list-sizer":""},p)))}),oYe=C.forwardRef((t,e)=>{let{open:r,onOpenChange:n,overlayClassName:i,contentClassName:o,container:c,...a}=t;return C.createElement(i3,{open:r,onOpenChange:n},C.createElement(s3,{container:c},C.createElement(tT,{"cmdk-overlay":"",className:i}),C.createElement(rT,{"aria-label":t.label,"cmdk-dialog":"",className:o},C.createElement(Ove,{ref:e,...a}))))}),lYe=C.forwardRef((t,e)=>vx(r=>r.filtered.count===0)?C.createElement(nn.div,{ref:e,...t,"cmdk-empty":"",role:"presentation"}):null),cYe=C.forwardRef((t,e)=>{let{progress:r,children:n,label:i="Loading...",...o}=t;return C.createElement(nn.div,{ref:e,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},G3(t,c=>C.createElement("div",{"aria-hidden":!0},c)))}),Bu=Object.assign(Ove,{List:aYe,Item:rYe,Input:sYe,Group:nYe,Separator:iYe,Dialog:oYe,Empty:lYe,Loading:cYe});function uYe(t,e){let r=t.nextElementSibling;for(;r;){if(r.matches(e))return r;r=r.nextElementSibling}}function dYe(t,e){let r=t.previousElementSibling;for(;r;){if(r.matches(e))return r;r=r.previousElementSibling}}function Fve(t){let e=C.useRef(t);return l_(()=>{e.current=t}),e}var l_=typeof window>"u"?C.useEffect:C.useLayoutEffect;function Lw(t){let e=C.useRef();return e.current===void 0&&(e.current=t()),e}function vx(t){let e=sH(),r=()=>t(e.snapshot());return C.useSyncExternalStore(e.subscribe,r,r)}function Bve(t,e,r,n=[]){let i=C.useRef(),o=GC();return l_(()=>{var c;let a=(()=>{var p;for(let y of r){if(typeof y=="string")return y.trim();if(typeof y=="object"&&"current"in y)return y.current?(p=y.current.textContent)==null?void 0:p.trim():i.current}})(),f=n.map(p=>p.trim());o.value(t,a,f),(c=e.current)==null||c.setAttribute(Rw,a),i.current=a}),i}var hYe=()=>{let[t,e]=C.useState(),r=Lw(()=>new Map);return l_(()=>{r.current.forEach(n=>n()),r.current=new Map},[t]),(n,i)=>{r.current.set(n,i),e({})}};function fYe(t){let e=t.type;return typeof e=="function"?e(t.props):"render"in e?e.render(t.props):t}function G3({asChild:t,children:e},r){return t&&C.isValidElement(e)?C.cloneElement(fYe(e),{ref:e.ref},r(e.props.children)):r(e)}var mYe={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const uk=C.forwardRef(({className:t,...e},r)=>s.jsx(Bu,{ref:r,className:qt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...e}));uk.displayName=Bu.displayName;const pYe=({children:t,...e})=>s.jsx(lo,{...e,children:s.jsx(qa,{className:"overflow-hidden p-0 shadow-lg",children:s.jsx(uk,{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})})}),dk=C.forwardRef(({className:t,...e},r)=>s.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[s.jsx(xd,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),s.jsx(Bu.Input,{ref:r,className:qt("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})]}));dk.displayName=Bu.Input.displayName;const hk=C.forwardRef(({className:t,...e},r)=>s.jsx(Bu.List,{ref:r,className:qt("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...e}));hk.displayName=Bu.List.displayName;const fk=C.forwardRef((t,e)=>s.jsx(Bu.Empty,{ref:e,className:"py-6 text-center text-sm",...t}));fk.displayName=Bu.Empty.displayName;const Rp=C.forwardRef(({className:t,...e},r)=>s.jsx(Bu.Group,{ref:r,className:qt("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}));Rp.displayName=Bu.Group.displayName;const gYe=C.forwardRef(({className:t,...e},r)=>s.jsx(Bu.Separator,{ref:r,className:qt("-mx-1 h-px bg-border",t),...e}));gYe.displayName=Bu.Separator.displayName;const nf=C.forwardRef(({className:t,...e},r)=>s.jsx(Bu.Item,{ref:r,className:qt("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}));nf.displayName=Bu.Item.displayName;const Ju=t=>Number.isFinite(Number(t))?Number(t):0,Sp=t=>Math.round(t*100)/100,yYe=[{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 xYe(){return{listingCommissionPct:3,buyerCommissionPct:3,brokerageFee:0,titleFees:yYe.map(t=>({...t})),firstPayoff:0,secondPayoff:0,annualTaxes:0,taxesInArrears:!0,otherCosts:[]}}function vYe(t,e=5){const r=Math.max(0,Ju(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 mGt(t){const e=Math.max(0,Ju(t));return["A","B","C"].map(r=>({id:`offer-${r}`,label:`Offer ${r}`,price:e,concessions:0,repairs:0}))}function _Ye(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;aR+Ju(D.amount),0)),p=Sp(Ju(t.firstPayoff)+Ju(t.secondPayoff)),y=bYe(t.annualTaxes,r,t.taxesInArrears),v=Sp((t.otherCosts||[]).reduce((R,D)=>R+Ju(D.amount),0)),T=Ju(e.concessions),E=Ju(e.repairs),k=Sp(c+a+f+p+y+v+T+E),P=Sp(n-k);return{price:n,commission:c,listingCommission:i,buyerCommission:o,brokerageFee:a,titleTotal:f,payoffs:p,taxProration:y,concessions:T,repairs:E,otherTotal:v,totalCosts:k,net:P,netPct:n>0?P/n:0}}const Kf=(t,e=!1)=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:e?2:0,maximumFractionDigits:e?2:0}).format(t||0),HC=()=>Re.from("seller_net_sheets"),pGt=t=>`${window.location.origin}/net-sheet/${t}`;function gGt(t){const e=Li();return mr({queryKey:["net-sheets",e,t??"all"],enabled:!!e,queryFn:async()=>{let r=HC().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 yGt(t){return mr({queryKey:["net-sheet",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await HC().select("*").eq("id",t).single();if(r)throw r;return e}})}function SYe(){const t=Li(),e=Ar();return Sr({mutationFn:async r=>{const{price:n,...i}=r,{data:o,error:c}=await HC().insert({...i,owner_user_id:t,title:r.title??"Seller net sheet",mode:"price",inputs:xYe(),scenarios:vYe(n||3e5)}).select().single();if(c)throw c;return o},onSuccess:()=>e.invalidateQueries({queryKey:["net-sheets"]})})}function xGt(){const t=Ar();return Sr({mutationFn:async({id:e,...r})=>{const{error:n}=await HC().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 vGt(){const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await HC().delete().eq("id",e);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["net-sheets"]})})}function TYe(t){return mr({queryKey:["public-net-sheet",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Re.rpc("get_public_net_sheet",{_slug:t});if(r)throw r;return e}})}const EYe=[{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 jYe(t,e=EYe){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 AYe(t){return/mac|iphone|ipad|ipod/i.test(t)?"⌘K":"Ctrl K"}function kYe(t){return t.replace(/[,()*%\\]/g," ").trim()}const CYe={event:{label:"Events",icon:pm,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:XO,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:WA,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:P9,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:xs,color:"bg-fuchsia-500/10 text-fuchsia-600"}},Gre=({hotkey:t=!0}={})=>{const[e,r]=C.useState(!1),[n,i]=C.useState(""),[o,c]=C.useState([]),[a,f]=C.useState(!1),p=Hs(),{searchDestinations:y,isFavorite:v,routeFor:T}=Ive(),E=n.trim()?y(n).slice(0,4):[],k=Li(),[P,R]=C.useState([]),[D,M]=C.useState([]),B=jYe(n),V=SYe(),G=typeof navigator<"u"?AYe(navigator.platform||navigator.userAgent):"Ctrl K",W=async ee=>{if(ee.id==="new-net-sheet"){r(!1),i("");try{const le=await V.mutateAsync({});p(`/mission-control/net-sheets/${le.id}`)}catch{p(ee.path)}return}J(ee.path)};C.useEffect(()=>{if(!t)return;const ee=le=>{le.key==="k"&&(le.metaKey||le.ctrlKey)&&(le.preventDefault(),r(pe=>!pe))};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[t]);const Y=C.useCallback(async ee=>{if(!ee.trim()){c([]),R([]),M([]);return}f(!0);const le=`%${ee}%`;try{const[pe,Se,je,Le,Ae]=await Promise.all([Re.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${le},description.ilike.${le}`).limit(5),Re.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${le},description.ilike.${le}`).limit(5),Re.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${le},description.ilike.${le}`).limit(5),Re.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${le},description.ilike.${le}`).limit(5),Re.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${le},description.ilike.${le}`).limit(5)]),be=[],me=kYe(ee);if(me&&k){const Te=`%${me}%`,Ne=me.split(/\s+/),Ee=Ne.length>1?`and(first_name.ilike.%${Ne[0]}%,last_name.ilike.%${Ne.slice(1).join(" ")}%)`:null,[we,He]=await Promise.all([Re.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city").eq("owner_user_id",k).or([`first_name.ilike.${Te}`,`last_name.ilike.${Te}`,`email.ilike.${Te}`,`phone.ilike.${Te}`,`address.ilike.${Te}`,Ee].filter(Boolean).join(",")).limit(6),Re.from("deal_pipeline").select("id, deal_name, property_address, city, deal_type").eq("owner_user_id",k).or(`deal_name.ilike.${Te},property_address.ilike.${Te},city.ilike.${Te}`).limit(6)]);R((we.data??[]).map(tt=>({id:tt.id,title:[tt.first_name,tt.last_name].filter(Boolean).join(" ")||tt.email||"Contact",sub:[tt.phone,tt.email,tt.address].filter(Boolean).join(" · ")}))),M((He.data??[]).map(tt=>({id:tt.id,title:tt.property_address||tt.deal_name||"Deal",sub:[tt.deal_name!==tt.property_address?tt.deal_name:null,tt.city,tt.deal_type].filter(Boolean).join(" · ")})))}pe.data&&pe.data.forEach(Te=>{be.push({id:Te.id,title:Te.title,description:Te.description,type:"event",date:Te.event_date,path:`/event/${Te.id}`})}),Se.data&&Se.data.forEach(Te=>{be.push({id:Te.id,title:Te.name,description:Te.description,type:"template",date:Te.publish_date,path:`/templates/${Te.id}`})}),je.data&&je.data.forEach(Te=>{be.push({id:Te.id,title:Te.title,description:Te.description,type:"academy",date:Te.publish_date,path:`/academy/${Te.id}`})}),Le.data&&Le.data.forEach(Te=>{be.push({id:Te.id,title:Te.name,description:Te.description,type:"toolbox",date:Te.publish_date,path:`/toolbox/${Te.id}`})}),Ae.data&&Ae.data.forEach(Te=>{be.push({id:Te.id,title:Te.title,description:Te.description,type:"social-swag",date:Te.publish_date,path:`/social-swag/${Te.id}`})}),c(be)}catch(pe){console.error("Search error:",pe)}finally{f(!1)}},[k]);C.useEffect(()=>{const ee=setTimeout(()=>{Y(n)},200);return()=>clearTimeout(ee)},[n,Y]);const J=ee=>{r(!1),i(""),p(ee)},Q=o.reduce((ee,le)=>(ee[le.type]||(ee[le.type]=[]),ee[le.type].push(le),ee),{});return s.jsxs(s.Fragment,{children:[s.jsxs(Bt,{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(xd,{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:G})]}),s.jsxs(pYe,{open:e,onOpenChange:r,children:[s.jsx(dk,{placeholder:"Name, address, or an action like “New Net Sheet”…",value:n,onValueChange:i}),s.jsxs(hk,{className:"max-h-[70vh]",children:[P.length>0&&s.jsx(Rp,{heading:"Contacts",children:P.map(ee=>s.jsxs(nf,{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(Ml,{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}`))}),D.length>0&&s.jsx(Rp,{heading:"Deals",children:D.map(ee=>s.jsxs(nf,{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(va,{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}`))}),B.length>0&&s.jsx(Rp,{heading:n?"Actions":"Quick actions",children:B.map(ee=>s.jsxs(nf,{value:`action-${ee.id}-${ee.label}-${ee.keywords.join(" ")}`,onSelect:()=>W(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(eS,{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}`))}),E.length>0&&s.jsx(Rp,{heading:"Go to",children:E.map(ee=>{const le=ee.icon;return s.jsxs(nf,{value:`nav-${ee.id}-${ee.label}`,onSelect:()=>{const pe=T(ee);ee.external||ee.openInNewTab?(r(!1),i(""),window.open(pe,"_blank","noopener,noreferrer")):J(pe)},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(le,{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(jD,{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(ss,{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&&E.length===0&&P.length===0&&D.length===0&&B.length===0&&s.jsxs(fk,{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,le])=>{const pe=CYe[ee],Se=pe.icon;return s.jsx(Rp,{heading:pe.label,children:le.map(je=>s.jsxs(nf,{value:`${je.type}-${je.id}-${je.title}`,onSelect:()=>J(je.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[s.jsx("div",{className:`p-2 rounded-md ${pe.color}`,children:s.jsx(Se,{className:"h-4 w-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"font-medium truncate",children:je.title}),je.description&&s.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:je.description})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[s.jsx(ss,{variant:"secondary",className:"text-xs",children:pe.label}),s.jsx("span",{className:"text-xs text-muted-foreground",children:wve(new Date(je.date),{addSuffix:!0})})]})]},`${je.type}-${je.id}`))},ee)})]})]})]})},NYe=({expiresAt:t,className:e,showUpgradeButton:r=!0})=>{const[n,i]=C.useState(null),o=Hs();if(C.useEffect(()=>{const p=()=>{const v=new Date().getTime(),E=new Date(t).getTime()-v;if(E<=0){i({days:0,hours:0,minutes:0});return}const k=Math.floor(E/(1e3*60*60*24)),P=Math.floor(E%(1e3*60*60*24)/(1e3*60*60)),R=Math.floor(E%(1e3*60*60)/(1e3*60));i({days:k,hours:P,minutes:R})};p();const y=setInterval(p,6e4);return()=>clearInterval(y)},[t]),!n)return null;const c=n.days===0&&n.hours===0&&n.minutes===0,a=n.days<=1,f=n.days<=3&&!a;return c?s.jsxs("div",{className:qt("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(JS,{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(Bt,{size:"sm",onClick:()=>o("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[s.jsx(xs,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):s.jsxs("div",{className:qt("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(Dl,{className:qt("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:qt("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:qt("text-sm font-bold",a?"text-destructive":f?"text-amber-600":"text-primary"),children:[n.days,"d"]}),s.jsxs("span",{className:qt("text-sm font-bold",a?"text-destructive":f?"text-amber-600":"text-primary"),children:[n.hours,"h"]}),s.jsxs("span",{className:qt("text-sm font-bold",a?"text-destructive":f?"text-amber-600":"text-primary"),children:[n.minutes,"m"]}),s.jsx("span",{className:qt("text-xs",a?"text-destructive/70":f?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),r&&s.jsxs(Bt,{size:"sm",onClick:()=>o("/subscription"),variant:a?"destructive":f?"default":"outline",className:qt("text-xs h-7 px-3",f&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[s.jsx(xs,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},IYe=()=>{const t=Hs();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($n,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[s.jsxs(ud,{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(JS,{className:"h-8 w-8 text-destructive"})}),s.jsx(dd,{className:"text-2xl",children:"Your Free Trial Has Ended"}),s.jsx(ak,{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(Kn,{className:"space-y-6",children:[s.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[s.jsx($n,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>t("/subscription"),children:s.jsxs(Kn,{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(fl,{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(Bt,{className:"w-full",onClick:e=>{e.stopPropagation(),t("/subscription")},children:[s.jsx(xs,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),s.jsx($n,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>t("/subscription"),children:s.jsxs(Kn,{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(_o,{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(Bt,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:e=>{e.stopPropagation(),t("/subscription")},children:[s.jsx(_o,{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(ri,{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(mi,{className:"h-4 w-4"}),s.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},PYe=({hasUnseenBrief:t,onClick:e,className:r})=>s.jsxs(_5e,{children:[s.jsx(b5e,{asChild:!0,children:s.jsxs(Bt,{variant:"ghost",size:"icon",onClick:e,className:qt("relative transition-colors",t&&"text-primary hover:text-primary",r),children:[s.jsx(wC,{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(Jpe,{children:s.jsx("p",{children:"The LevelUp Brief"})})]});var H3="Checkbox",[RYe,_Gt]=Qo(H3),[LYe,aH]=RYe(H3);function DYe(t){const{__scopeCheckbox:e,checked:r,children:n,defaultChecked:i,disabled:o,form:c,name:a,onCheckedChange:f,required:p,value:y="on",internal_do_not_use_render:v}=t,[T,E]=yd({prop:r,defaultProp:i??!1,onChange:f,caller:H3}),[k,P]=C.useState(null),[R,D]=C.useState(null),M=C.useRef(!1),B=k?!!c||!!k.closest("form"):!0,V={checked:T,disabled:o,setChecked:E,control:k,setControl:P,name:a,form:c,value:y,hasConsumerStoppedPropagationRef:M,required:p,defaultChecked:nx(i)?!1:i,isFormControl:B,bubbleInput:R,setBubbleInput:D};return s.jsx(LYe,{scope:e,...V,children:MYe(v)?v(V):n})}var $ve="CheckboxTrigger",zve=C.forwardRef(({__scopeCheckbox:t,onKeyDown:e,onClick:r,...n},i)=>{const{control:o,value:c,disabled:a,checked:f,required:p,setControl:y,setChecked:v,hasConsumerStoppedPropagationRef:T,isFormControl:E,bubbleInput:k}=aH($ve,t),P=Yn(i,y),R=C.useRef(f);return C.useEffect(()=>{const D=o==null?void 0:o.form;if(D){const M=()=>v(R.current);return D.addEventListener("reset",M),()=>D.removeEventListener("reset",M)}},[o,v]),s.jsx(nn.button,{type:"button",role:"checkbox","aria-checked":nx(f)?"mixed":f,"aria-required":p,"data-state":Hve(f),"data-disabled":a?"":void 0,disabled:a,value:c,...n,ref:P,onKeyDown:Or(e,D=>{D.key==="Enter"&&D.preventDefault()}),onClick:Or(r,D=>{v(M=>nx(M)?!0:!M),k&&E&&(T.current=D.isPropagationStopped(),T.current||D.stopPropagation())})})});zve.displayName=$ve;var oH=C.forwardRef((t,e)=>{const{__scopeCheckbox:r,name:n,checked:i,defaultChecked:o,required:c,disabled:a,value:f,onCheckedChange:p,form:y,...v}=t;return s.jsx(DYe,{__scopeCheckbox:r,checked:i,defaultChecked:o,disabled:a,required:c,onCheckedChange:p,name:n,form:y,value:f,internal_do_not_use_render:({isFormControl:T})=>s.jsxs(s.Fragment,{children:[s.jsx(zve,{...v,ref:e,__scopeCheckbox:r}),T&&s.jsx(Gve,{__scopeCheckbox:r})]})})});oH.displayName=H3;var Uve="CheckboxIndicator",Vve=C.forwardRef((t,e)=>{const{__scopeCheckbox:r,forceMount:n,...i}=t,o=aH(Uve,r);return s.jsx(vl,{present:n||nx(o.checked)||o.checked===!0,children:s.jsx(nn.span,{"data-state":Hve(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:e,style:{pointerEvents:"none",...t.style}})})});Vve.displayName=Uve;var qve="CheckboxBubbleInput",Gve=C.forwardRef(({__scopeCheckbox:t,...e},r)=>{const{control:n,hasConsumerStoppedPropagationRef:i,checked:o,defaultChecked:c,required:a,disabled:f,name:p,value:y,form:v,bubbleInput:T,setBubbleInput:E}=aH(qve,t),k=Yn(r,E),P=UC(o),R=IC(n);C.useEffect(()=>{const M=T;if(!M)return;const B=window.HTMLInputElement.prototype,G=Object.getOwnPropertyDescriptor(B,"checked").set,W=!i.current;if(P!==o&&G){const Y=new Event("click",{bubbles:W});M.indeterminate=nx(o),G.call(M,nx(o)?!1:o),M.dispatchEvent(Y)}},[T,P,o,i]);const D=C.useRef(nx(o)?!1:o);return s.jsx(nn.input,{type:"checkbox","aria-hidden":!0,defaultChecked:c??D.current,required:a,disabled:f,name:p,value:y,form:v,...e,tabIndex:-1,ref:k,style:{...e.style,...R,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});Gve.displayName=qve;function MYe(t){return typeof t=="function"}function nx(t){return t==="indeterminate"}function Hve(t){return nx(t)?"indeterminate":t?"checked":"unchecked"}const WC=C.forwardRef(({className:t,...e},r)=>s.jsx(oH,{ref:r,className:qt("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(Vve,{className:qt("flex items-center justify-center text-current"),children:s.jsx(no,{className:"h-4 w-4"})})}));WC.displayName=oH.displayName;var lH="Radio",[OYe,Wve]=Qo(lH),[FYe,BYe]=OYe(lH),Kve=C.forwardRef((t,e)=>{const{__scopeRadio:r,name:n,checked:i=!1,required:o,disabled:c,value:a="on",onCheck:f,form:p,...y}=t,[v,T]=C.useState(null),E=Yn(e,R=>T(R)),k=C.useRef(!1),P=v?p||!!v.closest("form"):!0;return s.jsxs(FYe,{scope:r,checked:i,disabled:c,children:[s.jsx(nn.button,{type:"button",role:"radio","aria-checked":i,"data-state":Qve(i),"data-disabled":c?"":void 0,disabled:c,value:a,...y,ref:E,onClick:Or(t.onClick,R=>{i||f==null||f(),P&&(k.current=R.isPropagationStopped(),k.current||R.stopPropagation())})}),P&&s.jsx(Xve,{control:v,bubbles:!k.current,name:n,value:a,checked:i,required:o,disabled:c,form:p,style:{transform:"translateX(-100%)"}})]})});Kve.displayName=lH;var Yve="RadioIndicator",Zve=C.forwardRef((t,e)=>{const{__scopeRadio:r,forceMount:n,...i}=t,o=BYe(Yve,r);return s.jsx(vl,{present:n||o.checked,children:s.jsx(nn.span,{"data-state":Qve(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:e})})});Zve.displayName=Yve;var $Ye="RadioBubbleInput",Xve=C.forwardRef(({__scopeRadio:t,control:e,checked:r,bubbles:n=!0,...i},o)=>{const c=C.useRef(null),a=Yn(c,o),f=UC(r),p=IC(e);return C.useEffect(()=>{const y=c.current;if(!y)return;const v=window.HTMLInputElement.prototype,E=Object.getOwnPropertyDescriptor(v,"checked").set;if(f!==r&&E){const k=new Event("click",{bubbles:n});E.call(y,r),y.dispatchEvent(k)}},[f,r,n]),s.jsx(nn.input,{type:"radio","aria-hidden":!0,defaultChecked:r,...i,tabIndex:-1,ref:a,style:{...i.style,...p,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});Xve.displayName=$Ye;function Qve(t){return t?"checked":"unchecked"}var zYe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],W3="RadioGroup",[UYe,bGt]=Qo(W3,[uT,Wve]),Jve=uT(),e_e=Wve(),[VYe,qYe]=UYe(W3),t_e=C.forwardRef((t,e)=>{const{__scopeRadioGroup:r,name:n,defaultValue:i,value:o,required:c=!1,disabled:a=!1,orientation:f,dir:p,loop:y=!0,onValueChange:v,...T}=t,E=Jve(r),k=S_(p),[P,R]=yd({prop:o,defaultProp:i??null,onChange:v,caller:W3});return s.jsx(VYe,{scope:r,name:n,required:c,disabled:a,value:P,onValueChange:R,children:s.jsx(f7,{asChild:!0,...E,orientation:f,dir:k,loop:y,children:s.jsx(nn.div,{role:"radiogroup","aria-required":c,"aria-orientation":f,"data-disabled":a?"":void 0,dir:k,...T,ref:e})})})});t_e.displayName=W3;var r_e="RadioGroupItem",n_e=C.forwardRef((t,e)=>{const{__scopeRadioGroup:r,disabled:n,...i}=t,o=qYe(r_e,r),c=o.disabled||n,a=Jve(r),f=e_e(r),p=C.useRef(null),y=Yn(e,p),v=o.value===i.value,T=C.useRef(!1);return C.useEffect(()=>{const E=P=>{zYe.includes(P.key)&&(T.current=!0)},k=()=>T.current=!1;return document.addEventListener("keydown",E),document.addEventListener("keyup",k),()=>{document.removeEventListener("keydown",E),document.removeEventListener("keyup",k)}},[]),s.jsx(m7,{asChild:!0,...a,focusable:!c,active:v,children:s.jsx(Kve,{disabled:c,required:o.required,checked:v,...f,...i,name:o.name,ref:y,onCheck:()=>o.onValueChange(i.value),onKeyDown:Or(E=>{E.key==="Enter"&&E.preventDefault()}),onFocus:Or(i.onFocus,()=>{var E;T.current&&((E=p.current)==null||E.click())})})})});n_e.displayName=r_e;var GYe="RadioGroupIndicator",i_e=C.forwardRef((t,e)=>{const{__scopeRadioGroup:r,...n}=t,i=e_e(r);return s.jsx(Zve,{...i,...n,ref:e})});i_e.displayName=GYe;var s_e=t_e,a_e=n_e,HYe=i_e;const o_e=C.forwardRef(({className:t,...e},r)=>s.jsx(s_e,{className:qt("grid gap-2",t),...e,ref:r}));o_e.displayName=s_e.displayName;const l_e=C.forwardRef(({className:t,...e},r)=>s.jsx(a_e,{ref:r,className:qt("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(HYe,{className:"flex items-center justify-center",children:s.jsx(t_,{className:"h-2.5 w-2.5 fill-current text-current"})})}));l_e.displayName=a_e.displayName;const WYe=({brief:t,open:e,onClose:r,onDismiss:n})=>{const{user:i}=Hn(),[o,c]=C.useState({}),[a,f]=C.useState({}),[p,y]=C.useState([]);C.useEffect(()=>{e&&i&&t.polls.length>0&&v()},[e,i,t.polls]);const v=async()=>{if(!i)return;const R=t.polls.map(M=>M.id),{data:D}=await Re.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",i.id).in("poll_id",R);if(D){const M={};D.forEach(B=>{M[B.poll_id]||(M[B.poll_id]=[]),M[B.poll_id].push(B.option_id)}),f(M)}},T=(R,D)=>{c(M=>({...M,[R]:D}))},E=(R,D,M)=>{c(B=>{const V=B[R]||[];return M?{...B,[R]:[...V,D]}:{...B,[R]:V.filter(G=>G!==D)}})},k=async R=>{if(!i)return;const D=o[R];if(!D||Array.isArray(D)&&D.length===0){Vt.error("Please select an option");return}y(M=>[...M,R]);try{await Re.from("levelup_brief_poll_responses").delete().eq("poll_id",R).eq("user_id",i.id);const M=Array.isArray(D)?D:[D],B=M.map(G=>({poll_id:R,option_id:G,user_id:i.id})),{error:V}=await Re.from("levelup_brief_poll_responses").insert(B);if(V)throw V;f(G=>({...G,[R]:M})),Vt.success("Response submitted!")}catch(M){console.error("Error submitting poll response:",M),Vt.error("Failed to submit response")}finally{y(M=>M.filter(B=>B!==R))}},P=R=>(R.includes("mediadelivery.net")||R.includes("bunny"),R);return s.jsx(lo,{open:e,onOpenChange:R=>!R&&r(),children:s.jsxs(qa,{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(Os,{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(wC,{className:"h-6 w-6"})}),s.jsxs("div",{children:[s.jsx(ss,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),s.jsx(Xo,{className:"text-xl font-bold text-white",children:t.brief.title})]})]})]}),s.jsx(Lm,{className:"max-h-[calc(90vh-240px)]",children:s.jsxs("div",{className:"p-6 space-y-6",children:[t.brief.description&&s.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:t.brief.description}}),t.brief.video_url&&s.jsx("div",{className:"relative w-full aspect-video rounded-lg overflow-hidden bg-muted",children:s.jsx("iframe",{src:P(t.brief.video_url),className:"absolute inset-0 w-full h-full",allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0})}),t.brief.graphic_url&&!t.brief.video_url&&s.jsx("div",{className:"rounded-lg overflow-hidden bg-muted",children:t.brief.graphic_link_url?s.jsx("a",{href:t.brief.graphic_link_url,target:"_blank",rel:"noopener noreferrer",className:"block",children:s.jsx("img",{src:t.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain cursor-pointer hover:opacity-90 transition-opacity"})}):s.jsx("img",{src:t.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain"})}),t.links.length>0&&s.jsxs("div",{className:"space-y-3",children:[s.jsx("h4",{className:"font-semibold text-foreground",children:"Quick Links"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:t.links.map(R=>s.jsxs(Bt,{variant:"outline",size:"sm",onClick:()=>window.open(R.url,"_blank"),className:"gap-2",children:[s.jsx(b_,{className:"h-4 w-4"}),R.title]},R.id))})]}),t.polls.map(R=>{var B,V;const D=((B=a[R.id])==null?void 0:B.length)>0,M=p.includes(R.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:R.question}),D&&s.jsxs(ss,{variant:"secondary",className:"gap-1",children:[s.jsx(oc,{className:"h-3 w-3"}),"Responded"]})]}),R.poll_type==="single"?s.jsx(o_e,{value:o[R.id]||((V=a[R.id])==null?void 0:V[0])||"",onValueChange:G=>T(R.id,G),className:"space-y-2",children:R.options.map(G=>s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(l_e,{value:G.id,id:G.id}),s.jsx(Mr,{htmlFor:G.id,className:"cursor-pointer",children:G.option_text})]},G.id))}):s.jsx("div",{className:"space-y-2",children:R.options.map(G=>{const Y=(o[R.id]||a[R.id]||[]).includes(G.id);return s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(WC,{id:G.id,checked:Y,onCheckedChange:J=>E(R.id,G.id,J)}),s.jsx(Mr,{htmlFor:G.id,className:"cursor-pointer",children:G.option_text})]},G.id)})}),s.jsx(Bt,{size:"sm",onClick:()=>k(R.id),disabled:M,children:M?"Submitting...":D?"Update Response":"Submit"})]},R.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(Bt,{onClick:r,className:"w-full max-w-xs",children:"Got it!"}),s.jsx(Bt,{variant:"ghost",size:"sm",onClick:n,children:"Don't show again"})]})]})})},KYe=()=>{const{user:t}=Hn(),[e,r]=C.useState(null),[n,i]=C.useState(!1),[o,c]=C.useState(!0),[a,f]=C.useState(!1),p=C.useCallback(async()=>{if(!t){c(!1);return}try{const{data:k,error:P}=await Re.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(P||!k){c(!1);return}const{data:R}=await Re.from("levelup_brief_views").select("*").eq("brief_id",k.id).eq("user_id",t.id).maybeSingle(),[D,M]=await Promise.all([Re.from("levelup_brief_links").select("*").eq("brief_id",k.id).order("sort_order"),Re.from("levelup_brief_polls").select("*").eq("brief_id",k.id).order("sort_order")]),B=[];if(M.data)for(const J of M.data){const{data:Q}=await Re.from("levelup_brief_poll_options").select("*").eq("poll_id",J.id).order("sort_order");B.push({...J,options:Q||[]})}const V={brief:k,links:D.data||[],polls:B};r(V);const G=!!R,W=(R==null?void 0:R.dismissed_at)!=null,Y=localStorage.getItem(`brief-dismissed-${k.id}`)==="true";if(W||Y)f(!1),i(!1);else if(!G)i(!0),f(!0);else if(k.show_frequency==="every_login")i(!0),f(!0);else if(k.show_frequency==="daily"){const J=new Date(R.viewed_at);(new Date().getTime()-J.getTime())/(1e3*60*60)>=24&&(i(!0),f(!0))}else f(!1)}catch(k){console.error("Error fetching brief:",k)}finally{c(!1)}},[t]);C.useEffect(()=>{p()},[p]);const y=async()=>{if(!(!t||!e))try{const{data:k}=await Re.from("levelup_brief_views").select("id").eq("brief_id",e.brief.id).eq("user_id",t.id).maybeSingle();k?await Re.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",k.id):await Re.from("levelup_brief_views").insert({brief_id:e.brief.id,user_id:t.id})}catch(k){console.error("Error marking brief as viewed:",k)}};return{currentBrief:e,shouldShowPopup:n,hasUnseenBrief:a,loading:o,openBrief:()=>{i(!0)},closeBrief:()=>{i(!1),y()},dismissBrief:async()=>{if(!(!t||!e)){i(!1),f(!1);try{const{data:k,error:P}=await Re.from("levelup_brief_views").select("id").eq("brief_id",e.brief.id).eq("user_id",t.id).maybeSingle();if(P&&console.error("Error checking existing brief view:",P),k){const{error:R}=await Re.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",k.id).eq("user_id",t.id);R&&console.error("Error updating brief dismiss:",R)}else{const{error:R}=await Re.from("levelup_brief_views").insert({brief_id:e.brief.id,user_id:t.id,dismissed_at:new Date().toISOString()});R&&console.error("Error inserting brief dismiss:",R)}localStorage.setItem(`brief-dismissed-${e.brief.id}`,"true")}catch(k){console.error("Error dismissing brief:",k),e&&localStorage.setItem(`brief-dismissed-${e.brief.id}`,"true")}}},refetch:p}};function YYe(){const[t,e]=C.useState(!1),[r,n]=C.useState(!1),[i,o]=C.useState(null);C.useEffect(()=>{const f=localStorage.getItem("install-banner-dismissed"),p=localStorage.getItem("install-banner-shown");if(f||p)return;if(window.matchMedia("(display-mode: standalone)").matches||window.matchMedia("(display-mode: fullscreen)").matches||window.matchMedia("(display-mode: minimal-ui)").matches||window.navigator.standalone===!0||document.referrer.startsWith("android-app://")){localStorage.setItem("install-banner-dismissed","true");return}if(!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const T=/iPhone|iPad|iPod/i.test(navigator.userAgent);n(T),e(!0),localStorage.setItem("install-banner-shown","true");const E=k=>{k.preventDefault(),o(k)};return window.addEventListener("beforeinstallprompt",E),()=>{window.removeEventListener("beforeinstallprompt",E)}},[]);const c=()=>{localStorage.setItem("install-banner-dismissed","true"),localStorage.setItem("install-banner-shown","true"),e(!1)},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(sc,{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(oMe,{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(Bt,{size:"sm",variant:"secondary",onClick:a,className:"text-xs",children:"Install"}),s.jsx(Bt,{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(Os,{className:"h-4 w-4"})})]})]})}):null}const ZYe=({children:t,onRefresh:e})=>{const[r,n]=C.useState(!1),[i,o]=C.useState(0),[c,a]=C.useState(!1),f=C.useRef(null),p=C.useRef(0),y=Ar(),v=80,T=120,E=C.useCallback(M=>{const B=f.current;B&&B.scrollTop<=0&&(p.current=M.touches[0].clientY,n(!0))},[]),k=C.useCallback(M=>{if(!r||c)return;const B=f.current;if(!B||B.scrollTop>0){n(!1),o(0);return}const G=M.touches[0].clientY-p.current;if(G>0){const Y=Math.min(G*.5,T);o(Y),Y>10&&M.preventDefault()}},[r,c]),P=C.useCallback(async()=>{if(r)if(n(!1),i>=v&&!c){a(!0),o(v);try{e?await e():await y.invalidateQueries()}catch(M){console.error("Refresh failed:",M)}finally{a(!1),o(0)}}else o(0)},[r,i,c,e,y]),R=Math.min(i/v,1),D=R*180;return s.jsxs("div",{ref:f,className:"h-full overflow-auto",onTouchStart:E,onTouchMove:k,onTouchEnd:P,children:[s.jsx("div",{className:"flex justify-center items-center overflow-hidden transition-all duration-200 ease-out",style:{height:i>0?i:0,opacity:R},children:s.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${c?"animate-spin":""}`,style:{transform:c?void 0:`rotate(${D}deg)`,transition:c?void 0:"transform 0.1s ease-out"},children:s.jsx(nMe,{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})]})},XYe=()=>{const{user:t}=Hn(),[e,r]=C.useState(!1),[n,i]=C.useState(!1),[o,c]=C.useState(0),[a,f]=C.useState(!0);C.useEffect(()=>{(async()=>{if(!t){f(!1);return}try{const{data:E}=await Re.from("membership_reviews").select("id").eq("user_id",t.id).maybeSingle();if(E){i(!0),r(!1),f(!1);return}const{data:k}=await Re.from("profiles").select("login_count").eq("id",t.id).single(),P=(k==null?void 0:k.login_count)||0;c(P);const R=sessionStorage.getItem("review-prompt-dismissed");r(P>=4&&!R)}catch(E){console.error("Error checking review eligibility:",E)}finally{f(!1)}})()},[t]);const p=C.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),r(!1)},[]),y=C.useCallback(async(T,E)=>{if(!t)return{success:!1,error:"Not authenticated"};try{const{error:k}=await Re.from("membership_reviews").insert({user_id:t.id,rating:T,review_text:E});if(k)throw k;return i(!0),r(!1),{success:!0,pointsAwarded:25}}catch(k){return console.error("Error submitting review:",k),{success:!1,error:k.message}}},[t]),v=C.useCallback(async()=>{if(t)try{await Re.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",t.id)}catch(T){console.error("Error updating Google review status:",T)}},[t]);return{shouldShowPrompt:e,hasSubmittedReview:n,loginCount:o,isLoading:a,dismissPrompt:p,submitReview:y,markPostedToGoogle:v}},QYe="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",JYe=()=>{const{shouldShowPrompt:t,isLoading:e,dismissPrompt:r,submitReview:n,markPostedToGoogle:i}=XYe(),[o,c]=C.useState(!1),[a,f]=C.useState("review"),[p,y]=C.useState(0),[v,T]=C.useState(0),[E,k]=C.useState(""),[P,R]=C.useState(!1),[D,M]=C.useState(!1);if(e||!t&&!D)return null;const B=async()=>{if(p===0){Ts({title:"Please select a rating",variant:"destructive"});return}R(!0);const W=await n(p,E);R(!1),W.success?(M(!0),Ts({title:"Thank you for your feedback!",description:"Your review helps us improve."}),f("google")):Ts({title:"Error submitting review",description:W.error,variant:"destructive"})},V=async W=>{W&&(await navigator.clipboard.writeText(E||`${p} star rating for LevelUp!`),Ts({title:"Review copied!",description:"Paste it on Google Reviews."}),await i(),window.open(QYe,"_blank")),c(!1),r()},G=()=>{c(!1),r()};return s.jsxs(s.Fragment,{children:[s.jsxs("button",{onClick:()=>c(!0),className:"fixed bottom-20 left-1/2 -translate-x-1/2 z-40 flex items-center gap-2 rounded-full bg-primary/90 px-3 py-2 text-xs text-primary-foreground shadow-lg backdrop-blur-sm transition-all hover:bg-primary hover:scale-105 md:bottom-6",children:[s.jsx(lc,{className:"h-3.5 w-3.5 fill-current"}),s.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),s.jsx(lo,{open:o,onOpenChange:G,children:s.jsx(qa,{className:"sm:max-w-md",children:a==="review"?s.jsxs(s.Fragment,{children:[s.jsxs(xl,{children:[s.jsx(Xo,{className:"text-center",children:"How are you enjoying LevelUp?"}),s.jsx(wd,{className:"text-center",children:"Your feedback helps us improve the experience for all members."})]}),s.jsxs("div",{className:"space-y-6 py-4",children:[s.jsx("div",{className:"flex justify-center gap-1",children:[1,2,3,4,5].map(W=>s.jsx("button",{type:"button",onClick:()=>y(W),onMouseEnter:()=>T(W),onMouseLeave:()=>T(0),className:"p-1 transition-transform hover:scale-110",children:s.jsx(lc,{className:qt("h-8 w-8 transition-colors",(v||p)>=W?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},W))}),s.jsx(Ad,{placeholder:"Tell us about your experience (optional)",value:E,onChange:W=>k(W.target.value),rows:4,className:"resize-none"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Bt,{variant:"outline",onClick:G,className:"flex-1",children:"Maybe Later"}),s.jsx(Bt,{onClick:B,disabled:P||p===0,className:"flex-1",children:P?"Submitting...":"Submit Review"})]})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs(xl,{children:[s.jsx(Xo,{className:"text-center",children:"🎉 Thank you!"}),s.jsx(wd,{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(Bt,{variant:"outline",onClick:()=>V(!1),className:"flex-1",children:"No Thanks"}),s.jsx(Bt,{onClick:()=>V(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function eZe(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 P="vapid_public_key";let R=localStorage.getItem(P);if(!R){const{data:B,error:V}=await Re.functions.invoke("get-vapid-public-key",{body:{}});if(V)throw V;if(R=(B==null?void 0:B.vapidPublicKey)??null,!R)throw new Error("Missing VAPID public key");localStorage.setItem(P,R)}y(R);const D=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});f(D),r(Notification.permission);const M=await D.pushManager.getSubscription();i(!!M)}catch(P){console.error("Error initializing push notifications:",P)}finally{c(!1)}})()},[v]);const T=C.useCallback(async()=>{if(!v||!a||!t)return console.error("Push notifications not supported or user not logged in"),!1;if(!p)return Vt.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{c(!0);const k=await a.pushManager.getSubscription();if(k){try{await k.unsubscribe()}catch(V){console.warn("Failed to unsubscribe existing push subscription:",V)}const{error:B}=await Re.from("push_subscriptions").delete().eq("user_id",t.id);B&&console.warn("Failed to cleanup push_subscriptions rows:",B)}if(Notification.permission!=="granted"){const B=await Notification.requestPermission();if(r(B),B!=="granted")return B==="denied"?Vt.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):Vt.error("Notification permission was dismissed. Please try again."),!1}const P=eZe(p);let R;try{R=await a.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:P})}catch(B){console.error("PushManager.subscribe() failed:",B);const V=(B==null?void 0:B.message)||String(B);return V.includes("permission")?Vt.error("Push permission denied. Check your browser notification settings."):V.includes("key")||V.includes("VAPID")?Vt.error("Push configuration error. Please contact support."):V.includes("AbortError")?Vt.error("Push subscription was cancelled. Please try again."):Vt.error(`Failed to subscribe: ${V}`),!1}const D=R.toJSON(),{error:M}=await Re.from("push_subscriptions").upsert({user_id:t.id,endpoint:D.endpoint,p256dh_key:D.keys.p256dh,auth_key:D.keys.auth},{onConflict:"user_id,endpoint"});if(M)throw console.error("Error saving subscription:",M),Vt.error("Failed to save notification preferences. Please try again."),M;return i(!0),Vt.success("Push notifications enabled!"),!0}catch(k){if(console.error("Error subscribing to push notifications:",k),!(k instanceof Error&&k.message.includes("toast"))){const P=k instanceof Error?k.message:"Unknown error";Vt.error("Failed to enable push notifications: "+P)}return!1}finally{c(!1)}},[v,a,t,p]),E=C.useCallback(async()=>{if(!a||!t)return!1;try{c(!0);const k=await a.pushManager.getSubscription();return k&&await k.unsubscribe(),await Re.from("push_subscriptions").delete().eq("user_id",t.id),i(!1),Vt.success("Push notifications disabled"),!0}catch(k){console.error("Error unsubscribing:",k);const P=k instanceof Error?k.message:"Unknown error";return Vt.error("Failed to disable push notifications: "+P),!1}finally{c(!1)}},[a,t]);return{isSupported:v,permission:e,isSubscribed:n,isLoading:o,vapidPublicKey:p,subscribe:T,unsubscribe:E}}const Y$="push_notification_prompt_dismissed",rZe=["/dashboard","/admin"],nZe=()=>{const{user:t}=Hn(),{isSupported:e,isSubscribed:r,isLoading:n,subscribe:i}=tZe(),o=ki(),[c,a]=C.useState(!1),[f,p]=C.useState(!1),y=rZe.some(E=>o.pathname===E||o.pathname.startsWith(`${E}/`));C.useEffect(()=>{if(y){a(!1);return}if(!t||!e||r||n||localStorage.getItem(`${Y$}_${t.id}`))return;const k=setTimeout(()=>{a(!0)},2e3);return()=>clearTimeout(k)},[t,e,r,n,y]);const v=async()=>{p(!0);const E=await i();p(!1),E&&(t&&localStorage.setItem(`${Y$}_${t.id}`,"true"),a(!1))},T=()=>{t&&localStorage.setItem(`${Y$}_${t.id}`,"true"),a(!1)};return!e||r||y?null:s.jsx(lo,{open:c,onOpenChange:E=>!E&&T(),children:s.jsxs(qa,{className:"sm:max-w-md",children:[s.jsxs(xl,{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(bC,{className:"h-6 w-6 text-primary"})}),s.jsx(Xo,{className:"text-center",children:"Stay in the Loop!"}),s.jsx(wd,{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(Bt,{onClick:v,disabled:f,className:"w-full",children:f?"Enabling...":"Enable Notifications"}),s.jsx(Bt,{variant:"ghost",onClick:T,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."})]})})},Hre=t=>{let e;const r=new Set,n=(p,y)=>{const v=typeof p=="function"?p(e):p;if(!Object.is(v,e)){const T=e;e=y??(typeof v!="object"||v===null)?v:Object.assign({},e,v),r.forEach(E=>E(e,T))}},i=()=>e,a={setState:n,getState:i,getInitialState:()=>f,subscribe:p=>(r.add(p),()=>r.delete(p))},f=e=t(n,i,a);return a},iZe=t=>t?Hre(t):Hre,sZe=t=>t;function aZe(t,e=sZe){const r=Xe.useSyncExternalStore(t.subscribe,Xe.useCallback(()=>e(t.getState()),[t,e]),Xe.useCallback(()=>e(t.getInitialState()),[t,e]));return Xe.useDebugValue(r),r}const Wre=t=>{const e=iZe(t),r=n=>aZe(e,n);return Object.assign(r,e),r},oZe=t=>t?Wre(t):Wre;function lZe(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 WV=t=>e=>{try{const r=t(e);return r instanceof Promise?r:{then(n){return WV(n)(r)},catch(n){return this}}}catch(r){return{then(n){return this},catch(n){return WV(n)(r)}}}},cZe=(t,e)=>(r,n,i)=>{let o={storage:lZe(()=>window.localStorage),partialize:R=>R,version:0,merge:(R,D)=>({...D,...R}),...e},c=!1,a=0;const f=new Set,p=new Set;let y=o.storage;if(!y)return t((...R)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),r(...R)},n,i);const v=()=>{const R=o.partialize({...n()});return y.setItem(o.name,{state:R,version:o.version})},T=i.setState;i.setState=(R,D)=>(T(R,D),v());const E=t((...R)=>(r(...R),v()),n,i);i.getInitialState=()=>E;let k;const P=()=>{var R,D;if(!y)return;const M=++a;c=!1,f.forEach(V=>{var G;return V((G=n())!=null?G:E)});const B=((D=o.onRehydrateStorage)==null?void 0:D.call(o,(R=n())!=null?R:E))||void 0;return WV(y.getItem.bind(y))(o.name).then(V=>{if(V)if(typeof V.version=="number"&&V.version!==o.version){if(o.migrate){const G=o.migrate(V.state,V.version);return G instanceof Promise?G.then(W=>[!0,W]):[!0,G]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,V.state];return[!1,void 0]}).then(V=>{var G;if(M!==a)return;const[W,Y]=V;if(k=o.merge(Y,(G=n())!=null?G:E),r(k,!0),W)return v()}).then(()=>{M===a&&(B==null||B(n(),void 0),k=n(),c=!0,p.forEach(V=>V(k)))}).catch(V=>{M===a&&(B==null||B(void 0,V))})};return i.persist={setOptions:R=>{o={...o,...R},R.storage&&(y=R.storage)},clearStorage:()=>{y==null||y.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>P(),hasHydrated:()=>c,onHydrate:R=>(f.add(R),()=>{f.delete(R)}),onFinishHydration:R=>(p.add(R),()=>{p.delete(R)})},o.skipHydration||P(),k||E},uZe=cZe,c_e=oZe()(uZe((t,e)=>({cartItems:[],addToCart:(r,n,i=1,o)=>{t(c=>{const a=c.cartItems.findIndex(f=>{var p;return f.product.id===r.id&&((p=f.variant)==null?void 0:p.id)===(n==null?void 0:n.id)});if(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})})),dZe="/admin/beta/boost",hZe=C.lazy(()=>Fe(()=>import("./BoostCompanion-TvSTrEwx.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])));function fZe(){const{user:t,isAdmin:e}=Hn(),{isFeatureEnabled:r}=C3(),{pathname:n}=ki(),i=n==="/main-stage"||n.startsWith("/main-stage/");return!(!!t&&(e||r("boost_mascot"))&&n!==dZe&&!i)||!t?null:s.jsx(C.Suspense,{fallback:null,children:s.jsx(hZe,{userId:t.id})})}async function mZe(t){const{data:e,error:r}=await Re.rpc("main_stage_list_events",t?{_event_id:t}:{});if(r)throw r;return(e||[]).map(n=>({...n,speakers:Array.isArray(n.speakers)?n.speakers:[],registered_count:Number(n.registered_count)}))}async function wGt(t){const{data:e,error:r}=await Re.functions.invoke("main-stage-events",{body:t});if(e!=null&&e.error)throw new Error(e.error);if(r)throw new Error(r.message);return e}const u_e="America/New_York",SGt=t=>new Intl.DateTimeFormat("en-US",{timeZone:u_e,weekday:"short",month:"short",day:"numeric"}).format(new Date(t)),TGt=t=>new Intl.DateTimeFormat("en-US",{timeZone:u_e,hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(new Date(t)),EGt=t=>t.trim().toUpperCase().replace(/\s+/g,"");function jGt(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 AGt(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 kGt=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 d_e(){const{data:t}=mr({queryKey:["main-stage-live-nav"],queryFn:async()=>(await mZe()).some(e=>e.status==="live"),refetchInterval:6e4,staleTime:3e4});return!!t}function pZe({activeCategory:t,currentCategory:e,onSelect:r,onHover:n,badgeCounts:i,categories:o=q3}){const c=d_e();return s.jsx("nav",{"aria-label":"Primary",className:"flex flex-col gap-1 p-2",children:o.map(a=>{const f=a.icon,p=t===a.id,y=e===a.id,v=(i==null?void 0:i[a.id])??0,T=`hsl(var(--${a.accent}))`,E=p||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:p,"aria-controls":a.route?void 0:"primary-nav-flyout","aria-current":y?"page":void 0,style:{color:E?T:void 0,backgroundColor:E?`hsl(var(--${a.accent}) / 0.12)`:void 0},className:qt("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:T}}),s.jsxs("span",{className:"relative",children:[s.jsx(f,{className:"h-5 w-5 transition-colors",style:{color:T}}),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:T},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 gZe({category:t,top:e,left:r,onClose:n,onNavigate:i,isFavorite:o,favorites:c,onToggleFavorite:a,isCurrent:f,badgeCounts:p}){const y=C.useRef(null);C.useEffect(()=>{const T=k=>{k.key==="Escape"&&n()},E=k=>{var R;if(!y.current)return;const P=k.target;!y.current.contains(P)&&!((R=P==null?void 0:P.closest)!=null&&R.call(P,"[data-nav-rail]"))&&n()};return document.addEventListener("keydown",T),document.addEventListener("mousedown",E),()=>{document.removeEventListener("keydown",T),document.removeEventListener("mousedown",E)}},[n]);const v=T=>{const E=T.icon,k=T.badgeKey?(p==null?void 0:p[T.badgeKey])??0:0;return s.jsxs("div",{className:qt("group flex items-start gap-3 rounded-lg border border-transparent p-2 transition-colors hover:bg-muted/60",f(T)&&"border-primary/30 bg-primary/5"),children:[s.jsxs("button",{type:"button",onClick:()=>i(T),className:"flex flex-1 items-start gap-3 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md",children:[s.jsx("span",{className:qt("mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",T.iconTone==="red"?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"),children:s.jsx(E,{className:qt("h-4 w-4",T.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:T.label}),T.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"}),T.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"}),T.locked&&s.jsx(hx,{className:"h-3 w-3 text-muted-foreground","aria-label":"Upgrade required"}),k>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:k>9?"9+":k})]}),T.description&&s.jsx("span",{className:"mt-0.5 block text-xs leading-snug text-muted-foreground line-clamp-2",children:T.description})]})]}),s.jsx("button",{type:"button","aria-label":o(T)?`Remove ${T.label} from favorites`:`Add ${T.label} to favorites`,onClick:P=>{P.stopPropagation(),a(T)},className:qt("mt-1 rounded p-1 opacity-0 transition-opacity focus:outline-none focus-visible:ring-2 focus-visible:ring-primary group-hover:opacity-100",o(T)&&"opacity-100 text-primary",!o(T)&&"text-muted-foreground/60 hover:text-primary"),children:s.jsx(jD,{className:qt("h-4 w-4",o(T)&&"fill-current")})})]},T.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(jD,{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(T=>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:T.title}),s.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:T.items.map(v)})]},T.title)),t.sections.length===0&&s.jsx("p",{className:"px-2 py-6 text-sm text-muted-foreground",children:"Nothing here yet."})]})]})}function yZe({categories:t,railCategories:e=q3,currentCategory:r,onNavigate:n,onNavigateRoute:i,isCurrent:o,badgeCounts:c,isFavorite:a,onToggleFavorite:f}){const[p,y]=C.useState(r),v=d_e();return s.jsx("nav",{"aria-label":"Primary",className:"p-2",children:e.map(T=>{const E=T.icon;if(T.route)return s.jsxs("button",{type:"button",onClick:()=>i(T.route),className:qt("flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent",r===T.id&&"bg-sidebar-accent"),children:[s.jsx(E,{className:"h-4 w-4",style:{color:`hsl(var(--${T.accent}))`}}),T.label,T.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"]})]},T.id);const k=t.find(R=>R.id===T.id),P=p===T.id;return s.jsxs("div",{children:[s.jsxs("button",{type:"button","aria-expanded":P,onClick:()=>y(P?null:T.id),className:qt("flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent",r===T.id&&"text-primary"),children:[s.jsx(E,{className:"h-4 w-4",style:{color:`hsl(var(--${T.accent}))`}}),T.label,s.jsx(yl,{className:qt("ml-auto h-4 w-4 transition-transform",P&&"rotate-180")})]}),P&&k&&s.jsx("div",{className:"space-y-3 pb-3 pl-4 pr-1",children:k.sections.map(R=>s.jsxs("div",{children:[s.jsx("p",{className:"px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:R.title}),R.items.map(D=>{const M=D.icon,B=D.badgeKey?(c==null?void 0:c[D.badgeKey])??0:0,V=(a==null?void 0:a(D))??!1;return s.jsxs("div",{className:qt("flex w-full items-center gap-2 rounded-md pr-1 hover:bg-sidebar-accent",o(D)&&"bg-sidebar-accent"),children:[s.jsxs("button",{type:"button",onClick:()=>n(D),className:"flex flex-1 items-center gap-2 px-2 py-2 text-left text-sm text-sidebar-foreground",children:[s.jsx(M,{className:qt("h-4 w-4 shrink-0",D.iconTone==="red"&&"text-destructive")}),s.jsx("span",{className:"truncate",children:D.label}),B>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:B>9?"9+":B})]}),f&&s.jsx("button",{type:"button","aria-label":V?`Remove ${D.label} from favorites`:`Add ${D.label} to favorites`,onClick:()=>f(D),className:qt("rounded p-2",V?"text-primary":"text-muted-foreground/60"),children:s.jsx(jD,{className:qt("h-4 w-4",V&&"fill-current")})})]},D.id)})]},R.title))})]},T.id)})})}function h_e(){const t=Hs(),e=ki(),r=Ive(),n=C.useCallback(a=>Nve(a,r.ctx),[r.ctx]),i=C.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 p=n(f);p!=="/"&&e.pathname.startsWith(p)&&(!a||p.length>a.len)&&(a={id:f.primaryCategory,len:p.length})}return(a==null?void 0:a.id)??null},[e.pathname,r.destinations,n]),o=C.useCallback(a=>!a.external&&e.pathname===n(a),[e.pathname,n]),c=C.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 xZe({communityUnreadCount:t=0,wishlistOpenCount:e=0,flyoutTop:r=64,flyoutLeft:n=80}){const{nav:i,navigate:o,currentCategory:c,isCurrent:a,go:f}=h_e(),[p,y]=C.useState(null),v=C.useRef(null),T=P=>{const R=q3.find(D=>D.id===P);if(R!=null&&R.route){y(null),o(R.route);return}y(D=>D===P?null:P)},E=p?i.categoryMap.get(p):void 0,k={more:t+e};return 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(pZe,{activeCategory:p,currentCategory:c,onSelect:T,categories:i.railCategories,badgeCounts:k}),E&&s.jsx(gZe,{category:E,top:r,left:n,onClose:()=>y(null),onNavigate:P=>{y(null),f(P)},isFavorite:i.isFavorite,favorites:i.favoritesFor(E.id),onToggleFavorite:P=>i.toggleFavorite(i.favoriteKey(P)),isCurrent:a,badgeCounts:{community:t,wishlist:e}})]})}function vZe({communityUnreadCount:t=0,wishlistOpenCount:e=0,onNavigated:r}){const{nav:n,navigate:i,currentCategory:o,isCurrent:c,go:a}=h_e();return s.jsx(yZe,{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 _Ze=({bannerHeight:t,communityUnreadCount:e,wishlistOpenCount:r,isTrial:n,isExpired:i})=>{const o=Hs();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:vVe,alt:"LevelUp",className:"h-8 w-auto"})})}),s.jsxs(Lm,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:[s.jsx(xZe,{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(xs,{className:"h-4 w-4"}),"Upgrade"]})})]})]})},bZe=({isTrial:t,isExpired:e,expiresAt:r,communityUnreadCount:n,wishlistOpenCount:i,pathname:o,onSignOut:c,onNavigated:a})=>{const f=Hs();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:xVe,alt:"LevelUp",className:"h-8 w-auto"})}),s.jsxs(Lm,{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:qt("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(xs,{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(vZe,{communityUnreadCount:n,wishlistOpenCount:i,onNavigated:a})]}),s.jsxs("div",{className:"border-t border-sidebar-border p-3",children:[s.jsxs(Bt,{variant:"ghost",size:"sm",className:qt("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(Ml,{className:"h-4 w-4"}),"Profile"]}),s.jsxs(Bt,{variant:"ghost",size:"sm",className:qt("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(I9,{className:"h-4 w-4"}),"Credits & Wallet"]}),s.jsxs(Bt,{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(ZO,{className:"h-4 w-4"}),"Sign Out"]})]})]})},hS=({children:t,title:e})=>{var at;const{user:r,signOut:n,isAdmin:i,isBrokerageManager:o,isCoach:c,brokerageId:a}=Hn(),{isAssistant:f,actingAsAgent:p,hasPermission:y}=E3();S7();const{isImpersonating:v}=iye(),E=(f&&!!p?40:0)+(v?40:0),{avatarUrl:k}=ZUe(r==null?void 0:r.id),{isTrial:P,isExpired:R,expiresAt:D}=XUe(r==null?void 0:r.id),{isInnerCircleEnabled:M,isMarketplaceEnabled:B}=C3(),{currentBrief:V,shouldShowPopup:G,hasUnseenBrief:W,openBrief:Y,closeBrief:J,dismissBrief:Q}=KYe(),{unreadCount:ee}=QUe(),{openCount:le}=JUe();hT();const Se=c_e(Et=>Et.cartItems).reduce((Et,vt)=>Et+vt.quantity,0),{leadSite:je,hasLeadSite:Le,siteUrl:Ae}=kve();Cve(!Le);const be=Hs(),me=ki(),[Te,Ne]=C.useState(null);C.useEffect(()=>{r!=null&&r.id&&Re.from("profiles").select("name").eq("id",r.id).single().then(({data:Et})=>{Et!=null&&Et.name&&Ne(Et.name)})},[r==null?void 0:r.id]);const Ee=Te||((at=r==null?void 0:r.user_metadata)==null?void 0:at.name)||(r==null?void 0:r.email)||"User",[we,He]=C.useState(!1),tt=Et=>Et.split(" ").map(vt=>vt[0]).join("").toUpperCase().slice(0,2);return s.jsx(Qpe,{children:s.jsxs("div",{className:"min-h-screen bg-background flex",children:[P&&R&&me.pathname!=="/subscription"&&s.jsx(IYe,{}),typeof document<"u"&&dg.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:`${E}px`,height:`calc(100vh - ${E}px)`},children:s.jsx(_Ze,{bannerHeight:E,communityUnreadCount:ee,wishlistOpenCount:le,isTrial:P,isExpired:R})}),document.body),s.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden md:ml-20",style:{height:`calc(100vh - ${E}px)`,marginTop:`${E}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(_xe,{open:we,onOpenChange:He,children:[s.jsx(tVe,{asChild:!0,children:s.jsx(Bt,{variant:"ghost",size:"icon",className:"md:hidden",children:s.jsx(QS,{className:"h-5 w-5"})})}),s.jsx(T7,{side:"left",className:"w-72 p-0 bg-card",children:s.jsx(bZe,{isTrial:P,isExpired:R,expiresAt:D,communityUnreadCount:ee,wishlistOpenCount:le,pathname:me.pathname,onSignOut:n,onNavigated:()=>He(!1)})})]}),s.jsx("div",{className:"flex-1 md:hidden",children:s.jsx("img",{src:_Ve,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(Gre,{})}),s.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[P&&!R&&D&&s.jsx(NYe,{expiresAt:D,className:"hidden lg:flex"}),s.jsx("div",{className:"md:hidden",children:s.jsx(Gre,{hotkey:!1})}),V&&s.jsx(PYe,{hasUnseenBrief:W,onClick:Y}),B&&s.jsxs(Bt,{variant:"ghost",size:"icon",className:"relative",onClick:()=>be("/marketplace/cart"),children:[s.jsx(_me,{className:"h-5 w-5"}),Se>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:Se>99?"99+":Se})]}),s.jsx(Bt,{variant:"ghost",size:"icon","aria-label":"My Calendar",title:"My Calendar",onClick:()=>be("/mission-control/calendar"),children:s.jsx(pm,{className:"h-5 w-5"})}),s.jsx(BKe,{}),s.jsx(uHe,{}),s.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",Ee.split(" ")[0],"!"]}),s.jsxs(FC,{children:[s.jsx(BC,{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(vd,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[s.jsx(_d,{src:k||void 0}),s.jsx(bd,{className:"bg-primary text-primary-foreground font-medium text-sm",children:tt(Ee)})]})})}),s.jsxs(dT,{align:"end",className:"w-48",children:[s.jsxs(Nu,{onClick:()=>be("/profile"),className:"cursor-pointer",children:[s.jsx(Ml,{className:"h-4 w-4 mr-2"}),"Profile"]}),s.jsxs(Nu,{onClick:()=>be("/credits"),className:"cursor-pointer",children:[s.jsx(I9,{className:"h-4 w-4 mr-2"}),"Credits & Wallet"]}),s.jsxs(Nu,{onClick:()=>be("/mission-control/integrations"),className:"cursor-pointer",children:[s.jsx(AD,{className:"h-4 w-4 mr-2"}),"Integrations"]}),s.jsxs(Nu,{onClick:()=>be("/mission-control/browser-extension"),className:"cursor-pointer",children:[s.jsx(AD,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),s.jsx(sk,{}),s.jsxs(Nu,{onClick:n,className:"cursor-pointer text-destructive focus:text-destructive",children:[s.jsx(ZO,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),s.jsx(ZYe,{children:s.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:t})}),V&&s.jsx(WYe,{brief:V,open:G,onClose:J,onDismiss:Q}),s.jsx(YYe,{}),s.jsx(JYe,{}),s.jsx(nZe,{}),s.jsx(fZe,{})]})]})})},lt=({children:t,requireAdmin:e=!1,requireBrokerageManager:r=!1})=>{const{user:n,loading:i,rolesLoading:o,isAdmin:c,isBrokerageManager:a}=Hn(),f=ki(),p=gxe();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(ci,{to:"/auth",replace:!0})}if(e&&!c)return s.jsx(ci,{to:"/dashboard",replace:!0});if(r&&!a&&!c)return s.jsx(ci,{to:"/dashboard",replace:!0});if(p.isRestricted&&!p.isLoading){const y=HUe(f.pathname);if(y&&!p.hasFeature(y))return s.jsx(hS,{title:"Upgrade required",children:s.jsx(YUe,{featureKey:y})})}return s.jsx(s.Fragment,{children:t})};function Z$({children:t}){const{isAdmin:e,loading:r,rolesLoading:n}=Hn(),{isFeatureEnabled:i,isLoading:o}=C3();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(ci,{to:"/apps",replace:!0}):s.jsx(hS,{title:"Staging Studio",children:s.jsx(C.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 cH={};(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 Ne=new OffscreenCanvas(1,1),Ee=Ne.getContext("2d");Ee.fillRect(0,0,1,1);var we=Ne.transferToImageBitmap();Ee.createPattern(we,"no-repeat")}catch{return!1}return!0}();function f(){}function p(Ne){var Ee=r.exports.Promise,we=Ee!==void 0?Ee:e.Promise;return typeof we=="function"?new we(Ne):(Ne(f,f),null)}var y=function(Ne,Ee){return{transform:function(we){if(Ne)return we;if(Ee.has(we))return Ee.get(we);var He=new OffscreenCanvas(we.width,we.height),tt=He.getContext("2d");return tt.drawImage(we,0,0),Ee.set(we,He),He},clear:function(){Ee.clear()}}}(a,new Map),v=function(){var Ne=Math.floor(16.666666666666668),Ee,we,He={},tt=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(Ee=function(at){var Et=Math.random();return He[Et]=requestAnimationFrame(function vt(Gt){tt===Gt||tt+Ne-1{const{data:e,error:r}=await Re.from("celebration_queue").select("*").eq("user_id",t.id).is("seen_at",null).order("created_at",{ascending:!0});if(r)throw r;return e},enabled:!!(t!=null&&t.id),refetchOnWindowFocus:!0,staleTime:0})}function SZe(){const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["celebrations"]})}})}function CGt(){const t=Ar(),{user:e}=Hn();return Sr({mutationFn:async r=>{const{error:n}=await Re.from("celebration_queue").insert({user_id:r.user_id,celebration_type:r.celebration_type,title:r.title,message:r.message||null,points_amount:r.points_amount||null,created_by:e==null?void 0:e.id});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["celebrations"]})}})}const TZe={points_earned:ND,listing_created:va,deal_closed:$p,custom:lc},Yre={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"},Zre=()=>{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 EZe(){const{user:t}=Hn(),e=Ar(),{data:r}=wZe(),n=SZe(),[i,o]=C.useState(null),[c,a]=C.useState(!1),f=C.useCallback(()=>{const E=Date.now()+3e3,k={startVelocity:30,spread:360,ticks:60,zIndex:9999},P=(D,M)=>Math.random()*(M-D)+D,R=setInterval(()=>{const D=E-Date.now();if(D<=0){clearInterval(R);return}const M=50*(D/3e3);Kre({...k,particleCount:M,origin:{x:P(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),Kre({...k,particleCount:M,origin:{x:P(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);C.useEffect(()=>{Zre()||r&&r.length>0&&!i&&(o(r[0]),a(!0),setTimeout(f,100))},[r,i,f]);const p=async()=>{if(i){const T=i.id;a(!1),o(null),e.setQueryData(["celebrations","pending",t==null?void 0:t.id],E=>(E==null?void 0:E.filter(k=>k.id!==T))??[]),await n.mutateAsync(T)}};if(Zre()||!i)return null;const y=TZe[i.celebration_type]||lc,v=Yre[i.celebration_type]||Yre.custom;return s.jsx(lo,{open:c,onOpenChange:T=>!T&&p(),children:s.jsxs(qa,{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(xs,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),s.jsx(xs,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),s.jsx(xs,{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(Bt,{onClick:p,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 ml({className:t,...e}){return s.jsx("div",{className:qt("animate-pulse rounded-md bg-muted",t),...e})}var K3="Tabs",[jZe,NGt]=Qo(K3,[uT]),f_e=uT(),[AZe,uH]=jZe(K3),m_e=C.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,onValueChange:i,defaultValue:o,orientation:c="horizontal",dir:a,activationMode:f="automatic",...p}=t,y=S_(a),[v,T]=yd({prop:n,onChange:i,defaultProp:o??"",caller:K3});return s.jsx(AZe,{scope:r,baseId:Fl(),value:v,onValueChange:T,orientation:c,dir:y,activationMode:f,children:s.jsx(nn.div,{dir:y,"data-orientation":c,...p,ref:e})})});m_e.displayName=K3;var p_e="TabsList",g_e=C.forwardRef((t,e)=>{const{__scopeTabs:r,loop:n=!0,...i}=t,o=uH(p_e,r),c=f_e(r);return s.jsx(f7,{asChild:!0,...c,orientation:o.orientation,dir:o.dir,loop:n,children:s.jsx(nn.div,{role:"tablist","aria-orientation":o.orientation,...i,ref:e})})});g_e.displayName=p_e;var y_e="TabsTrigger",x_e=C.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,disabled:i=!1,...o}=t,c=uH(y_e,r),a=f_e(r),f=b_e(c.baseId,n),p=w_e(c.baseId,n),y=n===c.value;return s.jsx(m7,{asChild:!0,...a,focusable:!i,active:y,children:s.jsx(nn.button,{type:"button",role:"tab","aria-selected":y,"aria-controls":p,"data-state":y?"active":"inactive","data-disabled":i?"":void 0,disabled:i,id:f,...o,ref:e,onMouseDown:Or(t.onMouseDown,v=>{!i&&v.button===0&&v.ctrlKey===!1?c.onValueChange(n):v.preventDefault()}),onKeyDown:Or(t.onKeyDown,v=>{[" ","Enter"].includes(v.key)&&c.onValueChange(n)}),onFocus:Or(t.onFocus,()=>{const v=c.activationMode!=="manual";!y&&!i&&v&&c.onValueChange(n)})})})});x_e.displayName=y_e;var v_e="TabsContent",__e=C.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,forceMount:i,children:o,...c}=t,a=uH(v_e,r),f=b_e(a.baseId,n),p=w_e(a.baseId,n),y=n===a.value,v=C.useRef(y);return C.useEffect(()=>{const T=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(T)},[]),s.jsx(vl,{present:i||y,children:({present:T})=>s.jsx(nn.div,{"data-state":y?"active":"inactive","data-orientation":a.orientation,role:"tabpanel","aria-labelledby":f,hidden:!T,id:p,tabIndex:0,...c,ref:e,style:{...t.style,animationDuration:v.current?"0s":void 0},children:T&&o})})});__e.displayName=v_e;function b_e(t,e){return`${t}-trigger-${e}`}function w_e(t,e){return`${t}-content-${e}`}var kZe=m_e,S_e=g_e,T_e=x_e,E_e=__e;const dH=kZe,Y3=C.forwardRef(({className:t,...e},r)=>s.jsx(S_e,{ref:r,className:qt("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...e}));Y3.displayName=S_e.displayName;const zp=C.forwardRef(({className:t,...e},r)=>s.jsx(T_e,{ref:r,className:qt("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}));zp.displayName=T_e.displayName;const ix=C.forwardRef(({className:t,...e},r)=>s.jsx(E_e,{ref:r,className:qt("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...e}));ix.displayName=E_e.displayName;const mk="#0d0d0d",sM="#1a1a1a",Jl="#c9a84c",KC="#f0d78c",Sm={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function Z3(t){const e={...t,source_page:typeof window<"u"?window.location.pathname:null,user_agent:typeof navigator<"u"?navigator.userAgent:null,referrer:typeof document<"u"?document.referrer:null},{data:r,error:n}=await Re.functions.invoke("public-site-lead",{body:e});if(n)throw n;try{localStorage.setItem(Sm.captured,JSON.stringify({email:t.email,ts:Date.now()}))}catch{}return r}function hH(){try{return!!localStorage.getItem(Sm.captured)}catch{return!1}}function CZe(){try{const t=localStorage.getItem(Sm.captured);return t?JSON.parse(t).email??null:null}catch{return null}}function fH({open:t,onClose:e,children:r}){return C.useEffect(()=>{if(!t)return;const n=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=n}},[t]),t?dg.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, ${sM} 0%, ${mk} 100%)`,border:`1px solid ${Jl}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${Jl}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(Os,{className:"h-4 w-4"})}),r]})}),document.body):null}function mH(){const[t,e]=C.useState({first_name:"",email:"",phone:"",area:""}),[r,n]=C.useState(!1),[i,o]=C.useState("");return{values:t,setValues:e,loading:r,setLoading:n,honeypot:i,setHoneypot:o}}function pH({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(Ml,{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:p=>e({...t,first_name:p.target.value}),className:a,style:f})]}),s.jsxs("div",{className:"relative",children:[s.jsx(mi,{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:p=>e({...t,email:p.target.value}),className:a,style:f})]}),i&&s.jsxs("div",{className:"relative",children:[s.jsx(ri,{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:p=>e({...t,phone:p.target.value}),className:a,style:f})]}),o&&s.jsxs("div",{className:"relative",children:[s.jsx(Es,{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:p=>e({...t,area:p.target.value}),className:a,style:f})]}),s.jsx("input",{type:"text",value:r,onChange:p=>n(p.target.value),tabIndex:-1,autoComplete:"off",className:"absolute -left-[9999px] w-0 h-0 opacity-0","aria-hidden":"true"})]})}function gH({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, ${KC} 0%, ${Jl} 100%)`,color:mk,boxShadow:`0 8px 24px ${Jl}55`},children:t})}function Xre({open:t,onClose:e,initialCriteria:r}){const{values:n,setValues:i,loading:o,setLoading:c,honeypot:a,setHoneypot:f}=mH(),[p,y]=C.useState(!1),v=async T=>{if(T.preventDefault(),!!n.email){c(!0);try{await Z3({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(Sm.stickyDismissed,"1")}catch{}setTimeout(e,2200)}catch{Vt.error("Something went wrong. Please try again.")}finally{c(!1)}}};return s.jsx(fH,{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(bC,{className:"h-4 w-4",style:{color:Jl}}),s.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:KC},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."}),p?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:`${Jl}22`,border:`1px solid ${Jl}55`},children:s.jsx(xs,{className:"h-5 w-5",style:{color:Jl}})}),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(pH,{values:n,setValues:i,honeypot:a,setHoneypot:f}),s.jsx(gH,{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 NZe(){const[t,e]=C.useState(!0),[r,n]=C.useState(!1);C.useEffect(()=>{try{const o=!!localStorage.getItem(Sm.stickyDismissed)||hH();e(o)}catch{e(!1)}},[]);const i=()=>{e(!0);try{localStorage.setItem(Sm.stickyDismissed,"1")}catch{}};return t?s.jsx(Xre,{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, ${sM} 0%, ${mk} 100%)`,borderTop:`1px solid ${Jl}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:`${Jl}22`,border:`1px solid ${Jl}55`},children:s.jsx(bC,{className:"h-4 w-4",style:{color:Jl}})}),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, ${KC} 0%, ${Jl} 100%)`,color:mk},children:"Get Alerts"}),s.jsx("button",{onClick:i,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:s.jsx(Os,{className:"h-4 w-4"})})]})}),s.jsx(Xre,{open:r,onClose:()=>n(!1)})]})}function IZe(){const[t,e]=C.useState(!1),r=C.useRef(!1);C.useEffect(()=>{try{if(sessionStorage.getItem(Sm.exitShown)||hH())return}catch{}const T=setTimeout(()=>{r.current=!0},8e3),E=k=>{if(r.current&&!(k.clientY>0)){e(!0);try{sessionStorage.setItem(Sm.exitShown,"1")}catch{}window.removeEventListener("mouseleave",E),document.removeEventListener("mouseleave",E)}};return document.addEventListener("mouseleave",E),()=>{clearTimeout(T),document.removeEventListener("mouseleave",E)}},[]);const{values:n,setValues:i,loading:o,setLoading:c,honeypot:a,setHoneypot:f}=mH(),[p,y]=C.useState(!1),v=async T=>{if(T.preventDefault(),!!n.email){c(!0);try{await Z3({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{Vt.error("Something went wrong. Please try again.")}finally{c(!1)}}};return s.jsx(fH,{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, ${mk} 0%, ${sM} 60%, ${Jl} 130%)`},children:s.jsx("div",{className:"absolute top-4 left-6",children:s.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:KC},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:sM,border:`1px solid ${Jl}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:s.jsx(xs,{className:"h-6 w-6",style:{color:Jl}})}),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."}),p?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(pH,{values:n,setValues:i,honeypot:a,setHoneypot:f,showPhone:!1}),s.jsx(gH,{type:"submit",disabled:o||!n.email,children:o?"Sending…":"Send My List"})]})]})]})})}function PZe(){const[t,e]=C.useState([]);C.useEffect(()=>{try{const a=localStorage.getItem(Sm.savedListings);a&&e(JSON.parse(a))}catch{}},[]);const r=a=>{e(a);try{localStorage.setItem(Sm.savedListings,JSON.stringify(a))}catch{}},n=C.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 RZe({listingId:t,listingAddress:e,className:r}){const{has:n,add:i,remove:o}=PZe(),c=n(t),[a,f]=C.useState(!1),p=()=>{if(c){o(t);return}if(hH()){i(t),Vt.success("Saved to your favorites"),Z3({lead_type:"saved_listing",email:CZe()||"unknown@local",listing_id:t,listing_address:e}).catch(()=>{});return}f(!0)};return s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:p,className:r,"aria-label":c?"Remove from favorites":"Save to favorites",children:s.jsx(bm,{className:`h-5 w-5 ${c?"fill-current":""}`})}),s.jsx(LZe,{open:a,onClose:()=>f(!1),listingId:t,listingAddress:e,onSaved:()=>i(t)})]})}function LZe({open:t,onClose:e,listingId:r,listingAddress:n,onSaved:i}){const{values:o,setValues:c,loading:a,setLoading:f,honeypot:p,setHoneypot:y}=mH(),v=async T=>{if(T.preventDefault(),!!o.email){f(!0);try{await Z3({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(),Vt.success("Saved to your favorites"),e()}catch{Vt.error("Something went wrong. Please try again.")}finally{f(!1)}}};return s.jsx(fH,{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(bm,{className:"h-4 w-4",style:{color:Jl}}),s.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:KC},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(pH,{values:o,setValues:c,honeypot:p,setHoneypot:y}),s.jsx(gH,{type:"submit",disabled:a||!o.email,children:a?"Saving…":"Save Home"})]})]})})}var j_e=["PageUp","PageDown"],A_e=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],k_e={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},pT="Slider",[KV,DZe,MZe]=vC(pT),[C_e,IGt]=Qo(pT,[MZe]),[OZe,X3]=C_e(pT),N_e=C.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:p=[n],value:y,onValueChange:v=()=>{},onValueCommit:T=()=>{},inverted:E=!1,form:k,...P}=t,R=C.useRef(new Set),D=C.useRef(0),B=c==="horizontal"?FZe:BZe,[V=[],G]=yd({prop:y,defaultProp:p,onChange:le=>{var Se;(Se=[...R.current][D.current])==null||Se.focus(),v(le)}}),W=C.useRef(V);function Y(le){const pe=qZe(V,le);ee(le,pe)}function J(le){ee(le,D.current)}function Q(){const le=W.current[D.current];V[D.current]!==le&&T(V)}function ee(le,pe,{commit:Se}={commit:!1}){const je=KZe(o),Le=YZe(Math.round((le-n)/o)*o+n,je),Ae=ok(Le,[n,i]);G((be=[])=>{const me=UZe(be,Ae,pe);if(WZe(me,f*o)){D.current=me.indexOf(Ae);const Te=String(me)!==String(be);return Te&&Se&&T(me),Te?me:be}else return be})}return s.jsx(OZe,{scope:t.__scopeSlider,name:r,disabled:a,min:n,max:i,valueIndexToChangeRef:D,thumbs:R.current,values:V,orientation:c,form:k,children:s.jsx(KV.Provider,{scope:t.__scopeSlider,children:s.jsx(KV.Slot,{scope:t.__scopeSlider,children:s.jsx(B,{"aria-disabled":a,"data-disabled":a?"":void 0,...P,ref:e,onPointerDown:Or(P.onPointerDown,()=>{a||(W.current=V)}),min:n,max:i,inverted:E,onSlideStart:a?void 0:Y,onSlideMove:a?void 0:J,onSlideEnd:a?void 0:Q,onHomeKeyDown:()=>!a&&ee(n,0,{commit:!0}),onEndKeyDown:()=>!a&&ee(i,V.length-1,{commit:!0}),onStepKeyDown:({event:le,direction:pe})=>{if(!a){const Le=j_e.includes(le.key)||le.shiftKey&&A_e.includes(le.key)?10:1,Ae=D.current,be=V[Ae],me=o*Le*pe;ee(be+me,Ae,{commit:!0})}}})})})})});N_e.displayName=pT;var[I_e,P_e]=C_e(pT,{startEdge:"left",endEdge:"right",size:"width",direction:1}),FZe=C.forwardRef((t,e)=>{const{min:r,max:n,dir:i,inverted:o,onSlideStart:c,onSlideMove:a,onSlideEnd:f,onStepKeyDown:p,...y}=t,[v,T]=C.useState(null),E=Yn(e,B=>T(B)),k=C.useRef(void 0),P=S_(i),R=P==="ltr",D=R&&!o||!R&&o;function M(B){const V=k.current||v.getBoundingClientRect(),G=[0,V.width],Y=yH(G,D?[r,n]:[n,r]);return k.current=V,Y(B-V.left)}return s.jsx(I_e,{scope:t.__scopeSlider,startEdge:D?"left":"right",endEdge:D?"right":"left",direction:D?1:-1,size:"width",children:s.jsx(R_e,{dir:P,"data-orientation":"horizontal",...y,ref:E,style:{...y.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:B=>{const V=M(B.clientX);c==null||c(V)},onSlideMove:B=>{const V=M(B.clientX);a==null||a(V)},onSlideEnd:()=>{k.current=void 0,f==null||f()},onStepKeyDown:B=>{const G=k_e[D?"from-left":"from-right"].includes(B.key);p==null||p({event:B,direction:G?-1:1})}})})}),BZe=C.forwardRef((t,e)=>{const{min:r,max:n,inverted:i,onSlideStart:o,onSlideMove:c,onSlideEnd:a,onStepKeyDown:f,...p}=t,y=C.useRef(null),v=Yn(e,y),T=C.useRef(void 0),E=!i;function k(P){const R=T.current||y.current.getBoundingClientRect(),D=[0,R.height],B=yH(D,E?[n,r]:[r,n]);return T.current=R,B(P-R.top)}return s.jsx(I_e,{scope:t.__scopeSlider,startEdge:E?"bottom":"top",endEdge:E?"top":"bottom",size:"height",direction:E?1:-1,children:s.jsx(R_e,{"data-orientation":"vertical",...p,ref:v,style:{...p.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:P=>{const R=k(P.clientY);o==null||o(R)},onSlideMove:P=>{const R=k(P.clientY);c==null||c(R)},onSlideEnd:()=>{T.current=void 0,a==null||a()},onStepKeyDown:P=>{const D=k_e[E?"from-bottom":"from-top"].includes(P.key);f==null||f({event:P,direction:D?-1:1})}})})}),R_e=C.forwardRef((t,e)=>{const{__scopeSlider:r,onSlideStart:n,onSlideMove:i,onSlideEnd:o,onHomeKeyDown:c,onEndKeyDown:a,onStepKeyDown:f,...p}=t,y=X3(pT,r);return s.jsx(nn.span,{...p,ref:e,onKeyDown:Or(t.onKeyDown,v=>{v.key==="Home"?(c(v),v.preventDefault()):v.key==="End"?(a(v),v.preventDefault()):j_e.concat(A_e).includes(v.key)&&(f(v),v.preventDefault())}),onPointerDown:Or(t.onPointerDown,v=>{const T=v.target;T.setPointerCapture(v.pointerId),v.preventDefault(),y.thumbs.has(T)?T.focus():n(v)}),onPointerMove:Or(t.onPointerMove,v=>{v.target.hasPointerCapture(v.pointerId)&&i(v)}),onPointerUp:Or(t.onPointerUp,v=>{const T=v.target;T.hasPointerCapture(v.pointerId)&&(T.releasePointerCapture(v.pointerId),o(v))})})}),L_e="SliderTrack",D_e=C.forwardRef((t,e)=>{const{__scopeSlider:r,...n}=t,i=X3(L_e,r);return s.jsx(nn.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...n,ref:e})});D_e.displayName=L_e;var YV="SliderRange",M_e=C.forwardRef((t,e)=>{const{__scopeSlider:r,...n}=t,i=X3(YV,r),o=P_e(YV,r),c=C.useRef(null),a=Yn(e,c),f=i.values.length,p=i.values.map(T=>B_e(T,i.min,i.max)),y=f>1?Math.min(...p):0,v=100-Math.max(...p);return s.jsx(nn.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...n,ref:a,style:{...t.style,[o.startEdge]:y+"%",[o.endEdge]:v+"%"}})});M_e.displayName=YV;var ZV="SliderThumb",O_e=C.forwardRef((t,e)=>{const r=DZe(t.__scopeSlider),[n,i]=C.useState(null),o=Yn(e,a=>i(a)),c=C.useMemo(()=>n?r().findIndex(a=>a.ref.current===n):-1,[r,n]);return s.jsx($Ze,{...t,ref:o,index:c})}),$Ze=C.forwardRef((t,e)=>{const{__scopeSlider:r,index:n,name:i,...o}=t,c=X3(ZV,r),a=P_e(ZV,r),[f,p]=C.useState(null),y=Yn(e,M=>p(M)),v=f?c.form||!!f.closest("form"):!0,T=IC(f),E=c.values[n],k=E===void 0?0:B_e(E,c.min,c.max),P=VZe(n,c.values.length),R=T==null?void 0:T[a.size],D=R?GZe(R,k,a.direction):0;return C.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(${k}% + ${D}px)`},children:[s.jsx(KV.ItemSlot,{scope:t.__scopeSlider,children:s.jsx(nn.span,{role:"slider","aria-label":t["aria-label"]||P,"aria-valuemin":c.min,"aria-valuenow":E,"aria-valuemax":c.max,"aria-orientation":c.orientation,"data-orientation":c.orientation,"data-disabled":c.disabled?"":void 0,tabIndex:c.disabled?void 0:0,...o,ref:y,style:E===void 0?{display:"none"}:t.style,onFocus:Or(t.onFocus,()=>{c.valueIndexToChangeRef.current=n})})}),v&&s.jsx(F_e,{name:i??(c.name?c.name+(c.values.length>1?"[]":""):void 0),form:c.form,value:E},n)]})});O_e.displayName=ZV;var zZe="RadioBubbleInput",F_e=C.forwardRef(({__scopeSlider:t,value:e,...r},n)=>{const i=C.useRef(null),o=Yn(i,n),c=UC(e);return C.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(nn.input,{style:{display:"none"},...r,ref:o,defaultValue:e})});F_e.displayName=zZe;function UZe(t=[],e,r){const n=[...t];return n[r]=e,n.sort((i,o)=>i-o)}function B_e(t,e,r){const o=100/(r-e)*(t-e);return ok(o,[0,100])}function VZe(t,e){return e>2?`Value ${t+1} of ${e}`:e===2?["Minimum","Maximum"][t]:void 0}function qZe(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 GZe(t,e,r){const n=t/2,o=yH([0,50],[0,n]);return(n-o(e)*r)*r}function HZe(t){return t.slice(0,-1).map((e,r)=>t[r+1]-e)}function WZe(t,e){if(e>0){const r=HZe(t);return Math.min(...r)>=e}return!0}function yH(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 KZe(t){return(String(t).split(".")[1]||"").length}function YZe(t,e){const r=Math.pow(10,e);return Math.round(t*r)/r}var $_e=N_e,ZZe=D_e,XZe=M_e,QZe=O_e;const w1=C.forwardRef(({className:t,...e},r)=>s.jsxs($_e,{ref:r,className:qt("relative flex w-full touch-none select-none items-center",t),...e,children:[s.jsx(ZZe,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:s.jsx(XZe,{className:"absolute h-full bg-primary"})}),s.jsx(QZe,{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"})]}));w1.displayName=$_e.displayName;const JZe=t=>mr({queryKey:["public-listings",t],queryFn:async()=>{let e=Re.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, listing_class, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, latitude, longitude, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).or("lifecycle_stage.is.null,lifecycle_stage.neq.pitch").or("listing_class.is.null,listing_class.neq.commercial").order("created_at",{ascending:!1});if(t!=null&&t.status?e=e.eq("status",t.status):e=e.not("status","in","(sold,temp_off_market,withdrawn)"),t!=null&&t.propertyType&&(e=e.eq("property_type",t.propertyType)),t!=null&&t.city){const i=t.city.replace(/[%,()]/g," ").trim();if(i){const o=`%${i}%`;e=e.or(`city.ilike.${o},neighborhood.ilike.${o},property_address.ilike.${o}`)}}t!=null&&t.minPrice&&(e=e.gte("price",t.minPrice)),t!=null&&t.maxPrice&&(e=e.lte("price",t.maxPrice));const{data:r,error:n}=await e;if(n)throw n;return r}}),eXe=()=>mr({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:t,error:e}=await Re.from("listings").select("city, state, neighborhood, property_address").eq("is_approved",!0).eq("is_public",!0);if(e)throw e;const r=new Map,n=new Map,i=new Map;return(t||[]).forEach(o=>{if(o.city){const c=`${o.city}|${o.state||""}`.toLowerCase(),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)}}}),tXe=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=Re.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, listing_class, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, agent_notes, agent_notes_public, mls_link, video_link, video_id, latitude, longitude, page_config, page_theme, created_at, updated_at, co_agent_name, co_agent_email, co_agent_phone, co_agent_brokerage, co_agent_photo_url, photos:listing_photos(id, photo_url, is_primary, sort_order), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds, bunny_video_id) `).eq("is_approved",!0).eq("is_public",!0);e?r=r.eq("id",t):r=r.eq("slug",t);const{data:n,error:i}=await r.single();if(i)throw i;const o=n;return Array.isArray(o==null?void 0:o.photos)&&(o.photos=[...o.photos].sort((c,a)=>(c.sort_order??0)-(a.sort_order??0)||(a.is_primary?1:0)-(c.is_primary?1:0))),o},enabled:!!t}),rXe=()=>Sr({mutationFn:async({listingId:t,agentId:e,firstName:r,lastName:n,email:i,phone:o,shareToken:c,leadType:a="info_request",preferredDate:f,preferredTime:p,showingMode:y,message:v})=>{let T=null,E=null;if(c){const{data:M}=await Re.from("listing_shares").select("id, sharing_agent_id").eq("share_token",c).eq("listing_id",t).maybeSingle();M&&(T=M.id,E=M.sharing_agent_id)}const k=crypto.randomUUID(),P={id:k},{error:R}=await Re.from("listing_leads").insert({id:k,listing_id:t,agent_id:E||e,first_name:r,last_name:n,email:i,phone:o,share_id:T,referred_by_agent_id:E,lead_type:a,preferred_date:f||null,preferred_time:p||null,showing_mode:y||null,message:v||null});if(R)throw R;const{error:D}=await Re.functions.invoke("process-listing-lead",{body:{leadId:P.id}});return D&&console.error("Error processing lead:",D),P}}),nXe=()=>Sr({mutationFn:async t=>{const{error:e}=await Re.rpc("increment_listing_share_click",{p_share_token:t});if(e)throw e}});function iXe({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(Q1,{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(Es,{className:"h-3.5 w-3.5"}),r]})]}),s.jsx("div",{className:"space-y-10",children:n.map((p,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:p.heading})]}),p.intro&&s.jsx("p",{className:`text-sm sm:text-base leading-relaxed ${a} mb-4`,children:p.intro}),s.jsx("ul",{className:"space-y-3",children:(p.items??[]).map((v,T)=>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})]},T))})]},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(ri,{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(mi,{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 yR="border-white/15 bg-white/5 text-white placeholder:text-white/40";function sXe({listingId:t}){const[e,r]=C.useState(null),[n,i]=C.useState({firstName:"",lastName:"",email:"",phone:""}),[o,c]=C.useState(!1),[a,f]=C.useState(null),[p,y]=C.useState(!1);if(C.useEffect(()=>{let T=!1;return Re.functions.invoke("community-guide-public",{body:{action:"teaser",listingId:t}}).then(({data:E})=>{!T&&E&&r(E)}).catch(()=>{}),()=>{T=!0}},[t]),!(e!=null&&e.available))return null;const v=async T=>{if(T.preventDefault(),!n.firstName.trim()||!n.email.trim()){Vt.error("Please add your name and email.");return}c(!0);try{const{data:E,error:k}=await Re.functions.invoke("community-guide-public",{body:{action:"unlock",listingId:t,...n}});if(k||E!=null&&E.error)throw new Error((E==null?void 0:E.error)||"Something went wrong.");f(E),y(!0),Vt.success("Your guide is ready!")}catch(E){Vt.error((E==null?void 0:E.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(Q1,{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((T,E)=>s.jsxs("li",{className:"flex gap-2 text-sm text-white/70",children:[s.jsx(no,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),T]},E))}),a?s.jsxs(Bt,{className:"w-full mt-5",onClick:()=>y(!0),children:[s.jsx(Q1,{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(Mr,{htmlFor:"cg-first",className:"text-xs text-white/60",children:"First name"}),s.jsx(Br,{id:"cg-first",value:n.firstName,onChange:T=>i({...n,firstName:T.target.value}),className:yR,required:!0})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Mr,{htmlFor:"cg-last",className:"text-xs text-white/60",children:"Last name"}),s.jsx(Br,{id:"cg-last",value:n.lastName,onChange:T=>i({...n,lastName:T.target.value}),className:yR})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Mr,{htmlFor:"cg-email",className:"text-xs text-white/60",children:"Email"}),s.jsx(Br,{id:"cg-email",type:"email",value:n.email,onChange:T=>i({...n,email:T.target.value}),className:yR,required:!0})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Mr,{htmlFor:"cg-phone",className:"text-xs text-white/60",children:"Cell phone"}),s.jsx(Br,{id:"cg-phone",type:"tel",value:n.phone,onChange:T=>i({...n,phone:T.target.value}),className:yR})]}),s.jsxs(Bt,{type:"submit",className:"w-full",disabled:o,children:[o?s.jsx(su,{className:"h-4 w-4 mr-2 animate-spin"}):s.jsx(sc,{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(hx,{className:"h-3 w-3"}),"Instant access. We never share your details."]})]})]}),s.jsx(lo,{open:p,onOpenChange:y,children:s.jsx(qa,{className:"max-w-2xl p-0 gap-0",children:s.jsx(Lm,{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(iXe,{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(Bt,{variant:"outline",onClick:()=>aXe(a==null?void 0:a.title),children:[s.jsx(sc,{className:"h-4 w-4 mr-2"}),"Save as PDF"]})})]})})})})]})}function aXe(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 Qre={sale:"For Sale",lease:"For Lease",sale_or_lease:"For Sale or Lease",investment:"Investment Offering"},z_e={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"},PGt=["NNN","Modified Gross","Full Service","Gross","Absolute Net","Ground Lease"],oXe={sf_year:"/SF/YR",sf_month:"/SF/MO",month:"/MO"},lXe={om:"Offering Memorandum",flyer:"Flyer",rent_roll:"Rent Roll",financials:"Financials",survey:"Survey",site_plan:"Site Plan",lease:"Lease Documents",other:"Other"},RGt={public:"Open download",email:"Email required",nda:"NDA required"},cXe={principal:"Principal / Investor",broker:"Broker",tenant:"Tenant / User",lender:"Lender",other:"Other"},LGt=[{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"}],X$=[{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"}],DGt=[{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 sf(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 Jre(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`:sf(e)}function XV(t){return t==null?null:`${new Intl.NumberFormat("en-US").format(Number(t))} SF`}function U_e(t,e=2){return t==null?null:`${Number(t).toFixed(e).replace(/\.?0+$/,"")}%`}function QV(t){if(!(t!=null&&t.lease_rate))return null;const e=oXe[t.lease_rate_unit||"sf_year"]??"";return`${t.lease_rate_unit==="month"?sf(t.lease_rate):`$${Number(t.lease_rate).toFixed(2).replace(/\.00$/,"")}`}${e}${t.lease_type?` ${t.lease_type}`:""}`}function ene(t,e){if(!t)return sf(e)??"Price on request";if(t.deal_type==="lease")return QV(t)??"Rate on request";const r=t.asking_price??e;if(t.deal_type==="sale_or_lease"){const n=[sf(r),QV(t)].filter(Boolean);return n.length?n.join(" · "):"Price on request"}return sf(r)??"Price on request"}function uXe(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?z_e[e.commercial_type]:"Commercial"} Opportunity`:t.property_address||`${t.city??""}, ${t.state??""}`}function dXe(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 MGt(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 X$)(i[c.key]||r[c.key])&&n.push(c.key);return{done:n,total:X$.length,score:Math.round(n.length/X$.length*100)}}const OGt={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 FGt(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 BGt="https://commercial.relevelup.com",Tm=Re;function $Gt(t){return mr({queryKey:["commercial-details",t],queryFn:async()=>{const{data:e,error:r}=await Tm.from("commercial_listing_details").select("*").eq("listing_id",t).maybeSingle();if(r)throw r;return e??null},enabled:!!t})}function zGt(){const t=Ar(),{user:e}=Hn();return Sr({mutationFn:async({listingId:r,values:n})=>{const{data:i,error:o}=await Tm.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 UGt(t){return mr({queryKey:["commercial-pitch",t],queryFn:async()=>{const{data:e,error:r}=await Tm.from("commercial_pitch_details").select("*").eq("listing_id",t).maybeSingle();if(r)throw r;return e??null},enabled:!!t})}function VGt(){const t=Ar(),{user:e}=Hn();return Sr({mutationFn:async({listingId:r,values:n})=>{const{data:i,error:o}=await Tm.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 qGt(){const t=Ar();return Sr({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 Tm.from("listings").update(c).eq("id",e);if(a)throw a;return(i||o)&&await Tm.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 GGt(){const t=Ar();return Sr({mutationFn:async({listingId:e,values:r})=>{const{error:n}=await Tm.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 HGt(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 Tm.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 WGt(t){return mr({queryKey:["commercial-leads",t],queryFn:async()=>{const{data:e,error:r}=await Tm.from("listing_leads").select("*").eq("listing_id",t).order("created_at",{ascending:!1});if(r)throw r;return e??[]},enabled:!!t})}const tne="lu_commercial_session";function V_e(){try{let t=localStorage.getItem(tne);return t||(t=crypto.randomUUID(),localStorage.setItem(tne,t)),t}catch{return"anonymous"}}async function xw(t,e,r={}){try{await Tm.from("commercial_engagement_events").insert({listing_id:t,event_type:e,session_id:V_e(),source:typeof document<"u"&&document.referrer||null,metadata:r})}catch{}}const hXe={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 fXe({open:t,onOpenChange:e,listingId:r,kind:n,documentId:i,requiresNda:o,brokerName:c}){const a=hXe[n],[f,p]=C.useState({firstName:"",lastName:"",email:"",phone:"",company:"",role:"principal",message:""}),[y,v]=C.useState(!1),[T,E]=C.useState(!1),[k,P]=C.useState(null),R=async()=>{if(!f.firstName.trim()||!f.email.trim()){Vt.error("Name and email are required");return}if(o&&n==="om_request"&&!y){Vt.error("Please acknowledge the confidentiality terms");return}E(!0);try{const{data:D,error:M}=await Re.functions.invoke("commercial-lead",{body:{listingId:r,documentId:i??null,leadType:n,firstName:f.firstName,lastName:f.lastName,email:f.email,phone:f.phone||null,company:f.company||null,role:f.role,message:f.message||null,ndaAccepted:y,sessionId:V_e()}});if(M)throw M;if(D!=null&&D.error)throw new Error(D.error);P({signedUrl:(D==null?void 0:D.signedUrl)??null,fileName:(D==null?void 0:D.fileName)??null}),D!=null&&D.signedUrl&&window.open(D.signedUrl,"_blank")}catch(D){Vt.error(D.message||"Something went wrong. Please try again.")}finally{E(!1)}};return s.jsx(lo,{open:t,onOpenChange:D=>{e(D),D||P(null)},children:s.jsxs(qa,{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:k?"Access granted":a.title}),s.jsx("p",{className:"mt-1.5 text-sm text-white/60",children:k?k.signedUrl?"Your download has opened in a new tab. The secure link expires in 30 minutes.":`Your request has been sent${c?` to ${c}`:""}. You'll hear back shortly.`:a.blurb})]}),k?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(oc,{className:"h-5 w-5 text-emerald-400"}),s.jsx("p",{className:"text-sm text-white/80",children:k.fileName??"Request received"})]}),k.signedUrl&&s.jsx(Bt,{className:"w-full",onClick:()=>window.open(k.signedUrl,"_blank"),children:"Download again"}),s.jsx(Bt,{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(nv,{label:"First name *",children:s.jsx(Br,{value:f.firstName,onChange:D=>p({...f,firstName:D.target.value}),className:"border-white/15 bg-white/5 text-white"})}),s.jsx(nv,{label:"Last name",children:s.jsx(Br,{value:f.lastName,onChange:D=>p({...f,lastName:D.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),s.jsx(nv,{label:"Email *",children:s.jsx(Br,{type:"email",value:f.email,onChange:D=>p({...f,email:D.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(nv,{label:"Company",children:s.jsx(Br,{value:f.company,onChange:D=>p({...f,company:D.target.value}),className:"border-white/15 bg-white/5 text-white"})}),s.jsx(nv,{label:"Phone",children:s.jsx(Br,{value:f.phone,onChange:D=>p({...f,phone:D.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),s.jsx(nv,{label:"I am a *",children:s.jsxs(ba,{value:f.role,onValueChange:D=>p({...f,role:D}),children:[s.jsx(oa,{className:"border-white/15 bg-white/5 text-white",children:s.jsx(wa,{})}),s.jsx(la,{children:Object.entries(cXe).map(([D,M])=>s.jsx(mn,{value:D,children:M},D))})]})}),n!=="om_request"&&s.jsx(nv,{label:"Message",children:s.jsx(Ad,{rows:3,value:f.message,onChange:D=>p({...f,message:D.target.value}),className:"border-white/15 bg-white/5 text-white",placeholder:n==="tour_request"?"Preferred dates and times…":"Your question…"})}),o&&n==="om_request"&&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(WC,{checked:y,onCheckedChange:D=>v(!!D),className:"mt-0.5 border-white/30"}),s.jsxs("span",{className:"text-xs leading-relaxed text-white/65",children:[s.jsx(k9,{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(Bt,{className:"w-full",size:"lg",onClick:R,disabled:T,children:[T?s.jsx(su,{className:"mr-2 h-4 w-4 animate-spin"}):s.jsx(hx,{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 nv({label:t,children:e}){return s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Mr,{className:"text-[11px] font-medium uppercase tracking-wider text-white/50",children:t}),e]})}function q_e(t){if(!t)return[];const e=[],r=(n,i)=>{i&&e.push({label:n,value:i})};return r("Cap Rate",U_e(t.cap_rate)),r("NOI",Jre(t.noi)),r("Occupancy",t.occupancy_pct!=null?`${Math.round(Number(t.occupancy_pct))}%`:null),r("Building SF",XV(t.building_sf)),r("Available SF",XV(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?sf(t.price_per_sf,2):null),r("Price / Unit",Jre(t.price_per_unit)),r("Lease Rate",t.deal_type!=="sale"?QV(t):null),r("Year Built",null),r("Zoning",t.zoning??null),e}function KGt({details:t,className:e="",tone:r="light"}){const n=q_e(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 mXe(t){return mr({queryKey:["commercial-microsite",t],queryFn:async()=>{const{data:e,error:r}=await Re.functions.invoke("commercial-public",{body:{slug:t}});if(r)throw r;if(e!=null&&e.error)throw new Error(e.error);return e},enabled:!!t})}function pXe({slug:t}){var le,pe;const{data:e,isLoading:r,error:n}=mXe(t),[i,o]=C.useState(null),[c,a]=C.useState(null),f=e==null?void 0:e.listing,p=(e==null?void 0:e.details)??void 0,y=(e==null?void 0:e.documents)??[],v=(f==null?void 0:f.photos)??[],T=f==null?void 0:f.agent,E=!!(p!=null&&p.is_confidential||p!=null&&p.hide_address),k=C.useMemo(()=>q_e(p).slice(0,8),[p]);if(C.useEffect(()=>{f!=null&&f.id&&xw(f.id,"page_view",{slug:t})},[f==null?void 0:f.id,t]),C.useEffect(()=>{if(i===null)return;const Se=je=>{je.key==="Escape"&&o(null),je.key==="ArrowRight"&&o(Le=>Le===null?Le:(Le+1)%v.length),je.key==="ArrowLeft"&&o(Le=>Le===null?Le:(Le-1+v.length)%v.length)};return window.addEventListener("keydown",Se),()=>window.removeEventListener("keydown",Se)},[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 P=uXe(f,p),R=dXe(f,p),D=f.latitude&&f.longitude?`${f.latitude},${f.longitude}`:E?[p==null?void 0:p.submarket,f.city,f.state].filter(Boolean).join(", ")||null:[f.property_address,f.city,f.state].filter(Boolean).join(", ")||null,M=(le=v[0])==null?void 0:le.photo_url,B=(p==null?void 0:p.tenants)??[],V=(p==null?void 0:p.spaces)??[],G=(p==null?void 0:p.demographics)??{},W=(p==null?void 0:p.traffic_counts)??[],Y=(p==null?void 0:p.investment_highlights)??[],J=(p==null?void 0:p.property_highlights)??[],Q=["radius_1","radius_3","radius_5"].some(Se=>(G==null?void 0:G[Se])&&Object.values(G[Se]).some(Boolean)),ee=(Se,je)=>{a({kind:Se,documentId:je}),xw(f.id,Se==="om_request"?"om_request":Se,{})};return s.jsxs("div",{className:"min-h-screen bg-[#0b0f14] text-white antialiased",children:[s.jsxs(Zo,{children:[s.jsx("title",{children:`${P} | ${R}`}),s.jsx("meta",{name:"description",content:(f.description??"").slice(0,155)||`${Qre[(p==null?void 0:p.deal_type)??"sale"]} — ${R}`}),E&&s.jsx("meta",{name:"robots",content:"noindex,nofollow"}),s.jsx("meta",{property:"og:title",content:P}),s.jsx("meta",{property:"og:type",content:"website"})]}),s.jsx("header",{className:"fixed inset-x-0 top-0 z-40 border-b border-white/10 bg-[#0b0f14]/80 backdrop-blur",children:s.jsxs("div",{className:"mx-auto flex max-w-7xl items-center justify-between px-6 py-3.5 md:px-10",children:[s.jsxs("a",{href:typeof window<"u"&&window.location.hostname.startsWith("commercial.")?"/":"/public/commercial",className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.22em] text-white/70 transition-colors hover:text-white",children:[s.jsx("span",{"aria-hidden":!0,children:"←"})," All opportunities"]}),s.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.22em] text-white/45",children:"LevelUp Commercial"})]})}),s.jsxs("section",{className:"relative min-h-[86vh] w-full overflow-hidden",children:[M?s.jsx("img",{src:M,alt:P,className:"absolute inset-0 h-full w-full object-cover"}):s.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#12202b] to-[#0b0f14]"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0b0f14] via-[#0b0f14]/60 to-[#0b0f14]/30"}),s.jsxs("div",{className:"relative mx-auto flex min-h-[86vh] max-w-7xl flex-col justify-end px-6 pb-16 pt-24 md:px-10",children:[s.jsxs("div",{className:"mb-5 flex flex-wrap items-center gap-2.5",children:[s.jsx("span",{className:"rounded-full border border-white/25 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em]",children:Qre[(p==null?void 0:p.deal_type)??"sale"]}),(p==null?void 0:p.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:z_e[p.commercial_type]}),E&&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(hx,{className:"h-3 w-3"})," Confidential offering"]})]}),s.jsx("h1",{className:"max-w-4xl font-serif text-4xl leading-[1.05] tracking-tight md:text-6xl lg:text-7xl",children:P}),s.jsxs("p",{className:"mt-4 flex items-center gap-2 text-sm uppercase tracking-[0.2em] text-white/60",children:[s.jsx(Es,{className:"h-4 w-4"})," ",R]}),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:(p==null?void 0:p.deal_type)==="lease"?"Lease rate":"Asking price"}),s.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:ene(p,f.price)})]}),(p==null?void 0:p.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:U_e(p.cap_rate)})]})]}),s.jsxs("div",{className:"mt-9 flex flex-wrap gap-3",children:[s.jsxs(Bt,{size:"lg",className:"rounded-full px-7",onClick:()=>{var Se;return ee("om_request",((Se=y.find(je=>je.doc_kind==="om"))==null?void 0:Se.id)??null)},children:["Request Offering Memorandum ",s.jsx(Ds,{className:"ml-2 h-4 w-4"})]}),s.jsx(Bt,{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"})]})]})]}),k.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(k.length,4)}, minmax(0, 1fr))`},children:k.map(Se=>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:Se.label}),s.jsx("p",{className:"mt-2 text-2xl font-semibold tabular-nums md:text-3xl",children:Se.value})]},Se.label))})}),Y.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:Y.map((Se,je)=>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(je+1).padStart(2,"0")}),s.jsx("p",{className:"text-lg leading-relaxed text-white/85",children:Se})]},je))})}),(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((Se,je)=>s.jsx("p",{children:Se},je))}),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((Se,je)=>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"})," ",Se]},je))})]})}),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((Se,je)=>s.jsx("button",{onClick:()=>{o(je+1),xw(f.id,"gallery_view",{})},className:`group relative overflow-hidden rounded-xl ${je===0?"md:col-span-2 md:row-span-2":""}`,children:s.jsx("img",{src:Se.photo_url,alt:`${P} — image ${je+2}`,loading:"lazy",className:`w-full object-cover transition-transform duration-700 group-hover:scale-[1.04] ${je===0?"h-full min-h-[280px] md:min-h-[560px]":"h-[180px] md:h-[275px]"}`})},Se.id))})}),((p==null?void 0:p.noi)||(p==null?void 0:p.gross_income)||(p==null?void 0:p.operating_expenses)||(p==null?void 0:p.occupancy_pct)!=null)&&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:sf(p==null?void 0:p.noi)},{l:"Gross income",v:sf(p==null?void 0:p.gross_income)},{l:"Operating expenses",v:sf(p==null?void 0:p.operating_expenses)},{l:"Occupancy",v:(p==null?void 0:p.occupancy_pct)!=null?`${Math.round(Number(p.occupancy_pct))}%`:null},{l:"Price per SF",v:(p==null?void 0:p.price_per_sf)!=null?sf(p.price_per_sf,2):null},{l:"Price per unit",v:sf(p==null?void 0:p.price_per_unit)},{l:"Tenancy",v:p!=null&&p.tenancy?`${p.tenancy[0].toUpperCase()}${p.tenancy.slice(1)} tenant`:null},{l:"Broker co-op",v:(p==null?void 0:p.broker_coop_pct)!=null?`${p.broker_coop_pct}%`:null}].filter(Se=>Se.v).map(Se=>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:Se.l}),s.jsx("p",{className:"mt-2 text-xl font-semibold tabular-nums",children:Se.v})]},Se.l))}),(p==null?void 0:p.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(p.call_for_offers_at).toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"})]})]}),(B.length>0||V.length>0)&&s.jsx(uy,{eyebrow:"Occupancy",title:V.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:V.length?"Suite":"Tenant"}),s.jsx("th",{className:"px-6 py-4",children:"SF"}),s.jsx("th",{className:"px-6 py-4",children:V.length?"Rate":"Rent"}),s.jsx("th",{className:"px-6 py-4",children:V.length?"Availability":"Lease expiry"})]})}),s.jsx("tbody",{className:"divide-y divide-white/5",children:(V.length?V:B).map((Se,je)=>s.jsxs("tr",{className:"text-white/80",children:[s.jsx("td",{className:"px-6 py-4 font-medium text-white",children:Se.suite??Se.name??"—"}),s.jsx("td",{className:"px-6 py-4 tabular-nums",children:Se.sf?XV(Number(Se.sf)):"—"}),s.jsx("td",{className:"px-6 py-4",children:Se.rate??Se.rent??"—"}),s.jsx("td",{className:"px-6 py-4",children:Se.availability??Se.lease_expiry??"—"})]},je))})]})})}),s.jsx(uy,{eyebrow:"Location",title:p!=null&&p.submarket?`${p.submarket} submarket`:R,children:s.jsxs("div",{className:"grid gap-8 lg:grid-cols-[1.2fr_1fr]",children:[D?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(D)}&z=${f.latitude&&f.longitude?15:12}&output=embed`,onLoad:()=>xw(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:E?"Exact location released with the Offering Memorandum.":R}),s.jsxs("div",{className:"space-y-5",children:[(p==null?void 0:p.zoning)&&s.jsx(vw,{label:"Zoning",value:p.zoning}),(p==null?void 0:p.lot_acres)!=null&&s.jsx(vw,{label:"Site size",value:`${p.lot_acres} acres`}),(p==null?void 0:p.parking_spaces)!=null&&s.jsx(vw,{label:"Parking",value:`${p.parking_spaces} spaces`}),(p==null?void 0:p.opportunity_zone)&&s.jsx(vw,{label:"Opportunity Zone",value:"Qualified"}),W.filter(Se=>Se.road||Se.count).map((Se,je)=>s.jsx(vw,{label:`Traffic count — ${Se.road??"Adjacent road"}`,value:`${Se.count??"—"} VPD`},je)),!(p!=null&&p.zoning)&&(p==null?void 0:p.lot_acres)==null&&(p==null?void 0:p.parking_spaces)==null&&!(p!=null&&p.opportunity_zone)&&s.jsx(vw,{label:"Submarket",value:(p==null?void 0:p.submarket)||R})]})]})}),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(([Se,je])=>{const Le=G==null?void 0:G[Se];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:je}),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(([,Ae])=>Ae).map(([Ae,be])=>s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("dt",{className:"text-white/50",children:Ae}),s.jsx("dd",{className:"font-medium tabular-nums",children:be})]},Ae))})]},Se)})})}),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(Se=>{const je=Se.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:je?s.jsx(sc,{className:"h-5 w-5"}):Se.gate_level==="nda"?s.jsx(k9,{className:"h-5 w-5"}):s.jsx(hx,{className:"h-5 w-5"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate font-medium",children:Se.title||lXe[Se.doc_kind||"other"]}),s.jsx("p",{className:"text-xs text-white/45",children:je?"Available to download":Se.gate_level==="nda"?"Confidentiality acknowledgement required":"Registration required"})]}),s.jsx(Bt,{size:"sm",variant:"outline",className:"border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>ee("om_request",Se.id),children:je?"Download":"Request"})]},Se.id)})})}),T&&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:[T.avatar_url&&s.jsx("img",{src:T.avatar_url,alt:T.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:T.name}),s.jsx("p",{className:"text-sm text-white/55",children:((pe=T.brokerage)==null?void 0:pe.name)||T.brokerage_name})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-3",children:[T.email&&s.jsxs(Bt,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{xw(f.id,"contact_click",{}),window.location.href=`mailto:${T.email}`},children:[s.jsx(mi,{className:"mr-2 h-4 w-4"})," Email"]}),T.phone&&s.jsxs(Bt,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{xw(f.id,"contact_click",{}),window.location.href=`tel:${T.phone}`},children:[s.jsx(ri,{className:"mr-2 h-4 w-4"})," Call"]}),s.jsx(Bt,{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:P}),s.jsxs("p",{className:"truncate text-xs text-white/50",children:[ene(p,f.price)," · ",R]})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Bt,{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(Bt,{size:"sm",className:"rounded-full",onClick:()=>{var Se;return ee("om_request",((Se=y.find(je=>je.doc_kind==="om"))==null?void 0:Se.id)??null)},children:"Request OM"})]})]})}),s.jsx(lo,{open:i!==null,onOpenChange:Se=>!Se&&o(null),children:s.jsx(qa,{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(Os,{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(Se=>(Se-1+v.length)%v.length),children:s.jsx(Cm,{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(Se=>(Se+1)%v.length),children:s.jsx(jd,{className:"h-6 w-6"})})]})})}),c&&s.jsx(fXe,{open:!0,onOpenChange:Se=>!Se&&a(null),listingId:f.id,kind:c.kind,documentId:c.documentId,requiresNda:!!(p!=null&&p.requires_nda)||(p==null?void 0:p.om_gate_mode)==="nda",brokerName:T==null?void 0:T.name})]})}function 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 vw({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 rne="/assets/levelup-logo-color-BeKd2k_g.png",gXe={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"},Q$={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"},nne={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},J$=t=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(t),d2=t=>new Intl.NumberFormat("en-US").format(t);function G_e(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 xH({slugOverride:t}={}){var ca,Nr,Vn,Ks,Ea,wo,Zr;const e=Pm(),r=t||e.slugOrId,[n]=Px(),{data:i,isLoading:o}=tXe(r||""),c=rXe(),a=nXe(),f=n.get("ref"),[p,y]=C.useState(""),[v,T]=C.useState(""),[E,k]=C.useState(""),[P,R]=C.useState(""),[D,M]=C.useState(""),[B,V]=C.useState(""),[G,W]=C.useState(""),[Y,J]=C.useState("in_person"),[Q,ee]=C.useState("info"),[le,pe]=C.useState(!1),[Se,je]=C.useState(!1),[Le,Ae]=C.useState(null),[be,me]=C.useState(!1);C.useState(!1);const[Te,Ne]=C.useState(!1),[Ee,we]=C.useState(20),[He,tt]=C.useState(6.5),[at,Et]=C.useState(30),vt=C.useRef(null),[Gt,pt]=C.useState(!1);C.useEffect(()=>{const fn=()=>pt(window.scrollY>300);return window.addEventListener("scroll",fn,{passive:!0}),()=>window.removeEventListener("scroll",fn)},[]),C.useEffect(()=>{f&&a.mutate(f)},[f]),C.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[r]);const Pt=(i==null?void 0:i.photos)||[],tr=Pt.find(fn=>fn.is_primary)||Pt[0],_t=C.useMemo(()=>{if(!(i!=null&&i.price))return 0;const fn=i.price*(1-Ee/100),xn=He/100/12,Xr=at*12;return xn===0?fn/Xr:fn*xn/(1-Math.pow(1+xn,-Xr))},[i==null?void 0:i.price,Ee,He,at]),cr=async()=>{const fn=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:fn})}catch{}else await navigator.clipboard.writeText(fn),Vt.success("Link copied to clipboard")},Tr=async fn=>{if(fn.preventDefault(),!p.trim()||!E.trim()||!i)return;const xn=Q==="showing";if(xn&&!B){Vt.error("Please pick a preferred date for your showing");return}pe(!0);try{await c.mutateAsync({listingId:i.id,agentId:i.agent_id,firstName:p.trim(),lastName:v.trim(),email:E.trim(),phone:P.trim(),shareToken:f,leadType:xn?"showing_request":"info_request",preferredDate:xn?B:null,preferredTime:xn&&G||null,showingMode:xn?Y:null,message:D.trim()||null}),je(!0),Vt.success(xn?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(Xr){console.error("Lead submission error:",Xr),Vt.error(`Failed to submit: ${Xr.message||"Please try again"}`)}finally{pe(!1)}},sn=()=>{Le!==null&&Ae(Le===0?Pt.length-1:Le-1)},ur=()=>{Le!==null&&Ae(Le===Pt.length-1?0:Le+1)};if((i==null?void 0:i.listing_class)==="commercial")return s.jsx(pXe,{slug:r});if(o)return s.jsx("div",{className:"min-h-screen bg-neutral-950",children:s.jsx(ml,{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(Wr,{to:"/public/listings",className:"flex items-center gap-2",children:s.jsx("img",{src:rne,alt:"LevelUp",className:"h-8"})})})}),s.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[s.jsx(va,{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(Bt,{asChild:!0,children:s.jsx(Wr,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const xr=i.property_address?`${i.property_address} — ${i.city}, ${i.state}`:`${i.city}, ${i.state} Home for Sale`,rr=((Nr=(ca=i.agent)==null?void 0:ca.brokerage)==null?void 0:Nr.name)||((Vn=i.agent)==null?void 0:Vn.brokerage_name),vn=((Ks=i.agent)==null?void 0:Ks.name)||"",ct=G_e(i.video_link),jt=rr||vn||"",er=Q$[i.status]==="Sold"?"Just Sold":Q$[i.status],Pr=er?`${er}: ${xr}`:xr,dr=[`${J$(i.price)} · ${i.city}, ${i.state}`,vn?`Presented by ${vn}${rr?`, ${rr}`:""}.`:""].filter(Boolean).join(" · "),ar=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,Nt=i.description||"",gr=Nt.length>420,En=Te||!gr?Nt:Nt.slice(0,420).trimEnd()+"…",ni=i.page_config||{},ii=fn=>{var xn;return(((xn=ni.sections)==null?void 0:xn[fn])??!0)!==!1},Ui=Array.isArray(ni.addons)?ni.addons:[],Ta=ni.custom_note||"",vi=ni.accent_color||null;return s.jsxs(s.Fragment,{children:[s.jsxs(Zo,{children:[s.jsx("title",{children:jt?`${xr} | ${jt}`:xr}),s.jsx("meta",{name:"description",content:`${J$(i.price)} · ${i.bedrooms||""}BD ${i.bathrooms||""}BA ${i.square_footage?i.square_footage.toLocaleString()+" sqft · ":""}${nne[i.property_type]} in ${i.city}, ${i.state}. ${Nt.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:Pr}),s.jsx("meta",{property:"og:description",content:dr}),s.jsx("meta",{property:"og:type",content:"website"}),s.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${i.slug||i.id}`}),tr&&s.jsx("meta",{property:"og:image",content:tr.photo_url}),jt&&s.jsx("meta",{property:"og:site_name",content:jt}),s.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),s.jsx("meta",{name:"twitter:title",content:Pr}),s.jsx("meta",{name:"twitter:description",content:dr}),tr&&s.jsx("meta",{name:"twitter:image",content:tr.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:Nt,url:`https://listings.relevelup.com/${i.slug||i.id}`,datePosted:i.created_at,image:Pt.map(fn=>fn.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(Wr,{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(dx,{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(([fn,xn])=>s.jsx("a",{href:`#${fn}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:xn},fn))}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(RZe,{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:cr,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(SC,{className:"h-4 w-4 text-white"})}),s.jsx(Bt,{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:vt,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[tr?s.jsx("img",{src:tr.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(ss,{className:`${gXe[i.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:Q$[i.status]}),Pt.length>0&&s.jsxs("button",{onClick:()=>Ae(0),className:"flex items-center gap-1.5 text-xs text-white/90 bg-black/40 backdrop-blur border border-white/20 rounded-full px-3 py-1.5 hover:bg-black/60 transition",children:[s.jsx(Dee,{className:"h-3.5 w-3.5"}),Pt.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:J$(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:d2(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(Ml,{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}),rr&&s.jsx("p",{className:"text-xs text-white/60",children:rr})]}),s.jsx(Bt,{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(Ml,{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(Bt,{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"]})]})})]}),ii("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:XS,label:"Bedrooms",value:i.bedrooms},i.bathrooms&&{icon:__,label:"Bathrooms",value:i.bathrooms},i.square_footage&&{icon:C9,label:"Interior",value:`${d2(i.square_footage)} sqft`},i.lot_size&&{icon:QO,label:"Lot Size",value:i.lot_size},i.year_built&&{icon:oo,label:"Year Built",value:i.year_built},!i.year_built&&i.square_footage&&{icon:RU,label:"Price / sqft",value:`$${d2(Math.round(i.price/i.square_footage))}`}].filter(Boolean).slice(0,5).map((fn,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(fn.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:fn.label}),s.jsx("p",{className:"font-display text-2xl text-white font-light",children:fn.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:[ii("story")&&Nt&&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:En})}),gr&&s.jsx("button",{onClick:()=>Ne(!Te),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:Te?"Show less":"Read more"}),s.jsxs("div",{className:"mt-8 flex flex-wrap gap-2",children:[s.jsxs(ss,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[s.jsx(_o,{className:"h-3 w-3 mr-1.5"}),nne[i.property_type]]}),i.has_hoa&&s.jsx(ss,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:"HOA"}),i.mls_link&&s.jsx(Bt,{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(b_,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(Ta||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(xs,{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:['"',Ta||i.agent_notes,'"']})]})]}),ii("gallery")&&Pt.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:()=>Ae(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",Pt.length]})]}),s.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:Pt.slice(0,7).map((fn,xn)=>{const Xr=["col-span-4 sm:col-span-2 sm:row-span-2 aspect-square sm:aspect-auto","col-span-2 sm:col-span-2 aspect-[4/3]","col-span-2 sm:col-span-2 aspect-[4/3]","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square"],ui=xn===6&&Pt.length>7;return s.jsxs("button",{onClick:()=>Ae(xn),className:`${Xr[xn]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[s.jsx("img",{src:fn.photo_url,alt:`Photo ${xn+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),ui&&s.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[s.jsx(Dee,{className:"h-6 w-6 mb-1"}),s.jsxs("span",{className:"font-medium",children:["+",Pt.length-7," more"]})]})]},fn.id)})})]}),ii("video")&&!((Ea=i.video)!=null&&Ea.playback_url)&&ct&&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:ct,className:"absolute inset-0 h-full w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Video Tour"})})]}),ii("video")&&((wo=i.video)==null?void 0:wo.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"})})]}),ii("map")&&ar&&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:ar,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(Es,{className:"h-4 w-4"}),i.property_address?`${i.property_address}, `:"",i.city,", ",i.state]})]}),ii("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:["$",d2(Math.round(_t))]}),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(Mr,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),s.jsxs("span",{className:"text-white font-medium",children:[Ee,"%"]})]}),s.jsx(w1,{value:[Ee],onValueChange:fn=>we(fn[0]),min:0,max:50,step:1}),s.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",d2(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(Mr,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),s.jsxs("span",{className:"text-white font-medium",children:[He.toFixed(2),"%"]})]}),s.jsx(w1,{value:[He],onValueChange:fn=>tt(fn[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(Mr,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),s.jsxs("span",{className:"text-white font-medium",children:[at," yr"]})]}),s.jsx(w1,{value:[at],onValueChange:fn=>Et(fn[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."})]})]}),Ui.map(fn=>{const xn=fn.type,Xr=fn.data||{};if(xn==="extra_video"&&Xr.url){const ui=String(Xr.url).includes("youtu")?`https://www.youtube.com/embed/${String(Xr.url).split(/[/=]/).pop()}`:Xr.url;return s.jsxs("section",{children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:Xr.eyebrow||"Featured Video"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Xr.title||"Watch"}),s.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:s.jsx("iframe",{src:ui,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:Xr.title||"Video"})})]},fn.id)}return xn==="3d_tour"&&Xr.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:Xr.title||"Step inside"}),s.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:s.jsx("iframe",{src:Xr.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},fn.id):xn==="floor_plan"&&Xr.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:Xr.title||"Layout"}),s.jsx("img",{src:Xr.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},fn.id):xn==="testimonial"&&Xr.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:['"',Xr.quote,'"']}),Xr.author&&s.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",Xr.author]})]},fn.id):xn==="custom_cta"&&Xr.label?s.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:vi?`${vi}22`:"rgba(255,255,255,0.05)",border:`1px solid ${vi||"rgba(255,255,255,0.1)"}`},children:[Xr.title&&s.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:Xr.title}),s.jsx(Bt,{asChild:!0,size:"lg",style:vi?{background:vi}:void 0,children:s.jsx("a",{href:Xr.url||"#agent",children:Xr.label})})]},fn.id):null})]}),s.jsxs("aside",{id:"agent",className:"lg:sticky lg:top-24 lg:self-start space-y-6",children:[s.jsx(sXe,{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(Ml,{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}),rr&&s.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:rr})]})]}),s.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[i.agent.phone&&s.jsx(Bt,{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(ri,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),i.agent.email&&s.jsx(Bt,{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(mi,{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(Ml,{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(Bt,{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(ri,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),i.co_agent_email&&s.jsx(Bt,{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(mi,{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(ine,{submitted:Se,activeTab:Q,setActiveTab:ee,firstName:p,setFirstName:y,lastName:v,setLastName:T,email:E,setEmail:k,phone:P,setPhone:R,message:D,setMessage:M,preferredDate:B,setPreferredDate:V,preferredTime:G,setPreferredTime:W,showingMode:Y,setShowingMode:J,isSubmitting:le,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:[((Zr=i.agent)==null?void 0:Zr.phone)&&s.jsx(Bt,{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(ri,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),s.jsxs(Bt,{onClick:()=>me(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[s.jsx(T9,{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:rne,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(lo,{open:Le!==null,onOpenChange:()=>Ae(null),children:s.jsxs(qa,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[s.jsx(xl,{className:"sr-only",children:s.jsx(Xo,{children:"Photo Gallery"})}),s.jsx("button",{onClick:()=>Ae(null),className:"absolute right-4 top-4 z-50 rounded-full bg-white/10 hover:bg-white/20 p-2 text-white",children:s.jsx(Os,{className:"h-5 w-5"})}),Le!==null&&Pt[Le]&&s.jsxs("div",{className:"relative",children:[s.jsx("img",{src:Pt[Le].photo_url,alt:`Photo ${Le+1}`,className:"w-full max-h-[85vh] object-contain"}),Pt.length>1&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:sn,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(Cm,{className:"h-6 w-6"})}),s.jsx("button",{onClick:ur,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(jd,{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," / ",Pt.length]})]})]})]})}),s.jsx(lo,{open:be,onOpenChange:me,children:s.jsxs(qa,{className:"max-w-md p-0 bg-white text-neutral-900",children:[s.jsx(xl,{className:"sr-only",children:s.jsx(Xo,{children:"Contact the agent"})}),s.jsx("div",{className:"p-6",children:s.jsx(ine,{submitted:Se,activeTab:Q,setActiveTab:ee,firstName:p,setFirstName:y,lastName:v,setLastName:T,email:E,setEmail:k,phone:P,setPhone:R,message:D,setMessage:M,preferredDate:B,setPreferredDate:V,preferredTime:G,setPreferredTime:W,showingMode:Y,setShowingMode:J,isSubmitting:le,onSubmit:Tr})})]})})]})]})}function ine(t){const{submitted:e,activeTab:r,setActiveTab:n,firstName:i,setFirstName:o,lastName:c,setLastName:a,email:f,setEmail:p,phone:y,setPhone:v,message:T,setMessage:E,preferredDate:k,setPreferredDate:P,preferredTime:R,setPreferredTime:D,showingMode:M,setShowingMode:B,isSubmitting:V,onSubmit:G}=t;return e?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"h-14 w-14 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:s.jsx(no,{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(dH,{value:r,onValueChange:W=>n(W),children:[s.jsxs(Y3,{className:"grid w-full grid-cols-2 mb-4",children:[s.jsxs(zp,{value:"info",className:"gap-1.5",children:[s.jsx(fh,{className:"h-3.5 w-3.5"})," Get Info"]}),s.jsxs(zp,{value:"showing",className:"gap-1.5",children:[s.jsx(T9,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),s.jsxs("form",{onSubmit:G,className:"space-y-3",children:[s.jsxs(ix,{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(Mr,{htmlFor:"preferredDate",children:"Preferred Date *"}),s.jsx(Br,{id:"preferredDate",type:"date",value:k,onChange:W=>P(W.target.value),min:new Date().toISOString().split("T")[0],required:r==="showing"})]}),s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"preferredTime",children:"Preferred Time"}),s.jsxs(ba,{value:R,onValueChange:D,children:[s.jsx(oa,{id:"preferredTime",children:s.jsx(wa,{placeholder:"Any time"})}),s.jsxs(la,{children:[s.jsx(mn,{value:"morning",children:"Morning (9am–12pm)"}),s.jsx(mn,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),s.jsx(mn,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"showingMode",children:"Tour Type"}),s.jsxs(ba,{value:M,onValueChange:W=>B(W),children:[s.jsx(oa,{id:"showingMode",children:s.jsx(wa,{})}),s.jsxs(la,{children:[s.jsx(mn,{value:"in_person",children:"🏡 In-person showing"}),s.jsx(mn,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),s.jsx(mn,{value:"either",children:"Either works for me"})]})]})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"firstName",children:"First Name *"}),s.jsx(Br,{id:"firstName",value:i,onChange:W=>o(W.target.value),required:!0})]}),s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"lastName",children:"Last Name"}),s.jsx(Br,{id:"lastName",value:c,onChange:W=>a(W.target.value)})]})]}),s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"email",children:"Email *"}),s.jsx(Br,{id:"email",type:"email",value:f,onChange:W=>p(W.target.value),required:!0})]}),s.jsxs("div",{children:[s.jsxs(Mr,{htmlFor:"phone",children:["Phone ",r==="showing"&&"*"]}),s.jsx(Br,{id:"phone",type:"tel",value:y,onChange:W=>v(W.target.value),required:r==="showing"})]}),s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"message",children:r==="showing"?"Anything else?":"Message (optional)"}),s.jsx(Ad,{id:"message",value:T,onChange:W=>E(W.target.value),rows:2})]}),s.jsx(Bt,{type:"submit",disabled:V,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:V?"Sending…":r==="showing"?"Request Showing":"Get More Info"}),s.jsx("p",{className:"text-[11px] text-neutral-500 text-center",children:"The listing agent will contact you directly. No spam."})]})]})]})}const yXe=Object.freeze(Object.defineProperty({__proto__:null,default:xH,toVideoEmbedUrl:G_e},Symbol.toStringTag,{value:"Module"})),sne="/assets/levelup-logo-white-C2RAgAoG.png",xXe="/assets/listings-hero-noir-BHCJrhvU.jpg";var H_e={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(tc,function(){let r,n,i;function o(a,f){if(!r)r=f;else if(!n)n=f;else{const p={};r(p),i=f(p);const y="self.onerror = function() { console.error('An error occurred while parsing the WebWorker bundle. This is most likely due to improper transpilation by Babel; please see https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling'); }; var sharedChunk = {}; ("+r+")(sharedChunk); ("+n+")(undefined, sharedChunk); self.onerror = null;";typeof window<"u"&&window&&window.URL&&window.URL.createObjectURL&&(i.workerUrl=window.URL.createObjectURL(new Blob([y],{type:"text/javascript"})))}}o(["exports"],function(a){var f=1e-6,p=typeof Float32Array<"u"?Float32Array:Array;function y(h,l){var u=l[0],m=l[1],x=l[2],b=l[3],S=u*b-x*m;return S?(h[0]=b*(S=1/S),h[1]=-m*S,h[2]=-x*S,h[3]=u*S,h):null}function v(){var h=new p(9);return p!=Float32Array&&(h[1]=0,h[2]=0,h[3]=0,h[5]=0,h[6]=0,h[7]=0),h[0]=1,h[4]=1,h[8]=1,h}function T(h,l){var u=l[0],m=l[1],x=l[2],b=l[3],S=l[4],A=l[5],N=l[6],O=l[7],$=l[8];return h[0]=S*$-A*O,h[1]=x*O-m*$,h[2]=m*A-x*S,h[3]=A*N-b*$,h[4]=u*$-x*N,h[5]=x*b-u*A,h[6]=b*O-S*N,h[7]=m*N-u*O,h[8]=u*S-m*b,h}function E(h,l,u){var m=l[0],x=l[1],b=l[2],S=l[3],A=l[4],N=l[5],O=l[6],$=l[7],U=l[8],q=u[0],K=u[1],X=u[2],te=u[3],ie=u[4],ae=u[5],he=u[6],ue=u[7],ve=u[8];return h[0]=q*m+K*S+X*O,h[1]=q*x+K*A+X*$,h[2]=q*b+K*N+X*U,h[3]=te*m+ie*S+ae*O,h[4]=te*x+ie*A+ae*$,h[5]=te*b+ie*N+ae*U,h[6]=he*m+ue*S+ve*O,h[7]=he*x+ue*A+ve*$,h[8]=he*b+ue*N+ve*U,h}function k(){var h=new p(16);return p!=Float32Array&&(h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[11]=0,h[12]=0,h[13]=0,h[14]=0),h[0]=1,h[5]=1,h[10]=1,h[15]=1,h}function P(h){var l=new p(16);return l[0]=h[0],l[1]=h[1],l[2]=h[2],l[3]=h[3],l[4]=h[4],l[5]=h[5],l[6]=h[6],l[7]=h[7],l[8]=h[8],l[9]=h[9],l[10]=h[10],l[11]=h[11],l[12]=h[12],l[13]=h[13],l[14]=h[14],l[15]=h[15],l}function R(h){return h[0]=1,h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[5]=1,h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[10]=1,h[11]=0,h[12]=0,h[13]=0,h[14]=0,h[15]=1,h}function D(h,l){var u=l[0],m=l[1],x=l[2],b=l[3],S=l[4],A=l[5],N=l[6],O=l[7],$=l[8],U=l[9],q=l[10],K=l[11],X=l[12],te=l[13],ie=l[14],ae=l[15],he=u*A-m*S,ue=u*N-x*S,ve=u*O-b*S,ke=m*N-x*A,Ie=m*O-b*A,We=x*O-b*N,ze=$*te-U*X,Ge=$*ie-q*X,Ue=$*ae-K*X,Ve=U*ie-q*te,yt=U*ae-K*te,wt=q*ae-K*ie,At=he*wt-ue*yt+ve*Ve+ke*Ue-Ie*Ge+We*ze;return At?(h[0]=(A*wt-N*yt+O*Ve)*(At=1/At),h[1]=(x*yt-m*wt-b*Ve)*At,h[2]=(te*We-ie*Ie+ae*ke)*At,h[3]=(q*Ie-U*We-K*ke)*At,h[4]=(N*Ue-S*wt-O*Ge)*At,h[5]=(u*wt-x*Ue+b*Ge)*At,h[6]=(ie*ve-X*We-ae*ue)*At,h[7]=($*We-q*ve+K*ue)*At,h[8]=(S*yt-A*Ue+O*ze)*At,h[9]=(m*Ue-u*yt-b*ze)*At,h[10]=(X*Ie-te*ve+ae*he)*At,h[11]=(U*ve-$*Ie-K*he)*At,h[12]=(A*Ge-S*Ve-N*ze)*At,h[13]=(u*Ve-m*Ge+x*ze)*At,h[14]=(te*ue-X*ke-ie*he)*At,h[15]=($*ke-U*ue+q*he)*At,h):null}function M(h,l,u){var m=l[0],x=l[1],b=l[2],S=l[3],A=l[4],N=l[5],O=l[6],$=l[7],U=l[8],q=l[9],K=l[10],X=l[11],te=l[12],ie=l[13],ae=l[14],he=l[15],ue=u[0],ve=u[1],ke=u[2],Ie=u[3];return h[0]=ue*m+ve*A+ke*U+Ie*te,h[1]=ue*x+ve*N+ke*q+Ie*ie,h[2]=ue*b+ve*O+ke*K+Ie*ae,h[3]=ue*S+ve*$+ke*X+Ie*he,h[4]=(ue=u[4])*m+(ve=u[5])*A+(ke=u[6])*U+(Ie=u[7])*te,h[5]=ue*x+ve*N+ke*q+Ie*ie,h[6]=ue*b+ve*O+ke*K+Ie*ae,h[7]=ue*S+ve*$+ke*X+Ie*he,h[8]=(ue=u[8])*m+(ve=u[9])*A+(ke=u[10])*U+(Ie=u[11])*te,h[9]=ue*x+ve*N+ke*q+Ie*ie,h[10]=ue*b+ve*O+ke*K+Ie*ae,h[11]=ue*S+ve*$+ke*X+Ie*he,h[12]=(ue=u[12])*m+(ve=u[13])*A+(ke=u[14])*U+(Ie=u[15])*te,h[13]=ue*x+ve*N+ke*q+Ie*ie,h[14]=ue*b+ve*O+ke*K+Ie*ae,h[15]=ue*S+ve*$+ke*X+Ie*he,h}function B(h,l,u){var m,x,b,S,A,N,O,$,U,q,K,X,te=u[0],ie=u[1],ae=u[2];return l===h?(h[12]=l[0]*te+l[4]*ie+l[8]*ae+l[12],h[13]=l[1]*te+l[5]*ie+l[9]*ae+l[13],h[14]=l[2]*te+l[6]*ie+l[10]*ae+l[14],h[15]=l[3]*te+l[7]*ie+l[11]*ae+l[15]):(x=l[1],b=l[2],S=l[3],A=l[4],N=l[5],O=l[6],$=l[7],U=l[8],q=l[9],K=l[10],X=l[11],h[0]=m=l[0],h[1]=x,h[2]=b,h[3]=S,h[4]=A,h[5]=N,h[6]=O,h[7]=$,h[8]=U,h[9]=q,h[10]=K,h[11]=X,h[12]=m*te+A*ie+U*ae+l[12],h[13]=x*te+N*ie+q*ae+l[13],h[14]=b*te+O*ie+K*ae+l[14],h[15]=S*te+$*ie+X*ae+l[15]),h}function V(h,l,u){var m=u[0],x=u[1],b=u[2];return h[0]=l[0]*m,h[1]=l[1]*m,h[2]=l[2]*m,h[3]=l[3]*m,h[4]=l[4]*x,h[5]=l[5]*x,h[6]=l[6]*x,h[7]=l[7]*x,h[8]=l[8]*b,h[9]=l[9]*b,h[10]=l[10]*b,h[11]=l[11]*b,h[12]=l[12],h[13]=l[13],h[14]=l[14],h[15]=l[15],h}function G(h,l,u){var m=Math.sin(u),x=Math.cos(u),b=l[4],S=l[5],A=l[6],N=l[7],O=l[8],$=l[9],U=l[10],q=l[11];return l!==h&&(h[0]=l[0],h[1]=l[1],h[2]=l[2],h[3]=l[3],h[12]=l[12],h[13]=l[13],h[14]=l[14],h[15]=l[15]),h[4]=b*x+O*m,h[5]=S*x+$*m,h[6]=A*x+U*m,h[7]=N*x+q*m,h[8]=O*x-b*m,h[9]=$*x-S*m,h[10]=U*x-A*m,h[11]=q*x-N*m,h}function W(h,l,u){var m=Math.sin(u),x=Math.cos(u),b=l[0],S=l[1],A=l[2],N=l[3],O=l[8],$=l[9],U=l[10],q=l[11];return l!==h&&(h[4]=l[4],h[5]=l[5],h[6]=l[6],h[7]=l[7],h[12]=l[12],h[13]=l[13],h[14]=l[14],h[15]=l[15]),h[0]=b*x-O*m,h[1]=S*x-$*m,h[2]=A*x-U*m,h[3]=N*x-q*m,h[8]=b*m+O*x,h[9]=S*m+$*x,h[10]=A*m+U*x,h[11]=N*m+q*x,h}function Y(h,l,u){var m=Math.sin(u),x=Math.cos(u),b=l[0],S=l[1],A=l[2],N=l[3],O=l[4],$=l[5],U=l[6],q=l[7];return l!==h&&(h[8]=l[8],h[9]=l[9],h[10]=l[10],h[11]=l[11],h[12]=l[12],h[13]=l[13],h[14]=l[14],h[15]=l[15]),h[0]=b*x+O*m,h[1]=S*x+$*m,h[2]=A*x+U*m,h[3]=N*x+q*m,h[4]=O*x-b*m,h[5]=$*x-S*m,h[6]=U*x-A*m,h[7]=q*x-N*m,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 m,x,b,S=u[0],A=u[1],N=u[2],O=Math.sqrt(S*S+A*A+N*N);return O0&&(b=1/Math.sqrt(b)),h[0]=l[0]*b,h[1]=l[1]*b,h[2]=l[2]*b,h}function Pt(h,l){return h[0]*l[0]+h[1]*l[1]+h[2]*l[2]}function tr(h,l,u){var m=l[0],x=l[1],b=l[2],S=u[0],A=u[1],N=u[2];return h[0]=x*N-b*A,h[1]=b*S-m*N,h[2]=m*A-x*S,h}function _t(h,l,u,m){var x=l[0],b=l[1],S=l[2];return h[0]=x+m*(u[0]-x),h[1]=b+m*(u[1]-b),h[2]=S+m*(u[2]-S),h}function cr(h,l,u){var m=l[0],x=l[1],b=l[2],S=u[3]*m+u[7]*x+u[11]*b+u[15];return h[0]=(u[0]*m+u[4]*x+u[8]*b+u[12])/(S=S||1),h[1]=(u[1]*m+u[5]*x+u[9]*b+u[13])/S,h[2]=(u[2]*m+u[6]*x+u[10]*b+u[14])/S,h}function Tr(h,l,u){var m=l[0],x=l[1],b=l[2];return h[0]=m*u[0]+x*u[3]+b*u[6],h[1]=m*u[1]+x*u[4]+b*u[7],h[2]=m*u[2]+x*u[5]+b*u[8],h}function sn(h,l,u){var m=u[0],x=u[1],b=u[2],S=u[3],A=l[0],N=l[1],O=l[2],$=x*O-b*N,U=b*A-m*O,q=m*N-x*A;return h[0]=A+S*($+=$)+x*(q+=q)-b*(U+=U),h[1]=N+S*U+b*$-m*q,h[2]=O+S*q+m*U-x*$,h}function ur(h){return h[0]=0,h[1]=0,h[2]=0,h}function xr(h,l){return h[0]===l[0]&&h[1]===l[1]&&h[2]===l[2]}var rr=Te,vn=Ne,ct=Le;function jt(){var h=new p(4);return p!=Float32Array&&(h[0]=0,h[1]=0,h[2]=0,h[3]=0),h}function er(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 Pr(h,l){var u=l[0],m=l[1],x=l[2],b=l[3],S=u*u+m*m+x*x+b*b;return S>0&&(S=1/Math.sqrt(S)),h[0]=u*S,h[1]=m*S,h[2]=x*S,h[3]=b*S,h}function dr(h,l){return h[0]*l[0]+h[1]*l[1]+h[2]*l[2]+h[3]*l[3]}function ar(h,l,u){var m=l[0],x=l[1],b=l[2],S=l[3];return h[0]=u[0]*m+u[4]*x+u[8]*b+u[12]*S,h[1]=u[1]*m+u[5]*x+u[9]*b+u[13]*S,h[2]=u[2]*m+u[6]*x+u[10]*b+u[14]*S,h[3]=u[3]*m+u[7]*x+u[11]*b+u[15]*S,h}function Nt(){var h=new p(4);return p!=Float32Array&&(h[0]=0,h[1]=0,h[2]=0),h[3]=1,h}function gr(h){return h[0]=0,h[1]=0,h[2]=0,h[3]=1,h}function En(h,l,u){u*=.5;var m=l[0],x=l[1],b=l[2],S=l[3],A=Math.sin(u),N=Math.cos(u);return h[0]=m*N+S*A,h[1]=x*N+b*A,h[2]=b*N-x*A,h[3]=S*N-m*A,h}function ni(h,l,u){u*=.5;var m=l[0],x=l[1],b=l[2],S=l[3],A=Math.sin(u),N=Math.cos(u);return h[0]=m*N-b*A,h[1]=x*N+S*A,h[2]=b*N+m*A,h[3]=S*N-x*A,h}Se(),jt();var ii,Ui,Ta,vi=Pr,ca=(ii=Se(),Ui=Ae(1,0,0),Ta=Ae(0,1,0),function(h,l,u){var m=Pt(l,u);return m<-.999999?(tr(ii,Ui,l),ct(ii)<1e-6&&tr(ii,Ta,l),pt(ii,ii),function(x,b,S){S*=.5;var A=Math.sin(S);x[0]=A*b[0],x[1]=A*b[1],x[2]=A*b[2],x[3]=Math.cos(S)}(h,ii,Math.PI),h):m>.999999?(h[0]=0,h[1]=0,h[2]=0,h[3]=1,h):(tr(ii,l,u),h[0]=ii[0],h[1]=ii[1],h[2]=ii[2],h[3]=1+m,vi(h,h))});function Nr(){var h=new p(2);return p!=Float32Array&&(h[0]=0,h[1]=0),h}function Vn(h,l){var u=new p(2);return u[0]=h,u[1]=l,u}function Ks(h,l,u){return h[0]=l,h[1]=u,h}function Ea(h,l,u){return h[0]=l[0]+u[0],h[1]=l[1]+u[1],h}function wo(h,l,u){return h[0]=l[0]-u[0],h[1]=l[1]-u[1],h}function Zr(h,l,u){return h[0]=l[0]*u,h[1]=l[1]*u,h}function fn(h){var l=h[0],u=h[1];return Math.sqrt(l*l+u*u)}function xn(h,l){var u=l[0],m=l[1],x=u*u+m*m;return x>0&&(x=1/Math.sqrt(x)),h[0]=l[0]*x,h[1]=l[1]*x,h}function Xr(h,l){return h[0]*l[0]+h[1]*l[1]}Nt(),Nt(),v();var ui,en,Fn=wo;function ts(h){return h&&h.__esModule&&Object.prototype.hasOwnProperty.call(h,"default")?h.default:h}Nr();var bl=function(){if(en)return ui;function h(l,u,m,x){this.cx=3*l,this.bx=3*(m-l)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*u,this.by=3*(x-u)-this.cy,this.ay=1-this.cy-this.by,this.p1x=l,this.p1y=u,this.p2x=m,this.p2y=x}return en=1,ui=h,h.prototype={sampleCurveX:function(l){return((this.ax*l+this.bx)*l+this.cx)*l},sampleCurveY:function(l){return((this.ay*l+this.by)*l+this.cy)*l},sampleCurveDerivativeX:function(l){return(3*this.ax*l+2*this.bx)*l+this.cx},solveCurveX:function(l,u){if(u===void 0&&(u=1e-6),l<0)return 0;if(l>1)return 1;for(var m=l,x=0;x<8;x++){var b=this.sampleCurveX(m)-l;if(Math.abs(b)b?A=m:N=m,m=.5*(N-A)+A;return m},solve:function(l,u){return this.sampleCurveY(this.solveCurveX(l,u))}},ui}(),Jo=ts(bl);function Ot(h,l){this.x=h,this.y=l}function Mo(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 ut(h,l,u,m){const x=new Jo(h,l,u,m);return function(b){return x.solve(b)}}const de=ut(.25,.1,.25,1);function fe(h,l,u){return Math.min(u,Math.max(l,h))}function Oe(h,l,u){return(u=fe((u-h)/(l-h),0,1))*u*(3-2*u)}function Ye(h,l,u){const m=u-l,x=((h-l)%m+m)%m+l;return x===l?u:x}function Je(h,l,u){if(!h.length)return u(null,[]);let m=h.length;const x=new Array(h.length);let b=null;h.forEach((S,A)=>{l(S,(N,O)=>{N&&(b=N),x[A]=O,--m===0&&u(b,x)})})}let rt=1;function dt(){return rt++}function it(h){return h<=1?1:Math.pow(2,Math.ceil(Math.log2(h)))}function ht(h,l){h.forEach(u=>{l[u]&&(l[u]=l[u].bind(l))})}function zt(h,l,u){const m={};for(const x in h)m[x]=l.call(this,h[x],x,h);return m}function Rt(h,l,u){const m={};for(const x in h)l.call(this,h[x],x,h)&&(m[x]=h[x]);return m}function hr(h){return Array.isArray(h)?h.map(hr):typeof h=="object"&&h?zt(h,hr):h}function Fr(h,l){for(let u=0;u=0)return!0;return!1}const qr={};function $r(h){qr[h]||(typeof console<"u"&&console.warn(h),qr[h]=!0)}function on(h,l,u){return(u.y-h.y)*(l.x-h.x)>(l.y-h.y)*(u.x-h.x)}function Cn(h){let l=0;for(let u,m,x=0,b=h.length,S=b-1;x@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(u,m,x,b)=>{const S=x||b;return l[m]=!S||S.toLowerCase(),""}),l["max-age"]){const u=parseInt(l["max-age"],10);isNaN(u)?delete l["max-age"]:l["max-age"]=u}return l}let ks,gs=null;function bi(h,l){return[h[4*l],h[4*l+1],h[4*l+2],h[4*l+3]]}function as(h,l,u,m){for(;l>1;h[x]>1;h[x]<=m?l=x+1:u=x}return l}function Mi(h){return h>0?1/(1.001-h):1+h}function os(h){return h>0?1-1/(1.001-h):-h}function ys(h,l,u){return(h-l.min)*(u.max-u.min)/(l.max-l.min)+u.min}const Mn={API_URL:"https://api.mapbox.com",get API_URL_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/|\?|$)/i},get API_TILEJSON_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/v[0-9]*\/.*\.json.*$)/i},get API_SPRITE_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*\/sprite.*\..*$)/i},get API_FONTS_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/fonts\/v[0-9]*\/)(.*\.pbf.*$)/i},get API_STYLE_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*$)/i},get API_CDN_URL_REGEX(){return/^((https?:)?\/\/)?api\.mapbox\.c(n|om)(\/mapbox-gl-js\/)(.*$)/i},get EVENTS_URL(){if(!Mn.API_URL)return null;try{const h=new URL(Mn.API_URL);return h.hostname==="api.mapbox.cn"?"https://events.mapbox.cn/events/v2":h.hostname==="api.mapbox.com"?"https://events.mapbox.com/events/v2":null}catch{return null}},SESSION_PATH:"/map-sessions/v1",FEEDBACK_URL:"https://apps.mapbox.com/feedback",TILE_URL_VERSION:"v4",RASTER_URL_PREFIX:"raster/v1",RASTERARRAYS_URL_PREFIX:"rasterarrays/v1",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null,DEFAULT_STYLE:"mapbox://styles/mapbox/standard",MAX_PARALLEL_IMAGE_REQUESTS:16,DRACO_URL:"/mapbox-gl-js/draco_decoder_gltf_v1.5.6.wasm",MESHOPT_URL:"/mapbox-gl-js/meshopt_base_v0.20.wasm",MESHOPT_SIMD_URL:"/mapbox-gl-js/meshopt_simd_v0.20.wasm",BUILDING_GEN_URL:"/mapbox-gl-js/building-gen/building_gen_v1.2.4.wasm",GLYPHS_URL:"mapbox://fonts/mapbox/{fontstack}/{range}.pbf",TILES3D_URL_PREFIX:"3dtiles/v1",TILE_PROVIDER_URLS:Object.assign(Object.create(null),{pmtiles:"/mapbox-gl-js/mapbox-gl-pmtiles-provider-v0.0.1.js"})};function ja(){return new URL(Mn.DRACO_URL,Mn.API_URL).href}function So(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(ks===void 0){if(typeof WebAssembly!="object")return!1;const h=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]);ks=WebAssembly.validate(h)}return ks}()?Mn.MESHOPT_SIMD_URL:Mn.MESHOPT_URL,Mn.API_URL).href}function mo(){return new URL(Mn.BUILDING_GEN_URL,Mn.API_URL).href}function cc(h){return Mn.API_URL_REGEX.test(h)}function uc(h){return Mn.API_SPRITE_REGEX.test(h)}let kd,wl,dc,Cd,kc,Nd;function hu(){return kd==null&&(kd=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),kd}const $l={now:()=>Cd!==void 0?Cd:performance.now(),setNow(h){Cd=h},restoreNow(){Cd=void 0},frame(h){const l=requestAnimationFrame(h);return{cancel:()=>cancelAnimationFrame(l)}},getImageData(h,l=0){const{width:u,height:m}=h;kc||(kc=document.createElement("canvas"));const x=kc.getContext("2d",{willReadFrequently:!0});if(!x)throw new Error("failed to create canvas 2d context");return(u>kc.width||m>kc.height)&&(kc.width=u,kc.height=m),x.clearRect(-l,-l,u+2*l,m+2*l),x.drawImage(h,0,0,u,m),x.getImageData(-l,-l,u+2*l,m+2*l)},resolveURL:h=>(wl||(wl=document.createElement("a")),wl.href=h,wl.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(dc==null&&(dc=window.matchMedia("(prefers-reduced-motion: reduce)")),dc.matches)},hasCanvasFingerprintNoise(){if(Nd!==void 0)return Nd;if(!hu())return Nd=!1,!1;const h=new OffscreenCanvas(85,1),l=h.getContext("2d",{willReadFrequently:!0});let u=0;for(let x=0;x0?`?${b}`:""}`}const Fm="mapbox-tiles";let I_=500,P_=50;const MT=["language","worldview","jobid"];let Id;function fN(){try{return caches}catch{}}function R_(){const h=fN();h&&Id==null&&(Id=h.open(Fm))}let OT=1/0;const L_={supported:!1,testSupport:function(h){!FT&&_g&&(fu?bg(h):Bm=h)}};let Bm,_g,FT=!1,fu=!1;const BT=typeof self<"u"?self:{};function bg(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,_g),h.isContextLost())return;L_.supported=!0}catch{}h.deleteTexture(l),FT=!0}BT.document&&(_g=BT.document.createElement("img"),_g.onload=function(){Bm&&bg(Bm),Bm=null,fu=!0},_g.onerror=function(){FT=!0,Bm=null},_g.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const Zx={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(Zx);class $T extends Error{constructor(l,u,m){u===401&&cc(m)&&(l+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(l),this.status=u,this.url=m}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function zT(h){return typeof h=="object"&&h!==null&&"status"in h&&h.status===404}const Jn=Di()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,wg=function(h,l){return/^file:/.test(u=h.url)||/^file:/.test(Jn())&&!/^\w+:/.test(u)?function(m,x){const b=new XMLHttpRequest;b.open(m.method||"GET",m.url,!0),m.type==="arrayBuffer"&&(b.responseType="arraybuffer");for(const S in m.headers)b.setRequestHeader(S,m.headers[S]);return m.type==="json"&&(b.responseType="text",b.setRequestHeader("Accept","application/json")),b.withCredentials=m.credentials==="include",b.onerror=()=>{x(new Error(b.statusText))},b.onload=()=>{if((b.status>=200&&b.status<300||b.status===0)&&b.response!==null){let S=b.response;if(m.type==="json")try{S=JSON.parse(b.response)}catch(N){return x(N)}const A=new Headers;b.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(N=>{const O=N.split(": "),$=O.shift(),U=O.join(": ");A.append($,U)}),x(null,S,A)}else x(new $T(b.statusText,b.status,m.url))},b.send(m.body),{cancel:()=>b.abort()}}(h,l):function(m,x){const b=new AbortController,S=new Request(m.url,{method:m.method||"GET",body:m.body,credentials:m.credentials,headers:m.headers,referrer:Jn(),referrerPolicy:m.referrerPolicy,signal:b.signal});let A=!1,N=!1;const O=($=S.url).indexOf("sku=")>0&&cc($);var $;m.type==="json"&&S.headers.set("Accept","application/json");const U=(K,X,te)=>{if(N)return;if(K&&K.message!=="SecurityError"&&$r(K.toString()),X&&te)return q(X);const ie=Date.now();fetch(S).then(ae=>{if(ae.ok){const he=O?ae.clone():null;return q(ae,he,ie)}return x(new $T(ae.statusText,ae.status,m.url))}).catch(ae=>{ae.name!=="AbortError"&&x(new Error(`${ae.message} ${m.url}`))})},q=(K,X,te)=>{(m.type==="arrayBuffer"?K.arrayBuffer():m.type==="json"?K.json():K.text()).then(ie=>{N||(X&&te&&function(ae,he,ue){if(R_(),Id==null)return;const ve=Fs(he.headers.get("cache-control")||"");if(ve["no-store"])return;const ke={status:he.status,statusText:he.statusText,headers:new Headers};he.headers.forEach((Ue,Ve)=>ke.headers.set(Ve,Ue)),ve["max-age"]&&ke.headers.set("Expires",new Date(ue+1e3*ve["max-age"]).toUTCString());const Ie=ke.headers.get("expires");if(!Ie||new Date(Ie).getTime()-ue<42e4)return;let We=DT(ae.url,{persistentParams:MT});if(he.status===206){const Ue=ae.headers.get("Range");if(!Ue)return;ke.status=200,We=Yx(We,{range:Ue})}const ze=new Response((Ge=he.status)!==200&&Ge!==404&&[101,103,204,205,304].includes(Ge)?null:he.body,ke);var Ge;R_(),Id!=null&&Id.then(Ue=>Ue.put(We,ze)).catch(Ue=>$r(Ue.message))}(S,X,te),A=!0,x(null,ie,K.headers))}).catch(ie=>{N||x(new Error(ie.message))})};return O?function(K,X){if(R_(),Id==null)return X(null);Id.then(te=>{let ie=DT(K.url,{persistentParams:MT});const ae=K.headers.get("Range");ae&&(ie=Yx(ie,{range:ae})),te.match(ie).then(he=>{const ue=function(ve){if(!ve)return!1;const ke=new Date(ve.headers.get("expires")||0),Ie=Fs(ve.headers.get("cache-control")||"");return Number(ke)>Date.now()&&!Ie["no-cache"]}(he);te.delete(ie).catch(X),ue&&te.put(ie,he.clone()).catch(X),X(null,he,ue)}).catch(X)}).catch(X)}(S,U):U(null,null),{cancel:()=>{N=!0,A||b.abort()}}}(h,l);var u},Sg=function(h,l){return wg(Object.assign(h,{type:"arrayBuffer"}),l)};function w5(h){const l=document.createElement("a");return l.href=h,l.protocol===location.protocol&&l.host===location.host}let D_,bf;D_=[],bf=0;const Tg=function(h,l){if(L_.supported&&(h.headers||(h.headers={}),h.headers.accept="image/webp,*/*"),bf>=Mn.MAX_PARALLEL_IMAGE_REQUESTS){const b={requestParameters:h,callback:l,cancelled:!1,cancel(){this.cancelled=!0}};return D_.push(b),b}bf++;let u=!1;const m=()=>{if(!u)for(u=!0,bf--;D_.length&&bf{m(),b?l(b):S&&function(N,O){const $=new Blob([new Uint8Array(N)],{type:"image/png"});createImageBitmap($).then(U=>{O(null,U)}).catch(U=>{O(new Error(`Could not load image because of ${U.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(S,(N,O)=>l(N,O,A))});return{cancel:()=>{x.cancel(),m()}}};var Xx,M_,mN,$m={exports:{}},pN={exports:{}},UT={exports:{}},S5=function(){if(mN)return $m.exports;mN=1;var h=(Xx||(Xx=1,pN.exports=function(u,m){var x,b,S,A,N,O,$,U;for(b=u.length-(x=3&u.length),S=m,N=3432918353,O=461845907,U=0;U>>16)*N&65535)<<16)&4294967295)<<15|$>>>17))*O+((($>>>16)*O&65535)<<16)&4294967295)<<13|S>>>19))+((5*(S>>>16)&65535)<<16)&4294967295))+(((A>>>16)+58964&65535)<<16);switch($=0,x){case 3:$^=(255&u.charCodeAt(U+2))<<16;case 2:$^=(255&u.charCodeAt(U+1))<<8;case 1:S^=$=(65535&($=($=(65535&($^=255&u.charCodeAt(U)))*N+((($>>>16)*N&65535)<<16)&4294967295)<<15|$>>>17))*O+((($>>>16)*O&65535)<<16)&4294967295}return S^=u.length,S=2246822507*(65535&(S^=S>>>16))+((2246822507*(S>>>16)&65535)<<16)&4294967295,S=3266489909*(65535&(S^=S>>>13))+((3266489909*(S>>>16)&65535)<<16)&4294967295,(S^=S>>>16)>>>0}),pN.exports),l=(M_||(M_=1,UT.exports=function(u,m){for(var x,b=u.length,S=m^b,A=0;b>=4;)x=1540483477*(65535&(x=255&u.charCodeAt(A)|(255&u.charCodeAt(++A))<<8|(255&u.charCodeAt(++A))<<16|(255&u.charCodeAt(++A))<<24))+((1540483477*(x>>>16)&65535)<<16),S=1540483477*(65535&S)+((1540483477*(S>>>16)&65535)<<16)^(x=1540483477*(65535&(x^=x>>>24))+((1540483477*(x>>>16)&65535)<<16)),b-=4,++A;switch(b){case 3:S^=(255&u.charCodeAt(A+2))<<16;case 2:S^=(255&u.charCodeAt(A+1))<<8;case 1:S=1540483477*(65535&(S^=255&u.charCodeAt(A)))+((1540483477*(S>>>16)&65535)<<16)}return S=1540483477*(65535&(S^=S>>>13))+((1540483477*(S>>>16)&65535)<<16),(S^=S>>>15)>>>0}),UT.exports);return $m.exports=h,$m.exports.murmur3=h,$m.exports.murmur2=l,$m.exports}(),wf=ts(S5);class Uu{constructor(l,...u){Object.assign(this,u[0]||{}),this.type=l}}class Eg extends Uu{constructor(l,u={}){super("error",Object.assign({error:l},u))}}function mu(h,l,u){u[h]&&u[h].indexOf(l)!==-1||(u[h]=u[h]||[],u[h].push(l))}function O_(h,l,u){if(u&&u[h]){const m=u[h].indexOf(l);m!==-1&&u[h].splice(m,1)}}class Qx{on(l,u){return this._listeners=this._listeners||{},mu(l,u,this._listeners),this}off(l,u){return O_(l,u,this._listeners),O_(l,u,this._oneTimeListeners),this}once(l,u){return u?(this._oneTimeListeners=this._oneTimeListeners||{},mu(l,u,this._oneTimeListeners),this):new Promise(m=>{this.once(l,m)})}fire(l,u){const m=typeof l=="string"?new Uu(l,u):l,x=m.type;if(this.listens(x)){m.target=this;const b=this._listeners&&this._listeners[x]?this._listeners[x].slice():[];for(const N of b)N.call(this,m);const S=this._oneTimeListeners&&this._oneTimeListeners[x]?this._oneTimeListeners[x].slice():[];for(const N of S)O_(x,N,this._oneTimeListeners),N.call(this,m);const A=this._eventedParent;if(A){const N=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(m,N),A.fire(m)}}else m instanceof Eg&&console.error(m.error);return this}listens(l){return!!(this._listeners&&this._listeners[l]&&this._listeners[l].length>0||this._oneTimeListeners&&this._oneTimeListeners[l]&&this._oneTimeListeners[l].length>0||this._eventedParent&&this._eventedParent.listens(l))}setEventedParent(l,u){return this._eventedParent=l,this._eventedParentData=u,this}}class hc{constructor(l){typeof l=="string"?this.name=l:(this.name=l.name,this.iconsetId=l.iconsetId)}static from(l){return new hc(l)}static toString(l){return l.iconsetId?`${l.name}${l.iconsetId}`:l.name}static parse(l){const[u,m]=l.split("");return new hc({name:u,iconsetId:m})}static isEqual(l,u){return l.name===u.name&&l.iconsetId===u.iconsetId}toString(){return hc.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var VT,F_={},qT=function(){if(VT)return F_;VT=1;var h={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function l(b){return(b=Math.round(b))<0?0:b>255?255:b}function u(b){return l(b[b.length-1]==="%"?parseFloat(b)/100*255:parseInt(b))}function m(b){return(S=b[b.length-1]==="%"?parseFloat(b)/100:parseFloat(b))<0?0:S>1?1:S;var S}function x(b,S,A){return A<0?A+=1:A>1&&(A-=1),6*A<1?b+(S-b)*A*6:2*A<1?S:3*A<2?b+(S-b)*(2/3-A)*6:b}try{F_.parseCSSColor=function(b){var S,A=b.replace(/ /g,"").toLowerCase();if(A in h)return h[A].slice();if(A[0]==="#")return A.length===4?(S=parseInt(A.substr(1),16))>=0&&S<=4095?[(3840&S)>>4|(3840&S)>>8,240&S|(240&S)>>4,15&S|(15&S)<<4,1]:null:A.length===7&&(S=parseInt(A.substr(1),16))>=0&&S<=16777215?[(16711680&S)>>16,(65280&S)>>8,255&S,1]:null;var N=A.indexOf("("),O=A.indexOf(")");if(N!==-1&&O+1===A.length){var $=A.substr(0,N),U=A.substr(N+1,O-(N+1)).split(","),q=1;switch($){case"rgba":if(U.length!==4)return null;q=m(U.pop());case"rgb":return U.length!==3?null:[u(U[0]),u(U[1]),u(U[2]),q];case"hsla":if(U.length!==4)return null;q=m(U.pop());case"hsl":if(U.length!==3)return null;var K=(parseFloat(U[0])%360+360)%360/360,X=m(U[1]),te=m(U[2]),ie=te<=.5?te*(X+1):te+X-te*X,ae=2*te-ie;return[l(255*x(ae,ie,K+1/3)),l(255*x(ae,ie,K)),l(255*x(ae,ie,K-1/3)),q];default:return null}}return null}}catch{}return F_}();class Xn{constructor(l,u,m,x=1){this.r=l,this.g=u,this.b=m,this.a=x}static parse(l){if(!l)return;if(l instanceof Xn)return l;if(typeof l!="string")return;const u=qT.parseCSSColor(l);return u?new Xn(u[0]/255,u[1]/255,u[2]/255,u[3]):void 0}toString(){const[l,u,m,x]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*l)},${Math.round(255*u)},${Math.round(255*m)},${x})`}toNonPremultipliedRenderColor(l){const{r:u,g:m,b:x,a:b}=this;return new B_(l,u,m,x,b)}toPremultipliedRenderColor(l){const{r:u,g:m,b:x,a:b}=this;return new jg(l,u*b,m*b,x*b,b)}clone(){return new Xn(this.r,this.g,this.b,this.a)}}class GT{constructor(l,u,m,x,b,S=!1){if(this.premultiplied=!1,this.premultiplied=S,l){const A=l.image.height,N=A*A;this.premultiplied?(u=b===0?0:u/b*(A-1),m=b===0?0:m/b*(A-1),x=b===0?0:x/b*(A-1)):(u*=A-1,m*=A-1,x*=A-1),u=Math.max(0,Math.min(A-1,u)),m=Math.max(0,Math.min(A-1,m)),x=Math.max(0,Math.min(A-1,x));const O=Math.floor(u),$=Math.floor(m),U=Math.floor(x),q=Math.ceil(u),K=Math.ceil(m),X=Math.ceil(x),te=u-O,ie=m-$,ae=x-U,he=l.image.data,ue=4*(O+$*N+U*A),ve=4*(O+$*N+X*A),ke=4*(O+K*N+U*A),Ie=4*(O+K*N+X*A),We=4*(q+$*N+U*A),ze=4*(q+$*N+X*A),Ge=4*(q+K*N+U*A),Ue=4*(q+K*N+X*A);this.r=Qr(Qr(Qr(he[ue],he[ve],ae),Qr(he[ke],he[Ie],ae),ie),Qr(Qr(he[We],he[ze],ae),Qr(he[Ge],he[Ue],ae),ie),te)/255*(this.premultiplied?b:1),this.g=Qr(Qr(Qr(he[ue+1],he[ve+1],ae),Qr(he[ke+1],he[Ie+1],ae),ie),Qr(Qr(he[We+1],he[ze+1],ae),Qr(he[Ge+1],he[Ue+1],ae),ie),te)/255*(this.premultiplied?b:1),this.b=Qr(Qr(Qr(he[ue+2],he[ve+2],ae),Qr(he[ke+2],he[Ie+2],ae),ie),Qr(Qr(he[We+2],he[ze+2],ae),Qr(he[Ge+2],he[Ue+2],ae),ie),te)/255*(this.premultiplied?b:1),this.a=b}else this.r=u,this.g=m,this.b=x,this.a=b}toArray(){const{r:l,g:u,b:m,a:x}=this;return[255*l,255*u,255*m,x]}toHslaArray(){let{r:l,g:u,b:m,a:x}=this;if(this.premultiplied){if(x===0)return[0,0,0,0];const X=1/x;l*=X,u*=X,m*=X}const b=Math.min(Math.max(l,0),1),S=Math.min(Math.max(u,0),1),A=Math.min(Math.max(m,0),1),N=Math.min(b,S,A),O=Math.max(b,S,A),$=O-N,U=.5*(N+O);if($===0)return[0,0,100*U,x];const q=U>.5?$/(2-O-N):$/(O+N);let K;switch(O){case b:K=60*((S-A)/$+(SQr(m,l[x],u))}Xn.black=new Xn(0,0,0,1),Xn.white=new Xn(1,1,1,1),Xn.transparent=new Xn(0,0,0,0),Xn.red=new Xn(1,0,0,1),Xn.blue=new Xn(0,0,1,1);var $_=Object.freeze({__proto__:null,array:Vu,color:function(h,l,u){return new Xn(Qr(h.r,l.r,u),Qr(h.g,l.g,u),Qr(h.b,l.b,u),Qr(h.a,l.a,u))},number:Qr});class pu extends Error{constructor(l,u){super(u),this.message=u,this.key=l}}class zm{constructor(l,u=[]){this.parent=l,this.bindings={};for(const[m,x]of u)this.bindings[m]=x}concat(l){return new zm(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 bh={kind:"null"},Dr={kind:"number"},di={kind:"string"},pi={kind:"boolean"},Sl={kind:"color"},Sf={kind:"object"},gi={kind:"value"},Um={kind:"collator"},Jx={kind:"formatted"},e0={kind:"resolvedImage"};function el(h,l){return{kind:"array",itemType:h,N:l}}function da(h){if(h.kind==="array"){const l=da(h.itemType);return typeof h.N=="number"?`array<${l}, ${h.N}>`:h.itemType.kind==="value"?"array":`array<${l}>`}return h.kind}const T5=[bh,Dr,di,pi,Sl,Jx,Sf,el(gi),e0];function t0(h,l){if(l.kind==="error")return null;if(h.kind==="array"){if(l.kind==="array"&&(l.N===0&&l.itemType.kind==="value"||!t0(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 T5)if(!t0(u,l))return null}}return`Expected ${da(h)} but found ${da(l)} instead.`}function HT(h,l){return l.some(u=>u.kind===h.kind)}function Ag(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 wh(h,l){return h.kind==="array"&&l.kind==="array"?h.N===l.N&&wh(h.itemType,l.itemType):h.kind===l.kind}class WT{constructor(l,u,m){this.sensitivity=l?u?"variant":"case":u?"accent":"base",this.locale=m,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(l,u){return this.collator.compare(l,u)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class r0{constructor(l,u,m,x,b){this.text=l.normalize?l.normalize():l,this.image=u,this.scale=m,this.fontStack=x,this.textColor=b}}class Oo{constructor(l){this.sections=l}static fromString(l){return new Oo([new r0(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 Oo?l:Oo.fromString(l)}toString(){return this.sections.length===0?"":this.sections.map(l=>l.text).join("")}serialize(){const l=["format"];for(const u of this.sections){if(u.image){const x=u.image.getPrimary().id.toString();l.push(["image",x]);continue}l.push(u.text);const m={};u.fontStack&&(m["text-font"]=["literal",u.fontStack.split(",")]),u.scale&&(m["font-scale"]=u.scale),u.textColor&&(m["text-color"]=["rgba"].concat(u.textColor.toNonPremultipliedRenderColor(null).toArray())),l.push(m)}return l}}class gu{constructor(l,u={}){this.id=hc.from(l),this.params=u.params,this.sx=u.sx||1,this.sy=u.sy||1}toString(){return JSON.stringify(this)}static parse(l){let u,m,x,b;try{({id:u,params:m,sx:x,sy:b}=JSON.parse(l)||{})}catch{return null}return u?new gu(u,{params:m,sx:x,sy:b}):null}scaleSelf(l,u=l){return this.sx*=l,this.sy*=u,this}}class zl{constructor(l,u,m,x,b=!1){this.primaryId=hc.from(l),this.primaryOptions=u,m&&(this.secondaryId=hc.from(m)),this.secondaryOptions=x,this.available=b}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new gu(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new gu(this.secondaryId,this.secondaryOptions):null}static from(l){return typeof l=="string"?zl.build({name:l}):l}static build(l,u,m,x){return!l||typeof l=="object"&&!("name"in l)?null:new zl(l,m,u,x)}}function gN(h,l,u,m){return typeof h=="number"&&h>=0&&h<=255&&typeof l=="number"&&l>=0&&l<=255&&typeof u=="number"&&u>=0&&u<=255?m===void 0||typeof m=="number"&&m>=0&&m<=1?null:`Invalid rgba value [${[h,l,u,m].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof m=="number"?[h,l,u,m]:[h,l,u]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function kg(h){if(h===null||typeof h=="string"||typeof h=="boolean"||typeof h=="number"||h instanceof Xn||h instanceof WT||h instanceof Oo||h instanceof zl)return!0;if(Array.isArray(h)){for(const l of h)if(!kg(l))return!1;return!0}if(typeof h=="object"){for(const l in h)if(!kg(h[l]))return!1;return!0}return!1}function Cs(h){if(h===null)return bh;if(typeof h=="string")return di;if(typeof h=="boolean")return pi;if(typeof h=="number")return Dr;if(h instanceof Xn)return Sl;if(h instanceof WT)return Um;if(h instanceof Oo)return Jx;if(h instanceof zl)return e0;if(Array.isArray(h)){const l=h.length;let u;for(const m of h){const x=Cs(m);if(u){if(u===x)continue;u=gi;break}u=x}return el(u||gi,l)}return Sf}function Yr(h){const l=typeof h;return h===null?"":l==="string"||l==="number"||l==="boolean"?String(h):h instanceof Oo||h instanceof zl||h instanceof Xn?h.toString():JSON.stringify(h)}class Ir{constructor(l,u){this.type=l,this.value=u}static parse(l,u){if(l.length!==2)return u.error(`'literal' expression requires exactly one argument, but found ${l.length-1} instead.`);if(!kg(l[1]))return u.error("invalid value");const m=l[1];let x=Cs(m);const b=u.expectedType;return x.kind!=="array"||x.N!==0||!b||b.kind!=="array"||typeof b.N=="number"&&b.N!==0||(x=b),new Ir(x,m)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Xn?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof Oo?this.value.serialize():this.value}}class ea{constructor(l){this.name="ExpressionEvaluationError",this.message=l}toJSON(){return this.message}}const Jr={string:di,number:Dr,boolean:pi,object:Sf};class Cc{constructor(l,u){this.type=l,this.args=u}static parse(l,u){if(l.length<2)return u.error("Expected at least one argument.");let m,x=1;const b=l[0];if(b==="array"){let A,N;if(l.length>2){const O=l[1];if(typeof O!="string"||!(O in Jr)||O==="object")return u.error('The item type argument of "array" must be one of string, number, boolean',1);A=Jr[O],x++}else A=gi;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);N=l[2],x++}m=el(A,N)}else m=Jr[b];const S=[];for(;xl.outputDefined())}serialize(){const l=this.type,u=[l.kind];if(l.kind==="array"){const m=l.itemType;if(m.kind==="string"||m.kind==="number"||m.kind==="boolean"){u.push(m.kind);const x=l.N;(typeof x=="number"||this.args.length>1)&&u.push(x)}}return u.concat(this.args.map(m=>m.serialize()))}}class Vm{constructor(l){this.type=Jx,this.sections=l}static parse(l,u){if(l.length<2)return u.error("Expected at least one argument.");const m=l[1];if(!Array.isArray(m)&&typeof m=="object")return u.error("First argument must be an image or text section.");const x=[];let b=!1;for(let S=1;S<=l.length-1;++S){const A=l[S];if(b&&typeof A=="object"&&!Array.isArray(A)){b=!1;let N=null;if(A["font-scale"]&&(N=u.parseObjectValue(A["font-scale"],S,"font-scale",Dr),!N))return null;let O=null;if(A["text-font"]&&(O=u.parseObjectValue(A["text-font"],S,"text-font",el(di)),!O))return null;let $=null;if(A["text-color"]&&($=u.parseObjectValue(A["text-color"],S,"text-color",Sl),!$))return null;const U=x[x.length-1];U.scale=N,U.font=O,U.textColor=$}else{const N=u.parse(l[S],S,gi);if(!N)return null;const O=N.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:N,scale:null,font:null,textColor:null})}}return new Vm(x)}evaluate(l){return new Oo(this.sections.map(u=>{const m=u.content.evaluate(l);return wh(Cs(m),e0)?new r0("",m,null,null,null):new r0(Yr(m),null,u.scale?u.scale.evaluate(l):null,u.font?u.font.evaluate(l).join(","):null,u.textColor?u.textColor.evaluate(l):null)}))}eachChild(l){for(const u of this.sections)l(u.content),u.scale&&l(u.scale),u.font&&l(u.font),u.textColor&&l(u.textColor)}outputDefined(){return!1}serialize(){const l=["format"];for(const u of this.sections){l.push(u.content.serialize());const m={};u.scale&&(m["font-scale"]=u.scale.serialize()),u.font&&(m["text-font"]=u.font.serialize()),u.textColor&&(m["text-color"]=u.textColor.serialize()),l.push(m)}return l}}class Gr{constructor(l,u,m,x){this._imageWarnHistory={},this.type=e0,this.namePrimary=l,this.nameSecondary=u,m&&(this.paramsPrimary=m.params,this.iconsetIdPrimary=m.iconset?m.iconset.id:void 0),x&&(this.paramsSecondary=x.params,this.iconsetIdSecondary=x.iconset?x.iconset.id:void 0)}static parse(l,u){if(l.length<2)return u.error("Expected two or more arguments.");let m=1;const x=[];function b(){if(mhc.isEqual(S,b)),x.available){const S=x.getSecondary()?x.getSecondary().id:null;S&&(x.available=l.availableImages.some(A=>hc.isEqual(A,S)))}}return x}eachChild(l){if(l(this.namePrimary),this.paramsPrimary)for(const u in this.paramsPrimary)this.paramsPrimary[u]&&l(this.paramsPrimary[u]);if(this.nameSecondary&&(l(this.nameSecondary),this.paramsSecondary))for(const u in this.paramsSecondary)this.paramsSecondary[u]&&l(this.paramsSecondary[u])}outputDefined(){return!1}serializeOptions(l,u){const m={};if(u&&(m.iconset={id:u}),l){m.params={};for(const x in l)l[x]&&(m.params[x]=l[x].serialize())}return Object.keys(m).length>0?m:void 0}serialize(){const l=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const u=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);u&&l.push(u)}if(this.nameSecondary&&(l.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const u=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);u&&l.push(u)}return l}}function n0(h){return U_(h)?"string":i0(h)?"number":s0(h)?"boolean":Array.isArray(h)?"array":h===null?"null":z_(h)?"object":typeof h}function z_(h){return h!=null&&!Array.isArray(h)&&typeof h!="function"&&!(h instanceof String||h instanceof Number||h instanceof Boolean)&&typeof h=="object"}function U_(h){return typeof h=="string"||h instanceof String}function i0(h){return typeof h=="number"||h instanceof Number}function s0(h){return typeof h=="boolean"||h instanceof Boolean}const E5={"to-boolean":pi,"to-color":Sl,"to-number":Dr,"to-string":di};class qu{constructor(l,u){this.type=l,this.args=u}static parse(l,u){if(l.length<2)return u.error("Expected at least one argument.");const m=l[0],x=[];let b=bh;if(m==="to-array"){if(!Array.isArray(l[1]))return null;const S=l[1].length;if(u.expectedType){if(u.expectedType.kind!=="array")return u.error(`Expected ${u.expectedType.kind} but found array.`);b=el(u.expectedType.itemType,S)}else{if(!(S>0&&kg(l[1][0])))return null;b=el(Cs(l[1][0]),S)}for(let A=0;A4?`Invalid rbga value ${JSON.stringify(u)}: expected an array containing either three or four numeric values.`:gN(u[0],u[1],u[2],u[3]),!m))return new Xn(u[0]/255,u[1]/255,u[2]/255,u[3])}throw new ea(m||`Could not parse color from value '${typeof u=="string"?u:String(JSON.stringify(u))}'`)}if(this.type.kind==="number"){let u=null;for(const m of this.args){if(u=m.evaluate(l),u===null)return 0;const x=Number(u);if(!isNaN(x))return x}throw new ea(`Could not convert ${JSON.stringify(u)} to number.`)}return this.type.kind==="formatted"?Oo.fromString(Yr(this.args[0].evaluate(l))):this.type.kind==="resolvedImage"?zl.build(Yr(this.args[0].evaluate(l))):this.type.kind==="array"?this.args.map(u=>u.evaluate(l)):Yr(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 Vm([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new Gr(this.args[0]).serialize();const l=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(u=>{l.push(u.serialize())}),l}}const qm=["Unknown","Point","LineString","Polygon"];class a0{constructor(l,u,m){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null,this.featureTileCoord=null,this.featureDistanceData=null,this.scope=l,this.options=u,this.iconImageUseTheme=m}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?qm[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}measureLight(l){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const l=this.featureDistanceData.center,u=this.featureDistanceData.scale,{x:m,y:x}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(m*u-l[0])+this.featureDistanceData.bearing[1]*(x*u-l[1])}return 0}parseColor(l){let u=this._parseColorCache[l];return u||(u=this._parseColorCache[l]=Xn.parse(l)),u}getConfig(l){return this.options?this.options.get(l):null}}class Ma{constructor(l,u,m,x,b){this.name=l,this.type=u,this._evaluate=m,this.args=x,this._overloadIndex=b}evaluate(l){if(!this._evaluate){const u=Ma.definitions[this.name];this._evaluate=Array.isArray(u)?u[2]:u.overloads[this._overloadIndex][1]}return this._evaluate(l,this.args)}eachChild(l){this.args.forEach(l)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(l=>l.serialize()))}static parse(l,u){const m=l[0],x=Ma.definitions[m];if(!x)return u.error(`Unknown expression "${m}". If you wanted a literal array, use ["literal", [...]].`,0);const b=Array.isArray(x)?x[0]:x.type,S=Array.isArray(x)?[[x[1],x[2]]]:x.overloads,A=[];let N=null,O=-1;for(const[$,U]of S){if(Array.isArray($)&&$.length!==l.length-1)continue;A.push($),O++,N=new Z_(u.registry,u.path,null,u.scope,void 0,u._scope,u.options,u.iconImageUseTheme);const q=[];let K=!1;for(let X=1;Xq)).map(Tf).join(" | "),U=[];for(let q=1;qu;){if(m-u>600){const N=m-u+1,O=l-u+1,$=Math.log(N),U=.5*Math.exp(2*$/3),q=.5*Math.sqrt($*U*(N-U)/N)*(O-N/2<0?-1:1);yN(h,l,Math.max(u,Math.floor(l-O*U/N+q)),Math.min(m,Math.floor(l+(N-O)*U/N+q)),x)}const b=h[l];let S=u,A=m;for(o0(h,u,l),x(h[m],b)>0&&o0(h,u,m);S0;)A--}x(h[u],b)===0?o0(h,u,A):(A++,o0(h,A,m)),A<=l&&(u=A+1),l<=A&&(m=A-1)}}function o0(h,l,u){const m=h[l];h[l]=h[u],h[u]=m}function q_(h,l){return hl?1:0}function xN(h){let l=0;for(let u,m,x=0,b=h.length,S=b-1;x=l[2]||h[1]<=l[1]||h[3]>=l[3])}function j5(h,l,u){const m=h[0]-l[0],x=h[1]-l[1],b=h[0]-u[0],S=h[1]-u[1];return m*S-b*x===0&&m*b<=0&&x*S<=0}function KT(h,l,u){return l[1]>h[1]!=u[1]>h[1]&&h[0]<(u[0]-l[0])*(h[1]-l[1])/(u[1]-l[1])+l[0]}function Cg(h,l,u=!1){let m=!1;for(let x=0,b=l.length;x0&&A<0||S<0&&A>0}function c0(h,l,u,m){return(x=[m[0]-u[0],m[1]-u[1]])[0]*(b=[l[0]-h[0],l[1]-h[1]])[1]-x[1]*b[0]!==0&&!(!vN(h,l,u,m)||!vN(u,m,h,l));var x,b}function YT(h){const l=new Ot(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),u=new Ot(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const m of h[0])l.x>m.x&&(l.x=m.x),l.y>m.y&&(l.y=m.y),u.xu[2]){const x=.5*m;let b=h[0]-u[0]>x?-m:u[0]-h[0]>x?m:0;b===0&&(b=h[0]-u[2]>x?-m:u[2]-h[0]>x?m:0),h[0]+=b}Gu(l,h)}function QT(h,l,u,m){const x=Math.pow(2,m.z)*Ef,b=[m.x*Ef,m.y*Ef],S=[];if(!h)return S;for(const A of h)for(const N of A){const O=[N.x+b[0],N.y+b[1]];yu(O,l,u,x),S.push(O)}return S}function JT(h,l,u,m){const x=Math.pow(2,m.z)*Ef,b=[m.x*Ef,m.y*Ef],S=[];if(!h)return S;for(const N of h){const O=[];for(const $ of N){const U=[$.x+b[0],$.y+b[1]];Gu(l,U),O.push(U)}S.push(O)}if(l[2]-l[0]<=x/2){(A=l)[0]=A[1]=1/0,A[2]=A[3]=-1/0;for(const N of S)for(const O of N)yu(O,l,u,x)}var A;return S}class jf{constructor(l,u){this.type=pi,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(kg(l[1])){const m=l[1];if(m.type==="FeatureCollection")for(let x=0;xu)return H_(b,S,(u-(m-A))/A)}return l[l.length-1]}pointToSegmentDistance(l,u,m){let[x,b]=u,S=Nc(m[0]-x)*this.kx,A=(m[1]-b)*this.ky;if(S!==0||A!==0){const N=(Nc(l[0]-x)*this.kx*S+(l[1]-b)*this.ky*A)/(S*S+A*A);N>1?(x=m[0],b=m[1]):N>0&&(x+=S/this.kx*N,b+=A/this.ky*N)}return S=Nc(l[0]-x)*this.kx,A=(l[1]-b)*this.ky,Math.sqrt(S*S+A*A)}pointOnLine(l,u){let m=1/0,x=l[0][0],b=l[0][1],S=0,A=0;for(let N=0;N1?(O=l[N+1][0],$=l[N+1][1]):K>0&&(O+=U/this.kx*K,$+=q/this.ky*K)),U=Nc(u[0]-O)*this.kx,q=(u[1]-$)*this.ky;const X=U*U+q*q;Xb.index||x.index===b.index&&x.t>b.t){const O=x;x=b,b=O}const S=[x.point],A=x.index+1,N=b.index;!rE(m[A],S[0])&&A<=N&&S.push(m[A]);for(let O=A+1;O<=N;O++)S.push(m[O]);return rE(m[N],b.point)||S.push(b.point),S}lineSliceAlong(l,u,m){let x=0;const b=[];for(let S=0;Sl&&b.length===0&&b.push(H_(A,N,(l-(x-O))/O)),x>=u)return b.push(H_(A,N,(u-(x-O))/O)),b;x>l&&b.push(N)}return b}bufferPoint(l,u){const m=u/this.ky,x=u/this.kx;return[l[0]-x,l[1]-m,l[0]+x,l[1]+m]}bufferBBox(l,u){const m=u/this.ky,x=u/this.kx;return[l[0]-x,l[1]-m,l[2]+x,l[3]+m]}insideBBox(l,u){return Nc(l[0]-u[0])>=0&&Nc(l[0]-u[2])<=0&&l[1]>=u[1]&&l[1]<=u[3]}}function rE(h,l){return h[0]===l[0]&&h[1]===l[1]}function H_(h,l,u){const m=Nc(l[0]-h[0]);return[h[0]+m*u,h[1]+(l[1]-h[1])*u]}function Nc(h){for(;h<-180;)h+=360;for(;h>180;)h-=360;return h}class d0{constructor(l=[],u=(m,x)=>mx?1:0){if(this.data=l,this.length=this.data.length,this.compare=u,this.length>0)for(let m=(this.length>>1)-1;m>=0;m--)this._down(m)}push(l){this.data.push(l),this._up(this.length++)}pop(){if(this.length===0)return;const l=this.data[0],u=this.data.pop();return--this.length>0&&(this.data[0]=u,this._down(0)),l}peek(){return this.data[0]}_up(l){const{data:u,compare:m}=this,x=u[l];for(;l>0;){const b=l-1>>1,S=u[b];if(m(x,S)>=0)break;u[l]=S,l=b}u[l]=x}_down(l){const{data:u,compare:m}=this,x=this.length>>1,b=u[l];for(;l=0)break;u[l]=u[S],l=S}u[l]=b}}var lr=8192;function bN(h,l){return l.dist-h.dist}function wN(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=Hm(h);if(l){if(u===2)return[h,null];const m=Math.floor(u/2);return[[h[0],h[0]+m],[h[0]+m,h[1]]]}{if(u===1)return[h,null];const m=Math.floor(u/2)-1;return[[h[0],h[0]+m],[h[0]+m+1,h[1]]]}}function Af(h,l){const u=[1/0,1/0,-1/0,-1/0];if(!Hu(l,h.length))return u;for(let m=l[0];m<=l[1];++m)Gu(u,h[m]);return u}function h0(h){const l=[1/0,1/0,-1/0,-1/0];for(let u=0;ul[2]&&(m=h[0]-l[2]),h[1]>l[3]&&(x=h[1]-l[3]),h[3]=m)return m;if(l0(x,b)){if(AN(h,l))return 0}else if(AN(l,h))return 0;let S=m;for(const A of h)for(let N=0,O=A.length,$=O-1;N=b)continue;const $=O.range1;if(Hm($)<=A){if(!Hu($,h.length))return NaN;if(l){const U=ls(h,$,u,m);if((b=Math.min(b,U))===0)return b}else for(let U=$[0];U<=$[1];++U){const q=I5(h[U],u,m);if((b=Math.min(b,q))===0)return b}}else{const U=Pg($,l);if(U[0]!==null){const q=Rg(Af(h,U[0]),N,m);q=S)continue;const U=$.range1,q=$.range2;if(Hm(U)<=N&&Hm(q)<=O){if(!Hu(U,h.length)||!Hu(q,u.length))return NaN;if(l&&m?S=Math.min(S,N5(h,U,u,q,x)):l||m?l&&!m?S=Math.min(S,EN(u,q,h,U,x)):!l&&m&&(S=Math.min(S,EN(h,U,u,q,x))):S=Math.min(S,jN(h,U,u,q,x)),S===0)return S}else{const K=Pg(U,l),X=Pg(q,m);W_(A,S,x,h,u,K[0],X[0]),W_(A,S,x,h,u,K[0],X[1]),W_(A,S,x,h,u,K[1],X[0]),W_(A,S,x,h,u,K[1],X[1])}}return S}function iE(h,l,u,m,x=1/0){let b=x;const S=Af(h,[0,h.length-1]);for(const A of u)if(!(b!==1/0&&Rg(S,Af(A,[0,A.length-1]),m)>=b)&&(b=Math.min(b,kN(h,l,A,!0,m,b)),b===0))return b;return b}function K_(h,l,u,m,x=1/0){let b=x;const S=Af(h,[0,h.length-1]);for(const A of u){if(b!==1/0&&Rg(S,h0(A),m)>=b)continue;const N=R5(h,l,A,m,b);if(isNaN(N))return N;if((b=Math.min(b,N))===0)return b}return b}function sE(h){return h==="Point"||h==="MultiPoint"||h==="LineString"||h==="MultiLineString"||h==="Polygon"||h==="MultiPolygon"}class Wm{constructor(l,u){this.type=Dr,this.geojson=l,this.geometries=u}static parse(l,u){if(l.length!==2)return u.error(`'distance' expression requires either one argument, but found ' ${l.length-1} instead.`);if(kg(l[1])){const m=l[1];if(m.type==="FeatureCollection"){for(let x=0;x{l&&!Km(u)&&(l=!1)}),l}function Lg(h){if(h instanceof Ma&&h.name==="feature-state")return!1;let l=!0;return h.eachChild(u=>{l&&!Lg(u)&&(l=!1)}),l}function Pd(h,l){if(h instanceof Ma&&l.indexOf(h.name)>=0)return!1;let u=!0;return h.eachChild(m=>{u&&!Pd(m,l)&&(u=!1)}),u}function CN(h,l,u){return[h,l,u].filter(Boolean).join("")}function aE(h,l){switch(h){case"string":return Yr(l);case"number":return+l;case"boolean":return!!l;case"color":return Xn.parse(l);case"formatted":return Oo.fromString(Yr(l));case"resolvedImage":return zl.build(Yr(l))}return l}function NN(h,l,u,m){return m!==void 0&&(h=m*Math.round(h/m)),l!==void 0&&hu&&(h=u),h}class Dg{constructor(l,u,m,x=!1){this.type=l,this.key=u,this.scope=m,this.featureConstant=x}static parse(l,u){let m=u.expectedType;if(m==null&&(m=gi),l.length<2||l.length>3)return u.error("Invalid number of arguments for 'config' expression.");const x=u.parse(l[1],1);if(!(x instanceof Ir))return u.error("Key name of 'config' expression must be a string literal.");let b,S=!0;const A=Yr(x.value);if(l.length>=3){const N=u.parse(l[2],2);if(!(N instanceof Ir))return u.error("Scope of 'config' expression must be a string literal.");b=Yr(N.value)}if(u.options){const N=CN(A,b,u._scope),O=u.options.get(N);O&&(S=Km(O.value||O.default))}return new Dg(m,A,b,S)}evaluate(l){const u=CN(this.key,this.scope,l.scope),m=l.getConfig(u);if(!m)return null;const{type:x,value:b,values:S,minValue:A,maxValue:N,stepValue:O}=m,$=m.default.evaluate(l);let U=$;if(b){const q=l.scope;l.scope=(q||"").split("").slice(1).join(""),U=b.evaluate(l),l.scope=q}return x&&(U=aE(x,U)),U===void 0||A===void 0&&N===void 0&&O===void 0||(typeof U=="number"?U=NN(U,A,N,O):Array.isArray(U)&&(U=U.map(q=>typeof q=="number"?NN(q,A,N,O):q))),b!==void 0&&U!==void 0&&S&&!S.includes(U)&&(U=$,x&&(U=aE(x,U))),(x&&x!==this.type||U!==void 0&&!wh(Cs(U),this.type))&&(U=aE(this.type.kind,U)),U}eachChild(){}outputDefined(){return!1}serialize(){const l=["config",this.key];return this.scope&&l.concat(this.scope),l}}class Y_{constructor(l,u){this.type=u.type,this.name=l,this.boundExpression=u}static parse(l,u){if(l.length!==2||typeof l[1]!="string")return u.error("'var' expression requires exactly one string literal argument.");const m=l[1];return u.scope.has(m)?new Y_(m,u.scope.get(m)):u.error(`Unknown variable "${m}". Make sure "${m}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(l){return this.boundExpression.evaluate(l)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class Z_{constructor(l,u=[],m,x=new zm,b=[],S,A,N){this.registry=l,this.path=u,this.key=u.map(O=>typeof O=="string"?`['${O}']`:`[${O}]`).join(""),this.scope=x,this.errors=b,this.expectedType=m,this._scope=S,this.options=A,this.iconImageUseTheme=N}parse(l,u,m,x,b={}){return u||m?this.concat(u,null,m,x)._parse(l,b):this._parse(l,b)}parseObjectValue(l,u,m,x,b,S={}){return this.concat(u,m,x,b)._parse(l,S)}_parse(l,u){function m(x,b,S){return S==="assert"?new Cc(b,[x]):S==="coerce"?new qu(b,[x]):x}if(l!==null&&typeof l!="string"&&typeof l!="boolean"&&typeof l!="number"||(l=["literal",l]),Array.isArray(l)){if(l.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const x=typeof l[0]=="string"?this.registry[l[0]]:void 0;if(x){let b=x.parse(l,this);if(!b)return null;if(this.expectedType){const S=this.expectedType,A=b.type;if(S.kind!=="string"&&S.kind!=="number"&&S.kind!=="boolean"&&S.kind!=="object"&&S.kind!=="array"||A.kind!=="value")if(S.kind!=="color"&&S.kind!=="formatted"&&S.kind!=="resolvedImage"||A.kind!=="value"&&A.kind!=="string"){if(this.checkSubtype(S,A))return null}else b=m(b,S,u.typeAnnotation||"coerce");else b=m(b,S,u.typeAnnotation||"assert")}if(!(b instanceof Ir)&&b.type.kind!=="resolvedImage"&&oE(b)){const S=new a0(this._scope,this.options,this.iconImageUseTheme);try{b=new Ir(b.type,b.evaluate(S))}catch(A){return this.error(A.message),null}}return b}return qu.parse(["to-array",l],this)}return this.error(l===void 0?"'undefined' value invalid. Use null instead.":typeof l=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof l} instead.`)}concat(l,u,m,x){let b=typeof l=="number"?this.path.concat(l):this.path;b=typeof u=="string"?b.concat(u):b;const S=x?this.scope.concat(x):this.scope;return new Z_(this.registry,b,m||null,S,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(l,...u){const m=`${this.key}${u.map(x=>`[${x}]`).join("")}`;this.errors.push(new pu(m,l))}checkSubtype(l,u){const m=t0(l,u);return m&&this.error(m),m}}function oE(h){if(h instanceof Y_)return oE(h.boundExpression);if(h instanceof Ma&&h.name==="error"||h instanceof V_||h instanceof jf||h instanceof Wm||h instanceof Dg)return!1;const l=h instanceof qu||h instanceof Cc;let u=!0;return h.eachChild(m=>{u=l?u&&oE(m):u&&m instanceof Ir}),!!u&&Km(h)&&Pd(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 X_(h,l){const u=h.length-1;let m,x,b=0,S=u,A=0;for(;b<=S;)if(A=Math.floor((b+S)/2),m=h[A],x=h[A+1],m<=l){if(A===u||ll))throw new ea("Input is not a number.");S=A-1}return 0}class f0{constructor(l,u,m){this.type=l,this.input=u,this.labels=[],this.outputs=[];for(const[x,b]of m)this.labels.push(x),this.outputs.push(b)}static parse(l,u){if(l.length-1<4)return u.error(`Expected at least 4 arguments, but found only ${l.length-1}.`);if((l.length-1)%2!=0)return u.error("Expected an even number of arguments.");const m=u.parse(l[1],1,Dr);if(!m)return null;const x=[];let b=null;u.expectedType&&u.expectedType.kind!=="value"&&(b=u.expectedType);for(let S=1;S=A)return u.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',O);const U=u.parse(N,$,b);if(!U)return null;b=b||U.type,x.push([A,U])}return new f0(b,m,x)}evaluate(l){const u=this.labels,m=this.outputs;if(u.length===1)return m[0].evaluate(l);const x=this.input.evaluate(l);if(x<=u[0])return m[0].evaluate(l);const b=u.length;return x>=u[b-1]?m[b-1].evaluate(l):m[X_(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 IN=.95047,PN=1.08883,RN=4/29,Mg=6/29,LN=3*Mg*Mg,L5=Mg*Mg*Mg,D5=Math.PI/180,M5=180/Math.PI;function lE(h){return h>L5?Math.pow(h,1/3):h/LN+RN}function cE(h){return h>Mg?h*h*h:LN*(h-RN)}function m0(h){return 255*(h<=.0031308?12.92*h:1.055*Math.pow(h,1/2.4)-.055)}function Og(h){return(h/=255)<=.04045?h/12.92:Math.pow((h+.055)/1.055,2.4)}function uE(h){const l=Og(h.r),u=Og(h.g),m=Og(h.b),x=lE((.4124564*l+.3575761*u+.1804375*m)/IN),b=lE((.2126729*l+.7151522*u+.072175*m)/1);return{l:116*b-16,a:500*(x-b),b:200*(b-lE((.0193339*l+.119192*u+.9503041*m)/PN)),alpha:h.a}}function DN(h){let l=(h.l+16)/116,u=isNaN(h.a)?l:l+h.a/500,m=isNaN(h.b)?l:l-h.b/200;return l=1*cE(l),u=IN*cE(u),m=PN*cE(m),new Xn(m0(3.2404542*u-1.5371385*l-.4985314*m),m0(-.969266*u+1.8760108*l+.041556*m),m0(.0556434*u-.2040259*l+1.0572252*m),h.alpha)}function O5(h,l,u){const m=l-h;return h+u*(m>180||m<-180?m-360*Math.round(m/360):m)}const p0={forward:uE,reverse:DN,interpolate:function(h,l,u){return{l:Qr(h.l,l.l,u),a:Qr(h.a,l.a,u),b:Qr(h.b,l.b,u),alpha:Qr(h.alpha,l.alpha,u)}}},Fg={forward:function(h){const{l,a:u,b:m}=uE(h),x=Math.atan2(m,u)*M5;return{h:x<0?x+360:x,c:Math.sqrt(u*u+m*m),l,alpha:h.a}},reverse:function(h){const l=h.h*D5,u=h.c;return DN({l:h.l,a:Math.cos(l)*u,b:Math.sin(l)*u,alpha:h.alpha})},interpolate:function(h,l,u){return{h:O5(h.h,l.h,u),c:Qr(h.c,l.c,u),l:Qr(h.l,l.l,u),alpha:Qr(h.alpha,l.alpha,u)}}};var dE=Object.freeze({__proto__:null,hcl:Fg,lab:p0});class Fo{constructor(l,u,m,x,b){this.type=l,this.operator=u,this.interpolation=m,this.input=x,this.labels=[],this.outputs=[];for(const[S,A]of b)this.labels.push(S),this.outputs.push(A)}static interpolationFactor(l,u,m,x){let b=0;if(l.name==="exponential")b=Q_(u,l.base,m,x);else if(l.name==="linear")b=Q_(u,1,m,x);else if(l.name==="cubic-bezier"){const S=l.controlPoints;b=new Jo(S[0],S[1],S[2],S[3]).solve(Q_(u,1,m,x))}return b}static parse(l,u){let[m,x,b,...S]=l;if(!Array.isArray(x)||x.length===0)return u.error("Expected an interpolation type expression.",1);if(x[0]==="linear")x={name:"linear"};else if(x[0]==="exponential"){const O=x[1];if(typeof O!="number")return u.error("Exponential interpolation requires a numeric base.",1,1);x={name:"exponential",base:O}}else{if(x[0]!=="cubic-bezier")return u.error(`Unknown interpolation type ${String(x[0])}`,1,0);{const O=x.slice(1);if(O.length!==4||O.some($=>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,Dr),!b)return null;const A=[];let N=null;m==="interpolate-hcl"||m==="interpolate-lab"?N=Sl:u.expectedType&&u.expectedType.kind!=="value"&&(N=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.',q);const X=u.parse(U,K,N);if(!X)return null;N=N||X.type,A.push([$,X])}return N.kind==="number"||N.kind==="color"||N.kind==="array"&&N.itemType.kind==="number"&&typeof N.N=="number"?new Fo(N,m,x,b,A):u.error(`Type ${da(N)} is not interpolatable.`)}evaluate(l){const u=this.labels,m=this.outputs;if(u.length===1)return m[0].evaluate(l);const x=this.input.evaluate(l);if(x<=u[0])return m[0].evaluate(l);const b=u.length;if(x>=u[b-1])return m[b-1].evaluate(l);const S=X_(u,x),A=Fo.interpolationFactor(this.interpolation,x,u[S],u[S+1]),N=m[S].evaluate(l),O=m[S+1].evaluate(l);return this.operator==="interpolate"?$_[this.type.kind.toLowerCase()](N,O,A):this.operator==="interpolate-hcl"?Fg.reverse(Fg.interpolate(Fg.forward(N),Fg.forward(O),A)):p0.reverse(p0.interpolate(p0.forward(N),p0.forward(O),A))}eachChild(l){l(this.input);for(const u of this.outputs)l(u)}outputDefined(){return this.outputs.every(l=>l.outputDefined())}serialize(){let l;l=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const u=[this.operator,l,this.input.serialize()];for(let m=0;mt0(x,A.type));return new g0(S?gi:m,b)}evaluate(l){let u,m=null,x=0;for(const b of this.args){if(x++,m=b.evaluate(l),m&&m instanceof zl&&!m.available&&(u||(u=m),m=null,x===this.args.length))return u;if(m!==null)break}return m}eachChild(l){this.args.forEach(l)}outputDefined(){return this.args.every(l=>l.outputDefined())}serialize(){const l=["coalesce"];return this.eachChild(u=>{l.push(u.serialize())}),l}}class J_{constructor(l,u){this.type=u.type,this.bindings=[].concat(l),this.result=u}evaluate(l){return this.result.evaluate(l)}eachChild(l){for(const u of this.bindings)l(u[1]);l(this.result)}static parse(l,u){if(l.length<4)return u.error(`Expected at least 3 arguments, but found ${l.length-1} instead.`);const m=[];for(let b=1;b=m.length)throw new ea("Array index out of bounds: index exceeds array size");if(u!==Math.floor(u))throw new ea("Array index must be an integer. Use at-interpolated for fractional indices");return m[u]}eachChild(l){l(this.index),l(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class x0{constructor(l,u,m){this.type=l,this.index=u,this.input=m}static parse(l,u){if(l.length!==3)return u.error(`Expected 2 arguments, but found ${l.length-1} instead.`);const m=u.parse(l[1],1,Dr),x=u.parse(l[2],2,el(u.expectedType||gi));return m&&x?new x0(x.type.itemType,m,x):null}evaluate(l){const u=this.index.evaluate(l),m=this.input.evaluate(l);if(u<0)throw new ea(`Array index out of bounds: ${u} < 0.`);if(u>m.length-1)throw new ea(`Array index out of bounds: ${u} > ${m.length-1}.`);if(u===Math.floor(u))return m[u];const x=Math.floor(u),b=Math.ceil(u),S=m[x],A=m[b];if(typeof S!="number"||typeof A!="number")throw new ea(`Cannot interpolate between non-number values at index ${u}.`);const N=u-x;return S*(1-N)+A*N}eachChild(l){l(this.index),l(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class v0{constructor(l,u){this.type=pi,this.needle=l,this.haystack=u}static parse(l,u){if(l.length!==3)return u.error(`Expected 2 arguments, but found ${l.length-1} instead.`),null;const m=u.parse(l[1],1,gi),x=u.parse(l[2],2,gi);return m&&x?HT(m.type,[pi,di,Dr,bh,gi])?new v0(m,x):(u.error(`Expected first argument to be of type boolean, string, number or null, but found ${da(m.type)} instead`),null):null}evaluate(l){const u=this.needle.evaluate(l),m=this.haystack.evaluate(l);if(m==null)return!1;if(!Ag(u,["boolean","string","number","null"]))throw new ea(`Expected first argument to be of type boolean, string, number or null, but found ${da(Cs(u))} instead.`);if(!Ag(m,["string","array"]))throw new ea(`Expected second argument to be of type array or string, but found ${da(Cs(m))} instead.`);return m.indexOf(u)>=0}eachChild(l){l(this.needle),l(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class eb{constructor(l,u,m){this.type=Dr,this.needle=l,this.haystack=u,this.fromIndex=m}static parse(l,u){if(l.length<=2||l.length>=5)return u.error(`Expected 3 or 4 arguments, but found ${l.length-1} instead.`),null;const m=u.parse(l[1],1,gi),x=u.parse(l[2],2,gi);if(!m||!x)return null;if(!HT(m.type,[pi,di,Dr,bh,gi]))return u.error(`Expected first argument to be of type boolean, string, number or null, but found ${da(m.type)} instead`),null;if(l.length===4){const b=u.parse(l[3],3,Dr);return b?new eb(m,x,b):null}return new eb(m,x)}evaluate(l){const u=this.needle.evaluate(l),m=this.haystack.evaluate(l);if(!Ag(u,["boolean","string","number","null"]))throw new ea(`Expected first argument to be of type boolean, string, number or null, but found ${da(Cs(u))} instead.`);if(!Ag(m,["string","array"]))throw new ea(`Expected second argument to be of type array or string, but found ${da(Cs(m))} instead.`);if(this.fromIndex){const x=this.fromIndex.evaluate(l);return m.indexOf(u,x)}return m.indexOf(u)}eachChild(l){l(this.needle),l(this.haystack),this.fromIndex&&l(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const l=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),l]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class hE{constructor(l,u,m,x,b,S){this.inputType=l,this.type=u,this.input=m,this.cases=x,this.outputs=b,this.otherwise=S}static parse(l,u){if(l.length<5)return u.error(`Expected at least 4 arguments, but found only ${l.length-1}.`);if(l.length%2!=1)return u.error("Expected an even number of arguments.");let m,x;u.expectedType&&u.expectedType.kind!=="value"&&(x=u.expectedType);const b={},S=[];for(let O=2;ONumber.MAX_SAFE_INTEGER)return q.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof X=="number"&&Math.floor(X)!==X)return q.error("Numeric branch labels must be integer values.");if(m){if(q.checkSubtype(m,Cs(X)))return null}else m=Cs(X);if(b[String(X)]!==void 0)return q.error("Branch labels must be unique.");b[String(X)]=S.length}const K=u.parse(U,O,x);if(!K)return null;x=x||K.type,S.push(K)}const A=u.parse(l[1],1,gi);if(!A)return null;const N=u.parse(l[l.length-1],l.length-1,x);return N?A.type.kind!=="value"&&u.concat(1).checkSubtype(m,A.type)?null:new hE(m,x,A,b,S,N):null}evaluate(l){const u=this.input.evaluate(l);return(wh(Cs(u),this.inputType)&&this.outputs[this.cases[u]]||this.otherwise).evaluate(l)}eachChild(l){l(this.input),this.outputs.forEach(l),l(this.otherwise)}outputDefined(){return this.outputs.every(l=>l.outputDefined())&&this.otherwise.outputDefined()}serialize(){const l=["match",this.input.serialize()],u=Object.keys(this.cases).sort(),m=[],x={};for(const S of u){const A=x[this.cases[S]];A===void 0?(x[this.cases[S]]=m.length,m.push([this.cases[S],[S]])):m[A][1].push(S)}const b=S=>this.inputType.kind==="number"?Number(S):S;for(const[S,A]of m)l.push(A.length===1?b(A[0]):A.map(b)),l.push(this.outputs[S].serialize());return l.push(this.otherwise.serialize()),l}}class tb{constructor(l,u,m){this.type=l,this.branches=u,this.otherwise=m}static parse(l,u){if(l.length<4)return u.error(`Expected at least 3 arguments, but found only ${l.length-1}.`),null;if(l.length%2!=0)return u.error("Expected an odd number of arguments."),null;let m;u.expectedType&&u.expectedType.kind!=="value"&&(m=u.expectedType);const x=[];for(let S=1;Su.outputDefined())&&this.otherwise.outputDefined()}serialize(){const l=["case"];return this.eachChild(u=>{l.push(u.serialize())}),l}}class _0{constructor(l,u,m,x){this.type=l,this.input=u,this.beginIndex=m,this.endIndex=x}static parse(l,u){if(l.length<=2||l.length>=5)return u.error(`Expected 3 or 4 arguments, but found ${l.length-1} instead.`),null;const m=u.parse(l[1],1,gi),x=u.parse(l[2],2,Dr);if(!m||!x)return null;if(!HT(m.type,[el(gi),di,gi]))return u.error(`Expected first argument to be of type array or string, but found ${da(m.type)} instead`),null;if(l.length===4){const b=u.parse(l[3],3,Dr);return b?new _0(m.type,m,x,b):null}return new _0(m.type,m,x)}evaluate(l){const u=this.input.evaluate(l),m=this.beginIndex.evaluate(l);if(!Ag(u,["string","array"]))throw new ea(`Expected first argument to be of type array or string, but found ${da(Cs(u))} instead.`);if(this.endIndex){const x=this.endIndex.evaluate(l);return u.slice(m,x)}return u.slice(m)}eachChild(l){l(this.input),l(this.beginIndex),this.endIndex&&l(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const l=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),l]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class fE{constructor(l,u){this.type=el(di),this.str=l,this.delimiter=u}static parse(l,u){if(l.length!==3)return u.error(`Expected 2 arguments, but found ${l.length-1} instead.`);const m=u.parse(l[1],1,di),x=u.parse(l[2],2,di);return m&&x?new fE(m,x):void 0}evaluate(l){const u=this.str.evaluate(l),m=this.delimiter.evaluate(l);return u.split(m)}eachChild(l){l(this.str),l(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function MN(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 ON(h,l,u,m){return m.compare(l,u)===0}function Ym(h,l,u){const m=h!=="=="&&h!=="!=";return class W_e{constructor(b,S,A){this.type=pi,this.lhs=b,this.rhs=S,this.collator=A,this.hasUntypedArgument=b.type.kind==="value"||S.type.kind==="value"}static parse(b,S){if(b.length!==3&&b.length!==4)return S.error("Expected two or three arguments.");const A=b[0];let N=S.parse(b[1],1,gi);if(!N)return null;if(!MN(A,N.type))return S.concat(1).error(`"${A}" comparisons are not supported for type '${da(N.type)}'.`);let O=S.parse(b[2],2,gi);if(!O)return null;if(!MN(A,O.type))return S.concat(2).error(`"${A}" comparisons are not supported for type '${da(O.type)}'.`);if(N.type.kind!==O.type.kind&&N.type.kind!=="value"&&O.type.kind!=="value")return S.error(`Cannot compare types '${da(N.type)}' and '${da(O.type)}'.`);m&&(N.type.kind==="value"&&O.type.kind!=="value"?N=new Cc(O.type,[N]):N.type.kind!=="value"&&O.type.kind==="value"&&(O=new Cc(N.type,[O])));let $=null;if(b.length===4){if(N.type.kind!=="string"&&O.type.kind!=="string"&&N.type.kind!=="value"&&O.type.kind!=="value")return S.error("Cannot use collator to compare non-string types.");if($=S.parse(b[3],3,Um),!$)return null}return new W_e(N,O,$)}evaluate(b){const S=this.lhs.evaluate(b),A=this.rhs.evaluate(b);if(m&&this.hasUntypedArgument){const N=Cs(S),O=Cs(A);if(N.kind!==O.kind||N.kind!=="string"&&N.kind!=="number")throw new ea(`Expected arguments for "${h}" to be (string, string) or (number, number), but found (${N.kind}, ${O.kind}) instead.`)}if(this.collator&&!m&&this.hasUntypedArgument){const N=Cs(S),O=Cs(A);if(N.kind!=="string"||O.kind!=="string")return l(b,S,A)}return this.collator?u(b,S,A,this.collator.evaluate(b)):l(b,S,A)}eachChild(b){b(this.lhs),b(this.rhs),this.collator&&b(this.collator)}outputDefined(){return!0}serialize(){const b=[h];return this.eachChild(S=>{b.push(S.serialize())}),b}}}const FN=Ym("==",function(h,l,u){return l===u},ON),rb=Ym("!=",function(h,l,u){return l!==u},function(h,l,u,m){return!ON(0,l,u,m)}),F5=Ym("<",function(h,l,u){return l",function(h,l,u){return l>u},function(h,l,u,m){return m.compare(l,u)>0}),B5=Ym("<=",function(h,l,u){return l<=u},function(h,l,u,m){return m.compare(l,u)<=0}),$5=Ym(">=",function(h,l,u){return l>=u},function(h,l,u,m){return m.compare(l,u)>=0});class nb{constructor(l,u,m,x,b,S){this.type=di,this.number=l,this.locale=u,this.currency=m,this.unit=x,this.minFractionDigits=b,this.maxFractionDigits=S}static parse(l,u){if(l.length!==3)return u.error("Expected two arguments.");const m=u.parse(l[1],1,Dr);if(!m)return null;const x=l[2];if(typeof x!="object"||Array.isArray(x))return u.error("NumberFormat options argument must be an object.");let b=null;if(x.locale&&(b=u.parseObjectValue(x.locale,2,"locale",di),!b))return null;let S=null;if(x.currency&&(S=u.parseObjectValue(x.currency,2,"currency",di),!S))return null;let A=null;if(x.unit&&(A=u.parseObjectValue(x.unit,2,"unit",di),!A))return null;let N=null;if(x["min-fraction-digits"]&&(N=u.parseObjectValue(x["min-fraction-digits"],2,"min-fraction-digits",Dr),!N))return null;let O=null;return x["max-fraction-digits"]&&(O=u.parseObjectValue(x["max-fraction-digits"],2,"max-fraction-digits",Dr),!O)?null:new nb(m,b,S,A,N,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 ib{constructor(l){this.type=Dr,this.input=l}static parse(l,u){if(l.length!==2)return u.error(`Expected 1 argument, but found ${l.length-1} instead.`),null;const m=u.parse(l[1],1);return m?m.type.kind!=="array"&&m.type.kind!=="string"&&m.type.kind!=="value"?(u.error(`Expected argument of type string or array, but found ${da(m.type)} instead.`),null):new ib(m):null}evaluate(l){const u=this.input.evaluate(l);if(typeof u=="string"||Array.isArray(u))return u.length;throw new ea(`Expected value to be of type string or array, but found ${da(Cs(u))} instead.`)}eachChild(l){l(this.input)}outputDefined(){return!1}serialize(){const l=["length"];return this.eachChild(u=>{l.push(u.serialize())}),l}}function $N(h){return function(){h=1831565813+(h|=0)|0;let l=Math.imul(h^h>>>15,1|h);return l=l+Math.imul(l^l>>>7,61|l)^l,((l^l>>>14)>>>0)/4294967296}}const Bg={"==":FN,"!=":rb,">":BN,"<":F5,">=":$5,"<=":B5,array:Cc,at:y0,"at-interpolated":x0,boolean:Cc,case:tb,coalesce:g0,collator:V_,format:Vm,image:Gr,in:v0,"index-of":eb,interpolate:Fo,"interpolate-hcl":Fo,"interpolate-lab":Fo,length:ib,let:J_,literal:Ir,match:hE,number:Cc,"number-format":nb,object:Cc,slice:_0,step:f0,string:Cc,"to-boolean":qu,"to-color":qu,"to-number":qu,"to-string":qu,var:Y_,within:jf,distance:Wm,config:Dg,split:fE};function zN(h,[l,u,m,x]){l=l.evaluate(h),u=u.evaluate(h),m=m.evaluate(h);const b=x?x.evaluate(h):1,S=gN(l,u,m,b);if(S)throw new ea(S);return new Xn(l/255,u/255,m/255,b)}function UN(h,[l,u,m,x]){l=l.evaluate(h),u=u.evaluate(h),m=m.evaluate(h);const b=x?x.evaluate(h):1,S=function(O,$,U,q){return typeof O=="number"&&O>=0&&O<=360?typeof $=="number"&&$>=0&&$<=100&&typeof U=="number"&&U>=0&&U<=100?q===void 0||typeof q=="number"&&q>=0&&q<=1?null:`Invalid hsla value [${[O,$,U,q].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof q=="number"?[O,$,U,q]:[O,$,U]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof q=="number"?[O,$,U,q]:[O,$,U]).join(", ")}]: 'h' must be between 0 and 360.`}(l,u,m,b);if(S)throw new ea(S);const A=`hsla(${l}, ${u}%, ${m}%, ${b})`,N=Xn.parse(A);if(!N)throw new ea(`Failed to parse HSLA color: ${A}`);return N}function b0(h,l){return h in l}function sb(h,l){const u=l[h];return u===void 0?null:u}function kf(h){return{type:h}}function ab(h){if(h instanceof Dg)return new Set([h.key]);let l=new Set;return h.eachChild(u=>{l=new Set([...l,...ab(u)])}),l}function ob(h){if(h instanceof Ma&&h.name==="is-active-floor")return!0;let l=!1;return h.eachChild(u=>{!l&&ob(u)&&(l=!0)}),l}function VN(h){return{result:"success",value:h}}function Cf(h){return{result:"error",value:h}}function w0(h,l){return!!h&&!!h.parameters&&h.parameters.indexOf(l)>-1}function lb(h){return h["property-type"]==="data-driven"}function qN(h){return w0(h.expression,"measure-light")}function mE(h){return w0(h.expression,"zoom")}function cb(h){return!!h.expression&&h.expression.interpolated}function pE(h){return typeof h=="object"&&h!==null&&!Array.isArray(h)}function GN(h){return h}function HN(h,l){const u=l.type==="color",m=h.stops&&typeof h.stops[0][0]=="object",x=m||!(m||h.property!==void 0),b=h.type||(cb(l)?"exponential":"interval");if(u&&((h=Object.assign({},h)).stops&&(h.stops=h.stops.map(O=>[O[0],Xn.parse(O[1])])),h.default=Xn.parse(h.default?h.default:l.default)),h.colorSpace&&h.colorSpace!=="rgb"&&!dE[h.colorSpace])throw new Error(`Unknown color space: ${h.colorSpace}`);let S,A,N;if(b==="exponential")S=WN;else if(b==="interval")S=U5;else if(b==="categorical"){S=z5,A=Object.create(null);for(const O of h.stops)A[O[0]]=O[1];N=typeof h.stops[0][0]}else{if(b!=="identity")throw new Error(`Unknown function type "${b}"`);S=KN}if(m){const O={},$=[];for(let K=0;KK[0]),evaluate:({zoom:K},X)=>WN({stops:U,base:h.base},l,K).evaluate(K,X)}}if(x){const O=b==="exponential"?{name:"exponential",base:h.base!==void 0?h.base:1}:null;return{kind:"camera",interpolationType:O,interpolationFactor:Fo.interpolationFactor.bind(void 0,O),zoomStops:h.stops.map($=>$[0]),evaluate:({zoom:$})=>S(h,l,$,A,N)}}return{kind:"source",evaluate(O,$){const U=$&&$.properties?$.properties[h.property]:void 0;return U===void 0?Rd(h.default,l.default):S(h,l,U,A,N)}}}function Rd(h,l,u){return h!==void 0?h:l!==void 0?l:u!==void 0?u:void 0}function z5(h,l,u,m,x){return Rd(typeof u===x?m[u]:void 0,h.default,l.default)}function U5(h,l,u){if(!i0(u))return Rd(h.default,l.default);const m=h.stops.length;if(m===1||u<=h.stops[0][0])return h.stops[0][1];if(u>=h.stops[m-1][0])return h.stops[m-1][1];const x=X_(h.stops.map(b=>b[0]),u);return h.stops[x][1]}function WN(h,l,u){const m=h.base!==void 0?h.base:1;if(!i0(u))return Rd(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=X_(h.stops.map($=>$[0]),u),S=function($,U,q,K){const X=K-q,te=$-q;return X===0?0:U===1?te/X:(Math.pow(U,te)-1)/(Math.pow(U,X)-1)}(u,m,h.stops[b][0],h.stops[b+1][0]),A=h.stops[b][1],N=h.stops[b+1][1];let O=$_[l.type]||GN;if(h.colorSpace&&h.colorSpace!=="rgb"){const $=dE[h.colorSpace];O=(U,q)=>$.reverse($.interpolate($.forward(U),$.forward(q),S))}return typeof A.evaluate=="function"?{evaluate(...$){const U=A.evaluate.apply(void 0,$),q=N.evaluate.apply(void 0,$);if(U!==void 0&&q!==void 0)return O(U,q,S)}}:O(A,N,S)}function KN(h,l,u){return l.type==="color"?u=Xn.parse(u):l.type==="formatted"?u=Oo.fromString(u.toString()):l.type==="resolvedImage"?u=zl.build(u.toString()):n0(u)===l.type||l.type==="enum"&&l.values[u]||(u=void 0),Rd(u,h.default,l.default)}Ma.register(Bg,{error:[{kind:"error"},[di],(h,[l])=>{throw new ea(l.evaluate(h))}],typeof:[di,[gi],(h,[l])=>da(Cs(l.evaluate(h)))],"to-rgba":[el(Dr,4),[Sl],(h,[l])=>l.evaluate(h).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[el(Dr,4),[Sl],(h,[l])=>l.evaluate(h).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[Sl,[Dr,Dr,Dr],zN],rgba:[Sl,[Dr,Dr,Dr,Dr],zN],hsl:[Sl,[Dr,Dr,Dr],UN],hsla:[Sl,[Dr,Dr,Dr,Dr],UN],has:{type:pi,overloads:[[[di],(h,[l])=>b0(l.evaluate(h),h.properties())],[[di,Sf],(h,[l,u])=>b0(l.evaluate(h),u.evaluate(h))]]},get:{type:gi,overloads:[[[di],(h,[l])=>sb(l.evaluate(h),h.properties())],[[di,Sf],(h,[l,u])=>sb(l.evaluate(h),u.evaluate(h))]]},"feature-state":[gi,[di],(h,[l])=>sb(l.evaluate(h),h.featureState||{})],properties:[Sf,[],h=>h.properties()],"geometry-type":[di,[],h=>h.geometryType()],worldview:[di,[],h=>h.globals.worldview||""],"is-active-floor":[pi,kf(di),(h,l)=>{if(!(h.globals&&h.globals.activeFloors&&h.globals.activeFloors.size>0))return!1;if(l.length===0)return!0;const u=h.globals.activeFloors;return l.some(m=>{const x=m.evaluate(h);return u.has(x)})}],id:[gi,[],h=>h.id()],zoom:[Dr,[],h=>h.globals.zoom],pitch:[Dr,[],h=>h.globals.pitch||0],"distance-from-center":[Dr,[],h=>h.distanceFromCenter()],"measure-light":[Dr,[di],(h,[l])=>h.measureLight(l.evaluate(h))],"heatmap-density":[Dr,[],h=>h.globals.heatmapDensity||0],"line-progress":[Dr,[],h=>h.globals.lineProgress||0],"raster-value":[Dr,[],h=>h.globals.rasterValue||0],"raster-particle-speed":[Dr,[],h=>h.globals.rasterParticleSpeed||0],"sky-radial-progress":[Dr,[],h=>h.globals.skyRadialProgress||0],accumulated:[gi,[],h=>h.globals.accumulated===void 0?null:h.globals.accumulated],"+":[Dr,kf(Dr),(h,l)=>{let u=0;for(const m of l)u+=m.evaluate(h);return u}],"*":[Dr,kf(Dr),(h,l)=>{let u=1;for(const m of l)u*=m.evaluate(h);return u}],"-":{type:Dr,overloads:[[[Dr,Dr],(h,[l,u])=>l.evaluate(h)-u.evaluate(h)],[[Dr],(h,[l])=>-l.evaluate(h)]]},"/":[Dr,[Dr,Dr],(h,[l,u])=>l.evaluate(h)/u.evaluate(h)],"%":[Dr,[Dr,Dr],(h,[l,u])=>l.evaluate(h)%u.evaluate(h)],ln2:[Dr,[],()=>Math.LN2],pi:[Dr,[],()=>Math.PI],e:[Dr,[],()=>Math.E],"^":[Dr,[Dr,Dr],(h,[l,u])=>Math.pow(l.evaluate(h),u.evaluate(h))],sqrt:[Dr,[Dr],(h,[l])=>Math.sqrt(l.evaluate(h))],log10:[Dr,[Dr],(h,[l])=>Math.log(l.evaluate(h))/Math.LN10],ln:[Dr,[Dr],(h,[l])=>Math.log(l.evaluate(h))],log2:[Dr,[Dr],(h,[l])=>Math.log2(l.evaluate(h))],sin:[Dr,[Dr],(h,[l])=>Math.sin(l.evaluate(h))],cos:[Dr,[Dr],(h,[l])=>Math.cos(l.evaluate(h))],tan:[Dr,[Dr],(h,[l])=>Math.tan(l.evaluate(h))],asin:[Dr,[Dr],(h,[l])=>Math.asin(l.evaluate(h))],acos:[Dr,[Dr],(h,[l])=>Math.acos(l.evaluate(h))],atan:[Dr,[Dr],(h,[l])=>Math.atan(l.evaluate(h))],min:[Dr,kf(Dr),(h,l)=>Math.min(...l.map(u=>u.evaluate(h)))],max:[Dr,kf(Dr),(h,l)=>Math.max(...l.map(u=>u.evaluate(h)))],abs:[Dr,[Dr],(h,[l])=>Math.abs(l.evaluate(h))],round:[Dr,[Dr],(h,[l])=>{const u=l.evaluate(h);return u<0?-Math.round(-u):Math.round(u)}],floor:[Dr,[Dr],(h,[l])=>Math.floor(l.evaluate(h))],ceil:[Dr,[Dr],(h,[l])=>Math.ceil(l.evaluate(h))],"filter-==":[pi,[di,gi],(h,[l,u])=>h.properties()[l.value]===u.value],"filter-id-==":[pi,[gi],(h,[l])=>h.id()===l.value],"filter-type-==":[pi,[di],(h,[l])=>h.geometryType()===l.value],"filter-<":[pi,[di,gi],(h,[l,u])=>{const m=h.properties()[l.value],x=u.value;return typeof m==typeof x&&m{const u=h.id(),m=l.value;return typeof u==typeof m&&u":[pi,[di,gi],(h,[l,u])=>{const m=h.properties()[l.value],x=u.value;return typeof m==typeof x&&m>x}],"filter-id->":[pi,[gi],(h,[l])=>{const u=h.id(),m=l.value;return typeof u==typeof m&&u>m}],"filter-<=":[pi,[di,gi],(h,[l,u])=>{const m=h.properties()[l.value],x=u.value;return typeof m==typeof x&&m<=x}],"filter-id-<=":[pi,[gi],(h,[l])=>{const u=h.id(),m=l.value;return typeof u==typeof m&&u<=m}],"filter->=":[pi,[di,gi],(h,[l,u])=>{const m=h.properties()[l.value],x=u.value;return typeof m==typeof x&&m>=x}],"filter-id->=":[pi,[gi],(h,[l])=>{const u=h.id(),m=l.value;return typeof u==typeof m&&u>=m}],"filter-has":[pi,[gi],(h,[l])=>l.value in h.properties()],"filter-has-id":[pi,[],h=>h.id()!==null&&h.id()!==void 0],"filter-type-in":[pi,[el(di)],(h,[l])=>l.value.indexOf(h.geometryType())>=0],"filter-id-in":[pi,[el(gi)],(h,[l])=>l.value.indexOf(h.id())>=0],"filter-in-small":[pi,[di,el(gi)],(h,[l,u])=>u.value.indexOf(h.properties()[l.value])>=0],"filter-in-large":[pi,[di,el(gi)],(h,[l,u])=>function(m,x,b,S){for(;b<=S;){const A=b+S>>1;if(x[A]===m)return!0;x[A]>m?S=A-1:b=A+1}return!1}(h.properties()[l.value],u.value,0,u.value.length-1)],all:{type:pi,overloads:[[[pi,pi],(h,[l,u])=>l.evaluate(h)&&u.evaluate(h)],[kf(pi),(h,l)=>{for(const u of l)if(!u.evaluate(h))return!1;return!0}]]},any:{type:pi,overloads:[[[pi,pi],(h,[l,u])=>l.evaluate(h)||u.evaluate(h)],[kf(pi),(h,l)=>{for(const u of l)if(u.evaluate(h))return!0;return!1}]]},"!":[pi,[pi],(h,[l])=>!l.evaluate(h)],"is-supported-script":[pi,[di],(h,[l])=>{const u=h.globals&&h.globals.isSupportedScript;return!u||u(l.evaluate(h))}],upcase:[di,[di],(h,[l])=>l.evaluate(h).toUpperCase()],downcase:[di,[di],(h,[l])=>l.evaluate(h).toLowerCase()],concat:[di,kf(gi),(h,l)=>l.map(u=>Yr(u.evaluate(h))).join("")],"resolved-locale":[di,[Um],(h,[l])=>l.evaluate(h).resolvedLocale()],random:[Dr,[Dr,Dr,gi],(h,l)=>{const[u,m,x]=l.map(S=>S.evaluate(h));if(u>m||u===m)return u;let b;if(typeof x=="string")b=function(S){let A=0;if(S.length===0)return A;for(let N=0;NJSON.stringify(U)).join(", ")}, but found ${JSON.stringify($)} instead.`);return $}catch($){const U=$;return this._warningHistory[U.message]||(this._warningHistory[U.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${U.message}`)),this._defaultValue}}}function S0(h){return Array.isArray(h)&&h.length>0&&typeof h[0]=="string"&&h[0]in Bg}function Nf(h,l,u,m,x){const b=new Z_(Bg,[],l?function(A){const N={color:Sl,string:di,number:Dr,enum:di,boolean:pi,formatted:Jx,resolvedImage:e0};return A.type==="array"?el(N[A.value]||gi,A.length):N[A.type]}(l):void 0,void 0,void 0,u,m,x),S=b.parse(h,void 0,void 0,void 0,l&&l.type==="string"?{typeAnnotation:"coerce"}:void 0);return S?VN(new ub(S,l,u,m,x)):Cf(b.errors)}class $g{constructor(l,u,m,x){this.kind=l,this._styleExpression=u,this.isLightConstant=m,this.isLineProgressConstant=x,this.isStateDependent=l!=="constant"&&!Lg(u.expression),this.configDependencies=ab(u.expression),this.isIndoorDependent=ob(u.expression)}evaluateWithoutErrorHandling(l,u,m,x,b,S){return this._styleExpression.evaluateWithoutErrorHandling(l,u,m,x,b,S)}evaluate(l,u,m,x,b,S,A){return this._styleExpression.evaluate(l,u,m,x,b,S,void 0,void 0,A)}}class Zm{constructor(l,u,m,x,b,S){this.kind=l,this.zoomStops=m,this._styleExpression=u,this.isStateDependent=l!=="camera"&&!Lg(u.expression),this.isIndoorDependent=ob(u.expression),this.isLightConstant=b,this.isLineProgressConstant=S,this.configDependencies=ab(u.expression),this.interpolationType=x}evaluateWithoutErrorHandling(l,u,m,x,b,S){return this._styleExpression.evaluateWithoutErrorHandling(l,u,m,x,b,S)}evaluate(l,u,m,x,b,S){return this._styleExpression.evaluate(l,u,m,x,b,S)}interpolationFactor(l,u,m){return this.interpolationType?Fo.interpolationFactor(this.interpolationType,l,u,m):0}}function gE(h,l,u,m,x){if((h=Nf(h,l,u,m,x)).result==="error")return h;const b=h.value.expression,S=Km(b);if(!S&&!lb(l))return Cf([new pu("","data expressions not supported")]);const A=Pd(b,["zoom","pitch","distance-from-center"]);if(!A&&!mE(l))return Cf([new pu("","zoom expressions not supported")]);const N=Pd(b,["measure-light"]);if(!N&&!qN(l))return Cf([new pu("","measure-light expression not supported")]);const O=Pd(b,["line-progress"]);if(!O&&!function(q){return w0(q.expression,"line-progress")}(l))return Cf([new pu("","line-progress expression not supported")]);const $=l.expression&&l.expression.relaxZoomRestriction,U=Wu(b);return U||A||$?U instanceof pu?Cf([U]):U instanceof Fo&&!cb(l)?Cf([new pu("",'"interpolate" expressions cannot be used with this property')]):VN(U?new Zm(S&&O?"camera":"composite",h.value,U.labels,U instanceof Fo?U.interpolation:void 0,N,O):new $g(S&&O?"constant":"source",h.value,N,O)):Cf([new pu("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class db{constructor(l,u){this._parameters=l,this._specification=u,Object.assign(this,HN(this._parameters,this._specification))}static deserialize(l){return new db(l._parameters,l._specification)}static serialize(l){return{_parameters:l._parameters,_specification:l._specification}}}function Wu(h){let l=null;if(h instanceof J_)l=Wu(h.result);else if(h instanceof g0){for(const u of h.args)if(l=Wu(u),l)break}else(h instanceof f0||h instanceof Fo)&&h.input instanceof Ma&&h.input.name==="zoom"&&(l=h);return l instanceof pu||h.eachChild(u=>{const m=Wu(u);m instanceof pu?l=m:l&&m&&l!==m&&(l=new pu("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),l}var yE,YN,T0=function(){if(YN)return yE;YN=1,yE=l;var h=3;function l(u,m,x){var b=this.cells=[];if(u instanceof ArrayBuffer){this.arrayBuffer=u;var S=new Int32Array(this.arrayBuffer);u=S[0],this.d=(m=S[1])+2*(x=S[2]);for(var A=0;A=q[te+0]&&b>=q[te+1])?(N[X]=!0,A.push(U[X])):N[X]=!1}}},l.prototype._forEachCell=function(u,m,x,b,S,A,N,O){for(var $=this._convertToCellCoord(u),U=this._convertToCellCoord(m),q=this._convertToCellCoord(x),K=this._convertToCellCoord(b),X=$;X<=q;X++)for(var te=U;te<=K;te++){var ie=this.d*te+X;if((!O||O(this._convertFromCellCoord(X),this._convertFromCellCoord(te),this._convertFromCellCoord(X+1),this._convertFromCellCoord(te+1)))&&S.call(this,u,m,x,b,ie,A,N,O))return}},l.prototype._convertFromCellCoord=function(u){return(u-this.padding)/this.scale},l.prototype._convertToCellCoord=function(u){return Math.max(0,Math.min(this.d-1,Math.floor(u*this.scale)+this.padding))},l.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var u=this.cells,m=h+this.cells.length+1+1,x=0,b=0;b=0||(x[b]=Th(h[b],l)));h instanceof Error&&(x.message=h.message)}if(x.$name)throw new Error("$name property is reserved for worker serialization logic.");return m!=="Object"&&(x.$name=m),x}throw new Error("can't serialize object of type "+typeof h)}function If(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||E0(h)||h instanceof ImageBitmap||ArrayBuffer.isView(h)||h instanceof ImageData)return h;if(Array.isArray(h))return h.map(If);if(typeof h=="object"){const l=h.$name||"Object";if(l==="Map"){const x=h.entries||[],b=new Map;for(let S=0;Sh>=1536&&h<=1791,hb=h=>h>=1872&&h<=1919,fb=h=>h>=2208&&h<=2303,mb=h=>h>=11904&&h<=12031,Eh=h=>h>=12032&&h<=12255,xE=h=>h>=12272&&h<=12287,j0=h=>h>=12288&&h<=12351,A0=h=>h>=12352&&h<=12447,Qm=h=>h>=12448&&h<=12543,vE=h=>h>=12544&&h<=12591,pb=h=>h>=12704&&h<=12735,Ld=h=>h>=12736&&h<=12783,XN=h=>h>=12784&&h<=12799,QN=h=>h>=12800&&h<=13055,JN=h=>h>=13056&&h<=13311,_E=h=>h>=13312&&h<=19903,gb=h=>h>=19968&&h<=40959,k0=h=>h>=40960&&h<=42127,bE=h=>h>=42128&&h<=42191,wE=h=>h>=44032&&h<=55215,yb=h=>h>=63744&&h<=64255,SE=h=>h>=64336&&h<=65023,eI=h=>h>=65040&&h<=65055,TE=h=>h>=65072&&h<=65103,tI=h=>h>=65104&&h<=65135,EE=h=>h>=65136&&h<=65279,jE=h=>h>=65280&&h<=65519;function AE(h){for(const l of h)if(kE(l.charCodeAt(0)))return!0;return!1}function V5(h){for(const l of h)if(!q5(l.charCodeAt(0)))return!1;return!0}function q5(h){return!(ZN(h)||hb(h)||fb(h)||SE(h)||EE(h))}function G5(h){return!(h<11904||!(pb(h)||vE(h)||TE(h)||yb(h)||JN(h)||mb(h)||Ld(h)||j0(h)||_E(h)||gb(h)||QN(h)||jE(h)||A0(h)||xE(h)||Eh(h)||XN(h)||Qm(h)||eI(h)||bE(h)||k0(h)))}function kE(h){return!(h!==746&&h!==747&&(h<4352||!(pb(h)||vE(h)||TE(h)&&!(h>=65097&&h<=65103)||yb(h)||JN(h)||mb(h)||Ld(h)||!(!j0(h)||h>=12296&&h<=12305||h>=12308&&h<=12319||h===12336)||_E(h)||gb(h)||QN(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)||wE(h)||A0(h)||xE(h)||(l=>l>=12688&&l<=12703)(h)||Eh(h)||XN(h)||Qm(h)&&h!==12540||!(!jE(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)||!(!tI(h)||h>=65112&&h<=65118||h>=65123&&h<=65126)||(l=>l>=5120&&l<=5759)(h)||(l=>l>=6320&&l<=6399)(h)||eI(h)||(l=>l>=19904&&l<=19967)(h)||k0(h)||bE(h))))}function rI(h){return h===12312||h===12313||h===12316||h===12540||h===12448}function Jm(h){return!(kE(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)||j0(l)||Qm(l)||(u=>u>=57344&&u<=63743)(l)||TE(l)||tI(l)||jE(l)||l===8734||l===8756||l===8757||l>=9984&&l<=10087||l>=10102&&l<=10131||l===65532||l===65533)}(h))}function nI(h){return ZN(h)||hb(h)||fb(h)||SE(h)||EE(h)}function CE(h){return h>=1424&&h<=2303||SE(h)||EE(h)}function xb(h,l){return!(!l&&CE(h)||h>=2304&&h<=3583||h>=3840&&h<=4255||(u=>u>=6016&&u<=6143)(h))}function H5(h){for(const l of h)if(CE(l.charCodeAt(0)))return!0;return!1}const fc={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let Dd=null,tl=fc.unavailable,Ic=null;const iI=function(h){h&&typeof h=="string"&&h.indexOf("NetworkError")>-1&&(tl=fc.error),Dd&&Dd(h)};function NE(){IE.fire(new Uu("pluginStateChange",{pluginStatus:tl,pluginURL:Ic}))}const IE=new Qx,PE=function(){return tl},sI=function(){if(tl!==fc.deferred||!Ic)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");tl=fc.loading,NE(),Ic&&Sg({url:Ic},h=>{h?iI(h):(tl=fc.loaded,NE())})},jh={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>tl===fc.loaded||jh.applyArabicShaping!=null,isLoading:()=>tl===fc.loading,setState(h){tl=h.pluginStatus,Ic=h.pluginURL},isParsing:()=>tl===fc.parsing,isParsed:()=>tl===fc.parsed,getPluginURL:()=>Ic},aI=function(){jh.isLoading()||jh.isLoaded()||PE()!=="deferred"||sI()};class si{constructor(l,u){this.zoom=l,u?(this.now=u.now,this.fadeDuration=u.fadeDuration,this.transition=u.transition,this.pitch=u.pitch,this.brightness=u.brightness,this.worldview=u.worldview,this.activeFloors=u.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(l){return function(u,m){for(const x of u)if(!xb(x.charCodeAt(0),m))return!1;return!0}(l,jh.isLoaded())}}class Ug{constructor(l,u,m,x,b){this.property=l,this.value=u,this.expression=function(S,A,N,O,$){if(pE(S))return new db(S,A);if(S0(S)||Array.isArray(S)&&S.length>0){const U=gE(S,A,N,O,$);if(U.result==="error")throw new Error(U.value.map(q=>`${q.key}: ${q.message}`).join(", "));return U.value}{let U=S;return typeof S=="string"&&A.type==="color"&&(U=Xn.parse(S)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>U}}}(u===void 0?l.specification.default:u,l.specification,m,x,b)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(l,u,m,x){return this.property.possiblyEvaluate(this,l,u,m,x)}}class vb{constructor(l,u,m,x){this.property=l,this.value=new Ug(l,void 0,u,m,x)}transitioned(l,u){return new Vg(this.property,this.value,u,Object.assign({},l.transition,this.transition),l.now)}untransitioned(){return new Vg(this.property,this.value,null,{},0)}}class _b{constructor(l,u,m,x){this._properties=l,this._values=Object.create(l.defaultTransitionablePropertyValues),this._scope=u,this._options=m,this._iconImageUseTheme=x,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(l){return hr(this._values[l].value.value)}setValue(l,u){this._values.hasOwnProperty(l)||(this._values[l]=new vb(this._values[l].property,this._scope,this._options,this._iconImageUseTheme)),this._values[l].value=new Ug(this._values[l].property,u===null?void 0:hr(u),this._scope,this._options,this._iconImageUseTheme),this._values[l].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[l].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[l].value.isIndoorDependent())}setTransitionOrValue(l,u){u&&(this._options=u);const m=this._properties.properties;if(l)for(const x in l){const b=l[x];if(x.endsWith("-transition")){const S=x.slice(0,-11);m[S]&&this.setTransition(S,b)}else m.hasOwnProperty(x)&&this.setValue(x,b)}}getTransition(l){return hr(this._values[l].transition)}setTransition(l,u){this._values.hasOwnProperty(l)||(this._values[l]=new vb(this._values[l].property)),this._values[l].transition=hr(u)||void 0}serialize(){const l={};for(const u of Object.keys(this._values)){const m=this.getValue(u);m!==void 0&&(l[u]=m);const x=this.getTransition(u);x!==void 0&&(l[`${u}-transition`]=x)}return l}transitioned(l,u){const m=new RE(this._properties);for(const x of Object.keys(this._values))m._values[x]=this._values[x].transitioned(l,u._values[x]);return m}untransitioned(){const l=new RE(this._properties);for(const u of Object.keys(this._values))l._values[u]=this._values[u].untransitioned();return l}isIndoorDependent(){return this._isIndoorDependent}}class Vg{constructor(l,u,m,x,b){const S=x.delay||0,A=x.duration||0;b=b||0,this.property=l,this.value=u,this.begin=b+S,this.end=this.begin+A,l.specification.transition&&(x.delay||x.duration)&&(this.prior=m)}possiblyEvaluate(l,u,m){const x=l.now||0,b=this.value.possiblyEvaluate(l,u,m),S=this.prior;if(S){if(x>this.end)return this.prior=null,b;if(this.value.isDataDriven())return this.prior=null,b;if(x":1,">=":1,"<":1,"<=":1,"in":1,"!in":1,"all":1,"any":1,"none":1,"has":1,"!has":1}},"geometry_type":{"type":"enum","values":{"Point":1,"LineString":1,"Polygon":1}},"function":{"expression":{"type":"expression"},"stops":{"type":"array","value":"function_stop"},"base":{"type":"number","default":1,"minimum":0},"property":{"type":"string","default":"$zoom"},"type":{"type":"enum","values":{"identity":1,"exponential":1,"interval":1,"categorical":1},"default":"exponential"},"colorSpace":{"type":"enum","values":{"rgb":1,"lab":1,"hcl":1},"default":"rgb"},"default":{"type":"*"}},"function_stop":{"type":"array","minimum":0,"maximum":24,"value":["number","color"],"length":2},"expression":{"type":"array","value":"*","minimum":1},"fog":{"range":{"type":"array","default":[0.5,10],"minimum":-20,"maximum":20,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"high-color":{"type":"color","default":"#245cdf","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"space-color":{"type":"color","default":["interpolate",["linear"],["zoom"],4,"#010b19",7,"#367ab9"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"horizon-blend":{"type":"number","default":["interpolate",["linear"],["zoom"],4,0.2,7,0.1],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"star-intensity":{"type":"number","default":["interpolate",["linear"],["zoom"],5,0.35,6,0],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vertical-range":{"type":"array","default":[0,0],"minimum":0,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}}},"snow":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.85],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.3],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette-color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"center-thinning":{"type":"number","default":0.4,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"direction":{"type":"array","default":[0,50],"minimum":0,"maximum":360,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"flake-size":{"type":"number","default":0.71,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true}},"rain":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.5],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#03113d",0.3,"#a8adbc"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"opacity":{"type":"number","default":["interpolate",["linear"],["measure-light","brightness"],0,0.88,1,0.7],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,1],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette-color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#001736",0.3,"#464646"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"center-thinning":{"type":"number","default":0.57,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"direction":{"type":"array","default":[0,80],"minimum":0,"maximum":360,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"droplet-size":{"type":"array","default":[2.6,18.2],"minimum":0,"maximum":50,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"distortion-strength":{"type":"number","default":0.7,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true}},"camera":{"camera-projection":{"type":"enum","values":{"perspective":1,"orthographic":1},"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"default":"perspective"}},"colorTheme":{"data":{"type":"string","expression":{}}},"indoor_source":{"sourceId":{"type":"string"},"sourceLayers":{"type":"array","value":"string"}},"indoor":{"*":{"type":"indoor_source"}},"light":{"anchor":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"position":{"type":"array","default":[1.15,210,30],"length":3,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom"]},"use-theme":true,"transition":true},"intensity":{"type":"number","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"projection":{"name":{"type":"enum","values":{"albers":1,"equalEarth":1,"equirectangular":1,"lambertConformalConic":1,"mercator":1,"naturalEarth":1,"winkelTripel":1,"globe":1},"default":"mercator"},"center":{"type":"array","length":2,"value":"number","minimum":[-180,-90],"maximum":[180,90]},"parallels":{"type":"array","length":2,"value":"number","minimum":[-90,-90],"maximum":[90,90]}},"terrain":{"source":{"type":"string"},"exaggeration":{"type":"number","default":1,"minimum":0,"maximum":1000,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"paint":["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_building","paint_symbol","paint_raster","paint_raster-particle","paint_hillshade","paint_background","paint_sky","paint_model"],"paint_fill":{"fill-antialias":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-outline-color":{"type":"color","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"fill-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-z-offset":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-bridge-guard-rail-color":{"type":"color","default":"rgba(241, 236, 225, 255)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature"]},"property-type":"data-driven"},"fill-tunnel-structure-color":{"type":"color","default":"rgba(241, 236, 225, 255)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature"]},"property-type":"data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-extrusion-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"fill-extrusion-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-extrusion-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-height":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-height-alignment":{"type":"enum","values":{"terrain":1,"flat":1},"default":"flat"},"fill-extrusion-base-alignment":{"type":"enum","values":{"terrain":1,"flat":1},"default":"terrain"},"fill-extrusion-vertical-gradient":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-extrusion-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-wall-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-flood-light-color":{"type":"color","default":"#ffffff","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-wall-radius":{"property-type":"data-driven","type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-radius":{"property-type":"data-driven","type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-vertical-scale":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-rounded-roof":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-extrusion-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"fill-extrusion-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"fill-extrusion-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"property-type":"data-driven"},"fill-extrusion-line-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-extrusion-cast-shadows":{"type":"boolean","default":true}},"paint_building":{"building-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"parameters":[]},"transition":true},"building-ambient-occlusion-ground-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"building-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"building-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-vertical-scale":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-cast-shadows":{"type":"boolean","default":true},"building-color":{"type":"color","default":"rgba(193, 154, 127, 1)","use-theme":true,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"property-type":"data-driven"},"building-emissive-strength":{"type":"number","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"property-type":"data-driven"},"building-facade-emissive-chance":{"type":"number","default":0.35,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["measure-light","zoom"]}},"building-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"building-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"building-flood-light-color":{"type":"color","default":"#ffffff","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"building-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"building-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_line":{"line-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"line-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"line-width":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light","line-progress"]},"property-type":"data-driven"},"line-gap-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-offset":{"type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-dasharray":{"type":"array","value":"number","minimum":0,"expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-gradient":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["line-progress"]}},"line-trim-offset":{"type":"array","value":"number","length":2,"default":[0,0],"minimum":[0,0],"maximum":[1,1]},"line-trim-fade-range":{"type":"array","value":"number","length":2,"default":[0,0],"minimum":[0,0],"maximum":[1,1],"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-trim-color":{"type":"color","default":"transparent","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-driven"},"line-border-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-border-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"line-blend-mode":{"type":"enum","values":{"default":1,"multiply":1,"additive":1},"default":"default","expression":{"parameters":["zoom"]}}},"paint_circle":{"circle-radius":{"type":"number","default":5,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-blur":{"type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"circle-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"circle-pitch-scale":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"circle-pitch-alignment":{"type":"enum","values":{"map":1,"viewport":1},"default":"viewport","expression":{"parameters":["zoom"]}},"circle-stroke-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-stroke-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-stroke-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_heatmap":{"heatmap-radius":{"type":"number","default":30,"minimum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"heatmap-weight":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"heatmap-intensity":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"heatmap-color":{"type":"color","default":["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",0.1,"royalblue",0.3,"cyan",0.5,"lime",0.7,"yellow",1,"red"],"use-theme":true,"expression":{"interpolated":true,"parameters":["heatmap-density"]}},"heatmap-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_symbol":{"icon-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-occlusion-opacity":{"type":"number","minimum":0,"maximum":1,"default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"appearance":true,"property-type":"data-driven"},"text-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"appearance":true,"property-type":"data-driven"},"icon-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-halo-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-halo-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"appearance":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"icon-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"icon-image-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"text-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-occlusion-opacity":{"type":"number","minimum":0,"maximum":1,"default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"overridable":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-halo-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-halo-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"appearance":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"text-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"icon-color-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{}},"icon-color-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{}},"icon-color-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"icon-color-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{}},"symbol-z-offset":{"type":"number","default":0,"minimum":0,"transition":true,"appearance":true,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"}},"paint_raster":{"raster-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-color":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["raster-value"]}},"raster-color-mix":{"type":"array","default":[0.2126,0.7152,0.0722,0],"length":4,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-color-range":{"type":"array","length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-hue-rotate":{"type":"number","default":0,"period":360,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-resampling":{"type":"enum","values":{"linear":1,"nearest":1},"default":"linear","expression":{"parameters":["zoom"]}},"raster-fade-duration":{"type":"number","default":300,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"raster-array-band":{"type":"string"},"raster-elevation":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-elevation-reference":{"type":"enum","values":{"sea":1,"ground":1},"default":"sea","expression":{}}},"paint_raster-particle":{"raster-particle-array-band":{"type":"string"},"raster-particle-count":{"type":"number","default":512,"minimum":1},"raster-particle-color":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["raster-particle-speed"]}},"raster-particle-max-speed":{"type":"number","default":1,"minimum":1},"raster-particle-speed-factor":{"type":"number","default":0.2,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-particle-fade-opacity-factor":{"type":"number","default":0.98,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-particle-reset-rate-factor":{"type":"number","default":0.8,"minimum":0,"maximum":1},"raster-particle-elevation":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_hillshade":{"hillshade-illumination-direction":{"type":"number","default":335,"minimum":0,"maximum":359,"expression":{"interpolated":true,"parameters":["zoom"]}},"hillshade-illumination-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"viewport","expression":{"parameters":["zoom"]}},"hillshade-exaggeration":{"type":"number","default":0.5,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"hillshade-shadow-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-highlight-color":{"type":"color","default":"#FFFFFF","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-accent-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_background":{"background-pitch-alignment":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":[]}},"background-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"background-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom"]}},"background-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"background-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_sky":{"sky-type":{"type":"enum","values":{"gradient":1,"atmosphere":1},"default":"atmosphere","expression":{"parameters":["zoom"]}},"sky-atmosphere-sun":{"type":"array","value":"number","length":2,"minimum":[0,0],"maximum":[360,180],"expression":{"parameters":["zoom"]}},"sky-atmosphere-sun-intensity":{"type":"number","default":10,"minimum":0,"maximum":100},"sky-gradient-center":{"type":"array","value":"number","default":[0,0],"length":2,"minimum":[0,0],"maximum":[360,180],"expression":{"parameters":["zoom"]}},"sky-gradient-radius":{"type":"number","default":90,"minimum":0,"maximum":180,"expression":{"parameters":["zoom"]}},"sky-gradient":{"type":"color","default":["interpolate",["linear"],["sky-radial-progress"],0.8,"#87ceeb",1,"white"],"use-theme":true,"expression":{"interpolated":true,"parameters":["sky-radial-progress"]}},"sky-atmosphere-halo-color":{"type":"color","default":"white","use-theme":true},"sky-atmosphere-color":{"type":"color","default":"white","use-theme":true},"sky-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_model":{"model-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"property-type":"data-driven"},"model-rotation":{"type":"array","value":"number","length":3,"default":[0,0,0],"period":360,"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-scale":{"type":"array","value":"number","length":3,"default":[1,1,1],"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-translation":{"type":"array","value":"number","length":3,"default":[0,0,0],"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-color":{"type":"color","default":"#ffffff","property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light","zoom"]},"use-theme":true,"transition":true},"model-color-mix-intensity":{"type":"number","property-type":"data-driven","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-type":{"type":"enum","values":{"common-3d":1,"location-indicator":1},"default":"common-3d"},"model-cast-shadows":{"type":"boolean","default":true},"model-receive-shadows":{"type":"boolean","default":true},"model-ambient-occlusion-intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"model-emissive-strength":{"type":"number","property-type":"data-driven","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-roughness":{"type":"number","default":1,"minimum":0,"maximum":1,"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state"]},"transition":true},"model-height-based-emissive-strength-multiplier":{"type":"array","default":[1,1,1,1,0],"length":5,"value":"number","property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"model-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"model-elevation-reference":{"type":"enum","values":{"sea":1,"ground":1,"hd-road-markup":1},"default":"ground","expression":{}},"model-ignore-line-cutout":{"type":"boolean","default":false,"expression":{}}},"transition":{"duration":{"type":"number","default":300,"minimum":0},"delay":{"type":"number","default":0,"minimum":0}},"promoteId":{"*":{"type":"*"}}}');function oI(h){return h instanceof Number||h instanceof String||h instanceof Boolean?h.valueOf():h}function bb(h){if(Array.isArray(h))return h.map(bb);if(h instanceof Object&&!(h instanceof Number||h instanceof String||h instanceof Boolean)){const l={};for(const u in h)l[u]=bb(h[u]);return l}return oI(h)}function DE(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(!DE(l)&&typeof l!="boolean")return!1;return!0;default:return!0}}function wb(h,l="",u=null,m="fill"){if(h==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};DE(h)||(h=Sb(h));const x=h;let b=!0;try{b=function($){if(!Gg($))return $;let U=bb($);return cI(U),U=lI(U),U}(x)}catch{console.warn(`Failed to extract static filter. Filter will continue working, but at higher memory usage and slower framerate. This is most likely a bug, please report this via https://github.com/mapbox/mapbox-gl-js/issues/new?assignees=&labels=&template=Bug_report.md and paste the contents of this message in the report. Thank you! Filter Expression: ${JSON.stringify(x,null,2)} `)}let S=null,A=null;if(m!=="background"&&m!=="sky"&&m!=="slot"){A=nt[`filter_${m}`];const $=Nf(b,A,l,u);if($.result==="error")throw new Error($.value.map(U=>`${U.key}: ${U.message}`).join(", "));S=(U,q,K)=>$.value.evaluate(U,q,{},K)}let N=null,O=null;if(b!==x){const $=Nf(x,A,l,u);if($.result==="error")throw new Error($.value.map(U=>`${U.key}: ${U.message}`).join(", "));N=(U,q,K,X,te)=>$.value.evaluate(U,q,{},K,void 0,void 0,X,te),O=!Km($.value.expression)}return{filter:S,dynamicFilter:N||void 0,needGeometry:dI(b),needFeature:!!O}}function lI(h){if(!Array.isArray(h))return h;const l=function(u){if(uI.has(u[0])){for(let m=1;mlI(u))}function cI(h){let l=!1;const u=[];if(h[0]==="case"){for(let m=1;m",">=","<","<=","to-boolean"]);function W5(h,l){return hl?1:0}function dI(h){if(!Array.isArray(h))return!1;if(h[0]==="within"||h[0]==="distance")return!0;for(let l=1;l"||l==="<="||l===">="?Tb(h[1],h[2],l):l==="any"?(u=h.slice(1),["any"].concat(u.map(Sb))):l==="all"?["all"].concat(h.slice(1).map(Sb)):l==="none"?["all"].concat(h.slice(1).map(Sb).map(C0)):l==="in"?ME(h[1],h.slice(2)):l==="!in"?C0(ME(h[1],h.slice(2))):l==="has"?kh(h[1]):l!=="!has"||C0(kh(h[1]));var u}function Tb(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 ME(h,l){if(l.length===0)return!1;switch(h){case"$type":return["filter-type-in",["literal",l]];case"$id":return["filter-id-in",["literal",l]];default:return l.length>200&&!l.some(u=>typeof u!=typeof l[0])?["filter-in-large",h,["literal",l.sort(W5)]]:["filter-in-small",h,["literal",l]]}}function kh(h){switch(h){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",h]}}function C0(h){return["!",h]}const N0="";function tp(h,l){return l?`${h}${N0}${l}`:h}function hI(h){const l=h.indexOf(N0);return l>=0?h.slice(l+1):""}let fI;const OE=()=>fI||(fI=new rs({"icon-size":new Ht(nt.layout_symbol["icon-size"]),"icon-image":new Ht(nt.layout_symbol["icon-image"]),"icon-rotate":new Ht(nt.layout_symbol["icon-rotate"]),"icon-offset":new Ht(nt.layout_symbol["icon-offset"]),"text-size":new Ht(nt.layout_symbol["text-size"]),"text-rotate":new Ht(nt.layout_symbol["text-rotate"]),"text-offset":new Ht(nt.layout_symbol["text-offset"])}));let FE;const BE=()=>FE||(FE=new rs({"icon-opacity":new Ht(nt.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new Ht(nt.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new Ht(nt.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new Ht(nt.paint_symbol["text-emissive-strength"]),"icon-color":new Ht(nt.paint_symbol["icon-color"]),"icon-halo-color":new Ht(nt.paint_symbol["icon-halo-color"]),"icon-halo-width":new Ht(nt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Ht(nt.paint_symbol["icon-halo-blur"]),"icon-translate":new Ht(nt.paint_symbol["icon-translate"]),"text-opacity":new Ht(nt.paint_symbol["text-opacity"]),"text-occlusion-opacity":new Ht(nt.paint_symbol["text-occlusion-opacity"]),"text-color":new Ht(nt.paint_symbol["text-color"],{runtimeType:Sl,getOverride:h=>h.textColor,hasOverride:h=>!!h.textColor}),"text-halo-color":new Ht(nt.paint_symbol["text-halo-color"]),"text-halo-width":new Ht(nt.paint_symbol["text-halo-width"]),"text-halo-blur":new Ht(nt.paint_symbol["text-halo-blur"]),"text-translate":new Ht(nt.paint_symbol["text-translate"]),"symbol-z-offset":new Ht(nt.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"})}));class K5{constructor(l,u,m,x,b,S){this._conditionSpec=l,this._propertiesSpec=m;const A=Nf(l,nt.appearance.condition);if(A.result==="success"&&(this.condition=A.value),this.name=u,m){this.layoutProperties=new Ah(OE()),this.unevaluatedLayout=new LE(OE(),x,b,S),this.paintProperties=new Ah(BE()),this.unevaluatedPaint=new LE(BE(),x,b,"");for(const N in m)N in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(N,m[N]):N in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(N,m[N])}}isActive(l){return!(this.condition||!l.isHidden||this.name!=="hidden")||this.condition.evaluate(l.globals,l.feature,l.featureState,l.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(l){return this.layoutProperties.get(l)}getPaintProperty(l){return this.paintProperties.get(l)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(l){return this.unevaluatedLayout._values[l]}getUnevaluatedPaintProperty(l){return this.unevaluatedPaint._values[l]}recalculate(l,u,m){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(l,void 0,u,m)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(l,void 0,u,""))}serialize(){const l={};l.condition=this.condition.expression.serialize(),this.name&&(l.name=this.name);const u=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},m=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},x=Object.assign({},u,m);return Object.keys(x).length>0&&(l.properties=x),l}hasIconLayoutProperties(){const l=this.hasLayoutProperty("icon-image"),u=this.hasLayoutProperty("icon-size"),m=this.hasLayoutProperty("icon-offset"),x=this.hasLayoutProperty("icon-rotate");return l||u||m||x}hasTextLayoutProperties(){const l=this.hasLayoutProperty("text-size"),u=this.hasLayoutProperty("text-offset"),m=this.hasLayoutProperty("text-rotate");return l||u||m}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(l=>!l.endsWith("-use-theme")).some(l=>(l.startsWith("icon-")||l==="symbol-z-offset")&&this.hasPaintProperty(l))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(l=>!l.endsWith("-use-theme")).some(l=>(l.startsWith("text-")||l==="symbol-z-offset")&&this.hasPaintProperty(l))}hasLayoutProperty(l){return this.unevaluatedLayout&&this.unevaluatedLayout._values[l].value!==void 0}hasPaintProperty(l){return this.unevaluatedPaint&&this.unevaluatedPaint._values[l].value!==void 0}}const $E="-transition",Y5=new Set(["fill","line","background","hillshade","raster"]);class rl extends Qx{constructor(l,u,m,x,b,S){if(super(),this.id=l.id,this.fqid=tp(this.id,m),this.type=l.type,this.scope=m,this.lut=x,this.options=b,this.iconImageUseTheme=S,this.appearances=new Array,this.appearancesVersion=0,this._featureFilter={filter:()=>!0,needGeometry:!1,needFeature:!1},this._filterCompiled=!1,this.expressionDependencies={isIndoorDependent:!1,configDependencies:new Set},l.type!=="custom"){if(this.metadata=l.metadata,this.minzoom=l.minzoom,this.maxzoom=l.maxzoom,l.type&&l.type!=="background"&&l.type!=="sky"&&l.type!=="slot"){this.source=l.source,this.sourceLayer=l["source-layer"],this.filter=l.filter;const A=Nf(this.filter,nt[`filter_${l.type}`]);A.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...A.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||A.value.isIndoorDependent)}if(l.slot&&(this.slot=l.slot),l.appearances&&this.setAppearances(l.appearances),u.layout&&(this._unevaluatedLayout=new LE(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 _b(u.paint,this.scope,b);for(const A in l.paint)this.setPaintProperty(A,l.paint[A]);for(const A in l.layout)this.setLayoutProperty(A,l.layout[A]);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 Ah(u.paint)}}}onAdd(l){}onRemove(l){}isDraped(l){return!this.is3D(!0)&&Y5.has(this.type)}getLayoutProperty(l){return l==="visibility"?this.visibility:this._unevaluatedLayout.getValue(l)}setLayoutProperty(l,u){if(this.type==="custom"&&l==="visibility")return void(this.visibility=u);const m=this._unevaluatedLayout;m._properties.properties[l]&&(m.setValue(l,u),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...m.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||m.isIndoorDependent(),l==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(l){this.appearances=[],l.forEach(u=>{this.appearances.push(new K5(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($E)?this._transitionablePaint.getTransition(l.slice(0,-11)):this._transitionablePaint.getValue(l)}isPaintProperty(l){return!!this._transitionablePaint._properties.properties[l]}setPaintProperty(l,u){const m=this._transitionablePaint,x=m._properties.properties;if(l.endsWith($E)){const U=l.slice(0,-11);return x[U]&&m.setTransition(U,u||void 0),!1}if(!x[l])return!1;const b=m._values[l],S=b.value.isDataDriven(),A=b.value;m.setValue(l,u),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...m.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||m.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(l);const N=m._values[l].value,O=N.isDataDriven(),$=l.endsWith("pattern")||l==="line-dasharray";return O||S||$||this._handleOverridablePaintPropertyUpdate(l,A,N)}_handleSpecialPaintPropertyUpdate(l){}getProgramIds(){return null}getDefaultProgramParams(l,u,m){return null}_handleOverridablePaintPropertyUpdate(l,u,m){return!1}isHidden(l){return!!(this.minzoom&&l=this.maxzoom)||this.visibility==="none"}updateTransitions(l){this._transitioningPaint=this._transitionablePaint.transitioned(l,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(l,u){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(l,void 0,u,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(l,void 0,u)}serialize(){const l={id:this.id,type:this.type,slot:this.slot,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.appearances.length!==0&&(l.appearances=this.appearances.map(u=>u.serialize())),Rt(l,(u,m)=>!(u===void 0||m==="layout"&&!Object.keys(u).length||m==="paint"&&!Object.keys(u).length))}is3D(l){return!1}hasElevation(){return!1}isSky(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}hasShadowPass(){return!1}canCastShadows(){return!1}hasLightBeamPass(){return!1}cutoffRange(){return 0}tileCoverLift(){return 0}resize(){}_clear(){}isStateDependent(){for(const l in this.paint._values){const u=this.paint.get(l);if(u instanceof ep&&lb(u.property.specification)&&(u.value.kind==="source"||u.value.kind==="composite")&&u.value.isStateDependent)return!0}for(const l of this.appearances)if(!Lg(l.condition.expression))return!0;return!1}compileFilter(l){this._filterCompiled||(this._featureFilter=wb(this.filter,this.scope,l),this._filterCompiled=!0)}invalidateCompiledFilter(){this._filterCompiled=!1}dynamicFilter(){return this._featureFilter.dynamicFilter}dynamicFilterNeedsFeature(){return this._featureFilter.needFeature}dynamicFilterNeedsGeometry(){return this._featureFilter.needGeometry}getLayerRenderingStats(){return this._stats}resetLayerRenderingStats(l){this._stats&&(l.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(l,u,m){return{}}queryRadius(l){}queryIntersectsFeature(l,u,m,x,b,S,A,N,O,$){}}const Eb={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class I0{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 Z5=new ArrayBuffer(0);class Gi{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=Z5),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 Rn(h,l=1){let u=0,m=0;return{members:h.map(x=>{const b=Eb[x.type].BYTES_PER_ELEMENT,S=u=mI(u,Math.max(l,b)),A=x.components||1;return m=Math.max(m,b),u+=b*A,{name:x.name,type:x.type,components:A,offset:S}}),size:mI(u,Math.max(m,l)),alignment:l}}function mI(h,l){return Math.ceil(h/l)*l}class mc extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u){const m=this.length;return this.resize(m+1),this.emplace(m,l,u)}emplace(l,u,m){const x=2*l;return this.int16[x+0]=u,this.int16[x+1]=m,l}}mc.prototype.bytesPerElement=4,br(mc,"StructArrayLayout2i4");class Md extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,m)}emplace(l,u,m,x){const b=3*l;return this.int16[b+0]=u,this.int16[b+1]=m,this.int16[b+2]=x,l}}Md.prototype.bytesPerElement=6,br(Md,"StructArrayLayout3i6");class To extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,m,x)}emplace(l,u,m,x,b){const S=4*l;return this.int16[S+0]=u,this.int16[S+1]=m,this.uint16[S+2]=x,this.uint16[S+3]=b,l}}To.prototype.bytesPerElement=8,br(To,"StructArrayLayout2i2ui8");class Pc extends Gi{_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}}Pc.prototype.bytesPerElement=4,br(Pc,"StructArrayLayout1f4");class zE extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,m)}emplace(l,u,m,x){const b=4*l,S=2*l;return this.int16[b+0]=u,this.int16[b+1]=m,this.float32[S+1]=x,l}}zE.prototype.bytesPerElement=8,br(zE,"StructArrayLayout2i1f8");class UE extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,m)}emplace(l,u,m,x){const b=4*l;return this.int16[b+0]=u,this.int16[b+1]=m,this.int16[b+2]=x,l}}UE.prototype.bytesPerElement=8,br(UE,"StructArrayLayout3i8");class VE extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,m,x)}emplace(l,u,m,x,b){const S=4*l;return this.int16[S+0]=u,this.int16[S+1]=m,this.int16[S+2]=x,this.int16[S+3]=b,l}}VE.prototype.bytesPerElement=8,br(VE,"StructArrayLayout4i8");class qE extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b){const S=this.length;return this.resize(S+1),this.emplace(S,l,u,m,x,b)}emplace(l,u,m,x,b,S){const A=5*l;return this.int16[A+0]=u,this.int16[A+1]=m,this.int16[A+2]=x,this.int16[A+3]=b,this.int16[A+4]=S,l}}qE.prototype.bytesPerElement=10,br(qE,"StructArrayLayout5i10");class P0 extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,A){const N=this.length;return this.resize(N+1),this.emplace(N,l,u,m,x,b,S,A)}emplace(l,u,m,x,b,S,A,N){const O=6*l,$=12*l,U=3*l;return this.int16[O+0]=u,this.int16[O+1]=m,this.uint8[$+4]=x,this.uint8[$+5]=b,this.uint8[$+6]=S,this.uint8[$+7]=A,this.float32[U+2]=N,l}}P0.prototype.bytesPerElement=12,br(P0,"StructArrayLayout2i4ub1f12");class xu extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,m)}emplace(l,u,m,x){const b=3*l;return this.float32[b+0]=u,this.float32[b+1]=m,this.float32[b+2]=x,l}}xu.prototype.bytesPerElement=12,br(xu,"StructArrayLayout3f12");class Od extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b){const S=this.length;return this.resize(S+1),this.emplace(S,l,u,m,x,b)}emplace(l,u,m,x,b,S){const A=6*l,N=3*l;return this.uint16[A+0]=u,this.uint16[A+1]=m,this.uint16[A+2]=x,this.uint16[A+3]=b,this.float32[N+2]=S,l}}Od.prototype.bytesPerElement=12,br(Od,"StructArrayLayout4ui1f12");class Hg extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,m,x)}emplace(l,u,m,x,b){const S=4*l;return this.uint16[S+0]=u,this.uint16[S+1]=m,this.uint16[S+2]=x,this.uint16[S+3]=b,l}}Hg.prototype.bytesPerElement=8,br(Hg,"StructArrayLayout4ui8");class jb extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S){const A=this.length;return this.resize(A+1),this.emplace(A,l,u,m,x,b,S)}emplace(l,u,m,x,b,S,A){const N=6*l;return this.int16[N+0]=u,this.int16[N+1]=m,this.int16[N+2]=x,this.int16[N+3]=b,this.int16[N+4]=S,this.int16[N+5]=A,l}}jb.prototype.bytesPerElement=12,br(jb,"StructArrayLayout6i12");class GE extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,A,N,O,$,U,q){const K=this.length;return this.resize(K+1),this.emplace(K,l,u,m,x,b,S,A,N,O,$,U,q)}emplace(l,u,m,x,b,S,A,N,O,$,U,q,K){const X=12*l;return this.int16[X+0]=u,this.int16[X+1]=m,this.int16[X+2]=x,this.int16[X+3]=b,this.uint16[X+4]=S,this.uint16[X+5]=A,this.uint16[X+6]=N,this.uint16[X+7]=O,this.int16[X+8]=$,this.int16[X+9]=U,this.int16[X+10]=q,this.int16[X+11]=K,l}}GE.prototype.bytesPerElement=24,br(GE,"StructArrayLayout4i4ui4i24");class HE extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S){const A=this.length;return this.resize(A+1),this.emplace(A,l,u,m,x,b,S)}emplace(l,u,m,x,b,S,A){const N=10*l,O=5*l;return this.int16[N+0]=u,this.int16[N+1]=m,this.int16[N+2]=x,this.float32[O+2]=b,this.float32[O+3]=S,this.float32[O+4]=A,l}}HE.prototype.bytesPerElement=20,br(HE,"StructArrayLayout3i3f20");class Ch extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,m,x)}emplace(l,u,m,x,b){const S=4*l;return this.float32[S+0]=u,this.float32[S+1]=m,this.float32[S+2]=x,this.float32[S+3]=b,l}}Ch.prototype.bytesPerElement=16,br(Ch,"StructArrayLayout4f16");class R0 extends Gi{_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}}R0.prototype.bytesPerElement=4,br(R0,"StructArrayLayout1ul4");class vu extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u){const m=this.length;return this.resize(m+1),this.emplace(m,l,u)}emplace(l,u,m){const x=2*l;return this.uint16[x+0]=u,this.uint16[x+1]=m,l}}vu.prototype.bytesPerElement=4,br(vu,"StructArrayLayout2ui4");class Ab extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,A,N,O,$,U,q,K){const X=this.length;return this.resize(X+1),this.emplace(X,l,u,m,x,b,S,A,N,O,$,U,q,K)}emplace(l,u,m,x,b,S,A,N,O,$,U,q,K,X){const te=20*l,ie=10*l;return this.int16[te+0]=u,this.int16[te+1]=m,this.int16[te+2]=x,this.int16[te+3]=b,this.int16[te+4]=S,this.float32[ie+3]=A,this.float32[ie+4]=N,this.float32[ie+5]=O,this.float32[ie+6]=$,this.int16[te+14]=U,this.uint32[ie+8]=q,this.uint16[te+18]=K,this.uint16[te+19]=X,l}}Ab.prototype.bytesPerElement=40,br(Ab,"StructArrayLayout5i4f1i1ul2ui40");class L0 extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,A){const N=this.length;return this.resize(N+1),this.emplace(N,l,u,m,x,b,S,A)}emplace(l,u,m,x,b,S,A,N){const O=8*l;return this.int16[O+0]=u,this.int16[O+1]=m,this.int16[O+2]=x,this.int16[O+4]=b,this.int16[O+5]=S,this.int16[O+6]=A,this.int16[O+7]=N,l}}L0.prototype.bytesPerElement=16,br(L0,"StructArrayLayout3i2i2i16");class WE extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b){const S=this.length;return this.resize(S+1),this.emplace(S,l,u,m,x,b)}emplace(l,u,m,x,b,S){const A=4*l,N=8*l;return this.float32[A+0]=u,this.float32[A+1]=m,this.float32[A+2]=x,this.int16[N+6]=b,this.int16[N+7]=S,l}}WE.prototype.bytesPerElement=16,br(WE,"StructArrayLayout2f1f2i16");class D0 extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S){const A=this.length;return this.resize(A+1),this.emplace(A,l,u,m,x,b,S)}emplace(l,u,m,x,b,S,A){const N=20*l,O=5*l;return this.uint8[N+0]=u,this.uint8[N+1]=m,this.float32[O+1]=x,this.float32[O+2]=b,this.float32[O+3]=S,this.float32[O+4]=A,l}}D0.prototype.bytesPerElement=20,br(D0,"StructArrayLayout2ub4f20");class _s extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,l,u,m)}emplace(l,u,m,x){const b=3*l;return this.uint16[b+0]=u,this.uint16[b+1]=m,this.uint16[b+2]=x,l}}_s.prototype.bytesPerElement=6,br(_s,"StructArrayLayout3ui6");class kb extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,A,N,O,$,U,q,K,X,te,ie,ae,he,ue,ve,ke){const Ie=this.length;return this.resize(Ie+1),this.emplace(Ie,l,u,m,x,b,S,A,N,O,$,U,q,K,X,te,ie,ae,he,ue,ve,ke)}emplace(l,u,m,x,b,S,A,N,O,$,U,q,K,X,te,ie,ae,he,ue,ve,ke,Ie){const We=30*l,ze=15*l,Ge=60*l;return this.int16[We+0]=u,this.int16[We+1]=m,this.int16[We+2]=x,this.float32[ze+2]=b,this.float32[ze+3]=S,this.uint16[We+8]=A,this.uint16[We+9]=N,this.uint32[ze+5]=O,this.uint32[ze+6]=$,this.uint32[ze+7]=U,this.uint16[We+16]=q,this.uint16[We+17]=K,this.uint16[We+18]=X,this.float32[ze+10]=te,this.float32[ze+11]=ie,this.uint8[Ge+48]=ae,this.uint8[Ge+49]=he,this.uint8[Ge+50]=ue,this.uint32[ze+13]=ve,this.int16[We+28]=ke,this.uint8[Ge+58]=Ie,l}}kb.prototype.bytesPerElement=60,br(kb,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class KE extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,A,N,O,$,U,q,K,X,te,ie,ae,he,ue,ve,ke,Ie,We,ze,Ge,Ue,Ve,yt,wt,At,It,kt,$t){const mt=this.length;return this.resize(mt+1),this.emplace(mt,l,u,m,x,b,S,A,N,O,$,U,q,K,X,te,ie,ae,he,ue,ve,ke,Ie,We,ze,Ge,Ue,Ve,yt,wt,At,It,kt,$t)}emplace(l,u,m,x,b,S,A,N,O,$,U,q,K,X,te,ie,ae,he,ue,ve,ke,Ie,We,ze,Ge,Ue,Ve,yt,wt,At,It,kt,$t,mt){const Ct=20*l,Dt=40*l,Ut=80*l;return this.float32[Ct+0]=u,this.float32[Ct+1]=m,this.int16[Dt+4]=x,this.int16[Dt+5]=b,this.int16[Dt+6]=S,this.int16[Dt+7]=A,this.int16[Dt+8]=N,this.int16[Dt+9]=O,this.int16[Dt+10]=$,this.int16[Dt+11]=U,this.int16[Dt+12]=q,this.uint16[Dt+13]=K,this.uint16[Dt+14]=X,this.uint16[Dt+15]=te,this.uint16[Dt+16]=ie,this.uint16[Dt+17]=ae,this.uint16[Dt+18]=he,this.uint16[Dt+19]=ue,this.uint16[Dt+20]=ve,this.uint16[Dt+21]=ke,this.uint16[Dt+22]=Ie,this.uint16[Dt+23]=We,this.uint16[Dt+24]=ze,this.uint16[Dt+25]=Ge,this.uint16[Dt+26]=Ue,this.uint16[Dt+27]=Ve,this.uint32[Ct+14]=yt,this.float32[Ct+15]=wt,this.float32[Ct+16]=At,this.float32[Ct+17]=It,this.float32[Ct+18]=kt,this.uint8[Ut+76]=$t,this.uint16[Dt+39]=mt,l}}KE.prototype.bytesPerElement=80,br(KE,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class Cb extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S){const A=this.length;return this.resize(A+1),this.emplace(A,l,u,m,x,b,S)}emplace(l,u,m,x,b,S,A){const N=6*l;return this.float32[N+0]=u,this.float32[N+1]=m,this.float32[N+2]=x,this.float32[N+3]=b,this.float32[N+4]=S,this.float32[N+5]=A,l}}Cb.prototype.bytesPerElement=24,br(Cb,"StructArrayLayout6f24");class rp extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b){const S=this.length;return this.resize(S+1),this.emplace(S,l,u,m,x,b)}emplace(l,u,m,x,b,S){const A=5*l;return this.float32[A+0]=u,this.float32[A+1]=m,this.float32[A+2]=x,this.float32[A+3]=b,this.float32[A+4]=S,l}}rp.prototype.bytesPerElement=20,br(rp,"StructArrayLayout5f20");class M0 extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,A){const N=this.length;return this.resize(N+1),this.emplace(N,l,u,m,x,b,S,A)}emplace(l,u,m,x,b,S,A,N){const O=7*l;return this.float32[O+0]=u,this.float32[O+1]=m,this.float32[O+2]=x,this.float32[O+3]=b,this.float32[O+4]=S,this.float32[O+5]=A,this.float32[O+6]=N,l}}M0.prototype.bytesPerElement=28,br(M0,"StructArrayLayout7f28");class YE extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,A,N,O,$,U){const q=this.length;return this.resize(q+1),this.emplace(q,l,u,m,x,b,S,A,N,O,$,U)}emplace(l,u,m,x,b,S,A,N,O,$,U,q){const K=11*l;return this.float32[K+0]=u,this.float32[K+1]=m,this.float32[K+2]=x,this.float32[K+3]=b,this.float32[K+4]=S,this.float32[K+5]=A,this.float32[K+6]=N,this.float32[K+7]=O,this.float32[K+8]=$,this.float32[K+9]=U,this.float32[K+10]=q,l}}YE.prototype.bytesPerElement=44,br(YE,"StructArrayLayout11f44");class ZE extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,A,N,O){const $=this.length;return this.resize($+1),this.emplace($,l,u,m,x,b,S,A,N,O)}emplace(l,u,m,x,b,S,A,N,O,$){const U=9*l;return this.float32[U+0]=u,this.float32[U+1]=m,this.float32[U+2]=x,this.float32[U+3]=b,this.float32[U+4]=S,this.float32[U+5]=A,this.float32[U+6]=N,this.float32[U+7]=O,this.float32[U+8]=$,l}}ZE.prototype.bytesPerElement=36,br(ZE,"StructArrayLayout9f36");class np extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u){const m=this.length;return this.resize(m+1),this.emplace(m,l,u)}emplace(l,u,m){const x=2*l;return this.float32[x+0]=u,this.float32[x+1]=m,l}}np.prototype.bytesPerElement=8,br(np,"StructArrayLayout2f8");class XE extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,m,x)}emplace(l,u,m,x,b){const S=6*l;return this.uint32[3*l+0]=u,this.uint16[S+2]=m,this.uint16[S+3]=x,this.uint16[S+4]=b,l}}XE.prototype.bytesPerElement=12,br(XE,"StructArrayLayout1ul3ui12");class ip extends Gi{_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}}ip.prototype.bytesPerElement=2,br(ip,"StructArrayLayout1ui2");class QE extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,A,N,O,$,U,q,K,X,te,ie){const ae=this.length;return this.resize(ae+1),this.emplace(ae,l,u,m,x,b,S,A,N,O,$,U,q,K,X,te,ie)}emplace(l,u,m,x,b,S,A,N,O,$,U,q,K,X,te,ie,ae){const he=16*l;return this.float32[he+0]=u,this.float32[he+1]=m,this.float32[he+2]=x,this.float32[he+3]=b,this.float32[he+4]=S,this.float32[he+5]=A,this.float32[he+6]=N,this.float32[he+7]=O,this.float32[he+8]=$,this.float32[he+9]=U,this.float32[he+10]=q,this.float32[he+11]=K,this.float32[he+12]=X,this.float32[he+13]=te,this.float32[he+14]=ie,this.float32[he+15]=ae,l}}QE.prototype.bytesPerElement=64,br(QE,"StructArrayLayout16f64");class Nb extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,m,x,b,S,A){const N=this.length;return this.resize(N+1),this.emplace(N,l,u,m,x,b,S,A)}emplace(l,u,m,x,b,S,A,N){const O=10*l,$=5*l;return this.uint16[O+0]=u,this.uint16[O+1]=m,this.uint16[O+2]=x,this.uint16[O+3]=b,this.float32[$+2]=S,this.float32[$+3]=A,this.float32[$+4]=N,l}}Nb.prototype.bytesPerElement=20,br(Nb,"StructArrayLayout4ui3f20");class Ib extends Gi{_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}}Ib.prototype.bytesPerElement=2,br(Ib,"StructArrayLayout1i2");class Pb extends Gi{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(l){const u=this.length;return this.resize(u+1),this.emplace(u,l)}emplace(l,u){return this.uint8[1*l+0]=u,l}}Pb.prototype.bytesPerElement=1,br(Pb,"StructArrayLayout1ub1");class pI extends I0{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]}}pI.prototype.size=40;class JE extends Ab{get(l){return new pI(this,l)}}br(JE,"CollisionBoxArray");class gI extends I0{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}}gI.prototype.size=60;class yI extends kb{get(l){return new gI(this,l)}}br(yI,"PlacedSymbolArray");class O0 extends I0{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]}}O0.prototype.size=80;class xI extends KE{get(l){return new O0(this,l)}}br(xI,"SymbolInstanceArray");class vI extends Pc{getoffsetX(l){return this.float32[1*l+0]}}br(vI,"GlyphOffsetArray");class F0 extends mc{getx(l){return this.int16[2*l+0]}gety(l){return this.int16[2*l+1]}}br(F0,"SymbolLineVertexArray");class _I extends I0{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]}}_I.prototype.size=12;class ej extends XE{get(l){return new _I(this,l)}}br(ej,"FeatureIndexArray");class bI extends vu{geta_centroid_pos0(l){return this.uint16[2*l+0]}geta_centroid_pos1(l){return this.uint16[2*l+1]}}br(bI,"FillExtrusionCentroidArray");class tj extends I0{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]}}tj.prototype.size=6;class rj extends Md{get(l){return new tj(this,l)}}br(rj,"FillExtrusionWallArray");const wI=Rn([{name:"a_pos",components:2,type:"Int16"}],4),X5=Rn([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),Q5=Rn([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Ci{constructor(l=[]){this.segments=l}_prepareSegment(l,u,m,x,b){let S=this.segments[this.segments.length-1];return l>Ci.MAX_VERTEX_ARRAY_LENGTH&&$r(`Max vertices per segment is ${Ci.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${l}`),(!S||S.vertexLength+l>Ci.MAX_VERTEX_ARRAY_LENGTH||S.sortKey!==x||b!==void 0&&S&&S.batchIndex!==void 0&&S.batchIndex!==b)&&(S={vertexOffset:u,primitiveOffset:m,vertexLength:0,primitiveLength:0},x!==void 0&&(S.sortKey=x),b!==void 0&&(S.batchIndex=b),this.segments.push(S)),S}prepareSegment(l,u,m,x,b){return this._prepareSegment(l,u.length,m.length,x,b)}get(){return this.segments}destroy(){for(const l of this.segments)for(const u in l.vaos)l.vaos[u].destroy()}static simpleSegment(l,u,m,x){return new Ci([{vertexOffset:l,primitiveOffset:u,vertexLength:m,primitiveLength:x,vaos:{},sortKey:0}])}}function Rb(h,l){return 256*(h=fe(Math.floor(h),0,255))+fe(Math.floor(l),0,255)}Ci.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,br(Ci,"SegmentVector");const J5=Rn([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),e4=Rn([{name:"a_pattern_b",components:4,type:"Uint16"}]),t4=Rn([{name:"a_dash",components:4,type:"Uint16"}]);class B0{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(l,u,m,x){this.ids.push(nj(l)),this.positions.push(u,m,x)}eachPosition(l,u){const m=nj(l);let x=0,b=this.ids.length-1;for(;x>1;this.ids[S]>=m?b=S:x=S+1}for(;this.ids[x]===m;)u(this.positions[3*x],this.positions[3*x+1],this.positions[3*x+2]),x++}static serialize(l,u){const m=new Float64Array(l.ids),x=new Uint32Array(l.positions);return $0(m,x,0,m.length-1),u&&(u.add(m.buffer),u.add(x.buffer)),{ids:m,positions:x}}static deserialize(l){const u=new B0;let m;u.ids=l.ids,u.positions=l.positions;for(const x of u.ids)x!==m&&u.uniqueIds.push(x),m=x;return u.indexed=!0,u}}function nj(h){const l=+h;return Number.isSafeInteger(l)?l:wf(String(h))}function $0(h,l,u,m){for(;u>1];let b=u-1,S=m+1;for(;;){do b++;while(h[b]x);if(b>=S)break;Rc(h,b,S),Rc(l,3*b,3*S),Rc(l,3*b+1,3*S+1),Rc(l,3*b+2,3*S+2)}S-u`u_${b}`),this.type=m,this.context=x}setUniform(l,u,m,x,b){const S=x.constantOr(this.value);u.set(l,b,S instanceof Xn?S.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):S)}getBinding(l,u){return this.type==="color"?new n4(l):new ha(l)}}class z{constructor(l,u){this.uniformNames=u.map(m=>`u_${m}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(l,u){this.pixelRatio=l.pixelRatio||1,this.pattern=l.tl.concat(l.br),this.patternTransition=u?u.tl.concat(u.br):this.pattern}setUniform(l,u,m,x,b){let S=null;b!=="u_pattern"&&b!=="u_dash"||(S=this.pattern),b==="u_pattern_b"&&(S=this.patternTransition),b==="u_pixel_ratio"&&(S=this.pixelRatio),S&&u.set(l,b,S)}getBinding(l,u){return u==="u_pattern"||u==="u_pattern_b"||u==="u_dash"?new r4(l):new ha(l)}}class H{constructor(l,u,m,x){this.expression=l,this.type=m,this.maxValue=0,this.paintVertexAttributes=u.map(b=>({name:`a_${b}`,type:"Float32",components:m==="color"?2:1,offset:0})),this.paintVertexArray=new x}populatePaintArray(l,u,m,x,b,S,A,N){const O=this.paintVertexArray.length,$=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new si(0,{brightness:S,worldview:N}),u,{},b,x,A):this.expression.kind==="constant"&&this.expression.value,U=L(this.lutExpression,u,{},x,b,S,A,N);this.paintVertexArray.resize(l),this._setPaintValue(O,l,$,U?null:this.context.lut)}updatePaintArray(l,u,m,x,b,S,A,N){const O=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:A,worldview:N},m,x,void 0,b):this.expression.kind==="constant"&&this.expression.value,$=L(this.lutExpression,m,x,b,void 0,A,void 0,N);this._setPaintValue(l,u,O,$?null:this.context.lut)}_setPaintValue(l,u,m,x){if(this.type==="color"){const b=I(m.toPremultipliedRenderColor(x));for(let S=l;S`u_${A}_t`),this.type=m,this.useIntegerZoom=x,this.context=b,this.maxValue=0,this.paintVertexAttributes=u.map(A=>({name:`a_${A}`,type:"Float32",components:m==="color"?4:2,offset:0})),this.paintVertexArray=new S}populatePaintArray(l,u,m,x,b,S,A,N){const O=this.expression.evaluate(new si(this.context.zoom,{brightness:S,worldview:N}),u,{},b,x,A),$=this.expression.evaluate(new si(this.context.zoom+1,{brightness:S,worldview:N}),u,{},b,x,A),U=L(this.lutExpression,u,{},x,b,S,A,N),q=this.paintVertexArray.length;this.paintVertexArray.resize(l),this._setPaintValue(q,l,O,$,U?null:this.context.lut)}updatePaintArray(l,u,m,x,b,S,A,N){const O=this.expression.evaluate({zoom:this.context.zoom,brightness:A,worldview:N},m,x,void 0,b),$=this.expression.evaluate({zoom:this.context.zoom+1,brightness:A,worldview:N},m,x,void 0,b),U=L(this.lutExpression,m,x,b,void 0,A,void 0,N);this._setPaintValue(l,u,O,$,U?null:this.context.lut)}_setPaintValue(l,u,m,x,b){if(this.type==="color"){const S=I(m.toPremultipliedRenderColor(b)),A=I(x.toPremultipliedRenderColor(b));for(let N=l;N!0){this.binders={},this._buffers=[],this.context=u;const x=[],b=l;for(const S in l.paint._values){const A=b.paint.get(S);if(S.endsWith("-use-theme")||!m(S)||!(A instanceof ep&&lb(A.property.specification)))continue;const N=oe(S,l.type),O=A.value,$=A.property.specification.type,U=!!A.property.useIntegerZoom,q=S==="line-dasharray"||S.endsWith("pattern"),K=b.paint.get(`${S}-use-theme`),X=S==="line-dasharray"&&b.layout.get("line-cap").value.kind!=="constant"||K&&K.value.kind!=="constant";if(O.kind!=="constant"||X)if(O.kind==="source"||X||q){const te=Pe(S,$,"source");this.binders[S]=q?new ne(O,N,$,te,l.id):new H(O,N,$,te),x.push(`/a_${S}`)}else{const te=Pe(S,$,"composite");this.binders[S]=new Z(O,N,$,U,u,te),x.push(`/z_${S}`)}else this.binders[S]=q?new z(O.value,N):new F(O.value,N,$,u),x.push(`/u_${S}`);K&&(this.binders[S].lutExpression=K.value)}this.cacheKey=x.sort().join("")}getMaxValue(l){const u=this.binders[l];return u instanceof H||u instanceof Z?u.maxValue:0}populatePaintArrays(l,u,m,x,b,S,A,N){for(const O in this.binders){const $=this.binders[O];$.context=this.context,($ instanceof H||$ instanceof Z||$ instanceof ne)&&$.populatePaintArray(l,u,m,x,b,S,A,N)}}setConstantPatternPositions(l,u){for(const m in this.binders){const x=this.binders[m];x instanceof z&&x.setConstantPatternPositions(l,u)}}getPatternTransitionVertexBuffer(l){const u=this.binders[l];return u instanceof ne?u.paintTransitionVertexBuffer:null}updatePaintArrays(l,u,m,x,b,S,A,N,O,$){let U=!1;const q=Object.keys(l),K=q.length!==0&&!N,X=K?q:u.uniqueIds;this.context.lut=b.lut;for(const te in this.binders){const ie=this.binders[te];if(ie.context=this.context,(ie instanceof H||ie instanceof Z||ie instanceof ne)&&ie.expression&&ie.expression.kind&&ie.expression.kind!=="constant"&&(ie.expression.isStateDependent===!0||ie.expression.isLightConstant===!1)){const ae=b.paint.get(te);ie.expression=ae.value;for(const he of X){const ue=l[he.toString()];u.eachPosition(he,(ve,ke,Ie)=>{const We=x.feature(ve);ie.updatePaintArray(ke,Ie,We,ue,S,A,O,$)})}if(!K)for(const he of m.uniqueIds){const ue=l[he.toString()];m.eachPosition(he,(ve,ke,Ie)=>{const We=x.feature(ve);ie.updatePaintArray(ke,Ie,We,ue,S,A,O,$)})}U=!0}}return U}defines(){const l=[];for(const u in this.binders){const m=this.binders[u];(m instanceof F||m instanceof z)&&l.push(...m.uniformNames.map(x=>`#define HAS_UNIFORM_${x}`))}return l}getPaintVertexBuffers(){return this._buffers}getUniforms(l){const u=[];for(const m in this.binders){const x=this.binders[m];if(x instanceof F||x instanceof z||x instanceof Z)for(const b of x.uniformNames)u.push({name:b,property:m,binding:x.getBinding(l,b)})}return u}setUniforms(l,u,m,x,b){for(const{name:S,property:A,binding:N}of m)this.binders[A].setUniform(l,N,b,x.get(A),S)}updatePaintBuffers(){this._buffers=[];for(const l in this.binders){const u=this.binders[l];(u instanceof H||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 m=this.binders[u];(m instanceof H||m instanceof Z||m instanceof ne)&&m.upload(l)}this.updatePaintBuffers()}destroy(){for(const l in this.binders){const u=this.binders[l];(u instanceof H||u instanceof Z||u instanceof ne)&&u.destroy()}}}class se{constructor(l,u,m=()=>!0){this.programConfigurations={};for(const x of l)this.programConfigurations[x.id]=new re(x,u,m);this.needsUpload=!1,this._featureMap=new B0,this._featureMapWithoutIds=new B0,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(l,u,m,x,b,S,A,N,O){for(const $ in this.programConfigurations)this.programConfigurations[$].populatePaintArrays(l,u,x,b,S,A,N,O);u.id!==void 0?this._featureMap.add(u.id,m,this._bufferOffset,l):(this._featureMapWithoutIds.add(this._idlessCounter,m,this._bufferOffset,l),this._idlessCounter+=1),this._bufferOffset=l,this.needsUpload=!0}updatePaintArrays(l,u,m,x,b,S,A,N){for(const O of m)this.needsUpload=this.programConfigurations[O.id].updatePaintArrays(l,this._featureMap,this._featureMapWithoutIds,u,O,x,b,S,A||0,N)||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 oe(h,l){return ce[h]||[h.replace(`${l}-`,"").replace(/-/g,"_")]}const ye={"line-pattern":{source:Od,composite:Od},"fill-pattern":{source:Od,composite:Od},"fill-extrusion-pattern":{source:Od,composite:Od},"line-dasharray":{source:Hg,composite:Hg}},ge={color:{source:np,composite:Ch},number:{source:Pc,composite:np}};function Pe(h,l,u){const m=ye[h];return m&&m[u]||ge[l][u]}br(F,"ConstantBinder"),br(z,"PatternConstantBinder"),br(H,"SourceExpressionBinder"),br(ne,"PatternCompositeBinder"),br(Z,"CompositeExpressionBinder"),br(re,"ProgramConfiguration",{omit:["_buffers"]}),br(se,"ProgramConfigurationSet");const De=lr/Math.PI/2,_e=64,Ze=[_e,32,16],$e=-De,Ke=De;function Me(h,l,u,m=De){return u=Zn(u),[h*Math.sin(u)*m,-l*m,h*Math.cos(u)*m]}function Be(h,l,u){return Me(Math.cos(Zn(h)),Math.sin(Zn(h)),l,u)}const qe=63710088e-1,st=2*Math.PI*qe;class Qe{constructor(l,u){if(isNaN(l)||isNaN(u))throw new Error(`Invalid LngLat object: (${l}, ${u})`);if(this.lng=+l,this.lat=+u,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Qe(Ye(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(l){const u=Math.PI/180,m=this.lat*u,x=l.lat*u,b=Math.sin(m)*Math.sin(x)+Math.cos(m)*Math.cos(x)*Math.cos((l.lng-this.lng)*u);return qe*Math.acos(Math.min(b,1))}toBounds(l=0){const u=360*l/40075017,m=u/Math.cos(Math.PI/180*this.lat);return new xt({lng:this.lng-m,lat:this.lat-u},{lng:this.lng+m,lat:this.lat+u})}toEcef(l){return Be(this.lat,this.lng,De+l*De/qe)}static convert(l){if(l instanceof Qe)return l;if(Array.isArray(l)&&(l.length===2||l.length===3))return new Qe(Number(l[0]),Number(l[1]));if(!Array.isArray(l)&&typeof l=="object"&&l!==null)return new Qe(Number("lng"in l?l.lng:l.lon),Number(l.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}class xt{constructor(l,u){l&&(u?this.setSouthWest(l).setNorthEast(u):Array.isArray(l)&&l.length===4?this.setSouthWest([l[0],l[1]]).setNorthEast([l[2],l[3]]):this.setSouthWest(l[0]).setNorthEast(l[1]))}setNorthEast(l){return this._ne=l instanceof Qe?new Qe(l.lng,l.lat):Qe.convert(l),this}setSouthWest(l){return this._sw=l instanceof Qe?new Qe(l.lng,l.lat):Qe.convert(l),this}extend(l){const u=this._sw,m=this._ne;let x,b;if(l instanceof Qe)x=l,b=l;else{if(!(l instanceof xt))return Array.isArray(l)?l.length===4||l.every(Array.isArray)?this.extend(xt.convert(l)):this.extend(Qe.convert(l)):typeof l=="object"&&l!==null&&l.hasOwnProperty("lat")&&(l.hasOwnProperty("lon")||l.hasOwnProperty("lng"))?this.extend(Qe.convert(l)):this;if(x=l._sw,b=l._ne,!x||!b)return this}return u||m?(u.lng=Math.min(x.lng,u.lng),u.lat=Math.min(x.lat,u.lat),m.lng=Math.max(b.lng,m.lng),m.lat=Math.max(b.lat,m.lat)):(this._sw=new Qe(x.lng,x.lat),this._ne=new Qe(b.lng,b.lat)),this}getCenter(){return new Qe((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new Qe(this.getWest(),this.getNorth())}getSouthEast(){return new Qe(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(l){const{lng:u,lat:m}=Qe.convert(l);let x=this._sw.lng<=u&&u<=this._ne.lng;return this._sw.lng>this._ne.lng&&(x=this._sw.lng>=u&&u>=this._ne.lng),this._sw.lat<=m&&m<=this._ne.lat&&x}static convert(l){if(l)return l instanceof xt?l:new xt(l)}}function ft(h){return st*Math.cos(h*Math.PI/180)}function Lt(h){return(180+h)/360}function Ft(h){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+h*Math.PI/360)))/360}function ot(h,l){return h/ft(l)}function et(h){return 360*h-180}function gt(h){return 360/Math.PI*Math.atan(Math.exp((180-360*h)*Math.PI/180))-90}function bt(h,l){return h*ft(gt(l))}const St=85.051129;function nr(h){return Math.cos(Zn(fe(h,-85.051129,St)))}function Wt(h,l){const u=fe(l,0,25.5),m=Math.pow(2,u);return nr(h)*st/(512*m)}function Kt(h){return 1/Math.cos(h*Math.PI/180)}function Mt(h,l=0){const u=Math.exp(Math.PI*(1-(h.y+l/lr)/(1<=N?(Lr(h,l,u,O,$,b,U,A,N),Lr(h,O,$,m,x,U,S,A,N)):h.push(S)}function yr(h,l,u){let m=h[0],x=m.x,b=m.y;l(m);const S=[m];for(let A=1;Ah.x+1||mh.y+1)&&$r("Geometry exceeds allowed extent, reduce your vector tile buffer size"),h}function Ur(h,l,u){const m=h.loadGeometry(),x=h.extent,b=lr/x;if(l&&u&&u.projection.isReprojectedInTileSpace){const S=1<{const K=et((l.x+q.x/x)/S),X=gt((l.y+q.y/x)/S),te=$.project(K,X);q.x=(te.x*A-N)*x,q.y=(te.y*A-O)*x};for(let q=0;q=x||X.y<0||X.y>=x||(U(X),K.push(X));m[q]=K}}for(const S of m)for(const A of S)bn(A,b);return m}function wn(h,l){return{type:h.type,id:h.id,properties:h.properties,geometry:l?Ur(h):[]}}class rn{constructor(l,u,m,x,b){this.properties={},this.extent=m,this.type=0,this.id=void 0,this._pbf=l,this._geometry=-1,this._keys=x,this._values=b,l.readFields(Gn,this,u)}loadGeometry(){const l=this._pbf;l.pos=this._geometry;const u=l.readVarint()+l.pos,m=[];let x,b=1,S=0,A=0,N=0;for(;l.pos>3}if(S--,b===1||b===2)A+=l.readSVarint(),N+=l.readSVarint(),b===1&&(x&&m.push(x),x=[]),x&&x.push(new Ot(A,N));else{if(b!==7)throw new Error(`unknown command ${b}`);x&&x.push(x[0].clone())}}return x&&m.push(x),m}bbox(){const l=this._pbf;l.pos=this._geometry;const u=l.readVarint()+l.pos;let m=1,x=0,b=0,S=0,A=1/0,N=-1/0,O=1/0,$=-1/0;for(;l.pos>3}if(x--,m===1||m===2)b+=l.readSVarint(),S+=l.readSVarint(),bN&&(N=b),S$&&($=S);else if(m!==7)throw new Error(`unknown command ${m}`)}return[A,O,N,$]}toGeoJSON(l,u,m){const x=this.extent*Math.pow(2,m),b=this.extent*l,S=this.extent*u,A=this.loadGeometry();function N(q){return[360*(q.x+b)/x-180,360/Math.PI*Math.atan(Math.exp((1-2*(q.y+S)/x)*Math.PI))-90]}function O(q){return q.map(N)}let $;if(this.type===1){const q=[];for(const X of A)q.push(X[0]);const K=O(q);$=q.length===1?{type:"Point",coordinates:K[0]}:{type:"MultiPoint",coordinates:K}}else if(this.type===2){const q=A.map(O);$=q.length===1?{type:"LineString",coordinates:q[0]}:{type:"MultiLineString",coordinates:q}}else{if(this.type!==3)throw new Error("unknown feature type");{const q=function(X){const te=X.length;if(te<=1)return[X];const ie=[];let ae,he;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 rn(this._pbf,u,this.extent,this._keys,this._values)}}function Ni(h,l,u){h===15?l.version=u.readVarint():h===1?l.name=u.readString():h===5?l.extent=u.readVarint():h===2?l._features.push(u.pos):h===3?l._keys.push(u.readString()):h===4&&l._values.push(function(m){let x=null;const b=m.readVarint()+m.pos;for(;m.pos>3;x=S===1?m.readString():S===2?m.readFloat():S===3?m.readDouble():S===4?m.readVarint64():S===5?m.readVarint():S===6?m.readSVarint():S===7?m.readBoolean():null}if(x==null)throw new Error("unknown feature value");return x}(u))}class ei{constructor(l,u){this.layers=l.readFields(gn,{},u)}}function gn(h,l,u){if(h===3){const m=new Xi(u,u.readVarint()+u.pos);m.length&&(l[m.name]=m)}}const yn="3d_elevation_id",Ii="level";class ns{constructor(){this._valid=!1}reset(l){return this.feature=l,this._valid=!0,this._geometry=l.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(l,u){return this._valid&&l(u(this._geometry)),this}require(l,u,m){return this.get(l,!0,u,m)}optional(l,u,m){return this.get(l,!1,u,m)}success(){return this._valid}get(l,u,m,x){const b=this.feature.properties.hasOwnProperty(l)?+this.feature.properties[l]:void 0;return this._valid&&b!==void 0&&!Number.isNaN(b)?m(x?x(b):b):u&&(this._valid=!1),this}}class ti{constructor(l,u){this.featureFunc=l,this.vertexFunc=u}parseFeature(l,u,m){return this.featureFunc(l,u,m)}parseVertex(l,u,m){return this.vertexFunc(l,u,m)}}const ln=new ti((h,l,u)=>h.reset(l).require(yn,m=>{u.id=m}).optional("fixed_height_relative",m=>{u.constantHeight=m},Si.decodeRelativeHeight).geometry(m=>{u.bounds=m},YT).success(),(h,l,u)=>h.reset(l).require(yn,m=>{u.id=m}).require("elevation_idx",m=>{u.idx=m}).require("extent",m=>{u.extent=m}).require("height_relative",m=>{u.height=m},Si.decodeRelativeHeight).geometry(m=>{u.position=m},Si.getPoint).success()),Yi=new ti((h,l,u)=>h.reset(l).require(yn,m=>{u.id=m}).optional("fixed_height",m=>{u.constantHeight=m},Si.decodeMetricHeight).geometry(m=>{u.bounds=m},YT).success(),(h,l,u)=>h.reset(l).require(yn,m=>{u.id=m}).require("elevation_idx",m=>{u.idx=m}).require("extent",m=>{u.extent=m}).require("height",m=>{u.height=m},Si.decodeMetricHeight).geometry(m=>{u.position=m},Si.getPoint).success());class Si{static getPoint(l){return Vn(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"?Yi:void 0:ln}static parse(l){const u=[],m=[],x=l.length,b=new ns;for(let S=0;S=0);if(b===0)return 0;b!==l.length&&(u=!1)}return u?2:1}function fa(h,l){for(const u of h.projections){const m=ta(l,h.points[0],u.axis);if(u.projection[1]m[1])return 0}return 1}function Ha(h,l){let u=0;const m=[0,0,0,0];for(let x=0;x=0&&u++;return u}class pc{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=li.fromPoints(this.points),this.projections=[],this.frustumEdges=[rr([],this.points[2],this.points[3]),rr([],this.points[0],this.points[3]),rr([],this.points[4],this.points[0]),rr([],this.points[5],this.points[1]),rr([],this.points[6],this.points[2]),rr([],this.points[7],this.points[3])];for(const m of this.frustumEdges){const x=[0,-m[2],m[1]],b=[m[2],0,-m[0]];this.projections.push({axis:x,projection:ta(this.points,this.points[0],x)}),this.projections.push({axis:b,projection:ta(this.points,this.points[0],b)})}}static fromInvProjectionMatrix(l,u,m,x){const b=Math.pow(2,m),S=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map(O=>{const $=ar([],O,l),U=1/$[3]/u*b;return(q=$)[0]=(K=$)[0]*(X=[U,U,x?1/$[3]:U,U])[0],q[1]=K[1]*X[1],q[2]=K[2]*X[2],q[3]=K[3]*X[3],q;var q,K,X}),A=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(O=>{const $=pt([],tr([],rr([],S[O[0]],S[O[1]]),rr([],S[O[2]],S[O[1]]))),U=-Pt($,S[O[1]]);return $.concat(U)}),N=[];for(let O=0;OO[1]||O[0]>N[1])return 0}return 1}containsPoint(l){for(const u of this.planes){const m=u[3];if(Pt([u[0],u[1],u[2]],l)+m<0)return!1}return!0}}class li{static fromPoints(l){const u=[1/0,1/0,1/0],m=[-1/0,-1/0,-1/0];for(const x of l)Ee(u,u,x),we(m,m,x);return new li(u,m)}static fromTileIdAndHeight(l,u,m){const x=1<l.max[u]||l.min[u]>this.max[u])return!1;return!0}intersectsAabbXY(l){return!(this.min[0]>l.max[0]||l.min[0]>this.max[0]||this.min[1]>l.max[1]||l.min[1]>this.max[1])}encapsulate(l){for(let u=0;u<3;u++)this.min[u]=Math.min(this.min[u],l.min[u]),this.max[u]=Math.max(this.max[u],l.max[u])}encapsulatePoint(l){for(let u=0;u<3;u++)this.min[u]=Math.min(this.min[u],l[u]),this.max[u]=Math.max(this.max[u],l[u])}closestPoint(l){return[Math.max(Math.min(this.max[0],l[0]),this.min[0]),Math.max(Math.min(this.max[1],l[1]),this.min[1]),Math.max(Math.min(this.max[2],l[2]),this.min[2])]}}br(li,"Aabb");class Lc{constructor(l,u){this.feature=l,this.metersToTile=u,this.index=0}get(){const l=this.feature.vertices[this.index],u=this.feature.vertexProps[this.index].dir,m=u[1],x=-u[0],b=(l.extent+1)*this.metersToTile;return[new Ot(Math.trunc(l.position[0]+m*b),Math.trunc(l.position[1]+x*b)),new Ot(Math.trunc(l.position[0]-m*b),Math.trunc(l.position[1]-x*b))]}next(){this.index++}valid(){return this.index{return A.a0?He(N,N,1/O):be(N,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(l){if(this.edges.length===0)return;let u=0,m=Number.POSITIVE_INFINITY,x=0;const[b,S,A,N,O,$,U]=this._tmpVec2;Ks(U,l.x,l.y);const q=new Bs(U,null);for(let K=0;K0?Xr(N,A)/ve:0,Ie=fe(ke,0,1),We=Math.abs((ke-Ie)*this.edgeProps[K].len);wo(O,U,ie),Ks($,te[1],-te[0]);const ze=We+Math.abs(Xr(O,$));ze=0;--S){const A=this.edges[S].a,N=this.edges[S].b,{position:O,height:$,extent:U}=this.vertices[A],{position:q,height:K,extent:X}=this.vertices[N],te=this.vertexProps[A].dir,ie=this.vertexProps[N].dir;if(be(u,O[0]/l,O[1]/l,$),be(m,q[0]/l,q[1]/l,K),be(x,te[1],-te[0],0),He(x,x,U),be(b,ie[1],-ie[0],0),He(b,b,X),this.distSqLines(Ae(u[0]+.5*x[0],u[1]+.5*x[1],u[2]+.5*x[2]),Ae(m[0]-.5*b[0],m[1]-.5*b[1],m[2]-.5*b[2]),Ae(u[0]-.5*x[0],u[1]-.5*x[1],u[2]-.5*x[2]),Ae(m[0]+.5*b[0],m[1]+.5*b[1],m[2]+.5*b[2]))<=.0025000000000000005)continue;const ae=this.vertices.length,he=Ea(Nr(),O,q);this.vertices.push({position:Zr(he,he,.5),height:.5*($+K),extent:.5*(U+X)});const ue=Ea(Nr(),te,ie);this.vertexProps.push({dir:xn(ue,ue)}),this.edges.splice(S,1),this.edgeProps.splice(S,1),this.edges.push({a:A,b:ae}),this.edges.push({a:ae,b:N});const ve=wo(Nr(),this.vertices[ae].position,O),ke=fn(ve),Ie={vec:ve,dir:Zr(Nr(),ve,1/ke),len:ke};this.edgeProps.push(Ie),this.edgeProps.push(Ie)}}distSqLines(l,u,m,x){const b=Te(Se(),u,l),S=Te(Se(),x,m),A=Te(Se(),l,m),N=Pt(b,b),O=Pt(b,S),$=Pt(b,A),U=Pt(S,S),q=Pt(S,A),K=N*U-O*O;if(K===0)return Et(_t(b,m,x,Pt(A,S)/Pt(S,S)),l);const X=(N*q-O*$)/K;return Et(_t(b,l,u,(O*q-$*U)/K),_t(S,m,x,X))}}class Oi{static parseFrom(l,u){const m=Si.parse(l);if(!m)return[];let{vertices:x,features:b}=m;const S=1/Mt(u);b.sort(($,U)=>$.id-U.id),x.sort(($,U)=>$.id-U.id||$.idx-U.idx),x=x.filter(($,U,q)=>U===q.findIndex(K=>K.id===$.id&&K.idx===$.idx));const A=new Array;let N=0;const O=x.length;for(const $ of b){if($.constantHeight){A.push(new Dc($.id,$.bounds,$.constantHeight));continue}for(;N!==O&&x[N].id<$.id;)N++;if(N===O||x[N].id!==$.id)continue;const U=new Array,q=new Array,K=N;for(;N!==O&&x[N].id===$.id;){const X=x[N];if(U.push({position:X.position,height:X.height,extent:X.extent}),N!==K&&x[N-1].idx===X.idx-1){const te=N-K;q.push({a:te-1,b:te})}N++}A.push(new Dc($.id,$.bounds,void 0,U,q,S))}return A}static getElevationFeature(l,u){if(!u)return;const m=+l.properties[yn];return Number.isNaN(m)?void 0:u.find(x=>x.id===m)}}class Vi{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)*lr,this.yOffset=(l.y*this.zScale-u.y)*lr)}constantElevation(l,u){if(l.constantHeight!=null)return this.computeBiasedHeight(l.constantHeight,u)}pointElevation(l,u,m){const x=this.constantElevation(u,m);return x??(l.x=l.x*this.zScale+this.xOffset,l.y=l.y*this.zScale+this.yOffset,this.computeBiasedHeight(u.pointElevation(l),m))}computeBiasedHeight(l,u){return u<=0?l:l+u*Oe(0,u,l>=0?l:Math.abs(.5*l))}}br(Dc,"ElevationFeature");class yi{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 mc,this.indexArray=new _s,this.segments=new Ci,this.programConfigurations=new se(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 Pc),this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,m,x){const b=this.layers[0],S=[];let A=null;b.type==="circle"&&(A=b.layout.get("circle-sort-key"));for(const{feature:O,id:$,index:U,sourceLayerIndex:q}of l){const K=this.layers[0]._featureFilter.needGeometry,X=wn(O,K);if(!this.layers[0]._featureFilter.filter(new si(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),X,m))continue;const te=A?A.evaluate(X,{},m):void 0,ie={id:$,properties:O.properties,type:O.type,sourceLayerIndex:q,index:U,geometry:K?X.geometry:Ur(O,m,x),patterns:{},sortKey:te};S.push(ie)}A&&S.sort((O,$)=>O.sortKey-$.sortKey);let N=null;x.projection.name==="globe"&&(this.globeExtVertexArray=new jb,N=x.projection);for(const O of S){const{geometry:$,index:U,sourceLayerIndex:q}=O,K=l[U].feature;this.addFeature(O,$,U,u.availableImages,m,N,u.brightness,u.elevationFeatures),u.featureIndex.insert(K,$,U,q,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(l,u,m,x,b,S,A){this.programConfigurations.updatePaintArrays(l,u,b,m,x,S,A,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,wI.members),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=l.createVertexBuffer(this.globeExtVertexArray,Q5.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=l.createVertexBuffer(this.elevatedLayoutVertexArray,X5.members))),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy())}addFeature(l,u,m,x,b,S,A,N){let O;this.elevationMode!=="none"&&(O=Oi.getElevationFeature(l,N));for(const $ of u)for(const U of $){const q=U.x,K=U.y;if(q<0||q>=lr||K<0||K>=lr)continue;if(S){const ie=S.projectTilePoint(q,K,b),ae=S.upVector(b,q,K);this.addGlobeExtVertex(ie,ae),this.addGlobeExtVertex(ie,ae),this.addGlobeExtVertex(ie,ae),this.addGlobeExtVertex(ie,ae)}const X=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,l.sortKey),te=X.vertexLength;if(this.addCircleVertex(q,K,-1,-1),this.addCircleVertex(q,K,1,-1),this.addCircleVertex(q,K,1,1),this.addCircleVertex(q,K,-1,1),this.elevationMode!=="none"){const ie=O?O.pointElevation(new Ot(q,K)):0;this.hasElevation=this.hasElevation||ie!==0;for(let ae=0;ae<4;ae++)this.elevatedLayoutVertexArray.emplaceBack(ie)}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,m,{},x,b,A,void 0,this.worldview)}addCircleVertex(l,u,m,x){this.layoutVertexArray.emplaceBack(2*l+(m+1)/2,2*u+(x+1)/2)}addGlobeExtVertex(l,u){this.globeExtVertexArray.emplaceBack(l.x,l.y,l.z,u[0]*16384,u[1]*16384,u[2]*16384)}}function Ns(h,l){for(let u=0;u1){if(Pf(h,l))return!0;for(let m=0;m1?u:u.sub(l)._mult(x)._add(l))}function Kg(h,l){let u,m,x,b=!1;for(let S=0;Sl.y!=x.y>l.y&&l.x<(x.x-m.x)*(l.y-m.y)/(x.y-m.y)+m.x&&(b=!b)}return b}function Ul(h,l){let u=!1;for(let m=0,x=h.length-1;ml.y!=S.y>l.y&&l.x<(S.x-b.x)*(l.y-b.y)/(S.y-b.y)+b.x&&(u=!u)}return u}function Rf(h,l,u,m,x){for(const S of h)if(l<=S.x&&u<=S.y&&m>=S.x&&x>=S.y)return!0;const b=[new Ot(l,u),new Ot(l,x),new Ot(m,x),new Ot(m,u)];if(h.length>2){for(const S of b)if(Ul(h,S))return!0}for(let S=0;Sx.x&&l.x>x.x||h.yx.y&&l.y>x.y)return!1;const b=on(h,l,u[0]);return b!==on(h,l,u[1])||b!==on(h,l,u[2])||b!==on(h,l,u[3])}function Df(h,l,u,m,x,b){let S=l.y-h.y,A=h.x-l.x;if(b=b||0){const N=S*S+A*A;if(N===0)return!0;const O=Math.sqrt(N);S/=O,A/=O}return!((u.x-h.x)*S+(u.y-h.y)*A-b<0||(m.x-h.x)*S+(m.y-h.y)*A-b<0||(x.x-h.x)*S+(x.y-h.y)*A-b<0)}function Db(h,l,u,m,x,b,S){return!(Df(h,l,m,x,b,S)||Df(l,u,m,x,b,S)||Df(u,h,m,x,b,S)||Df(m,x,h,l,u,S)||Df(x,b,h,l,u,S)||Df(b,m,h,l,u,S))}function Yg(h,l,u){const m=l.paint.get(h).value;return m.kind==="constant"?m.value:u.programConfigurations.get(l.id).getMaxValue(h)}function SI(h){return Math.sqrt(h[0]*h[0]+h[1]*h[1])}function iY(h,l,u,m,x){if(!l[0]&&!l[1])return h;const b=Ot.convert(l)._mult(x);u==="viewport"&&b._rotate(-m);const S=[];for(let A=0;A>u&&l.y===this.y>>u}url(l,u){const m=function(b,S,A){const N=2**A,O=2*Math.PI*6378137,$=O*(b/N-.5),U=O*(.5-(S+1)/N);return`${$},${U},${$+O/N},${U+O/N}`}(this.x,this.y,this.z),x=function(b,S,A){let N,O="";for(let $=b;$>0;$--)N=1<<$-1,O+=(S&N?1:0)+(A&N?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}",m)}toString(){return`${this.z}/${this.x}/${this.y}`}}class lY{constructor(l,u){this.wrap=l,this.canonical=u,this.key=Mb(l,u.z,u.z,u.x,u.y)}}class Tl{constructor(l,u,m,x,b){this.overscaledZ=l,this.wrap=u,this.canonical=new V0(m,+x,+b),this.key=u===0&&l===m?this.canonical.key:Mb(u,l,m,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 Tl(l,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Tl(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 Mb(this.wrap*+u,l,this.canonical.z,this.canonical.x,this.canonical.y);{const m=this.canonical.z-l;return Mb(this.wrap*+u,l,l,this.canonical.x>>m,this.canonical.y>>m)}}isChildOf(l){if(l.wrap!==this.wrap)return!1;const u=this.canonical.z-l.canonical.z;return l.overscaledZ===0||l.overscaledZ>u&&l.canonical.y===this.canonical.y>>u}children(l){if(this.overscaledZ>=l)return[new Tl(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const u=this.canonical.z+1,m=2*this.canonical.x,x=2*this.canonical.y;return[new Tl(u,this.wrap,u,m,x),new Tl(u,this.wrap,u,m+1,x),new Tl(u,this.wrap,u,m,x+1),new Tl(u,this.wrap,u,m+1,x+1)]}isLessThan(l){return this.wrapl.wrap)&&(this.overscaledZl.overscaledZ)&&(this.canonical.xl.canonical.x)&&this.canonical.y{let l=h.canonical.x-1,u=h.wrap;return l<0&&(l=(1<{let l=h.canonical.x+1,u=h.wrap;return l===1<new Tl(h.overscaledZ,h.wrap,h.canonical.z,h.canonical.x,(h.canonical.y===0?1<new Tl(h.overscaledZ,h.wrap,h.canonical.z,h.canonical.x,h.canonical.y===(1<1?null:function(m,x,b,S){const A=Math.sin(b);return m*(Math.sin((1-S)*b)/A)+x*(Math.sin(S*b)/A)}(h.a[l],h.b[l],h.angle,fe(u,0,1))+h.center[l]}function Mf(h){if(h.z<=1)return ZAe[h.z+2*h.y+h.x];const l=s4(jI(h));return li.fromPoints(l)}function op(h,l,u){return He(h,h,1-u),tt(h,h,l,u)}function dY(h,l){const u=lp(l.zoom);if(u===0)return Mf(h);const m=jI(h),x=s4(m),b=Lt(m.getWest())*l.worldSize,S=Lt(m.getEast())*l.worldSize,A=Ft(m.getNorth())*l.worldSize,N=Ft(m.getSouth())*l.worldSize,O=[b,A,0],$=[S,A,0],U=[b,N,0],q=[S,N,0],K=D([],l.globeMatrix);return cr(O,O,K),cr($,$,K),cr(U,U,K),cr(q,q,K),x[0]=op(x[0],U,u),x[1]=op(x[1],q,u),x[2]=op(x[2],$,u),x[3]=op(x[3],O,u),li.fromPoints(x)}function hY(h,l,u){for(const m of h)cr(m,m,l),He(m,m,u)}function fY(h,l,u,m){const x=l/h.worldSize,b=h.globeMatrix;if(u.z<=1){const Ge=Mf(u).getCorners();return hY(Ge,b,x),li.fromPoints(Ge)}const S=jI(u,m),A=s4(S,De+EI(h._tileCoverLift));hY(A,b,x);const N=Number.MAX_VALUE,O=[-N,-N,-N],$=[N,N,N];if(S.contains(h.center)){for(const Ve of A)Ee($,$,Ve),we(O,O,Ve);O[2]=0;const Ge=h.point,Ue=[Ge.x*x,Ge.y*x,0];return Ee($,$,Ue),we(O,O,Ue),new li($,O)}if(h._tileCoverLift>0){for(const Ge of A)Ee($,$,Ge),we(O,O,Ge);return new li($,O)}const U=[b[12]*x,b[13]*x,b[14]*x],q=S.getCenter(),K=fe(h.center.lat,-85.051129,St),X=fe(q.lat,-85.051129,St),te=Lt(h.center.lng),ie=Ft(K);let ae=te-Lt(q.lng);const he=ie-Ft(X);ae>.5?ae-=1:ae<-.5&&(ae+=1);let ue=0;Math.abs(ae)>Math.abs(he)?ue=ae>=0?1:3:(ue=he>=0?0:2,tt(U,U,[b[4]*x,b[5]*x,b[6]*x],-Math.sin(Zn(he>=0?S.getSouth():S.getNorth()))*De));const ve=A[ue],ke=A[(ue+1)%4],Ie=new XAe(ve,ke,U),We=[i4(Ie,0)||ve[0],i4(Ie,1)||ve[1],i4(Ie,2)||ve[2]],ze=lp(h.zoom);if(ze>0){const Ge=function({x:Ve,y:yt,z:wt},At,It,kt,$t){const mt=1/(1<.5?vr=-1:sr<-.5&&(vr=1),Ct=((Ct+vr)*At-(kt*=At))*It+kt,Dt=((Dt+vr)*At-kt)*It+kt,Ut=(Ut*At-($t*=At))*It+$t,Yt=(Yt*At-$t)*It+$t,[[Ct,Yt,0],[Dt,Yt,0],[Dt,Ut,0],[Ct,Ut,0]]}(u,l,h._pixelsPerMercatorPixel,te,ie);for(let Ve=0;VeMath.PI/2*1.01}const xY=Zn(85),QAe=Math.cos(xY),JAe=Math.sin(xY),eke=k(),vY=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 _Y(h,l,u,m,x,b,S,A,N){if(b&&h.queryGeometry.isAboveHorizon)return!1;b&&(N*=h.pixelToTileUnitsFactor);const O=h.tileID.canonical,$=u.projection.upVectorScale(O,u.center.lat,u.worldSize).metersToTile;for(const U of l)for(const q of U){const K=q.add(A),X=x&&u.elevation?u.elevation.exaggeration()*x.getElevationAt(K.x,K.y,!0):0,te=u.projection.projectTilePoint(K.x,K.y,O);if(X>0){const ue=u.projection.upVector(O,K.x,K.y);te.x+=ue[0]*$*X,te.y+=ue[1]*$*X,te.z+=ue[2]*$*X}const ie=b?K:tke(te.x,te.y,te.z,m),ae=b?h.tilespaceRays.map(ue=>nke(ue,X)):h.queryGeometry.screenGeometry,he=ar([],[te.x,te.y,te.z,1],m);if(!S&&b?N*=he[3]/u.cameraToCenterDistance:S&&!b&&(N*=u.cameraToCenterDistance/he[3]),b){const ue=gt((q.y/lr+O.y)/(1<h.width||x.height>h.height||u.x>h.width-x.width||u.y>h.height-x.height)throw new RangeError("out of range source coordinates for image copy");if(x.width>l.width||x.height>l.height||m.x>l.width-x.width||m.y>l.height-x.height)throw new RangeError("out of range destination coordinates for image copy");const N=h.data,O=l.data,$=b===4&&A;for(let U=0;U{l[h.evaluationKey]=N;const O=h.expression.evaluate(l),$=O?O.toNonPremultipliedRenderColor(null):null;$&&(x.data[S+A+0]=Math.floor(255*$.r),x.data[S+A+1]=Math.floor(255*$.g),x.data[S+A+2]=Math.floor(255*$.b),x.data[S+A+3]=Math.floor(255*$.a))};if(h.clips)for(let S=0,A=0;S80*u){A=h[0],N=h[1];let $=A,U=N;for(let q=u;q$&&($=K),X>U&&(U=X)}O=Math.max($-A,U-N),O=O!==0?32767/O:0}return lj(b,S,u,A,N,O,0),S}function NY(h,l,u,m,x){let b;if(x===function(S,A,N,O){let $=0;for(let U=A,q=N-O;U0)for(let S=l;S=l;S-=m)b=LY(S/m|0,h[S],h[S+1],b);return b&&Fb(b,b.next)&&(dj(b),b=b.next),b}function q0(h,l){if(!h)return h;l||(l=h);let u,m=h;do if(u=!1,m.steiner||!Fb(m,m.next)&&Wa(m.prev,m,m.next)!==0)m=m.next;else{if(dj(m),m=l=m.prev,m===m.next)break;u=!0}while(u||m!==l);return l}function lj(h,l,u,m,x,b,S){if(!h)return;!S&&b&&function(N,O,$,U){let q=N;do q.z===0&&(q.z=u4(q.x,q.y,O,$,U)),q.prevZ=q.prev,q.nextZ=q.next,q=q.next;while(q!==N);q.prevZ.nextZ=null,q.prevZ=null,function(K){let X,te=1;do{let ie,ae=K;K=null;let he=null;for(X=0;ae;){X++;let ue=ae,ve=0;for(let Ie=0;Ie0||ke>0&&ue;)ve!==0&&(ke===0||!ue||ae.z<=ue.z)?(ie=ae,ae=ae.nextZ,ve--):(ie=ue,ue=ue.nextZ,ke--),he?he.nextZ=ie:K=ie,ie.prevZ=he,he=ie;ae=ue}he.nextZ=null,te*=2}while(X>1)}(q)}(h,m,x,b);let A=h;for(;h.prev!==h.next;){const N=h.prev,O=h.next;if(b?cke(h,m,x,b):lke(h))l.push(N.i,h.i,O.i),dj(h),h=O.next,A=O.next;else if((h=O)===A){S?S===1?lj(h=uke(q0(h),l),l,u,m,x,b,2):S===2&&dke(h,l,u,m,x,b):lj(q0(h),l,u,m,x,b,1);break}}}function lke(h){const l=h.prev,u=h,m=h.next;if(Wa(l,u,m)>=0)return!1;const x=l.x,b=u.x,S=m.x,A=l.y,N=u.y,O=m.y,$=Math.min(x,b,S),U=Math.min(A,N,O),q=Math.max(x,b,S),K=Math.max(A,N,O);let X=m.next;for(;X!==l;){if(X.x>=$&&X.x<=q&&X.y>=U&&X.y<=K&&cj(x,A,b,N,S,O,X.x,X.y)&&Wa(X.prev,X,X.next)>=0)return!1;X=X.next}return!0}function cke(h,l,u,m){const x=h.prev,b=h,S=h.next;if(Wa(x,b,S)>=0)return!1;const A=x.x,N=b.x,O=S.x,$=x.y,U=b.y,q=S.y,K=Math.min(A,N,O),X=Math.min($,U,q),te=Math.max(A,N,O),ie=Math.max($,U,q),ae=u4(K,X,l,u,m),he=u4(te,ie,l,u,m);let ue=h.prevZ,ve=h.nextZ;for(;ue&&ue.z>=ae&&ve&&ve.z<=he;){if(ue.x>=K&&ue.x<=te&&ue.y>=X&&ue.y<=ie&&ue!==x&&ue!==S&&cj(A,$,N,U,O,q,ue.x,ue.y)&&Wa(ue.prev,ue,ue.next)>=0||(ue=ue.prevZ,ve.x>=K&&ve.x<=te&&ve.y>=X&&ve.y<=ie&&ve!==x&&ve!==S&&cj(A,$,N,U,O,q,ve.x,ve.y)&&Wa(ve.prev,ve,ve.next)>=0))return!1;ve=ve.nextZ}for(;ue&&ue.z>=ae;){if(ue.x>=K&&ue.x<=te&&ue.y>=X&&ue.y<=ie&&ue!==x&&ue!==S&&cj(A,$,N,U,O,q,ue.x,ue.y)&&Wa(ue.prev,ue,ue.next)>=0)return!1;ue=ue.prevZ}for(;ve&&ve.z<=he;){if(ve.x>=K&&ve.x<=te&&ve.y>=X&&ve.y<=ie&&ve!==x&&ve!==S&&cj(A,$,N,U,O,q,ve.x,ve.y)&&Wa(ve.prev,ve,ve.next)>=0)return!1;ve=ve.nextZ}return!0}function uke(h,l){let u=h;do{const m=u.prev,x=u.next.next;!Fb(m,x)&&PY(m,u,u.next,x)&&uj(m,x)&&uj(x,m)&&(l.push(m.i,u.i,x.i),dj(u),dj(u.next),u=h=x),u=u.next}while(u!==h);return q0(u)}function dke(h,l,u,m,x,b){let S=h;do{let A=S.next.next;for(;A!==S.prev;){if(S.i!==A.i&&gke(S,A)){let N=RY(S,A);return S=q0(S,S.next),N=q0(N,N.next),lj(S,l,u,m,x,b,0),void lj(N,l,u,m,x,b,0)}A=A.next}S=S.next}while(S!==h)}function hke(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 fke(h,l){const u=function(x,b){let S=b;const A=x.x,N=x.y;let O,$=-1/0;if(Fb(x,S))return S;do{if(Fb(x,S.next))return S.next;if(N<=S.y&&N>=S.next.y&&S.next.y!==S.y){const te=S.x+(N-S.y)*(S.next.x-S.x)/(S.next.y-S.y);if(te<=A&&te>$&&($=te,O=S.x=S.x&&S.x>=q&&A!==S.x&&IY(NO.x||S.x===O.x&&mke(O,S)))&&(O=S,X=te)}S=S.next}while(S!==U);return O}(h,l);if(!u)return l;const m=RY(u,h);return q0(m,m.next),q0(u,u.next)}function mke(h,l){return Wa(h.prev,h,l.prev)<0&&Wa(l.next,h,h.next)<0}function u4(h,l,u,m,x){return(h=1431655765&((h=858993459&((h=252645135&((h=16711935&((h=(h-u)*x|0)|h<<8))|h<<4))|h<<2))|h<<1))|(l=1431655765&((l=858993459&((l=252645135&((l=16711935&((l=(l-m)*x|0)|l<<8))|l<<4))|l<<2))|l<<1))<<1}function pke(h){let l=h,u=h;do(l.x=(h-S)*(b-A)&&(h-S)*(m-A)>=(u-S)*(l-A)&&(u-S)*(b-A)>=(x-S)*(m-A)}function cj(h,l,u,m,x,b,S,A){return!(h===S&&l===A)&&IY(h,l,u,m,x,b,S,A)}function gke(h,l){return h.next.i!==l.i&&h.prev.i!==l.i&&!function(u,m){let x=u;do{if(x.i!==u.i&&x.next.i!==u.i&&x.i!==m.i&&x.next.i!==m.i&&PY(x,x.next,u,m))return!0;x=x.next}while(x!==u);return!1}(h,l)&&(uj(h,l)&&uj(l,h)&&function(u,m){let x=u,b=!1;const S=(u.x+m.x)/2,A=(u.y+m.y)/2;do x.y>A!=x.next.y>A&&x.next.y!==x.y&&S<(x.next.x-x.x)*(A-x.y)/(x.next.y-x.y)+x.x&&(b=!b),x=x.next;while(x!==u);return b}(h,l)&&(Wa(h.prev,h,l.prev)||Wa(h,l.prev,l))||Fb(h,l)&&Wa(h.prev,h,h.next)>0&&Wa(l.prev,l,l.next)>0)}function Wa(h,l,u){return(l.y-h.y)*(u.x-l.x)-(l.x-h.x)*(u.y-l.y)}function Fb(h,l){return h.x===l.x&&h.y===l.y}function PY(h,l,u,m){const x=CI(Wa(h,l,u)),b=CI(Wa(h,l,m)),S=CI(Wa(u,m,h)),A=CI(Wa(u,m,l));return x!==b&&S!==A||!(x!==0||!kI(h,u,l))||!(b!==0||!kI(h,m,l))||!(S!==0||!kI(u,h,m))||!(A!==0||!kI(u,l,m))}function kI(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 CI(h){return h>0?1:h<0?-1:0}function uj(h,l){return Wa(h.prev,h,h.next)<0?Wa(h,l,h.next)>=0&&Wa(h,h.prev,l)>=0:Wa(h,l,h.prev)<0||Wa(h,h.next,l)<0}function RY(h,l){const u=d4(h.i,h.x,h.y),m=d4(l.i,l.x,l.y),x=h.next,b=l.prev;return h.next=l,l.prev=h,u.next=x,x.prev=u,m.next=u,u.prev=m,b.next=m,m.prev=b,m}function LY(h,l,u,m){const x=d4(h,l,u);return m?(x.next=m.next,x.prev=m,m.next.prev=x,m.next=x):(x.prev=x,x.next=x),x}function dj(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 d4(h,l,u){return{i:h,x:l,y:u,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function hj(h,l){const u=h.length;if(u<=1)return[h];const m=[];let x,b;for(let S=0;S1)for(let S=0;S=lr&&u>=lr}static evaluate(l){if(l.length===0)return new cp;let u=[];for(const N of l)u.push(...N.portals);if(u.length===0)return new cp;for(const N of u){const O=N.va,$=N.vb;(cp.isOnBorder(O.x,$.x)||cp.isOnBorder(O.y,$.y))&&(N.type="border")}const m=u.filter(N=>N.type!=="unevaluated"),x=u.filter(N=>N.type==="unevaluated");if(x.length===0)return new cp;x.sort((N,O)=>N.hash===O.hash?N.isTunnel===O.isTunnel?0:N.isTunnel?-1:1:N.hashN.hashb!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new se(u,{zoom:m,lut:x},b=>b!=="fill-bridge-guard-rail-color")}addVertices(l,u){const m=this.unevalVertices.length;for(let x=0;x=b.min.x&&U.x<=b.max.x&&U.y>=b.min.y&&U.y<=b.max.y||q.x>=b.min.x&&q.x<=b.max.x&&q.y>=b.min.y&&q.y<=b.max.y||Lf(U,q,A))||this.isOnBorder(U.x,q.x)||this.isOnBorder(U.y,q.y))continue;const K=Mc.computeEdgeHash(this.unevalVertices[O],this.unevalVertices[$]);let X,te=this.vertexHashLookup.get(Mc.computePosHash(U));te!=null?X=te.next:(te=this.vertexHashLookup.get(Mc.computePosHash(q)),X=te!=null?te.prev:K),this.unevalEdges.push({polygonIdx:l,a:O,b:$,hash:K,portalHash:X,isTunnel:x,type:"unevaluated",featureInfo:S})}}addPortalCandidates(l,u,m,x,b){if(u.length!==0){this.vertexHashLookup.clear();for(const S of u){if(S.length===0)continue;const A=S[0];let N=Mc.computeEdgeHash(A[A.length-2],A[A.length-1]);for(let O=0;O({vertexOffset:0,primitiveOffset:this.indexArray.length}),m=q=>{q.primitiveLength=this.indexArray.length-q.primitiveOffset},x=new xke(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(l.portals,this.unevalEdges);const b=u(),S=u(),A=u(),N=(q,K)=>{q.sort((te,ie)=>te.type===K&&ie.type!==K?-1:te.type!==K&&ie.type===K?1:0);const X=q.findIndex(te=>te.type!==K);return X>=0?X:q.length};let O=0;this.unevalEdges.length>0&&(O=N(this.unevalEdges,"none"),this.constructBridgeStructures(x,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:O},this.tileToMeters)),m(A);const $=u(),U=u();if(this.unevalEdges.length>0){const q=this.unevalEdges.splice(O),K=N(q,"tunnel")+O;this.unevalEdges.push(...q),this.constructTunnelStructures(x,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:O},{min:O,max:K})}m($),x.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),m(U),x.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),m(S),x.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),m(b),this.maskSegments=Ci.simpleSegment(0,U.primitiveOffset,0,U.primitiveLength),this.depthSegments=Ci.simpleSegment(0,S.primitiveOffset,0,S.primitiveLength),this.renderableBridgeSegments=Ci.simpleSegment(0,A.primitiveOffset,0,A.primitiveLength),this.renderableTunnelSegments=Ci.simpleSegment(0,$.primitiveOffset,0,$.primitiveLength),this.shadowCasterSegments=Ci.simpleSegment(0,b.primitiveOffset,0,b.primitiveLength)}update(l,u,m,x,b,S,A,N){this.bridgeProgramConfigurations.updatePaintArrays(l,u,b,m,x,S,A,N),this.tunnelProgramConfigurations.updatePaintArrays(l,u,b,m,x,S,A,N)}upload(l){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=l.createVertexBuffer(this.vertexPositions,ake.members),this.vertexBufferNormal=l.createVertexBuffer(this.vertexNormals,oke.members),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(l),this.tunnelProgramConfigurations.upload(l))}destroy(){this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBufferNormal.destroy(),this.indexBuffer.destroy()),this.maskSegments&&(this.maskSegments.destroy(),this.depthSegments.destroy(),this.renderableBridgeSegments.destroy(),this.renderableTunnelSegments.destroy(),this.shadowCasterSegments.destroy()),this.bridgeProgramConfigurations.destroy(),this.tunnelProgramConfigurations.destroy()}populatePaintArrays(l,u,m,x,b){const S=(A,N)=>{for(let O=0;Obe(It,u[kt].x,u[kt].y,m[kt]*N),U=Se(),q=Se(),K=Se(),X=Se(),te=Se(),ie=(It,kt)=>{const $t=A.get(Mc.computePosHash(u[kt])),mt=$t.from,Ct=$t.to;if(!mt||!Ct)return;$(U,mt),$(q,kt),$(K,Ct),ur(X),xr(U,q)||(rr(te,q,U),pt(X,te)),xr(K,q)||(rr(te,K,q),me(X,X,pt(te,te)));const Dt=ct(X);return Dt>0?He(It,X,1/Dt):void 0};let ae=Number.POSITIVE_INFINITY;this.sortSubarray(x,b.min,b.max,(It,kt)=>It.featureInfo.featureIndex-kt.featureInfo.featureIndex);const he=Se(),ue=Se(),ve=Se(),ke=Se(),Ie=Se(),We=Se(),ze=Se(),Ge=Se(),Ue=Se(),Ve=[Se(),Se(),Se(),Se()],yt=[Se(),Se(),Se(),Se()],wt=[{coord:new Ot(0,0),height:0},{coord:new Ot(0,0),height:0}],At=(It,kt)=>It>kt;for(let It=b.min;Itae.featureInfo.featureIndex-he.featureInfo.featureIndex;this.sortSubarray(x,b.min,b.max,N),this.sortSubarray(x,S.min,S.max,N);const O=ae=>pt(ae,ae),$=[{coord:new Ot(0,0),height:0},{coord:new Ot(0,0),height:0}],U=(ae,he)=>aeA.hash===N.hash?N.polygonIdx-A.polygonIdx:N.hash>A.hash?1:-1);let m=0,x=0,b=0,S=u[m].polygonIdx;do x++,(x===u.length||u[m].hash!==u[x].hash)&&((x-m===1||u[x-1].polygonIdx!==S)&&(bO.portalHash<$.portalHash?1:-1);let A=0,N=0;for(;A!==u.length&&N!==l.length;){const O=u[A],$=l[N];O.portalHash>$.hash?A++:$.hash>O.portalHash?N++:(O.type=$.type,A++)}}}isOnBorder(l,u){return l<=0&&u<=0||l>=lr&&u>=lr}addFeatureSection(l,u,m,x){return l!==u&&(u=l,m.push({featureIndex:l,vertexStart:x.getVertexCount()}),x.clearVertexLookup()),u}sortSubarray(l,u,m,x){const b=l.slice(u,m);b.sort(x),l.splice(u,b.length,...b)}static computeEdgeHash(l,u){return(l.y===u.y&&l.x>u.x||l.y>u.y)&&([l,u]=[u,l]),BigInt(Mc.computePosHash(l))<<32n|BigInt(Mc.computePosHash(u))}static computePosHash(l){return((65535&l.x)<<16|65535&l.y)>>>0}}function vke(h,l){return h>l?1:h0))return u;u=u.left}}return null}contains(l){for(var u=this._root,m=this._compare;u;){var x=m(l,u.key);if(x===0)return!0;u=x<0?u.left:u.right}return!1}remove(l){var u=this.find(l);if(!u)return!1;if(this.splay(u),u.left)if(u.right){var m=this.minNode(u.right);m.parent!==u&&(this.replace(m,m.right),m.right=u.right,m.right.parent=m),this.replace(u,m),m.left=u.left,m.left.parent=m}else this.replace(u,u.left);else this.replace(u,u.right);return this._size--,!0}removeNode(l){if(!l)return!1;if(this.splay(l),l.left)if(l.right){var u=this.minNode(l.right);u.parent!==l&&(this.replace(u,u.right),u.right=l.right,u.right.parent=u),this.replace(l,u),u.left=l.left,u.left.parent=u}else this.replace(l,l.left);else this.replace(l,l.right);return this._size--,!0}erase(l){var u=this.find(l);if(u){this.splay(u);var m=u.left,x=u.right,b=null;m&&(m.parent=null,b=this.maxNode(m),this.splay(b),this._root=b),x&&(m?b.right=x:this._root=x,x.parent=b),this._size--}}pop(){var l=this._root,u=null;if(l){for(;l.left;)l=l.left;u={key:l.key,data:l.data},this.remove(l.key)}return u}next(l){var u=l;if(u)if(u.right)for(u=u.right;u&&u.left;)u=u.left;else for(u=l.parent;u&&u.right===l;)l=u,u=u.parent;return u}prev(l){var u=l;if(u)if(u.left)for(u=u.left;u&&u.right;)u=u.right;else for(u=l.parent;u&&u.left===l;)l=u,u=u.parent;return u}forEach(l){for(var u=this._root,m=[],x=!1,b=0;!x;)u?(m.push(u),u=u.left):m.length>0?(l(u=m.pop(),b++),u=u.right):x=!0;return this}range(l,u,m,x){const b=[],S=this._compare;let A,N=this._root;for(;b.length!==0||N;)if(N)b.push(N),N=N.left;else{if(N=b.pop(),A=S(N.key,u),A>0)break;if(S(N.key,l)>=0&&m.call(x,N))return this;N=N.right}return this}keys(){for(var l=this._root,u=[],m=[],x=!1;!x;)l?(u.push(l),l=l.left):u.length>0?(l=u.pop(),m.push(l.key),l=l.right):x=!0;return m}values(){for(var l=this._root,u=[],m=[],x=!1;!x;)l?(u.push(l),l=l.left):u.length>0?(l=u.pop(),m.push(l.data),l=l.right):x=!0;return m}at(l){for(var u=this._root,m=[],x=!1,b=0;!x;)if(u)m.push(u),u=u.left;else if(m.length>0){if(u=m.pop(),b===l)return u;b++,u=u.right}else x=!0;return null}load(l=[],u=[],m=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const x=l.length;return m&&g4(l,u,0,x-1,this._compare),this._root=p4(null,l,u,0,x),this._size=x,this}min(){var l=this.minNode(this._root);return l?l.key:null}max(){var l=this.maxNode(this._root);return l?l.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(l,u,m,x,b){return new m4(m,b).load(l,u,x)}}function p4(h,l,u,m,x){const b=x-m;if(b>0){const S=m+Math.floor(b/2),A={key:l[S],data:u[S],parent:h};return A.left=p4(A,l,u,m,S),A.right=p4(A,l,u,S+1,x),A}return null}function g4(h,l,u,m,x){if(u>=m)return;const b=h[u+m>>1];let S=u-1,A=m+1;for(;;){do S++;while(x(h[S],b)<0);do A--;while(x(h[A],b)>0);if(S>=A)break;let N=h[S];h[S]=h[A],h[A]=N,N=l[S],l[S]=l[A],l[A]=N}g4(h,l,u,A,x),g4(h,l,A+1,m,x)}const MY=11102230246251565e-32,yc=134217729,_ke=(3+8*MY)*MY;function y4(h,l,u,m,x){let b,S,A,N,O=l[0],$=m[0],U=0,q=0;$>O==$>-O?(b=O,O=l[++U]):(b=$,$=m[++q]);let K=0;if(UO==$>-O?(S=O+b,A=b-(S-O),O=l[++U]):(S=$+b,A=b-(S-$),$=m[++q]),b=S,A!==0&&(x[K++]=A);UO==$>-O?(S=b+O,N=S-b,A=b-(S-N)+(O-N),O=l[++U]):(S=b+$,N=S-b,A=b-(S-N)+($-N),$=m[++q]),b=S,A!==0&&(x[K++]=A);for(;U0:(m[0]-l[0])*(u[1]-l[1])-(u[0]-l[0])*(m[1]-l[1])>0}isAbove(l){return!this.isBelow(l)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const l=new $b(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 Of(h,l){return h[0]===l[0]&&h[1]===l[1]}function x4(h,l,u){const m=function(x,b,S,A,N,O){const $=(b-O)*(S-N),U=(x-N)*(A-O),q=$-U;if($===0||U===0||$>0!=U>0)return q;const K=Math.abs($+U);return Math.abs(q)>=33306690738754716e-32*K?q:-function(X,te,ie,ae,he,ue,ve){let ke,Ie,We,ze,Ge,Ue,Ve,yt,wt,At,It,kt,$t,mt,Ct,Dt,Ut,Yt;const vr=X-he,sr=ie-he,ir=te-ue,Zt=ae-ue;mt=vr*Zt,Ue=yc*vr,Ve=Ue-(Ue-vr),yt=vr-Ve,Ue=yc*Zt,wt=Ue-(Ue-Zt),At=Zt-wt,Ct=yt*At-(mt-Ve*wt-yt*wt-Ve*At),Dt=ir*sr,Ue=yc*ir,Ve=Ue-(Ue-ir),yt=ir-Ve,Ue=yc*sr,wt=Ue-(Ue-sr),At=sr-wt,Ut=yt*At-(Dt-Ve*wt-yt*wt-Ve*At),It=Ct-Ut,Ge=Ct-It,Bb[0]=Ct-(It+Ge)+(Ge-Ut),kt=mt+It,Ge=kt-mt,$t=mt-(kt-Ge)+(It-Ge),It=$t-Dt,Ge=$t-It,Bb[1]=$t-(It+Ge)+(Ge-Dt),Yt=kt+It,Ge=Yt-kt,Bb[2]=kt-(Yt-Ge)+(It-Ge),Bb[3]=Yt;let pr=function(zn,un){let qn=un[0];for(let Sn=1;Sn<4;Sn++)qn+=un[Sn];return qn}(0,Bb),Cr=22204460492503146e-32*ve;if(pr>=Cr||-pr>=Cr||(Ge=X-vr,ke=X-(vr+Ge)+(Ge-he),Ge=ie-sr,We=ie-(sr+Ge)+(Ge-he),Ge=te-ir,Ie=te-(ir+Ge)+(Ge-ue),Ge=ae-Zt,ze=ae-(Zt+Ge)+(Ge-ue),ke===0&&Ie===0&&We===0&&ze===0)||(Cr=11093356479670487e-47*ve+_ke*Math.abs(pr),pr+=vr*ze+Zt*ke-(ir*We+sr*Ie),pr>=Cr||-pr>=Cr))return pr;mt=ke*Zt,Ue=yc*ke,Ve=Ue-(Ue-ke),yt=ke-Ve,Ue=yc*Zt,wt=Ue-(Ue-Zt),At=Zt-wt,Ct=yt*At-(mt-Ve*wt-yt*wt-Ve*At),Dt=Ie*sr,Ue=yc*Ie,Ve=Ue-(Ue-Ie),yt=Ie-Ve,Ue=yc*sr,wt=Ue-(Ue-sr),At=sr-wt,Ut=yt*At-(Dt-Ve*wt-yt*wt-Ve*At),It=Ct-Ut,Ge=Ct-It,Oc[0]=Ct-(It+Ge)+(Ge-Ut),kt=mt+It,Ge=kt-mt,$t=mt-(kt-Ge)+(It-Ge),It=$t-Dt,Ge=$t-It,Oc[1]=$t-(It+Ge)+(Ge-Dt),Yt=kt+It,Ge=Yt-kt,Oc[2]=kt-(Yt-Ge)+(It-Ge),Oc[3]=Yt;const zr=y4(4,Bb,4,Oc,OY);mt=vr*ze,Ue=yc*vr,Ve=Ue-(Ue-vr),yt=vr-Ve,Ue=yc*ze,wt=Ue-(Ue-ze),At=ze-wt,Ct=yt*At-(mt-Ve*wt-yt*wt-Ve*At),Dt=ir*We,Ue=yc*ir,Ve=Ue-(Ue-ir),yt=ir-Ve,Ue=yc*We,wt=Ue-(Ue-We),At=We-wt,Ut=yt*At-(Dt-Ve*wt-yt*wt-Ve*At),It=Ct-Ut,Ge=Ct-It,Oc[0]=Ct-(It+Ge)+(Ge-Ut),kt=mt+It,Ge=kt-mt,$t=mt-(kt-Ge)+(It-Ge),It=$t-Dt,Ge=$t-It,Oc[1]=$t-(It+Ge)+(Ge-Dt),Yt=kt+It,Ge=Yt-kt,Oc[2]=kt-(Yt-Ge)+(It-Ge),Oc[3]=Yt;const Rr=y4(zr,OY,4,Oc,FY);mt=ke*ze,Ue=yc*ke,Ve=Ue-(Ue-ke),yt=ke-Ve,Ue=yc*ze,wt=Ue-(Ue-ze),At=ze-wt,Ct=yt*At-(mt-Ve*wt-yt*wt-Ve*At),Dt=Ie*We,Ue=yc*Ie,Ve=Ue-(Ue-Ie),yt=Ie-Ve,Ue=yc*We,wt=Ue-(Ue-We),At=We-wt,Ut=yt*At-(Dt-Ve*wt-yt*wt-Ve*At),It=Ct-Ut,Ge=Ct-It,Oc[0]=Ct-(It+Ge)+(Ge-Ut),kt=mt+It,Ge=kt-mt,$t=mt-(kt-Ge)+(It-Ge),It=$t-Dt,Ge=$t-It,Oc[1]=$t-(It+Ge)+(Ge-Dt),Yt=kt+It,Ge=Yt-kt,Oc[2]=kt-(Yt-Ge)+(It-Ge),Oc[3]=Yt;const cn=y4(Rr,FY,4,Oc,BY);return BY[cn-1]}(x,b,S,A,N,O,K)}(h[0],h[1],l[0],l[1],u[0],u[1]);return m>0?-1:m<0?1:0}function Xg(h,l){const u=h.point,m=l.point;return u[0]>m[0]?1:u[0]m[1]?1:-1:function(x,b,S){return x.left!==b.left?x.left?1:-1:x4(S,x.otherEvent.point,b.otherEvent.point)!==0?x.isBelow(b.otherEvent.point)?-1:1:!x.isSubject&&b.isSubject?1:-1}(h,l,u)}function Qg(h,l,u){const m=new $b(l,!1,h,h.isSubject),x=new $b(l,!0,h.otherEvent,h.isSubject);return Of(h.point,h.otherEvent.point)&&console.warn("what is that, a collapsed segment?",h),m.contourId=x.contourId=h.contourId,Xg(x,h.otherEvent)>0&&(h.otherEvent.left=!0,x.left=!1),h.otherEvent.otherEvent=x,h.otherEvent=m,u.push(x),u.push(m),u}function NI(h,l){return h[0]*l[1]-h[1]*l[0]}function v4(h,l){return h[0]*l[0]+h[1]*l[1]}function _4(h,l,u){const m=function(N,O,$,U){const q=[O[0]-N[0],O[1]-N[1]],K=[U[0]-$[0],U[1]-$[1]];function X(We,ze,Ge){return[We[0]+ze*Ge[0],We[1]+ze*Ge[1]]}const te=[$[0]-N[0],$[1]-N[1]];let ie=NI(q,K),ae=ie*ie;const he=v4(q,q);if(ae>0){const We=NI(te,K)/ie;if(We<0||We>1)return null;const ze=NI(te,q)/ie;return ze<0||ze>1?null:We===0||We===1?[X(N,We,q)]:ze===0||ze===1?[X($,ze,K)]:[X(N,We,q)]}if(ie=NI(te,q),ae=ie*ie,ae>0)return null;const ue=v4(q,te)/he,ve=ue+v4(q,K)/he,ke=Math.min(ue,ve),Ie=Math.max(ue,ve);return ke<=1&&Ie>=0?ke===1?[X(N,ke>0?ke:0,q)]:Ie===0?[X(N,Ie<1?Ie:1,q)]:[X(N,ke>0?ke:0,q),X(N,Ie<1?Ie:1,q)]:null}(h.point,h.otherEvent.point,l.point,l.otherEvent.point),x=m?m.length:0;if(x===0||x===1&&(Of(h.point,l.point)||Of(h.otherEvent.point,l.otherEvent.point))||x===2&&h.isSubject===l.isSubject)return 0;if(x===1)return!Of(h.point,m[0])&&!Of(h.otherEvent.point,m[0])&&Qg(h,m[0],u),!Of(l.point,m[0])&&!Of(l.otherEvent.point,m[0])&&Qg(l,m[0],u),1;const b=[];let S=!1,A=!1;return Of(h.point,l.point)?S=!0:Xg(h,l)===1?b.push(l,h):b.push(h,l),Of(h.otherEvent.point,l.otherEvent.point)?A=!0:Xg(h.otherEvent,l.otherEvent)===1?b.push(l.otherEvent,h.otherEvent):b.push(h.otherEvent,l.otherEvent),S&&A||S?(l.type=1,h.type=l.inOut===h.inOut?2:3,S&&!A&&Qg(b[1].otherEvent,b[0].point,u),2):A?(Qg(b[0],b[1].point,u),3):b[0]!==b[3].otherEvent?(Qg(b[0],b[1].point,u),Qg(b[1],b[2].point,u),3):(Qg(b[0],b[1].point,u),Qg(b[3].otherEvent,b[2].point,u),3)}function bke(h,l){if(h===l)return 0;if(x4(h.point,h.otherEvent.point,l.point)!==0||x4(h.point,h.otherEvent.point,l.otherEvent.point)!==0)return Of(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 Xg(h,l)===1?1:-1}class wke{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function Ske(h,l,u,m){let x,b=h+1,S=l[h].point;const A=l.length;for(bm;)b--;return b}function Tke(h,l,u){const m=new wke;if(h.prevInResult!=null){const x=h.prevInResult,b=x.outputContourId;if(x.resultTransition>0){const S=l[b];if(S.holeOf!=null){const A=S.holeOf;l[A].holeIds.push(u),m.holeOf=A,m.depth=l[b].depth}else l[b].holeIds.push(u),m.holeOf=b,m.depth=l[b].depth+1}else m.holeOf=null,m.depth=l[b].depth}else m.holeOf=null,m.depth=0;return m}const zY=Math.max,UY=Math.min;let II=0;function VY(h,l,u,m,x,b){let S,A,N,O,$,U;for(S=0,A=h.length-1;S0?U.left=!0:$.left=!0;const q=N[0],K=N[1];x[0]=UY(x[0],q),x[1]=UY(x[1],K),x[2]=zY(x[2],q),x[3]=zY(x[3],K),m.push($),m.push(U)}}const PI=[];function qY(h,l,u){let m=h,x=l;typeof h[0][0][0]=="number"&&(m=[h]),typeof l[0][0][0]=="number"&&(x=[l]);let b=function(q,K,X){let te=null;return q.length*K.length===0&&(X===0?te=PI:X===2?te=q:(X===1||X===3)&&(te=q.length===0?K:q)),te}(m,x,u);if(b)return b===PI?null:b;const S=[1/0,1/0,-1/0,-1/0],A=[1/0,1/0,-1/0,-1/0],N=function(q,K,X,te,ie){const ae=new d0(void 0,Xg);let he,ue,ve,ke,Ie,We;for(ve=0,ke=q.length;vete[2]||te[0]>X[2]||X[1]>te[3]||te[1]>X[3])&&(ie===0?ae=PI:ie===2?ae=q:(ie===1||ie===3)&&(ae=q.concat(K))),ae}(m,x,S,A,u),b)return b===PI?null:b;const O=function(q,K,X,te,ie,ae){const he=new m4(bke),ue=[],ve=Math.min(te[2],ie[2]);let ke,Ie,We;for(;q.length!==0;){let ze=q.pop();if(ue.push(ze),ae===0&&ze.point[0]>ve||ae===2&&ze.point[0]>te[2])break;if(ze.left){Ie=ke=he.insert(ze),We=he.minNode(),ke=ke!==We?he.prev(ke):null,Ie=he.next(Ie);const Ge=ke?ke.key:null;let Ue;if(mj(ze,Ge,ae),Ie&&_4(ze,Ie.key,q)===2&&(mj(ze,Ge,ae),mj(Ie.key,ze,ae)),ke&&_4(ke.key,ze,q)===2){let Ve=ke;Ve=Ve!==We?he.prev(Ve):null,Ue=Ve?Ve.key:null,mj(Ge,Ue,ae),mj(ze,Ge,ae)}}else ze=ze.otherEvent,Ie=ke=he.find(ze),ke&&Ie&&(ke=ke!==We?he.prev(ke):null,Ie=he.next(Ie),he.remove(ze),Ie&&ke&&_4(ke.key,Ie.key,q))}return ue}(N,0,0,S,A,u),$=function(q){let K,X;const te=function(he){let ue,ve,ke,Ie,We;const ze=[];for(ve=0,ke=he.length;ve{ie[We]=!0,We=te.length)&&te[ke];);ae.push(ue)}return ae}(O),U=[];for(let q=0;q<$.length;q++){let K=$[q];if(K.isExterior()){let X=[K.points];for(let te=0;te{S.push(new Ot(U,N+(U-A)/(O-A)*($-N)))}:(S,A,N,O,$,U)=>{S.push(new Ot(A+(U-N)/($-N)*(O-A),U))};for(const S of h){const A=[];for(const N of S){if(N.length<=2)continue;const O=[];for(let q=0;ql&&b(O,K,X,te,ie,l):ae>u?he=l&&b(O,K,X,te,ie,l),he>u&&ae<=u&&b(O,K,X,te,ie,u)}let $=N[N.length-1];const U=m===0?$.x:$.y;U>=l&&U<=u&&O.push($),O.length&&($=O[O.length-1],O[0].x===$.x&&O[0].y===$.y||O.push(O[0]),A.push(O))}A.length&&x.push(A)}return x}function Eke(h,l){const u=qY(b4(h),b4([l]),0);return u==null?[]:GY(u)}function jke(h,l,u=0){let x=b4(h,65536);const b=[];for(;l.valid();l.next()){const[S,A]=l.get();let N=S.x*65536,O=S.y*65536,$=A.x*65536,U=A.y*65536;const q=$-N,K=U-O,X=Math.hypot(q,K);if(X===0)continue;N-=q*u,O-=K*u,$+=q*u,U+=K*u;const te=Math.trunc(K/X*3),ie=-Math.trunc(q/X*3);b.push([[[N,O],[$,U],[$+te,U+ie],[N+te,O+ie],[N,O]]])}return b.length>0&&(x=qY(x,b,2)),GY(x,1/65536,128)}function b4(h,l=1){return[h.map(u=>u.map(m=>[m.x*l,m.y*l]))]}function GY(h,l=1,u){return h.map(m=>m.map((x,b)=>{const S=x.map(A=>{let N=A[0],O=A[1];return u&&(N=Math.round(N/u)*u,O=Math.round(O/u)*u),new Ot(N*l,O*l)._round()});return b>0&&S.reverse(),S}))}class w4{constructor(l,u){this.layoutVertexArray=new mc,this.indexArray=new _s,this.lineIndexArray=new vu,this.triangleSegments=new Ci,this.lineSegments=new Ci,this.programConfigurations=new se(l.layers,{zoom:l.zoom,lut:l.lut}),this.uploaded=!1,u&&(this.elevatedLayoutVertexArray=new Pc)}update(l,u,m,x,b,S,A,N){this.programConfigurations.updatePaintArrays(l,u,b,m,x,S,A,N)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(l){this.uploaded||(this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,ike.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,ske.members))),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.lineIndexBuffer.destroy(),this.programConfigurations.destroy(),this.triangleSegments.destroy(),this.lineSegments.destroy())}populatePaintArrays(l,u,m,x,b,S,A){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,l,u,m,x,b,S,void 0,A)}}class LI{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 w4(l,!1),this.elevationBufferData=new w4(l,!0),this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.projection=l.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=l.sourceLayerIndex,this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,m,x){this.hasPattern=h4("fill",this.layers,this.pixelRatio,u);const b=this.layers[0].layout.get("fill-sort-key"),S=[];for(const{feature:A,id:N,index:O,sourceLayerIndex:$}of l){const U=this.layers[0]._featureFilter.needGeometry,q=wn(A,U);if(!this.layers[0]._featureFilter.filter(new si(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),q,m))continue;const K=b?b.evaluate(q,{},m,u.availableImages):void 0,X={id:N,properties:A.properties,type:A.type,sourceLayerIndex:$,index:O,geometry:U?q.geometry:Ur(A,m,x),patterns:{},sortKey:K};S.push(X)}b&&S.sort((A,N)=>A.sortKey-N.sortKey);for(const A of S){const{geometry:N,index:O,sourceLayerIndex:$}=A;if(this.hasPattern){const U=f4("fill",this.layers,A,this.zoom,this.pixelRatio,u);this.patternFeatures.push(U)}else this.addFeature(A,N,O,m,{},u.availableImages,u.brightness,u.elevationFeatures);u.featureIndex.insert(l[O].feature,N,O,$,this.index)}}update(l,u,m,x,b,S,A){this.bufferData.update(l,u,m,x,b,S,A,this.worldview),this.elevationBufferData.update(l,u,m,x,b,S,A,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(l,u,m,x,b,S,A,this.worldview)}addFeatures(l,u,m,x,b,S){for(const A of this.patternFeatures)this.addFeature(A,A.geometry,A.index,u,m,x,S,l.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(l){this.bufferData.upload(l),this.elevationBufferData.upload(l),this.elevatedStructures&&this.elevatedStructures.upload(l)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(l,u,m,x,b,S=[],A,N){const O=hj(u,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(l,O,x,m,N):this.addGeometry(O,this.bufferData),this.bufferData.populatePaintArrays(l,m,b,S,x,A,this.worldview),this.elevationBufferData.populatePaintArrays(l,m,b,S,x,A,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(l,u,m,x,b){this.elevatedStructures&&(this.elevatedStructures.construct(l),this.elevatedStructures.populatePaintArrays(u,m,x,b,this.worldview))}addElevatedRoadFeature(l,u,m,x,b){const S=new Array,A=Oi.getElevationFeature(l,b);if(!A)return void this.addGeometry(u,this.bufferData);{const O=this.clipPolygonsToTile(u,1);O.length>0&&S.push({polygons:O,elevationFeature:A,elevationTileID:m})}const N={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(l,{},m),featureIndex:x};for(const O of S)if(O.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new Mc(O.elevationTileID,this.layers,this.zoom,this.lut));const U=O.elevationFeature.isTunnel();let q=0;l.properties.hasOwnProperty(Ii)&&(q=+l.properties[Ii]),this.elevatedStructures.addPortalCandidates(O.elevationFeature.id,O.polygons,U,O.elevationFeature,q)}O.elevationFeature.constantHeight==null&&(O.polygons=this.prepareElevatedPolygons(O.polygons,O.elevationFeature,O.elevationTileID));const $=new Vi(m,O.elevationTileID);this.addElevatedGeometry(O.polygons,$,O.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,x,N)}}addElevatedGeometry(l,u,m,x,b,S){const A={elevation:m,elevationSampler:u,bias:x,index:b,featureInfo:S},[N,O]=this.addGeometry(l,this.elevationBufferData,A);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:N,max:O}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,N),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,O))}addGeometry(l,u,m){let x=Number.POSITIVE_INFINITY,b=Number.NEGATIVE_INFINITY,S=null;m&&(S=m.elevationSampler.constantElevation(m.elevation,m.bias),S!=null&&(x=S,b=S));const A=(N,O,$)=>{if(m!=null)if(O.push(N),S!=null)u.elevatedLayoutVertexArray.emplaceBack(S),$.push(S);else{const U=m.elevationSampler.pointElevation(N,m.elevation,m.bias);u.elevatedLayoutVertexArray.emplaceBack(U),$.push(U),x=Math.min(x,U),b=Math.max(b,U)}};for(const N of l){let O=0;for(const ue of N)O+=ue.length;const $=u.triangleSegments.prepareSegment(O,u.layoutVertexArray,u.indexArray),U=$.vertexLength,q=[],K=[],X=[],te=[],ie=[],ae=u.layoutVertexArray.length;for(const ue of N){if(ue.length===0)continue;ue!==N[0]&&K.push(q.length/2);const ve=u.lineSegments.prepareSegment(ue.length,u.layoutVertexArray,u.lineIndexArray),ke=ve.vertexLength;m&&ie.push(u.layoutVertexArray.length-ae),A(ue[0],X,te),u.layoutVertexArray.emplaceBack(ue[0].x,ue[0].y),u.lineIndexArray.emplaceBack(ke+ue.length-1,ke),q.push(ue[0].x),q.push(ue[0].y);for(let Ie=1;Ie0&&m&&this.elevationMode==="hd-road-base"){const ue=m.elevation.isTunnel(),ve=m.elevation.safeArea,ke=this.elevatedStructures.addVertices(X,te);this.elevatedStructures.addTriangles(he,ke,ue);const Ie=ie.length;if(Ie>0){for(let We=0;We=m&&K.max.x<=b&&K.min.y>=x&&K.max.y<=S?N:O).push(q)}if(N.length===l.length)return l;const $=[new Ot(m,x),new Ot(b,x),new Ot(b,S),new Ot(m,S),new Ot(m,x)],U=N;for(const q of O)U.push(...Eke(q,$));return U}}let HY,WY,KY,YY;br(LI,"FillBucket",{omit:["layers","patternFeatures"]}),br(w4,"FillBufferData"),br(Mc,"ElevatedStructures");class DI{constructor(l,u,m,x){if(this.triangleCount=u.length/3,this.min=new Ot(0,0),this.max=new Ot(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||l.length===0)return;const[b,S]=[l[0].clone(),l[0].clone()];for(let U=1;UU.cellIdx-q.cellIdx||U.triIdx-q.triIdx);let $=0;for(;$this.max.x||this.min.x>l.x||l.y>this.max.y||this.min.y>l.y)return;const m=Ff(l.x-this.min.x,this.xScale,this.cellsX),x=Ff(l.y-this.min.y,this.yScale,this.cellsY),b=this.cells[x*this.cellsX+m];if(b){this._lazyInitLookup();for(let S=0;Sthis.max.x||this.min.x>u.x||l.y>this.max.y||this.min.y>u.y)return;this._lazyInitLookup();const x=Ff(l.x-this.min.x,this.xScale,this.cellsX),b=Ff(u.x-this.min.x,this.xScale,this.cellsX),S=Ff(l.y-this.min.y,this.yScale,this.cellsY),A=Ff(u.y-this.min.y,this.yScale,this.cellsY);for(let N=S;N<=A;N++)for(let O=x;O<=b;O++){const $=this.cells[N*this.cellsX+O];if($)for(let U=0;U<$.len;U++){const q=this.payload[$.start+U],K=Math.floor(q/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 m of this.footprints)u.push({footprint:m,id:l})}updateAppearances(l,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,m,x){const b=[];for(const{feature:S,id:A,index:N,sourceLayerIndex:O}of l){const $=this.layers[0]._featureFilter.needGeometry,U=wn(S,$);if(!this.layers[0]._featureFilter.filter(new si(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),U,m))continue;const q={id:A,properties:S.properties,type:S.type,sourceLayerIndex:O,index:N,geometry:$?U.geometry:Ur(S,m,x),patterns:{}};b.push(q)}for(const S of b){const{geometry:A,index:N,sourceLayerIndex:O}=S;this.addFeature(S,A,N,m,{},u.availableImages,u.brightness),u.featureIndex.insert(l[N].feature,A,N,O,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(l){}update(l,u,m,x,b,S,A){}destroy(){}addFeature(l,u,m,x,b,S=[],A){for(const N of hj(u,2)){const O=[],$=[],U=[],q=new Ot(1/0,1/0),K=new Ot(-1/0,-1/0);for(const ie of N)if(ie.length!==0){ie!==N[0]&&U.push($.length/2);for(let ae=0;ael.max.x||h.max.xl.max.y||h.max.ynew Ot((N.x+b.x*lr)*A-S.x*lr,(N.y+b.y*lr)*A-S.y*lr))}return T4(u,x,h.indices,0,h.indices.length,0,0)}function tZ(h,l,u,m){const x=Math.pow(2,m.z-u.z);return new Ot((h+u.x*lr)*x-m.x*lr,(l+u.y*lr)*x-m.y*lr)}function rZ(h,l){const u=[];l.grid.queryPoint(h,u);const m=l.indices,x=l.vertices;for(let b=0;b0&&(m.length>1&&u.push(m),m=[])}return m.length>1&&u.push(m),u}const j4=rn.types,Oke=["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"],Fke=["fill-extrusion-flood-light-ground-radius"],Bke=Math.pow(2,13),$ke=Math.pow(2,15)-1,BI=new Ot(0,1),up=2147483648,$I=1073741824;function gj(h,l,u,m,x,b,S,A){h.emplaceBack((l<<1)+S,(u<<1)+b,(Math.floor(m*Bke)<<1)+x,Math.round(A))}function yj(h,l,u){h.emplaceBack(l.x*lr,l.y*lr,u?1:0)}function zI(h,l,u,m,x,b){h.emplaceBack(l.x,l.y,(u.x<<1)+m,(u.y<<1)+x,b)}function xj(h,l,u){h.emplaceBack(l.x,l.y,l.z,u[0]*16384,u[1]*16384,u[2]*16384)}class iZ{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class A4{constructor(){this.centroidXY=new Ot(0,0),this.vertexArrayOffset=0,this.vertexCount=0,this.groundVertexArrayOffset=0,this.groundVertexCount=0,this.flags=0,this.footprintSegIdx=-1,this.footprintSegLen=0,this.polygonSegIdx=-1,this.polygonSegLen=0,this.min=new Ot(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new Ot(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new Ot(0,0)}span(){return new Ot(this.max.x-this.min.x,this.max.y-this.min.y)}}class k4{constructor(){this.acc=new Ot(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(l,u){l.min.x===Number.MAX_VALUE&&(l.min.x=l.max.x=u.x,l.min.y=l.max.y=u.y)}appendEdge(l,u,m){this.accCount++,this.acc._add(u);let x=!!this.borders;u.xl.max.x&&(l.max.x=u.x,x=!0),u.yl.max.y&&(l.max.y=u.y,x=!0),((u.x===0||u.x===lr)&&u.x===m.x)!=((u.y===0||u.y===lr)&&u.y===m.y)&&this.processBorderOverlap(u,m),x&&this.checkBorderIntersection(u,m)}checkBorderIntersection(l,u){u.x<0!=l.x<0&&this.addBorderIntersection(0,Qr(u.y,l.y,(0-u.x)/(l.x-u.x))),u.x>lr!=l.x>lr&&this.addBorderIntersection(1,Qr(u.y,l.y,(lr-u.x)/(l.x-u.x))),u.y<0!=l.y<0&&this.addBorderIntersection(2,Qr(u.x,l.x,(0-u.y)/(l.y-u.y))),u.y>lr!=l.y>lr&&this.addBorderIntersection(3,Qr(u.x,l.x,(lr-u.y)/(l.y-u.y)))}addBorderIntersection(l,u){this.borders||(this.borders=[[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE]]);const m=this.borders[l];um[1]&&(m[1]=u)}processBorderOverlap(l,u){if(l.x===u.x){if(l.y===u.y)return;const m=l.x===0?0:1;this.addBorderIntersection(m,u.y),this.addBorderIntersection(m,l.y)}else{const m=l.y===0?2:3;this.addBorderIntersection(m,u.x),this.addBorderIntersection(m,l.x)}}centroid(){return this.accCount===0?new Ot(0,0):new Ot(Math.floor(Math.max(0,this.acc.x)/this.accCount),Math.floor(Math.max(0,this.acc.y)/this.accCount))}intersectsCount(){return this.borders?this.borders.reduce((l,u)=>l+ +(u[0]!==Number.MAX_VALUE),0):0}}function sZ(h,l){const u=h.add(l)._unit(),m=fe(h.x*u.x+h.y*u.y,-1,1);var x,b,S;return S=Math.acos(m),Math.min(4,Math.max(-4,Math.tan(S)))/4*$ke*((x=h).x*(b=l).y-x.y*b.x<0?-1:1)}const zke=[h=>h.x<0,h=>h.x>lr,h=>h.y<0,h=>h.y>lr];function Uke(h,l,u,m){const x=[4];if(m===0)return x;u._mult(m);const b=h.sub(u),S=l.sub(u),A=[h,l,b,S];for(let N=0;N<4;N++)for(const O of A)if(zke[N](O)){x.push(N);break}return x}class C4{constructor(l){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new qE,this.indexArray=new _s,this.programConfigurations=new se(l.layers,{zoom:l.zoom,lut:l.lut},u=>Fke.includes(u)),this._segments=new Ci,this.hiddenByLandmarkVertexArray=new Pb,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Ci}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(l,u,m,x=!1){const b=l.length;if(b>2){let S=Math.max(0,this._segments.get().length-1);const A=this._segments._prepareSegment(4*b,this.vertexArray.length,2*this._segmentToGroundQuads[S].length);let N;S!==this._segments.get().length-1&&(S++,this._segmentToGroundQuads[S]=[],this._segmentToRegionTriCounts[S]=[0,0,0,0,0]);{const O=l[0],$=l[1];N=sZ(O.sub(l[b-1])._perp()._unit(),$.sub(O)._perp()._unit())}for(let O=0;Ox.region-b.region);for(let m=0;mN+O,0);let A=0;for(let N=0;N<=4;N++){const O=S[N];if(O!==0){let $=this.regionSegments[N];$||($=this.regionSegments[N]=new Ci);const U={vertexOffset:b.vertexOffset,primitiveOffset:b.primitiveOffset+A,vertexLength:b.vertexLength,primitiveLength:O};$.get().push(U)}A+=O}for(let N=0;N0?this.hiddenByLandmarkVertexBuffer=l.createVertexBuffer(this.hiddenByLandmarkVertexArray,Pke.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 UI{constructor(l){this.zoom=l.zoom,this.canonical=l.canonical,this.overscaling=l.overscaling,this.layers=l.layers,this.pixelRatio=l.pixelRatio,this.layerIds=this.layers.map(u=>u.fqid),this.index=l.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=l.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new _s,this.footprintVertices=new mc,this.footprintSegments=[],this.layoutVertexArray=new VE,this.centroidVertexArray=new bI,this.wallVertexArray=new rj,this.indexArray=new _s,this.programConfigurations=new se(l.layers,{zoom:l.zoom,lut:l.lut},u=>Oke.includes(u)),this.segments=new Ci,this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.groundEffect=new C4(l),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,m,x){this.features=[],this.hasPattern=h4("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=Mt(m),this.edgeRadius=this.layers[0].layout.get("fill-extrusion-edge-radius")/this.tileToMeter,this.wallMode=this.layers[0].paint.get("fill-extrusion-line-width").constantOr(1)!==0;for(const{feature:b,id:S,index:A,sourceLayerIndex:N}of l){const O=this.layers[0]._featureFilter.needGeometry,$=wn(b,O);if(!this.layers[0]._featureFilter.filter(new si(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),$,m))continue;const U={id:S,sourceLayerIndex:N,index:A,geometry:O?$.geometry:Ur(b,m,x),properties:b.properties,type:b.type,patterns:{}},q=this.layoutVertexArray.length,K=j4[U.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:b.id,feature:f4("fill-extrusion",this.layers,U,this.zoom,this.pixelRatio,u)});else if(this.wallMode)for(const X of U.geometry)for(const te of nZ(X,K))this.addFeature(b.id,U,[te],A,m,{},u.availableImages,x,u.brightness);else this.addFeature(b.id,U,U.geometry,A,m,{},u.availableImages,x,u.brightness);u.featureIndex.insert(b,U.geometry,A,N,this.index,q)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(l,u,m,x,b,S){for(const{featureId:A,feature:N}of this.features){const O=j4[N.type]==="Polygon",{geometry:$}=N;if(this.wallMode)for(const U of $)for(const q of nZ(U,O))this.addFeature(A,N,[q],N.index,u,m,x,b,S);else this.addFeature(A,N,$,N.index,u,m,x,b,S)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(l,u,m,x,b,S,A){this.programConfigurations.updatePaintArrays(l,u,b,m,x,S,A,this.worldview),this.groundEffect.update(l,u,b,m,x,S,A,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,Lke),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.wallVertexBuffer=l.createVertexBuffer(this.wallVertexArray,Ike.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=l.createVertexBuffer(this.layoutVertexExtArray,Rke.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,Nke.members,!0):this.centroidVertexBuffer&&this.centroidVertexBuffer.updateData(this.centroidVertexArray),this.needsCentroidUpdate=!1)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.centroidVertexBuffer&&this.centroidVertexBuffer.destroy(),this.layoutVertexExtBuffer&&this.layoutVertexExtBuffer.destroy(),this.groundEffect.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(l,u,m,x,b,S,A,N,O){const $=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(u,{})/this.tileToMeter,U=[new Ot(0,0),new Ot(lr,lr)],q=N.projection,K=q.name==="globe",X=this.wallMode||j4[u.type]==="Polygon",te=new k4;te.centroidDataIndex=this.centroidData.length;const ie=new A4;ie.buildingId=l,u.properties&&u.properties.hasOwnProperty("building_id")&&(ie.buildingId=Number(u.properties.building_id)),te.buildingId=ie.buildingId;const ae=this.layers[0].paint.get("fill-extrusion-base").evaluate(u,{},b)<=0,he=this.layers[0].paint.get("fill-extrusion-height").evaluate(u,{},b);let ue;if(ie.height=he,ie.vertexArrayOffset=this.layoutVertexArray.length,ie.groundVertexArrayOffset=this.groundEffect.vertexArray.length,K&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new jb),this.wallMode){if(K)return void $r("Non zero fill-extrusion-line-width is not yet supported on globe.");if(m.length!==1)return;ue=function(Ue){const Ve=Ue[0].x===Ue[Ue.length-1].x&&Ue[0].y===Ue[Ue.length-1].y;(function(ir){let Zt=0;const pr=ir.length;for(let Cr=0;Cr=0})(Ue)||(Ue=Ue.reverse());const wt={geometry:[],joinNormals:[],indices:[]},At=[],It=[],kt=[];let $t=Ue.length;for(;$t>=2&&Ue[$t-1].equals(Ue[$t-2]);)$t--;if($t<(Ve?3:2))return wt;let mt,Ct,Dt,Ut,Yt,vr=0;for(;vr<$t-1&&Ue[vr].equals(Ue[vr+1]);)vr++;Ve&&(mt=Ue[$t-2],Yt=Ue[vr].sub(mt)._unit()._perp());for(let ir=vr;ir<$t;ir++){if(Dt=ir===$t-1?Ve?Ue[vr+1]:void 0:Ue[ir+1],Dt&&Ue[ir].equals(Dt))continue;Yt&&(Ut=Yt),mt&&(Ct=mt),mt=Ue[ir],Yt=Dt?Dt.sub(mt)._unit()._perp():Ut,Ut=Ut||Yt;let Zt=Ut.add(Yt);Zt.x===0&&Zt.y===0||Zt._unit();const pr=Zt.x*Yt.x+Zt.y*Yt.y,Cr=pr!==0?1/pr:1/0,zr=Ut.x*Yt.y-Ut.y*Yt.x>0;let Rr="miter";const cn=2;Rr==="miter"&&Cr>cn&&(Rr="bevel"),Rr==="bevel"&&(Cr>100&&(Rr="flipbevel"),Cr{const ai=new Ot(un.x,un.y),Wn=new Ot(un.x,un.y);ai.x+=qn.x*fs,ai.y+=qn.y*fs,Wn.x-=qn.x*Math.max(Sn,1),Wn.y-=qn.y*Math.max(Sn,1),kt.push(qn),At.push(ai),It.push(Wn)};if(Rr==="miter")Zt._mult(Cr),zn(mt,Zt,0,0);else if(Rr==="flipbevel")Zt=Yt.mult(-1),zn(mt,Zt,0,0),zn(mt,Zt.mult(-1),0,0);else{const un=-Math.sqrt(Cr*Cr-1),qn=zr?un:0,Sn=zr?0:un;Ct&&zn(mt,Ut,qn,Sn),Dt&&zn(mt,Yt,qn,Sn)}}wt.geometry=[...At,...It.reverse(),At[0]],wt.joinNormals=[...kt,...kt.reverse(),kt[kt.length-1]];const sr=wt.geometry.length-1;for(let ir=0;irUe<(Ve.length-1)/2||Ue===Ve.length-1,ke=this.wallMode?[m]:hj(m,500);for(let Ue=ke.length-1;Ue>=0;Ue--){const Ve=ke[Ue];(Ve.length===0||qke(Ve[0]))&&ke.splice(Ue,1)}let Ie;if(K)Ie=hZ(ke,U,b);else{Ie=[];for(const Ue of ke)Ie.push({polygon:Ue,bounds:U})}const We=X?this.edgeRadius:0,ze=We>0&&this.zoom<17,Ge=(Ue,Ve)=>{if(Ue.length===0)return!1;const yt=Ue[Ue.length-1];return Ve.x===yt.x&&Ve.y===yt.y};for(const{polygon:Ue,bounds:Ve}of Ie){let yt=0,wt=0;for(const $t of Ue)X&&!$t[0].equals($t[$t.length-1])&&$t.push($t[0]),wt+=X?$t.length-1:$t.length;const At=this.segments.prepareSegment((X?5:4)*wt,this.layoutVertexArray,this.indexArray);ie.footprintSegIdx<0&&(ie.footprintSegIdx=this.footprintSegments.length),ie.polygonSegIdx<0&&(ie.polygonSegIdx=this.polygonSegments.length);const It={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},kt=new iZ;if(kt.vertexOffset=this.footprintVertices.length,kt.indexOffset=3*this.footprintIndices.length,kt.ringIndices=[],X){const $t=[],mt=[];yt=At.vertexLength;for(let Dt=0;Dt4&&cZ(mt[mt.length-2],mt[0],mt[1]),Dt=We?Vke(mt[mt.length-2],mt[0],mt[1],We):0;const Ut=[];let Yt,vr,sr;vr=mt[1].sub(mt[0])._perp()._unit();let ir=!0;for(let Zt=1,pr=0;Zt0?1:0,qn=Cr.dist(zr);if(pr+qn>32768&&(pr=0),We){sr=Rr.sub(zr)._perp()._unit();let Wn=oZ(Cr,zr,Rr,aZ(vr,sr),We);isNaN(Wn)&&(Wn=0);const Pi=zr.sub(Cr)._unit();Cr=Cr.add(Pi.mult(Dt))._round(),zr=zr.add(Pi.mult(-Wn))._round(),Dt=Wn,vr=sr,ae&&this.zoom>=17&&(Ge(Ut,Cr)||Ut.push(Cr),Ge(Ut,zr)||Ut.push(zr))}const Sn=At.vertexLength,fs=mt.length>4&&cZ(Cr,zr,Rr);let ai=uZ(pr,Ct,ir);if(gj(this.layoutVertexArray,Cr.x,Cr.y,zn,un,0,0,ai),gj(this.layoutVertexArray,Cr.x,Cr.y,zn,un,0,1,ai),this.wallMode){const Wn=ve(Zt-1,mt),Pi=ue.joinNormals[Zt-1];yj(this.wallVertexArray,Pi,Wn),yj(this.wallVertexArray,Pi,Wn)}if(pr+=qn,ai=uZ(pr,fs,!ir),Ct=fs,gj(this.layoutVertexArray,zr.x,zr.y,zn,un,0,0,ai),gj(this.layoutVertexArray,zr.x,zr.y,zn,un,0,1,ai),this.wallMode){const Wn=ve(Zt,mt),Pi=ue.joinNormals[Zt];yj(this.wallVertexArray,Pi,Wn),yj(this.wallVertexArray,Pi,Wn)}if(At.vertexLength+=4,this.indexArray.emplaceBack(Sn+0,Sn+1,Sn+2),this.indexArray.emplaceBack(Sn+1,Sn+3,Sn+2),At.primitiveLength+=2,We){const Wn=yt+(Zt===1?mt.length-2:Zt-2),Pi=Zt===1?yt:Wn+1;if(this.indexArray.emplaceBack(Sn+1,Wn,Sn+3),this.indexArray.emplaceBack(Wn,Pi,Sn+3),At.primitiveLength+=2,Yt===void 0&&(Yt=Sn),!N4(Rr,mt[Zt],Ve)){const cs=Zt===mt.length-1?Yt:At.vertexLength;this.indexArray.emplaceBack(Sn+2,Sn+3,cs),this.indexArray.emplaceBack(Sn+3,cs+1,cs),this.indexArray.emplaceBack(Sn+3,Pi,cs+1),At.primitiveLength+=3}ir=!ir}if(K){const Wn=this.layoutVertexExtArray,Pi=q.projectTilePoint(Cr.x,Cr.y,b),cs=q.projectTilePoint(zr.x,zr.y,b),Fa=q.upVector(b,Cr.x,Cr.y),us=q.upVector(b,zr.x,zr.y);xj(Wn,Pi,Fa),xj(Wn,Pi,Fa),xj(Wn,cs,us),xj(Wn,cs,us)}}X&&(yt+=mt.length-1),ae&&We&&this.zoom>=17&&(Ut.length!==0&&Ge(Ut,Ut[0])&&Ut.pop(),this.groundEffect.addData(Ut,Ve,$,We>0))}this.footprintSegments.push(kt),It.triangleCount=this.indexArray.length-It.triangleArrayOffset,this.polygonSegments.push(It),++ie.footprintSegLen,++ie.polygonSegLen}if(ie.vertexCount=this.layoutVertexArray.length-ie.vertexArrayOffset,ie.groundVertexCount=this.groundEffect.vertexArray.length-ie.groundVertexArrayOffset,ie.vertexCount!==0){if(ie.centroidXY=te.borders?BI:this.encodeCentroid(te,ie),u.properties&&u.properties.hasOwnProperty("building_id")){const Ue=ie.buildingId;let Ve=this.buildingGroups.get(Ue);Ve||(Ve={accX:0,accY:0,accCount:0,mergedMin:new Ot(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new Ot(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(Ue,Ve)),Ve.accX+=te.acc.x,Ve.accY+=te.acc.y,Ve.accCount+=te.accCount,Ve.mergedMin.x=Math.min(Ve.mergedMin.x,ie.min.x),Ve.mergedMin.y=Math.min(Ve.mergedMin.y,ie.min.y),Ve.mergedMax.x=Math.max(Ve.mergedMax.x,ie.max.x),Ve.mergedMax.y=Math.max(Ve.mergedMax.y,ie.max.y),Ve.partIndices.push(this.centroidData.length)}if(this.centroidData.push(ie),te.borders){this.featuresOnBorder.push(te);const Ue=this.featuresOnBorder.length-1;for(let Ve=0;Vethis.featuresOnBorder[u].borders[l][0]-this.featuresOnBorder[m].borders[l][0])}splitToSubtiles(){const l=[];for(let A=0;Alr),$=2*O+(+(N.min.x+N.max.x>lr)^O);for(let U=0;UA.triangleSegmentIdx===N.triangleSegmentIdx?A.subtile-N.subtile:A.triangleSegmentIdx-N.triangleSegmentIdx);let m=0,x=0,b=0;for(const A of l){if(A.triangleSegmentIdx!==m)break;b++}const S=l.length;for(;x!==l.length;){m=l[x].triangleSegmentIdx;let A=0,N=x,O=x;for(let $=N;$0&&this.triangleSubSegments.push({segment:K,min:U,max:q}),N=O;for(let X=N;X[te[0]*(1-ae[0])+ie[0]*ae[0],te[1]*(1-ae[1])+ie[1]*ae[1]],K=[],X=[];for(const te of this.triangleSubSegments){K[0]=te.min.x/lr,K[1]=te.min.y/lr,X[0]=te.max.x/lr,X[1]=te.max.y/lr;const ie=q($,U,K),ae=q($,U,X);if(new li([ie[0],ie[1],b],[ae[0],ae[1],S]).intersectsPrecise(m)===0){O&&(x.segments.push(O),O=void 0);continue}const he=te.segment;O&&O.vertexOffset!==he.vertexOffset&&(x.segments.push(O),O=void 0),O?(O.vertexLength+=he.vertexLength,O.primitiveLength+=he.primitiveLength):O={vertexOffset:he.vertexOffset,primitiveLength:he.primitiveLength,vertexLength:he.vertexLength,primitiveOffset:he.primitiveOffset,sortKey:void 0,vaos:{}}}return O&&x.segments.push(O),x}encodeCentroid(l,u){const m=l.centroid(),x=u.span(),b=Math.min(7,Math.round(x.x*this.tileToMeter/10)),S=Math.min(6,Math.round(x.y*this.tileToMeter/10));return new Ot(fe(m.x,1,8191)<<3|b,fe(m.y,1,8191)<<3|S)}encodeBorderCentroid(l){if(!l.borders)return new Ot(0,0);const u=l.borders,m=Number.MAX_VALUE;if(u[0][0]!==m||u[1][0]!==m){const x=u[0][0]!==m?0:1;return new Ot(6|(u[0][0]!==m?0:65528),(u[x][0]+u[x][1])/2<<3|6)}{const x=u[2][0]!==m?2:3;return new Ot((u[x][0]+u[x][1])/2<<3|6,6|(u[2][0]!==m?0:65528))}}showCentroid(l){const u=this.centroidData[l.centroidDataIndex];if(u.flags&=up,u.groupCentroidPos.x!==0||u.groupCentroidPos.y!==0){const m=u.span(),x=Math.min(7,Math.round(m.x*this.tileToMeter/10)),b=Math.min(6,Math.round(m.y*this.tileToMeter/10));u.centroidXY=new Ot(fe(u.groupCentroidPos.x,1,8191)<<3|x,fe(u.groupCentroidPos.y,1,8191)<<3|b)}else u.centroidXY=new Ot(0,0);this.writeCentroidToBuffer(u)}writeCentroidToBuffer(l){this.groundEffect.updateHiddenByLandmark(l);const u=l.vertexArrayOffset,m=l.vertexCount+l.vertexArrayOffset,x=-1073741824&l.flags?BI:l.centroidXY,b=this.centroidVertexArray.geta_centroid_pos0(u);if(this.centroidVertexArray.geta_centroid_pos1(u)!==x.y||b!==x.x){for(let S=u;SN.max.x||N.min.x>S.max.x||S.min.y>N.max.y||N.min.y>S.max.y||S.footprint.buildingIds.has(N.buildingId)&&(N.flags|=S.clipMask!==FI.None?-1073741824:up);else for(const N of this.centroidData)if(!(N.flags&up||N.flags&$I||S.min.x>N.max.x||N.min.x>S.max.x||S.min.y>N.max.y||N.min.y>S.max.y))for(let O=0;Ou!=K>u&&l<(this.footprintVertices.int16[2*($+S.vertexOffset)+0]-U)*(u-q)/(K-q)+U&&(x=!x)}A=N}}return x}getHeightAtTileCoord(l,u){let m=Number.NEGATIVE_INFINITY,x=!0;const b=4*(l+lr)*lr+(u+lr);if(this.partLookup.hasOwnProperty(b)){const S=this.partLookup[b];return S?{height:S.height,hidden:!!(S.flags&up)}:void 0}for(const S of this.centroidData)l>S.max.x||S.min.x>l||u>S.max.y||S.min.y>u||S.height<=m||this.footprintContainsPoint(l,u,S)&&(m=S.height,this.partLookup[b]=S,x=!!(S.flags&up));if(m!==Number.NEGATIVE_INFINITY)return{height:m,hidden:x};this.partLookup[b]=void 0}}function aZ(h,l){const u=h.add(l)._unit();return h.x*u.x+h.y*u.y}function Vke(h,l,u,m){const x=l.sub(h)._perp()._unit(),b=u.sub(l)._perp()._unit();return oZ(h,l,u,aZ(x,b),m)}function oZ(h,l,u,m,x){const b=Math.sqrt(1-m*m);return Math.min(h.dist(l)/3,l.dist(u)/3,x*b/m)}function N4(h,l,u){return h.xu[1].x&&l.x>u[1].x||h.yu[1].y&&l.y>u[1].y}function lZ(h,l){return h.xl[1].x||h.yl[1].y}function qke(h){return h.every(l=>l.x<=0)||h.every(l=>l.x>=lr)||h.every(l=>l.y<=0)||h.every(l=>l.y>=lr)}function cZ(h,l,u){if(h.x<0||h.x>=lr||l.x<0||l.x>=lr||u.x<0||u.x>=lr)return!1;const m=u.sub(l),x=m.perp(),b=h.sub(l);return(m.x*b.x+m.y*b.y)/Math.sqrt((m.x*m.x+m.y*m.y)*(b.x*b.x+b.y*b.y))>-.866&&x.x*b.x+x.y*b.y<0}function uZ(h,l,u){const m=l?2|h:-3&h;return u?1|m:-2&m}function dZ(){const h=Math.PI/32,l=Math.tan(h),u=qe;return u*Math.sqrt(1+2*l*l)-u}function hZ(h,l,u){const m=1<{for(const ze of Ie)X.push({polygon:ze,bounds:We})},ie=Math.ceil(Math.log2($)),ae=Math.ceil(Math.log2(U)),he=ie-ae,ue=[];for(let Ie=0;Ie0?0:1);for(let Ie=0;IeWe+1?ke.push({polygons:At,bounds:kt,depth:We+1}):te(At,kt)}if(It.length){const kt=[new Ot(ze===0?wt:Ge.x,ze===1?wt:Ge.y),Ue];ue.length>We+1?ke.push({polygons:It,bounds:kt,depth:We+1}):te(It,kt)}}return X}(h,l,Math.ceil((b-x)/11.25),Math.ceil((S-A)/11.25),1,(N,O,$)=>{if(N===0)return .5*(O+$);{const U=gt((u.y+O/lr)/m);return(Ft(.5*(gt((u.y+$/lr)/m)+U))*m-u.y)*lr}})}function Gke(h,l,u,m,x,b){const S=Math.pow(2,m.z-x.z);for(let A=0;A=N[S]&&(A=l,N=h),A[S]x&&gZ(A,N,S,x),A[S]b&&gZ(N,A,S,b)}}function VI(h,l,u,m,x,b){const S=[];for(let A=0;A=m&&X.x>=m||(K.x>=m?K=new Ot(m,K.y+(m-K.x)/(X.x-K.x)*(X.y-K.y))._round():X.x>=m&&(X=new Ot(m,K.y+(m-K.x)/(X.x-K.x)*(X.y-K.y))._round()),K.y>=x&&X.y>=x||(K.y>=x?K=new Ot(K.x+(x-K.y)/(X.y-K.y)*(X.x-K.x),x)._round():X.y>=x&&(X=new Ot(K.x+(x-K.y)/(X.y-K.y)*(X.x-K.x),x)._round()),O&&K.equals(O[O.length-1])||(O=[K],S.push(O),b&&b.push({progress:{min:ie+xZ(ae,he,K)*te,max:1},parentIndex:A,prevPoint:ae,nextPoint:he})),O.push(X),b&&(b[b.length-1].progress.max=ie+xZ(ae,he,X)*te,b[b.length-1].nextPoint=he)))))}if(b&&U>0)for(let q=$;qO.t-$.t);let S=0,A=0,N=[];for(m.push(N);S!==h.length;){if(A===b.length){for(;S!==h.length;)N.length!==0&&N[N.length-1].equals(h[S])||N.push(h[S]),S++;break}b[A].t<=S?(N.length!==0&&N[N.length-1].equals(b[A].point)||N.push(b[A].point),Math.trunc(b[A].t),A++):(N.length!==0&&N[N.length-1].equals(h[S])||N.push(h[S]),S++)}}function xZ(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 vj(h,l){return h.x*l.x+h.y*l.y}function vZ(h,l){if(h.length===1){let u=0;const m=l[u++];let x;for(;!x||m.equals(x);)if(x=l[u++],!x)return 1/0;for(;u{wt[0]=At,wt[1]=It,wt[2]=kt,wt[3]=1},yt=dZ();K>0&&(K+=yt),X+=yt;for(const wt of q){const At=[],It=[];for(const kt of wt){const $t=kt.x+te.x,mt=kt.y+te.y,Ct=U.projection.projectTilePoint($t,mt,ke),Dt=U.projection.upVector(ke,kt.x,kt.y);let Ut=K,Yt=X;if(ae){const vr=wZ($t,mt,K,X,ae,he,ue,ve);Ut+=vr.base,Yt+=vr.top}K!==0?Ve(Ge,Ct.x+Dt[0]*ze*Ut,Ct.y+Dt[1]*ze*Ut,Ct.z+Dt[2]*ze*Ut):Ve(Ge,Ct.x,Ct.y,Ct.z),Ve(Ue,Ct.x+Dt[0]*ze*Yt,Ct.y+Dt[1]*ze*Yt,Ct.z+Dt[2]*ze*Yt),cr(Ge,Ge,ie),cr(Ue,Ue,ie),At.push(new G0(Ge[0],Ge[1],Ge[2])),It.push(new G0(Ue[0],Ue[1],Ue[2]))}Ie.push(At),We.push(It)}return[Ie,We]}(h,l,u,m,x,b,S,A,N,O,$):S?function(U,q,K,X,te,ie,ae,he,ue){const ve=[],ke=[],Ie=[0,0,0,1];for(const We of U){const ze=[],Ge=[];for(const Ue of We){const Ve=Ue.x+X.x,yt=Ue.y+X.y,wt=wZ(Ve,yt,q,K,ie,ae,he,ue);Ie[0]=Ve,Ie[1]=yt,Ie[2]=wt.base,Ie[3]=1,ar(Ie,Ie,te),Ie[3]=Math.max(Ie[3],1e-5);const At=new G0(Ie[0]/Ie[3],Ie[1]/Ie[3],Ie[2]/Ie[3]);Ie[0]=Ve,Ie[1]=yt,Ie[2]=wt.top,Ie[3]=1,ar(Ie,Ie,te),Ie[3]=Math.max(Ie[3],1e-5);const It=new G0(Ie[0]/Ie[3],Ie[1]/Ie[3],Ie[2]/Ie[3]);ze.push(At),Ge.push(It)}ve.push(ze),ke.push(Ge)}return[ve,ke]}(l,u,m,x,b,S,A,N,O):function(U,q,K,X,te){const ie=[],ae=[],he=te[8]*q,ue=te[9]*q,ve=te[10]*q,ke=te[11]*q,Ie=te[8]*K,We=te[9]*K,ze=te[10]*K,Ge=te[11]*K;for(const Ue of U){const Ve=[],yt=[];for(const wt of Ue){const At=wt.x+X.x,It=wt.y+X.y,kt=te[0]*At+te[4]*It+te[12],$t=te[1]*At+te[5]*It+te[13],mt=te[2]*At+te[6]*It+te[14],Ct=te[3]*At+te[7]*It+te[15],Dt=kt+he,Ut=$t+ue,Yt=mt+ve,vr=Math.max(Ct+ke,1e-5),sr=kt+Ie,ir=$t+We,Zt=mt+ze,pr=Math.max(Ct+Ge,1e-5);Ve.push(new G0(Dt/vr,Ut/vr,Yt/vr)),yt.push(new G0(sr/pr,ir/pr,Zt/pr))}ie.push(Ve),ae.push(yt)}return[ie,ae]}(l,u,m,x,b)}function wZ(h,l,u,m,x,b,S,A){const N=S*x.getElevationAt(h,l,!0,!0),O=b[0]!==0,$=O?b[1]===0?S*(b[0]/7-450):S*function(U,q,K){const X=Math.floor(q[0]/8),te=Math.floor(q[1]/8),ie=10*(q[0]-8*X),ae=10*(q[1]-8*te),he=U.getElevationAt(X,te,!0,!0),ue=U.getMeterToDEM(K),ve=Math.floor(.5*(ie*ue-1)),ke=Math.floor(.5*(ae*ue-1)),Ie=U.tileCoordToPixel(X,te),We=2*ve+1,ze=2*ke+1,Ge=function(It,kt,$t,mt,Ct){return[It.getElevationAtPixel(kt,$t,!0),It.getElevationAtPixel(kt+Ct,$t,!0),It.getElevationAtPixel(kt,$t+Ct,!0),It.getElevationAtPixel(kt+mt,$t+Ct,!0)]}(U,Ie.x-ve,Ie.y-ke,We,ze),Ue=Math.abs(Ge[0]-Ge[1]),Ve=Math.abs(Ge[2]-Ge[3]),yt=Math.abs(Ge[0]-Ge[2])+Math.abs(Ge[1]-Ge[3]),wt=Math.min(.25,.5*ue*(Ue+Ve)/We),At=Math.min(.25,.5*ue*yt/ze);return he+Math.max(wt*ie,At*ae)}(x,b,A):N;return{base:N+(u===0?-1:u),top:O?Math.max($+m,N+u+2):N+m}}const I4=4096;class Wke{constructor(l){this.module=l,this.memoryStack=this.module.malloc(I4),this.memoryStackNextFree=this.memoryStack}createIntArray(l){const u=this.memoryStackNextFree;return this.memoryStackNextFree+=l.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>I4?-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>I4?-1:(new Float32Array(this.module.heapF32.buffer,u,l.length).set(l),u)}readStringBuffer(l){let u="";for(;this.module.heapU8[l]!==0;)u+=String.fromCharCode(this.module.heapU8[l]),++l;return u}setStyle(l){const u=l.normalScale;this.module.setStyle(u[0],u[1],u[2],l.tileToMeters)}setAOOptions(l,u){this.module.setAOOptions(l?1:0,u)}setMetricOptions(l,u){this.module.setMetricOptions(l?1:0,u)}setStructuralOptions(l){this.module.setStructuralOptions(l?1:0)}setFacadeOptions(l,u){this.module.setFacadeOptions(l,u?1:0)}setFauxFacadeOptions(l,u,m){this.module.setFauxFacadeOptions(l?1:0,u?1:0,m)}setFacadeClassifierOptions(l){this.module.setFacadeClassifierOptions(l)}generateMesh(l,u){this.memoryStackNextFree=this.memoryStack;for(const A of l){const N=this.createIntArray(A.ringIndices),O=this.createFloatArray(A.coordinates);if(N===-1||O===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(A.id,A.sourceId,A.minHeight,A.height,A.roofType,O,N,A.ringIndices.length-1)}for(const A of u){let N;N=A.entrances?JSON.parse(A.entrances):[];const O=this.createFloatArray(N),$=this.createFloatArray(A.coordinates);if(O===-1||$===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(A.sourceId,A.crossPerc,A.distanceToRoad,O,N.length,$,A.coordinates.length)}if(!this.module.generateMesh()){const A=this.module.getLastError();return this.readStringBuffer(A)}const m=this.module.getMeshCount(),x=new Array(m);for(let A=0;A>2)-3,ie=K[X++]>>2;if(X++,x.json=JSON.parse(PZ.decode(K.subarray(X,X+ie))),X+=ie,X>>0,Math.ceil(1.2*ve)),Ie=Math.ceil((ke-ve)/65536);try{return te.grow(Ie),ie(),!0}catch{return!1}},b:ae}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(K,he):K.then(ue=>ue.arrayBuffer()).then(ue=>WebAssembly.instantiate(ue,he))).then(ue=>{const{Rb:ve,Qb:ke,P:Ie,T:We,X:ze,Ja:Ge,La:Ue,Qa:Ve,Va:yt,Wa:wt,eb:At,jb:It,f:kt,e:$t,yb:mt,zb:Ct,Ab:Dt,Bb:Ut,Db:Yt,Gb:vr}=ue.instance.exports;te=$t;const sr=(()=>{let ir=0,Zt=0,pr=0,Cr=0;return zr=>{pr&&(ve(Cr),ve(ir),Zt+=pr,pr=ir=0),ir||(Zt+=128,ir=ke(Zt));const Rr=zr.length+7&-8;let cn=ir;Rr>=Zt&&(pr=Rr,cn=Cr=ke(Rr));for(let zn=0;zn{Ih=K,_j=void 0}))}()),q&&$.push(function(){if(P4)return;const K=function(X){let te;const ie=WebAssembly.instantiateStreaming(X,{}).then(ue=>{te=ue.instance,te.exports.__wasm_call_ctors()}),ae={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},he={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:ie,supported:!0,decodeGltfBuffer(ue,ve,ke,Ie,We,ze){(function(Ge,Ue,Ve,yt,wt,At,It){const kt=Ge.exports.sbrk,$t=yt+3&-4,mt=kt($t*wt),Ct=kt(At.length),Dt=new Uint8Array(Ge.exports.memory.buffer);Dt.set(At,Ct);const Ut=Ue(mt,yt,wt,Ct,At.length);if(Ut===0&&It&&It(mt,$t,wt),Ve.set(Dt.subarray(mt,mt+yt*wt)),kt(mt-kt(0)),Ut!==0)throw new Error(`Malformed buffer data: ${Ut}`)})(te,te.exports[he[We]],ue,ve,ke,Ie,te.exports[ae[ze]])}}}(fetch(So()));return K.ready.then(()=>{P4=K})}()),S)for(let K=0;K{const A=wg(m,(N,O)=>{N?S(N):b(O)});x&&x.addEventListener("abort",()=>{A.cancel(),S(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:h,type:"arrayBuffer"},l);return DZ(u,0,h,l)}function L4(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 D4(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 Bf{constructor(l,u,m,x){this.context=l,this.format=m,this.useMipmap=x&&x.useMipmap,this.texture=l.gl.createTexture(),this.update(u,{premultiply:x&&x.premultiply})}update(l,u){const m=l&&l instanceof HTMLVideoElement&&l.width===0?l.videoWidth:l.width,x=l&&l instanceof HTMLVideoElement&&l.height===0?l.videoHeight:l.height,{context:b}=this,{gl:S}=b,{x:A,y:N}=u&&u.position?u.position:{x:0,y:0},O=A+m,$=N+x;this.size&&(this.size[0]!==O||this.size[1]!==$)&&(!u||u.recreateWhenResize===void 0||u.recreateWhenResize)&&(S.bindTexture(S.TEXTURE_2D,null),S.deleteTexture(this.texture),this.texture=S.createTexture(),this.size=null),S.bindTexture(S.TEXTURE_2D,this.texture),b.pixelStoreUnpackFlipY.set(!1),b.pixelStoreUnpack.set(1),b.pixelStoreUnpackPremultiplyAlpha.set(this.format===S.RGBA8&&(!u||u.premultiply!==!1));const U=l instanceof HTMLImageElement||l instanceof HTMLCanvasElement||l instanceof HTMLVideoElement||l instanceof ImageData||ImageBitmap&&l instanceof ImageBitmap;if(!this.size&&O>0&&$>0){const q=this.useMipmap?Math.floor(Math.log2(Math.max(O,$)))+1:1;S.texStorage2D(S.TEXTURE_2D,q,this.format,O,$),this.size=[O,$]}this.size&&(U?S.texSubImage2D(S.TEXTURE_2D,0,A,N,L4(this.format),D4(this.format),l):"data"in l&&l.data&&S.texSubImage2D(S.TEXTURE_2D,0,A,N,m,x,L4(this.format),D4(this.format),l.data)),this.useMipmap&&S.generateMipmap(S.TEXTURE_2D)}bind(l,u,m=!1){const{context:x}=this,{gl:b}=x;b.bindTexture(b.TEXTURE_2D,this.texture),l!==this.minFilter&&(b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,l),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,this.useMipmap&&!m?l===b.NEAREST?b.NEAREST_MIPMAP_NEAREST:b.LINEAR_MIPMAP_LINEAR:l),this.minFilter=l),u!==this.wrapS&&(b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,u),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,u),this.wrapS=u)}bindExtraParam(l,u,m,x,b){const{context:S}=this,{gl:A}=S;A.bindTexture(A.TEXTURE_2D,this.texture),u!==this.magFilter&&(A.texParameteri(A.TEXTURE_2D,A.TEXTURE_MAG_FILTER,u),this.magFilter=u),l!==this.minFilter&&(A.texParameteri(A.TEXTURE_2D,A.TEXTURE_MIN_FILTER,this.useMipmap?l===A.NEAREST?A.NEAREST_MIPMAP_NEAREST:A.LINEAR_MIPMAP_LINEAR:l),this.minFilter=l),m!==this.wrapS&&(A.texParameteri(A.TEXTURE_2D,A.TEXTURE_WRAP_S,m),this.wrapS=m),x!==this.wrapT&&(A.texParameteri(A.TEXTURE_2D,A.TEXTURE_WRAP_T,x),this.wrapT=x),b!==this.compareMode&&(b?(A.texParameteri(A.TEXTURE_2D,A.TEXTURE_COMPARE_MODE,A.COMPARE_REF_TO_TEXTURE),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_COMPARE_FUNC,b)):A.texParameteri(A.TEXTURE_2D,A.TEXTURE_COMPARE_MODE,A.NONE),this.compareMode=b)}destroy(){const{gl:l}=this.context;l.deleteTexture(this.texture),this.texture=null}}class wj{constructor(l,u){this.context=l,this.texture=u}bind(l,u){const{context:m}=this,{gl:x}=m;x.bindTexture(x.TEXTURE_2D,this.texture),l!==this.minFilter&&(x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MAG_FILTER,l),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MIN_FILTER,l),this.minFilter=l),u!==this.wrapS&&(x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_S,u),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_T,u),this.wrapS=u)}}const eCe=Rn([{name:"a_pos_3f",components:3,type:"Float32"}]),tCe=Rn([{name:"a_color_3f",components:3,type:"Float32"}]),rCe=Rn([{name:"a_color_4f",components:4,type:"Float32"}]),nCe=Rn([{name:"a_uv_2f",components:2,type:"Float32"}]),iCe=Rn([{name:"a_normal_3f",components:3,type:"Float32"}]),sCe=Rn([{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"}]),aCe=Rn([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function OZ(h,l){const u=WI(h.projection,h.zoom,h.width,h.height),m=function(b,S,A,N,O){const $=new Qe(A.lng-180*Jg,A.lat),U=new Qe(A.lng+180*Jg,A.lat),q=b.project($.lng,$.lat),K=b.project(U.lng,U.lat),X=-Math.atan2(K.y-q.y,K.x-q.x),te=kr.fromLngLat(A);te.y=fe(te.y,-1+Jg,1-Jg);const ie=te.toLngLat(),ae=b.project(ie.lng,ie.lat),he=kr.fromLngLat(ie);he.x+=Jg;const ue=he.toLngLat(),ve=b.project(ue.lng,ue.lat),ke=BZ(ve.x-ae.x,ve.y-ae.y,X),Ie=kr.fromLngLat(ie);Ie.y+=Jg;const We=Ie.toLngLat(),ze=b.project(We.lng,We.lat),Ge=BZ(ze.x-ae.x,ze.y-ae.y,X),Ue=Math.abs(ke.x)/Math.abs(Ge.y),Ve=R([]);Y(Ve,Ve,-X*(1-(O?0:N)));const yt=R([]);return V(yt,yt,[1,1-(1-Ue)*N,1]),yt[4]=-Ge.x/Ge.y*N,Y(yt,yt,X),M(yt,Ve,yt),yt}(h.projection,0,h.center,u,l),x=FZ(h);return V(m,m,[x,x,1]),m}function FZ(h){const l=h.projection,u=WI(h.projection,h.zoom,h.width,h.height),m=M4(l,h.center),x=M4(l,Qe.convert(l.center));return Math.pow(2,m*u+(1-u)*x)}function WI(h,l,u,m,x=1/0){const b=h.range;if(!b)return 0;const S=Math.min(x,Math.max(u,m)),A=Math.log2(S/1024);return Oe(b[0]+A,b[1]+A,l)}const Jg=1/4e4;function M4(h,l){const u=fe(l.lat,-85.051129,St),m=new Qe(l.lng-180*Jg,u),x=new Qe(l.lng+180*Jg,u),b=h.project(m.lng,u),S=h.project(x.lng,u),A=kr.fromLngLat(m),N=kr.fromLngLat(x),O=S.x-b.x,$=S.y-b.y,U=N.x-A.x,q=N.y-A.y,K=Math.sqrt((U*U+q*q)/(O*O+$*$));return Math.log2(K)}function BZ(h,l,u){const m=Math.cos(u),x=Math.sin(u);return{x:h*m-l*x,y:h*x+l*m}}function $Z(h,l,u){R(h),Y(h,h,Zn(l[2])),G(h,h,Zn(l[0])),W(h,h,Zn(l[1])),V(h,h,u),M(h,h,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function KI(h,l,u,m,x,b,S,A){const N=[u[0]-l[0],u[1]-l[1],0],O=[m[0]-l[0],m[1]-l[1],0];if(Le(N)<1e-12||Le(O)<1e-12)return gr(h);const $=tr([],N,O);pt($,$),Te(O,m,l),N[2]=(b-x)*A,O[2]=(S-x)*A;const U=N;return tr(U,N,O),pt(U,U),ca(h,$,U)}function YI(h,l,u=!1){const m=lp(l.zoom),x=function(b,S,A){const N=S.worldSize,O=[b[12],b[13],b[14]],$=gt(O[1]/N),U=et(O[0]/N),q=R([]),K=ot(1,$)*N,X=ot(1,0)*N*Wt($,S.zoom),te=1/o4(N);let ie=X*te;if(A){const ve=WI(S.projection,S.zoom,S.width,S.height,1024);ie=te*S.projection.pixelSpaceConversion(S.center.lat,N,ve)}const ae=Be($,U);me(ae,ae,He([],pt([],ae),K*ie*O[2]));const he=function(ve){const ke=[ve[0],ve[1],ve[2]];let Ie=[0,1,0];const We=tr([],Ie,ke);return tr(Ie,ke,We),vt(Ie)===0&&(Ie=[0,1,0],tr(We,ke,Ie)),pt(We,We),pt(Ie,Ie),pt(ke,ke),[We[0],We[1],We[2],0,Ie[0],Ie[1],Ie[2],0,ke[0],ke[1],ke[2],0,ve[0],ve[1],ve[2],1]}(ae);V(q,q,[ie,ie,ie*K]),B(q,q,[-O[0],-O[1],-O[2]]);const ue=M([],S.globeMatrix,he);return M(ue,ue,q),M(ue,ue,b),ue}(h,l,u);if(m>0){const b=function(S,A){const N=A.worldSize,O=ot(1,0)*N*Wt(A.center.lat,A.zoom)/o4(N),$=ot(1,A.center.lat)*N,U=R([]);W(U,U,Zn(A.center.lng)),G(U,U,Zn(A.center.lat)),B(U,U,[0,0,De]),V(U,U,[O,O,O*$]);const q=A.point;return B(U,U,[-q.x,-q.y,0]),M(U,U,S),M(U,A.globeMatrix,U)}(h,l);return function(S,A,N){const O=(X,te,ie)=>{const ae=Le(X),he=Le(te),ue=op(X,te,ie);return He(ue,ue,1/Le(ue)*Qr(ae,he,ie))},$=O([S[0],S[1],S[2]],[A[0],A[1],A[2]],N),U=O([S[4],S[5],S[6]],[A[4],A[5],A[6]],N),q=O([S[8],S[9],S[10]],[A[8],A[9],A[10]],N),K=op([S[12],S[13],S[14]],[A[12],A[13],A[14]],N);return[$[0],$[1],$[2],0,U[0],U[1],U[2],0,q[0],q[1],q[2],0,K[0],K[1],K[2],1]}(x,b,m)}return x}function O4(h,l,u,m){const x=li.projectAabbCorners(m,u);let b=Number.MAX_VALUE;for(let A=0;A0||ie===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])&&($=K)}U=$}while(U!==O);return N.length>0&&N.push(N[0]),N}(x);if(Ns(h,S))return b}const H0=64,Ub={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function ZI(h,l,u,m,x,b,S,A,N,O=!1){const $=u.zoom,U=u.project(m),q=Wt(m.lat,$),K=1/q;R(h),B(h,h,[U.x+S[0]*K,U.y+S[1]*K,S[2]]);let X=1,te=1;const ie=u.worldSize;if(O){if(u.projection.name==="mercator"){let ve=0;u.elevation&&(ve=u.elevation.getAtPointOrZero(new kr(U.x/ie,U.y/ie),0));const ke=ar([],[U.x,U.y,ve,1],u.projMatrix)[3]/u.cameraToCenterDistance;X=ke,te=ke*Wt(u.center.lat,$)}else if(u.projection.name==="globe"){const ve=YI(h,u),ke=[0,0,0,1];ar(ke,ke,M([],u.projMatrix,ve));const Ie=ke[3]/u.cameraToCenterDistance,We=lp($),ze=u.projection.pixelsPerMeter(m.lat,ie)*Wt(m.lat,$),Ge=u.projection.pixelsPerMeter(u.center.lat,ie)*Wt(u.center.lat,$);X=Ie/Qr(ze,nr(u.center.lat),We),te=Ie*q/ze,X*=Ge,te*=Ge}}else X=K;V(h,h,[X,X,te]);const ae=[...h],he=l.orientation,ue=[];if($Z(ue,[he[0]+(x?x[0]:0),he[1]+(x?x[1]:0),he[2]+(x?x[2]:0)],b),M(h,ae,ue),A&&u.elevation){let ve=0;const ke=[];if(N&&u.elevation){ve=function(We,ze,Ge,Ue,Ve){const yt=ze.elevation;if(!yt)return 0;const wt=li.projectAabbCorners(Ge,Ue),At=ot(1,Ve.lat)*ze.worldSize,It=function(Zt,pr){const Cr=[0,0,1],zr=[{corners:[0,1,3,2],dotProductWithUp:0},{corners:[1,5,2,6],dotProductWithUp:0},{corners:[0,4,1,5],dotProductWithUp:0},{corners:[2,6,3,7],dotProductWithUp:0},{corners:[4,7,5,6],dotProductWithUp:0},{corners:[0,3,4,7],dotProductWithUp:0}];for(const Rr of zr){const cn=Zt[Rr.corners[0]],zn=Zt[Rr.corners[1]],un=Zt[Rr.corners[2]],qn=[zn[0]-cn[0],zn[1]-cn[1],pr*(zn[2]-cn[2])],Sn=tr(qn,qn,[un[0]-cn[0],un[1]-cn[1],pr*(un[2]-cn[2])]);pt(Sn,Sn),Rr.dotProductWithUp=Pt(Sn,Cr)}return zr.sort((Rr,cn)=>Rr.dotProductWithUp-cn.dotProductWithUp),zr[0].corners}(wt,At),kt=wt[It[0]],$t=wt[It[1]],mt=wt[It[2]],Ct=wt[It[3]],Dt=yt.getAtPointOrZero(new kr(kt[0]/ze.worldSize,kt[1]/ze.worldSize),0),Ut=yt.getAtPointOrZero(new kr($t[0]/ze.worldSize,$t[1]/ze.worldSize),0),Yt=yt.getAtPointOrZero(new kr(mt[0]/ze.worldSize,mt[1]/ze.worldSize),0),vr=yt.getAtPointOrZero(new kr(Ct[0]/ze.worldSize,Ct[1]/ze.worldSize),0),sr=(Dt+vr)/2,ir=(Ut+Yt)/2;return sr>ir?Ut=l.gl.NEAREST_MIPMAP_NEAREST}),h.uploaded=!0,h.image=null)}function oCe(h,l,u){h.indexBuffer=l.createIndexBuffer(h.indexArray,!1,!0),h.vertexBuffer=l.createVertexBuffer(h.vertexArray,eCe.members,!1,!0),h.normalArray&&(h.normalBuffer=l.createVertexBuffer(h.normalArray,iCe.members,!1,!0)),h.texcoordArray&&(h.texcoordBuffer=l.createVertexBuffer(h.texcoordArray,nCe.members,!1,!0)),h.colorArray&&(h.colorBuffer=l.createVertexBuffer(h.colorArray,(h.colorArray.bytesPerElement===12?tCe:rCe).members,!1,!0)),h.featureArray&&(h.pbrBuffer=l.createVertexBuffer(h.featureArray,aCe.members,!0)),h.segments=Ci.simpleSegment(0,0,h.vertexArray.length,h.indexArray.length);const m=h.material;m.pbrMetallicRoughness.baseColorTexture&&Sj(m.pbrMetallicRoughness.baseColorTexture,l),m.pbrMetallicRoughness.metallicRoughnessTexture&&Sj(m.pbrMetallicRoughness.metallicRoughnessTexture,l),m.normalTexture&&Sj(m.normalTexture,l),m.occlusionTexture&&Sj(m.occlusionTexture,l,u),m.emissionTexture&&Sj(m.emissionTexture,l)}function F4(h,l,u){if(h.meshes)for(const m of h.meshes)oCe(m,l,u);if(h.children)for(const m of h.children)F4(m,l,u)}function XI(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)XI(l)}function lCe(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 B4(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&&lCe(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)B4(l)}function W0(h,l){const u=h.json.bufferViews[l.bufferView],m=GI[l.componentType];return new m(h.buffers[u.buffer],(l.byteOffset||0)+(u.byteOffset||0),l.count*(u.byteStride&&u.byteStride!==bj[l.type]*m.BYTES_PER_ELEMENT?u.byteStride/m.BYTES_PER_ELEMENT:bj[l.type]))}function $4(h,l,u,m){const x=GI[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),S=h.json.bufferViews[l.bufferView],A=S.byteStride?S.byteStride/x.BYTES_PER_ELEMENT:bj[l.type],N=u.float32,O=N.length/u.capacity;for(let $=0,U=0;$0){for(let ie=0;ie0){b.texcoordArray=new np;const q=l.json.accessors[x.TEXCOORD_0];b.texcoordArray.resize(q.count);const K=W0(l,q);$4(l,q,b.texcoordArray,K)}if(x._FEATURE_ID_RGBA4444!==void 0){const q=l.json.accessors[x._FEATURE_ID_RGBA4444];l.json.extensionsUsed&&l.json.extensionsUsed.includes("EXT_meshopt_compression")&&(b.featureData=W0(l,q))}x._FEATURE_RGBA4444!==void 0&&(b.featureData=new Uint32Array(W0(l,l.json.accessors[x._FEATURE_RGBA4444]).buffer));const U=h.material;return b.material=function(q,K){const{emissiveFactor:X=[0,0,0],alphaMode:te="OPAQUE",alphaCutoff:ie=.5,normalTexture:ae,occlusionTexture:he,emissiveTexture:ue,doubleSided:ve,name:ke}=q,{baseColorFactor:Ie=[1,1,1,1],metallicFactor:We=1,roughnessFactor:ze=1,baseColorTexture:Ge,metallicRoughnessTexture:Ue}=q.pbrMetallicRoughness||{},Ve=he?K[he.index]:void 0;if(he&&he.extensions&&he.extensions.KHR_texture_transform&&Ve){const yt=he.extensions.KHR_texture_transform;Ve.offsetScale=[yt.offset[0],yt.offset[1],yt.scale[0],yt.scale[1]]}return{name:ke,pbrMetallicRoughness:{baseColorFactor:new Xn(...Ie),metallicFactor:We,roughnessFactor:ze,baseColorTexture:Ge?K[Ge.index]:void 0,metallicRoughnessTexture:Ue?K[Ue.index]:void 0},doubleSided:ve,emissiveFactor:new Xn(...X),alphaMode:te,alphaCutoff:ie,normalTexture:ae?K[ae.index]:void 0,occlusionTexture:Ve,emissionTexture:ue?K[ue.index]:void 0,defined:q.defined===void 0}}(U!==void 0?l.json.materials[U]:{defined:!1},u),b}function UZ(h,l,u){const{matrix:m,rotation:x,translation:b,scale:S,mesh:A,extras:N,children:O,name:$}=h,U={};if(U.name=$,U.localMatrix=m||function(q,K,X,te){var ie=K[0],ae=K[1],he=K[2],ue=K[3],ve=ie+ie,ke=ae+ae,Ie=he+he,We=ie*ve,ze=ie*ke,Ge=ie*Ie,Ue=ae*ke,Ve=ae*Ie,yt=he*Ie,wt=ue*ve,At=ue*ke,It=ue*Ie,kt=te[0],$t=te[1],mt=te[2];return q[0]=(1-(Ue+yt))*kt,q[1]=(ze+It)*kt,q[2]=(Ge-At)*kt,q[3]=0,q[4]=(ze-It)*$t,q[5]=(1-(We+yt))*$t,q[6]=(Ve+wt)*$t,q[7]=0,q[8]=(Ge+At)*mt,q[9]=(Ve-wt)*mt,q[10]=(1-(We+Ue))*mt,q[11]=0,q[12]=X[0],q[13]=X[1],q[14]=X[2],q[15]=1,q}([],x||[0,0,0,1],b||[0,0,0],S||[1,1,1]),U.globalMatrix=P(U.localMatrix),A!==void 0){U.meshes=u[A];const q=U.anchor=[0,0];for(const K of U.meshes){const{min:X,max:te}=K.aabb;q[0]+=X[0]+te[0],q[1]+=X[1]+te[1]}q[0]=Math.floor(q[0]/U.meshes.length/2),q[1]=Math.floor(q[1]/U.meshes.length/2)}if(N&&(N.id&&(U.id=N.id),N.lights&&(U.lights=function(q){if(!q.length)return[];const K=function(he){const ue=atob(he),ve=new Uint8Array(ue.length);for(let ke=0;ke1&&m[m.length-1].equals(m[0])&&m.pop();let x=0;for(let S=0;S0&&m.reverse();const b=Ob(m.flatMap(S=>[S.x,S.y]),[]);return b.length===0?null:{vertices:m,indices:b}}function hCe(h,l){const u=[],m=[];let x=0;const b=[];for(const S of h){x=u.length;const A=S.vertexArray.float32,N=S.indexArray.uint16;for(let O=0;O0&&([m[S+1],m[S+2]]=[m[S+2],m[S+1]])}return{vertices:u,indices:m}}function z4(h){const l=function(N,O){const $=[],U=WebGL2RenderingContext;if(N.json.textures)for(const q of N.json.textures){const K={magFilter:U.LINEAR,minFilter:U.NEAREST,wrapS:U.REPEAT,wrapT:U.REPEAT};q.sampler!==void 0&&Object.assign(K,N.json.samplers[q.sampler]),$.push({image:O[q.source],sampler:K,uploaded:!1})}return $}(h,h.images),u=function(N,O){const $=[];for(const U of N.json.meshes){const q=[];for(const K of U.primitives)q.push(cCe(K,N,O));$.push(q)}return $}(h,l),{scenes:m,scene:x,nodes:b}=h.json,S=m?m[x||0].nodes:[...b.keys()],A=[];for(const N of S)A.push(UZ(b[N],h,u));return function(N,O,$){const U={},q=new Set;for(let K=0;K0){const K=Array.from(q.values()).sort((X,te)=>X-te);for(let X=K.length-1;X>=0;X--)N.splice(K[X],1)}}(A,S,h.json.nodes),A}function fCe(h){h.heightmap=new Float32Array(4096),h.heightmap.fill(-1);const l=h.vertexArray.float32,u=h.aabb.min[0]-1,m=h.aabb.min[1]-1,x=H0/(h.aabb.max[0]-u+2),b=H0/(h.aabb.max[1]-m+2);for(let S=0;Sh.heightmap[O*H0+N]&&(h.heightmap[O*H0+N]=A)}}function VZ(h,l,u,m,x){u.reserve(u.length+4*h.length),m.reserve(m.length+10*h.length),x.reserve(x.length+10*h.length);let b=m.length;for(const S of h){const A=Math.min(10,Math.max(4,1.3*S.height))*l,N=[-S.normal[1],S.normal[0],0],O=Math.min(.29,.1*S.width/S.depth),$=S.width-2*S.depth*l*(O+.01),U=tt([],S.pos,N,$/2),q=tt([],S.pos,N,-$/2),K=[U[0],U[1],U[2]+S.height],X=[q[0],q[1],q[2]+S.height],te=tt([],S.normal,N,O);He(te,te,A);const ie=tt([],S.normal,N,-O);He(ie,ie,A),me(te,U,te),me(ie,q,ie),U[2]+=.1,q[2]+=.1,m.emplaceBack(te[0],te[1],te[2]),m.emplaceBack(ie[0],ie[1],ie[2]),m.emplaceBack(U[0],U[1],U[2]),m.emplaceBack(q[0],q[1],q[2]),m.emplaceBack(K[0],K[1],K[2]),m.emplaceBack(X[0],X[1],X[2]),m.emplaceBack(U[0],U[1],U[2]),m.emplaceBack(q[0],q[1],q[2]),m.emplaceBack(te[0],te[1],te[2]),m.emplaceBack(ie[0],ie[1],ie[2]);const ae=$/A/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 mCe(h,l){const u={};u.indexArray=new _s,u.vertexArray=new xu,u.colorArray=new Ch,VZ(h,l,u.indexArray,u.vertexArray,u.colorArray);const m={defined:!0};m.emissiveFactor=Xn.black;const x={};return x.baseColorFactor=Xn.white,m.pbrMetallicRoughness=x,u.material=m,u.aabb=new li([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),u}const qZ=Rn([{name:"a_pos_3f",components:3,type:"Float32"}]),pCe=Rn([{name:"a_normal_3",components:3,type:"Int16"}]),gCe=Rn([{name:"a_centroid_3",components:3,type:"Int16"}]),GZ=Rn([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),yCe=Rn([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),xCe=Rn([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),vCe=Rn([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),_Ce=Rn([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),bCe=Rn([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),HZ=rn.types,QI=32767;function wCe(h,l){const u=lr+l;for(const m of h)for(const x of m)if(x.x<-l||x.x>u||x.y<-l||x.y>u)return!1;return!0}function SCe(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 U4{constructor(){this.layoutVertexArray=new xu,this.layoutAttenuationArray=new Ch,this.layoutColorArray=new vu,this.indexArray=new _s,this.indexArrayForConflation=new _s,this.segmentsBucket=new Ci}}class V4{constructor(l){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Ci,this.entranceBloom=new U4;const u=66560;this.layoutVertexArray=new xu,this.layoutVertexArray.reserve(u),this.layoutNormalArray=new Md,this.layoutNormalArray.reserve(u),this.layoutCentroidArray=new Md,this.layoutCentroidArray.reserve(u),this.layoutColorArray=new vu,this.layoutColorArray.reserve(u),this.layoutFloodLightDataArray=new Ib,this.layoutFloodLightDataArray.reserve(u),this.layoutAOArray=new Pb,this.layoutAOArray.reserve(u),this.indexArray=new _s,this.indexArray.reserve(66560),this.indexArrayForConflation=new _s,this.segmentsBucket=new Ci,this.entranceBloom=new U4,l&&(this.layoutFacadePaintArray=new vu,this.layoutFacadeDataArray=new Hg,this.layoutFacadeVerticalRangeArray=new vu)}reserve(l,u,m){this.layoutVertexArray.reserveForAdditional(l),this.layoutCentroidArray.reserveForAdditional(l),this.layoutFloodLightDataArray.reserveForAdditional(l),this.layoutNormalArray.reserveForAdditional(l),this.layoutAOArray.reserveForAdditional(l),this.layoutColorArray.reserveForAdditional(l),this.indexArray.reserveForAdditional(u),m&&(this.layoutFacadePaintArray.reserveForAdditional(l),this.layoutFacadeDataArray.reserveForAdditional(l),this.layoutFacadeVerticalRangeArray.reserveForAdditional(l))}}class WZ{constructor(l){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new np,this.footprintsIndices=new ip,this.footprintsMin=new Ot(1/0,1/0),this.footprintsMax=new Ot(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new V4(!1),this.buildingWithFacade=new V4(!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 se(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 C4(l),this.groundEffect.groundRadiusArray=new Pc,this.hasAppearances=null}updateFootprints(l,u){const m=new DI([],[],1),x={vertices:[],indices:new Uint32Array(0),grid:m,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};u.push({footprint:x,id:l})}updateAppearances(l,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if(qI!=null||SZ!=null)return null;if(zb!=null)return zb;const l=fetch(mo());return zb=function(u){let m,x,b,S,A;function N(){m=new Uint8Array(A.buffer),x=new Int16Array(A.buffer),b=new Int32Array(A.buffer),S=new Float32Array(A.buffer)}function O(){throw new Error("Unexpected BuildingGen error.")}const $=()=>{},U={a:{a:O,f:function(q){const K=m.length,X=Math.max(q>>>0,Math.ceil(1.2*K)),te=Math.ceil((X-K)/65536);try{return A.grow(te),N(),!0}catch{return!1}},g:O,b:$,c:$,d:$,e:$}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(u,U):u.then(q=>q.arrayBuffer()).then(q=>WebAssembly.instantiate(q,U))).then(q=>{const K=q.instance.exports;return(0,K.g)(),A=K.f,N(),new Wke({setStyle:K.h,setAOOptions:K.i,setMetricOptions:K.j,setStructuralOptions:K.k,setFacadeOptions:K.l,setFauxFacadeOptions:K.m,setFacadeClassifierOptions:K.n,addFeature:K.o,addFacade:K.p,generateMesh:K.q,getLastError:K.r,getOuterRingLength:K.s,getMeshCount:K.t,getPositionsPtr:K.u,getPositionsLength:K.v,getNormalsPtr:K.w,getNormalsLength:K.x,getAOPtr:K.y,getAOLength:K.z,getUVPtr:K.A,getUVLength:K.B,getFauxFacadePtr:K.C,getFauxFacadeLength:K.D,getIndicesPtr:K.E,getIndicesLength:K.F,getBuildingPart:K.G,getRingCount:K.H,getRingPtr:K.I,getRingLength:K.J,malloc:K.K,free:K.L,heapU8:m,heap16:x,heap32:b,heapF32:S})})}(l).then(u=>(zb=null,qI=u,qI)).catch(u=>{$r("Could not load building-gen"),zb=null,SZ=u instanceof Error?u:new Error("Unknown error")}),zb}()}populate(l,u,m,x){const b=Kke();if(!b)return;const S=Mt(m);this.tileToMeter=S,this.brightness=u.brightness,b.setStyle({normalScale:[1,-1,S],tileToMeters:S}),b.setAOOptions(!1,.3),b.setMetricOptions(!1,16),b.setStructuralOptions(!0),b.setFacadeClassifierOptions(3);const A=new Map,N=new Map;let O=0;for(const{feature:ae}of l){if(HZ[ae.type]!=="LineString"){A.set(ae.id,ae.properties.source_id);continue}const he=this.layers[0]._featureFilter.needGeometry;if(he&&!this.layers[0]._featureFilter.filter(new si(this.zoom),ae,m))continue;const ue=wn(ae,he);if(!he&&!this.layers[0]._featureFilter.filter(new si(this.zoom),ue,m))continue;const ve=he?ue.geometry:Ur(ae,m,x),ke=[];for(const Ge of ve)for(const Ue of Ge)ke.push(Ue.x),ke.push(Ue.y);const Ie={coordinates:ke,crossPerc:ae.properties.cross_perc,distanceToRoad:ae.properties.distance_to_road,entrances:ae.properties.entrances,sourceId:0},We=ae.properties.source_id;let ze=N.get(We);ze||(ze=[],N.set(We,ze)),ze.push(Ie),++O}this.maxHeight=0;const $=new Array,U=new Set,q=ae=>{ae!=null&&U.add(ae)},K=(ae,he)=>{ae!=null&&$.push({buildingId:ae,footprintIndex:he})},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:he,index:ue,sourceLayerIndex:ve}of l){if(HZ[ae.type]==="LineString")continue;const ke=this.layers[0]._featureFilter.needGeometry;if(ke&&!this.layers[0]._featureFilter.filter(new si(this.zoom),ae,m))continue;let Ie=null;if(ae.properties&&ae.properties.hasOwnProperty("building_id")&&(Ie=Number(ae.properties.building_id),U.has(Ie)))continue;const We=wn(ae,ke);if(!ke&&!this.layers[0]._featureFilter.filter(new si(this.zoom),We,m))continue;const ze=ke?We.geometry:Ur(ae,m,x),Ge=hj(ze,500);let Ue=!1;for(const Nn of Ge)if(Nn.length!==1){Ue=!0;break}if(Ue){q(Ie);continue}if(!wCe(ze,163)){q(Ie);continue}const Ve=this.layers[0],yt=SCe(Ve.layout.get("building-roof-shape").evaluate(ae,{},m)),wt=Ve.layout.get("building-base").evaluate(ae,{},m),At=Ve.layout.get("building-height").evaluate(ae,{},m),It=Ve.layout.get("building-flood-light-ground-radius").evaluate(ae,{},m),kt=Ve.paint.get("building-ambient-occlusion-intensity"),$t=It/this.tileToMeter;ae.properties["building-part"]="roof";const mt=Ve.paint.get("building-color").evaluate(ae,{},this.canonical).toPremultipliedRenderColor(this.lut),Ct=Ve.paint.get("building-emissive-strength").evaluate(ae,{},this.canonical);ae.properties["building-part"]="wall";const Dt=Ve.paint.get("building-color").evaluate(ae,{},this.canonical).toPremultipliedRenderColor(this.lut),Ut=Ve.paint.get("building-emissive-strength").evaluate(ae,{},this.canonical);ae.properties["building-part"]="window";const Yt=Ve.paint.get("building-color").evaluate(ae,{},this.canonical).toPremultipliedRenderColor(this.lut),vr=Ve.paint.get("building-emissive-strength").evaluate(ae,{},this.canonical);ae.properties["building-part"]="door";const sr=Ve.paint.get("building-color").evaluate(ae,{},this.canonical).toPremultipliedRenderColor(this.lut),ir=Ve.paint.get("building-emissive-strength").evaluate(ae,{},this.canonical);let Zt=Ve.layout.get("building-flood-light-wall-radius").evaluate(ae,{},m);Zt=fe(Zt,0,2048);const pr=Zt/2048*QI,Cr=A.get(he),zr=N.get(Cr)||[],Rr=zr.length!==0&&Ve.layout.get("building-facade").evaluate(ae,{},m);b.setFacadeOptions(4,!0),b.setFauxFacadeOptions(Rr,!1,1);let cn=0,zn=0,un=0,qn=0,Sn=0,fs=0,ai=0,Wn=0,Pi=0,cs=0,Fa=0;if(Rr){let Nn=Math.round(Ve.layout.get("building-facade-floors").evaluate(ae,{},m));if(wt===0){Nn=Math.max(1,Nn-(zr.length>0?1:0));let Ss=4;if(At>100){const ka=[10,13,15];Ss=ka[ae.id?ae.id%ka.length:0]}else At<=10&&(Ss=3);b.setFacadeOptions(Ss,!0),Sn=(At<15?1.3:1.61803)*Ss/S}else Sn=wt/S;fs=At/S,Sn=Math.min(Sn,fs),un=Ve.layout.get("building-facade-unit-width").evaluate(ae,{},m)/S,qn=(fs-Sn)/Nn,b.setFauxFacadeOptions(!0,!0,un);const Za=Ve.layout.get("building-facade-window").evaluate(ae,{},m);cn=Za[0],zn=Za[1],ai=Math.floor(65535*Math.min(1,Sn/lr)),Wn=Math.floor(65535*Math.min(1,fs/lr)),Pi=Math.floor(255*cn)<<8|Math.floor(255*zn),cs=Math.floor(65535*Math.min(1,un/lr)),Fa=Math.floor(65535*Math.min(1,qn/lr))}const us=Array(Ge.length),bs={x:1/0,y:1/0},Ys={x:-1/0,y:-1/0},ws={x:0,y:0};let jo=0;for(let Nn=0;Nn0){const Ss=[],ka=Array(Za.length+1);ka[0]=0;for(let Xu=0;Xulr||bs.y<0||Ys.y>lr)&&this.featuresOnBorder.push({featureId:ae.id,footprintIndex:this.footprints.length});{const Nn=Ob(mp,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+Nn.length),this.footprintsIndices.uint16.set(Nn,tw),this.buildingIds.add(Ie??ae.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,Yu.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,Yu.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,Zu.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,Zu.y);const Za={footprintVertexOffset:fp,footprintVertexLength:this.footprintsVertices.length-fp,footprintIndexOffset:tw,footprintIndexLength:this.footprintsIndices.length-tw,min:Yu,max:Zu,hiddenFlags:0,indicesOffset:AP,indicesLength:RB,bloomIndicesOffset:Ao,bloomIndicesLength:ms,groundEffectVertexOffset:ev,groundEffectVertexLength:rw,hasFauxFacade:Rr,height:ew,promoteId:he,feature:We,parts:Ka,buildingBloom:jl},Ss=this.footprints.length;ae.id!==void 0&&this.featureFootprintLookup.set(ae.id,Ss),K(Ie,Ss),this.footprints.push(Za)}this.programConfigurations.populatePaintArrays(jn.layoutVertexArray.length,ae,ue,{},u.availableImages,m,u.brightness),this.groundEffect.addPaintPropertiesData(ae,ue,{},u.availableImages,m,u.brightness),u.featureIndex.insert(ae,ze,ue,ve,this.index,nl)}$.forEach(({buildingId:ae,footprintIndex:he})=>{U.has(ae)&&(this.footprints[he].hiddenFlags|=4)});const ie=new Set;this.buildingIds.forEach((ae,he,ue)=>{U.has(ae)||ie.add(ae)}),this.buildingIds=ie,this.groundEffect.prepareBorderSegments()}update(l,u,m,x,b,S,A){this.programConfigurations.updatePaintArrays(l,u,b,m,x,S,A),this.groundEffect.update(l,u,b,m,x,S,A),this.evaluate(this.layers[0],l),this.colorBufferUploaded=!1}isEmpty(){return this.buildingWithoutFacade.layoutVertexArray.length===0&&this.buildingWithFacade.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(l){const u=m=>{m.layoutVertexBuffer=l.createVertexBuffer(m.layoutVertexArray,qZ.members),m.layoutNormalBuffer=l.createVertexBuffer(m.layoutNormalArray,pCe.members),m.layoutCentroidBuffer=l.createVertexBuffer(m.layoutCentroidArray,gCe.members),m.layoutFloodLightDataBuffer=l.createVertexBuffer(m.layoutFloodLightDataArray,bCe.members),m.layoutFacadeDataArray&&m.layoutFacadeDataArray.length&&(m.layoutFacadeDataBuffer=l.createVertexBuffer(m.layoutFacadeDataArray,xCe.members)),m.layoutFacadeVerticalRangeArray&&m.layoutFacadeVerticalRangeArray.length&&(m.layoutFacadeVerticalRangeBuffer=l.createVertexBuffer(m.layoutFacadeVerticalRangeArray,vCe.members)),m.entranceBloom.layoutVertexArray.length&&(m.entranceBloom.layoutVertexBuffer=l.createVertexBuffer(m.entranceBloom.layoutVertexArray,qZ.members),m.entranceBloom.layoutAttenuationBuffer=l.createVertexBuffer(m.entranceBloom.layoutAttenuationArray,_Ce.members)),this.uploadUpdatedColorBuffer(l),this.uploadUpdatedIndexBuffer(l)};this.uploaded||(u(this.buildingWithoutFacade),u(this.buildingWithFacade),this.groundEffect.upload(l)),this.groundEffect.uploadPaintProperties(l),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){const l=u=>{u.layoutVertexBuffer&&(u.layoutVertexBuffer.destroy(),u.layoutNormalBuffer.destroy(),u.layoutColorBuffer.destroy(),u.segmentsBucket.destroy(),u.indexBuffer&&u.indexBuffer.destroy(),u.entranceBloom.layoutVertexBuffer&&(u.entranceBloom.layoutVertexBuffer.destroy(),u.entranceBloom.layoutColorBuffer.destroy(),u.entranceBloom.layoutAttenuationBuffer.destroy(),u.entranceBloom.indexBuffer.destroy(),u.entranceBloom.segmentsBucket.destroy()))};l(this.buildingWithoutFacade),l(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(l,u,m=!0){let x=!1;const b=m?u:0,S=0|(m?-1:~u);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const A of l){const N=this.footprints[A],O=N.hiddenFlags&S|b;N.hiddenFlags!==O&&(N.hiddenFlags=O,x=!0,this.groundEffect.updateHiddenByLandmarkRange(N.groundEffectVertexOffset,N.groundEffectVertexLength,N.hiddenFlags!==0))}return x&&(this.indexArrayForConflationUploaded=!1),x}uploadUpdatedIndexBuffer(l){if(this.groundEffect.uploadHiddenByLandmark(l),this.indexArrayForConflationUploaded)return;const u=x=>{x.indexArray.length!==0&&(x.indexArrayForConflation.resize(x.indexArray.length),x.indexArrayForConflation.uint16.set(x.indexArray.uint16),x.entranceBloom.indexArrayForConflation.resize(x.entranceBloom.indexArray.length),x.entranceBloom.indexArrayForConflation.uint16.set(x.entranceBloom.indexArray.uint16))};u(this.buildingWithoutFacade),u(this.buildingWithFacade);for(const x of this.footprints){const b=x.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,S=x.indicesOffset+x.indicesLength;if(x.hiddenFlags!==0){for(let N=x.indicesOffset;N{x.indexArray.length!==0&&(x.indexBuffer?x.indexBuffer.updateData(x.indexArrayForConflation):x.indexBuffer=l.createIndexBuffer(x.indexArrayForConflation,!0),x.entranceBloom.indexBuffer?x.entranceBloom.indexBuffer.updateData(x.entranceBloom.indexArrayForConflation):x.entranceBloom.indexBuffer=l.createIndexBuffer(x.entranceBloom.indexArrayForConflation,!0))};m(this.buildingWithoutFacade),m(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(l){const u=m=>{m.layoutColorBuffer?m.layoutColorBuffer.updateData(m.layoutColorArray):m.layoutColorBuffer=l.createVertexBuffer(m.layoutColorArray,GZ.members,!0),m.layoutFacadePaintArray&&(m.layoutFacadePaintBuffer?m.layoutFacadePaintBuffer.updateData(m.layoutFacadePaintArray):m.layoutFacadePaintBuffer=l.createVertexBuffer(m.layoutFacadePaintArray,yCe.members,!0)),m.entranceBloom.layoutColorBuffer?m.entranceBloom.layoutColorBuffer.updateData(m.entranceBloom.layoutColorArray):m.entranceBloom.layoutColorBuffer=l.createVertexBuffer(m.entranceBloom.layoutColorArray,GZ.members,!0)};u(this.buildingWithoutFacade),u(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(l,u){const m=l.paint.get("building-ambient-occlusion-intensity");for(const x of this.footprints){if(4&x.hiddenFlags)continue;const b=u[x.promoteId],S=x.feature;S.properties["building-part"]="roof";const A=l.paint.get("building-color").evaluate(S,b,this.canonical).toPremultipliedRenderColor(this.lut),N=l.paint.get("building-emissive-strength").evaluate(S,b,this.canonical);S.properties["building-part"]="wall";const O=l.paint.get("building-color").evaluate(S,b,this.canonical).toPremultipliedRenderColor(this.lut),$=l.paint.get("building-emissive-strength").evaluate(S,b,this.canonical);S.properties["building-part"]="window";const U=l.paint.get("building-color").evaluate(S,b,this.canonical).toPremultipliedRenderColor(this.lut),q=l.paint.get("building-emissive-strength").evaluate(S,b,this.canonical);S.properties["building-part"]="door";const K=l.paint.get("building-color").evaluate(S,b,this.canonical).toPremultipliedRenderColor(this.lut),X=l.paint.get("building-emissive-strength").evaluate(S,b,this.canonical),te=x.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const ae of x.parts){let he,ue=A;ae.part===1?(ue=A,he=N):ae.part===0?(ue=O,he=$):ae.part===2?(ue=U,he=q):ae.part===3&&(ue=K,he=X),he=fe(he,0,1);for(let ve=0;veS.max.x||N.max.xS.max.y||N.max.yA.max.x||A.min.x>l||u>A.max.y||A.min.y>u||A.height<=m||TCe(S,this.footprintsVertices.float32.subarray(2*A.footprintVertexOffset,2*(A.footprintVertexOffset+A.footprintVertexLength)),this.footprintsIndices.uint16.subarray(A.footprintIndexOffset,A.footprintIndexOffset+A.footprintIndexLength))&&(m=A.height,this.footprintLookup[b]=A,x=A.hiddenFlags!==0);if(m!==Number.NEGATIVE_INFINITY)return{height:m,hidden:x};this.footprintLookup[b]=void 0}}function TCe(h,l,u){for(let m=0;m1&&(N=l[++A]);const $=Math.abs(O-N.left),U=Math.abs(O-N.right),q=Math.min($,U);let K;const X=b/m*(x+1);if(N.isDash){const te=x-Math.abs(X);K=Math.sqrt(q*q+te*te)}else K=x-Math.sqrt(q*q+X*X);this.image.data[S+O]=Math.max(0,Math.min(255,K+128))}}}addRegularDash(l,u){for(let N=l.length-1;N>=0;--N){const O=l[N],$=l[N+1];O.zeroLength?l.splice(N,1):$&&$.isDash===O.isDash&&($.left=O.left,l.splice(N,1))}const m=l[0],x=l[l.length-1];m.isDash===x.isDash&&(m.left=x.left-this.width,x.right=m.right+this.width);const b=this.width*this.nextRow;let S=0,A=l[S];for(let N=0;N1&&(A=l[++S]);const O=Math.abs(N-A.left),$=Math.abs(N-A.right),U=Math.min(O,$);this.image.data[b+N]=Math.max(0,Math.min(255,(A.isDash?U:-U)+u+128))}}addDash(l,u){const m=this.getKey(l,u);if(this.positions[m])return this.positions[m];const x=u==="round",b=x?7:0,S=2*b+1;if(this.nextRow+S>this.height)return $r("LineAtlas out of space"),null;l.length===0&&l.push(1);let A=0;for(let U=0;Uu.fqid),this.index=l.index,this.projection=l.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(u=>{this.gradients[u.id]={}}),this.layoutVertexArray=new P0,this.layoutVertexArray2=new xu,this.patternVertexArray=new xu,this.indexArray=new _s,this.programConfigurations=new se(l.layers,{zoom:l.zoom,lut:l.lut}),this.segments=new Ci,this.maxLineLength=0,this.zOffsetVertexArray=new xu,this.elevationGroundScaleVertexArray=new Pc,this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.tessellationStep=l.tessellationStep?l.tessellationStep:128,this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,m,x){this.hasPattern=h4("line",this.layers,this.pixelRatio,u);const b=this.layers[0].layout.get("line-sort-key");this.tileToMeter=Mt(m);const S=this.layers[0].layout.get("line-elevation-reference");if(S==="hd-road-markup")this.elevationType="road";else{const q=this.layers[0].layout.get("line-z-offset"),K=q.isConstant()&&!q.constantOr(0);this.elevationType=S!=="sea"&&S!=="ground"&&K?"none":"offset",this.elevationType==="offset"&&S==="none"&&$r(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=S==="sea"}const A=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&A!==void 0;const N=[];for(const{feature:q,id:K,index:X,sourceLayerIndex:te}of l){const ie=this.layers[0]._featureFilter.needGeometry,ae=wn(q,ie);if(!this.layers[0]._featureFilter.filter(new si(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),ae,m))continue;const he=b?b.evaluate(ae,{},m):void 0,ue={id:K,properties:q.properties,type:q.type,sourceLayerIndex:te,index:X,geometry:ie?ae.geometry:Ur(q,m,x),patterns:{},sortKey:he};N.push(ue)}b&&N.sort((q,K)=>q.sortKey-K.sortKey);const{lineAtlas:O,featureIndex:$}=u,U=this.addConstantDashes(O);for(const q of N){const{geometry:K,index:X,sourceLayerIndex:te}=q;if(U&&this.addFeatureDashes(q,O),this.hasPattern){const ie=f4("line",this.layers,q,this.zoom,this.pixelRatio,u);this.patternFeatures.push(ie)}else this.addFeature(q,K,X,m,O.positions,u.availableImages,u.brightness,u.elevationFeatures);$.insert(l[X].feature,K,X,te,this.index)}}addConstantDashes(l){let u=!1;for(const m of this.layers){const x=m.paint.get("line-dasharray").value,b=m.layout.get("line-cap").value;if(x.kind!=="constant"||b.kind!=="constant")u=!0;else{const S=b.value,A=x.value;if(!A)continue;l.addDash(A,S)}}return u}addFeatureDashes(l,u){const m=this.zoom;for(const x of this.layers){const b=x.paint.get("line-dasharray").value,S=x.layout.get("line-cap").value;if(b.kind==="constant"&&S.kind==="constant")continue;let A,N;if(b.kind==="constant"){if(A=b.value,!A)continue}else A=b.evaluate({zoom:m},l);N=S.kind==="constant"?S.value:S.evaluate({zoom:m},l),u.addDash(A,N),l.patterns[x.id]=[u.getKey(A,N)]}}update(l,u,m,x,b,S,A,N,O){this.programConfigurations.updatePaintArrays(l,u,b,m,x,S,A,O)}addFeatures(l,u,m,x,b,S){for(const A of this.patternFeatures)this.addFeature(A,A.geometry,A.index,u,m,x,S,l.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(l){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=l.createVertexBuffer(this.layoutVertexArray2,ICe)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=l.createVertexBuffer(this.patternVertexArray,RCe)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=l.createVertexBuffer(this.zOffsetVertexArray,ACe.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=l.createVertexBuffer(this.elevationGroundScaleVertexArray,kCe.members,!0)),this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,CCe),this.indexBuffer=l.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(l,u){let m,x;if(u&&u>0?(m=`mapbox_clip_start_${u}`,x=`mapbox_clip_end_${u}`):(m="mapbox_clip_start",x="mapbox_clip_end"),l.properties&&l.properties.hasOwnProperty(m)&&l.properties.hasOwnProperty(x))return{start:+l.properties[m],end:+l.properties[x]}}addFeature(l,u,m,x,b,S,A,N){const O=this.layers[0].layout,$=O.get("line-join").evaluate(l,{}),U=O.get("line-cap").evaluate(l,{}),q=O.get("line-miter-limit"),K=O.get("line-round-limit");this.lineClips=this.lineFeatureClips(l),this.lineFeature=l;const X=!(!l.properties||!l.properties.hasOwnProperty("mapbox_line_metrics"))&&l.properties.mapbox_line_metrics;this.zOffsetValue=O.get("line-z-offset").value;const te=this.layers[0].paint.get("line-width").value;if(te.kind!=="constant"&&te.isLineProgressConstant===!1&&(this.variableWidthValue=te),this.isSeaLevelReference){const ie=O.get("line-elevation-ground-scale").value;ie.kind==="constant"&&ie.value===0||(this.elevationGroundScaleValue=ie)}if(this.elevationType==="road"){const ie=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(l,u,x,N,$,U,q,K)){const[ae,he]=this.clipRuntimeLinesToTile(u,1);for(let ue=0;ue0?ke.parentIndex:null)}this.fillNonElevatedRoadSegment(ie)}}else for(let ie=0;ie0?ie:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,l,m,b,S,x,A,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 VI(l,-u,-u,lr+u,lr+u)}clipRuntimeLinesToTile(l,u){const m=[];return[VI(l,-u,-u,lr+u,lr+u,m),m]}addElevatedRoadFeature(l,u,m,x,b,S,A,N){const O=[],$=Oi.getElevationFeature(l,x);if($){const U=this.clipLinesToTile(u,1),q=this.prepareElevatedLines(U,$,m);for(const K of q)O.push({geometry:K,elevation:$,elevationTileID:m,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(O.length===0)return!1;for(const U of O){const q=this.layoutVertexArray.length;this.addLine(U.geometry,l,m,b,S,A,N);const K=new Vi(m,U.elevationTileID);if(U.elevation)for(let X=q;X>1,this.layoutVertexArray.int16[6*X+1]>>1),ie=K.pointElevation(te,U.elevation,.05);this.updateHeightRange(ie),this.zOffsetVertexArray.emplaceBack(ie,0,0)}else this.fillNonElevatedRoadSegment(q)}return!0}prepareElevatedLines(l,u,m){if(u.constantHeight!=null)return l;const x=[],b=1/Mt(m);for(const S of l)Hke(S,new Lc(u,b),0,x);return x}fillNonElevatedRoadSegment(l){for(let u=l;u0,q=N&&N.progress.max<1;if(this.lineClips){let Ge={min:this.lineClips.start,max:this.lineClips.end},Ue=1;if(N){const wt=this.lineClips.end-this.lineClips.start;Ge=function(At,It,kt){return{min:ys(At.min,It,kt),max:ys(At.max,It,kt)}}(N.progress,{min:0,max:1},Ge),wt>0&&(Ue=(Ge.max-Ge.min)/wt)}const Ve=+u.properties.mapbox_clip_feature_len,yt=+u.properties.mapbox_clip_seg_len;if(Number.isNaN(Ve)||Number.isNaN(yt)){for(let At=0;At=2&&l[X-1].equals(l[X-2]);)X--;let te=0;for(;te0,Ct=this.overscaling<=16?122880/(512*this.overscaling):0;if(Ue&&Ve==="round"){if(ItS&&(Ve="bevel"),Ve==="bevel"&&(It>2&&(Ve="flipbevel"),It2*Ct){const Yt=ae.sub(ae.sub(he)._mult(Ct/Dt)._round());this.updateDistance(he,Yt),this.addCurrentVertex(Yt,ve,0,0,ie,ze),he=Yt}this.updateDistance(he,ae),wt._mult(It),this.addCurrentVertex(ae,wt,0,0,ie,ze);const Ut=ae.dist(ue);if(Ut>2*Ct){const Yt=ae.add(ue.sub(ae)._mult(Ct/Ut)._round());this.updateDistance(ae,Yt),this.addCurrentVertex(Yt,ke,0,0,ie,ze),ae=Yt}}else wt._mult(It),this.addCurrentVertex(ae,wt,0,0,ie,ze);else if(Ve==="flipbevel"){if(It>100)wt=ke.mult(-1);else{const Dt=It*ve.add(ke).mag()/ve.sub(ke).mag();wt._perp()._mult(Dt*(mt?-1:1))}this.addCurrentVertex(ae,wt,0,0,ie,ze),this.addCurrentVertex(ae,wt.mult(-1),0,0,ie,ze)}else if(Ve==="bevel"||Ve==="fakeround"){const Dt=ae.dist(he);let Ut=1;if(this.elevationType==="offset"&&Ve==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&ze!=null&&he&&ue){const pr=4*Ct;Dt1){this.lineSoFar=l.w;const te=(u.x-l.x)/U,ie=(u.y-l.y)/U,ae=(u.z-l.z)/U,he=(u.w-l.w)/U,ue=u.x-l.x,ve=u.y-l.y,ke=Math.sqrt(ue*ue+ve*ve);if(ke===0)return;const Ie=-ve/ke,We=ue/ke,ze=Ie,Ge=We,Ue=-Ie,Ve=-We;for(let yt=1;yt=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,$),N.primitiveLength++),S?this.e2=$:this.e1=$,O!=null&&this.zOffsetVertexArray.emplaceBack(O.zOffset,O.variableWidth,O.variableWidth),this.elevationGroundScaleValue){const U=O?O.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(U)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(l,u){this.prevDistance=this.distance,this.distance+=l.dist(u),this.updateScaledDistance()}}function q4(h,l,u){return h.xu||h.yu}let XZ,QZ;function JZ(h,l,u){return l*(lr/(h.tileSize*Math.pow(2,u-h.tileID.overscaledZ)))}br(JI,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const eX=(h,l,u)=>(1-u)*h+u*l;function tX(h,l){return 1/JZ(h,1,l.tileZoom)}function rX(h,l,u,m){return h.translatePosMatrix(m||l.tileID.projMatrix,l,u.paint.get("line-translate"),u.paint.get("line-translate-anchor"))}const nX=h=>{const l=[];iX(h)&&l.push("RENDER_LINE_DASH"),h.paint.get("line-gradient")&&l.push("RENDER_LINE_GRADIENT"),h.paint.get("line-blend-mode")==="multiply"&&l.push("LINE_BLEND_MULTIPLY");const u=h.paint.get("line-trim-offset");u[0]===0&&u[1]===0||l.push("RENDER_LINE_TRIM_OFFSET"),h.paint.get("line-border-width").constantOr(1)!==0&&l.push("RENDER_LINE_BORDER");const m=h.layout.get("line-join").constantOr("miter")==="none",x=!!h.paint.get("line-pattern").constantOr(1);return m&&x&&l.push("LINE_JOIN_NONE"),l};function iX(h){const l=h.paint.get("line-dasharray").value;return l.kind!=="constant"||l.value}let G4;const sX=()=>G4||(G4={layout:XZ||(XZ=new rs({"line-cap":new Ht(nt.layout_line["line-cap"]),"line-join":new Ht(nt.layout_line["line-join"]),"line-miter-limit":new Qt(nt.layout_line["line-miter-limit"]),"line-round-limit":new Qt(nt.layout_line["line-round-limit"]),"line-sort-key":new Ht(nt.layout_line["line-sort-key"]),"line-z-offset":new Ht(nt.layout_line["line-z-offset"]),"line-elevation-reference":new Qt(nt.layout_line["line-elevation-reference"]),"line-cross-slope":new Qt(nt.layout_line["line-cross-slope"]),visibility:new Qt(nt.layout_line.visibility),"line-width-unit":new Qt(nt.layout_line["line-width-unit"]),"line-elevation-ground-scale":new Ht(nt.layout_line["line-elevation-ground-scale"])})),paint:QZ||(QZ=new rs({"line-opacity":new Ht(nt.paint_line["line-opacity"]),"line-color":new Ht(nt.paint_line["line-color"]),"line-translate":new Qt(nt.paint_line["line-translate"]),"line-translate-anchor":new Qt(nt.paint_line["line-translate-anchor"]),"line-width":new Ht(nt.paint_line["line-width"]),"line-gap-width":new Ht(nt.paint_line["line-gap-width"]),"line-offset":new Ht(nt.paint_line["line-offset"]),"line-blur":new Ht(nt.paint_line["line-blur"]),"line-dasharray":new Ht(nt.paint_line["line-dasharray"]),"line-pattern":new Ht(nt.paint_line["line-pattern"]),"line-pattern-cross-fade":new Qt(nt.paint_line["line-pattern-cross-fade"]),"line-gradient":new qg(nt.paint_line["line-gradient"]),"line-trim-offset":new Qt(nt.paint_line["line-trim-offset"]),"line-trim-fade-range":new Qt(nt.paint_line["line-trim-fade-range"]),"line-trim-color":new Qt(nt.paint_line["line-trim-color"]),"line-emissive-strength":new Ht(nt.paint_line["line-emissive-strength"]),"line-border-width":new Ht(nt.paint_line["line-border-width"]),"line-border-color":new Ht(nt.paint_line["line-border-color"]),"line-occlusion-opacity":new Qt(nt.paint_line["line-occlusion-opacity"]),"line-blend-mode":new Qt(nt.paint_line["line-blend-mode"]),"line-color-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"})}))},G4);class OCe extends Ht{possiblyEvaluate(l,u){return u=new si(Math.floor(u.zoom),{now:u.now,fadeDuration:u.fadeDuration,transition:u.transition,worldview:u.worldview}),super.possiblyEvaluate(l,u)}evaluate(l,u,m,x){return u=Object.assign({},u,{zoom:Math.floor(u.zoom)}),super.evaluate(l,u,m,x)}}let Tj;function aX(h,l){return l>0?l+2*h:h}const FCe=Rn([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),BCe=Rn([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),$Ce=Rn([{name:"a_projected_pos",components:4,type:"Float32"}],4);Rn([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const zCe=Rn([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),UCe=Rn([{name:"a_feature_index",components:1,type:"Float32"}],4),VCe=Rn([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),qCe=Rn([{name:"a_texb",components:2,type:"Uint16"}]),GCe=Rn([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),HCe=Rn([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);Rn([{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 oX=Rn([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),WCe=Rn([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);Rn([{name:"triangle",components:3,type:"Uint16"}]),Rn([{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"}]),Rn([{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"}]),Rn([{type:"Float32",name:"offsetX"}]),Rn([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const H4=class PL{constructor(l=null,u=0,m=4096){this.batchIndex=u,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=l||null,this.propsDwords=m,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(PL.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,PL.HEADER_BYTES,u.DYNAMIC_DRAW),this.propertiesBuffer=u.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(u.bindBuffer(u.UNIFORM_BUFFER,this.propertiesBuffer),u.bufferData(u.UNIFORM_BUFFER,this.totalBytes,u.DYNAMIC_DRAW),this.blockIndicesBuffer=u.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");u.bindBuffer(u.UNIFORM_BUFFER,this.blockIndicesBuffer),u.bufferData(u.UNIFORM_BUFFER,this.totalBytes,u.DYNAMIC_DRAW),u.bindBuffer(u.UNIFORM_BUFFER,null)}writeHeader(l){const u=this.headerData;u[0]=l.dataDrivenMask,u[1]=l.zoomDependentMask,u[2]=l.dataDrivenBlockSizeVec4,u[3]=l.offsets[0],u[4]=l.offsets[1],u[5]=l.offsets[2],u[6]=l.offsets[3],u[7]=l.offsets[4],u[8]=l.offsets[5],u[9]=l.offsets[6],u[10]=l.offsets[7],u[11]=l.offsets[8]}writeDataDrivenBlock(l,u,m){const x=4*m.dataDrivenBlockSizeVec4;if(x===0)return;const b=u*x;if(b+x>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${u} exceeds propertiesData capacity`);for(let S=0;S<9;S++)m.dataDrivenMask&1<{if(!A)return;const O=m.getUniformBlockIndex(u,S);O!==m.INVALID_INDEX&&(m.uniformBlockBinding(u,O,N),m.bindBufferBase(m.UNIFORM_BUFFER,N,A))},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)}}};H4.HEADER_DWORDS=12,H4.HEADER_BYTES=48;let W4=H4;function K4(h,l,u,m){return[Rb(255*h,255*l),Rb(255*u,255*m)]}function lX(h,l,u,m,x,b,S,A){return!!h&&(h.kind==="constant"?h.value==="none":h.kind==="composite"||h.kind==="source"?h.evaluate({zoom:0,brightness:b,worldview:A},l,u,x,m,S)==="none":typeof h=="string"&&h==="none")}br(W4,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class Y4{constructor(l,u,m,x,b="",S,A){this.layer=l,this.zoom=u,this.lut=m,this.isText=x,this.propDefs=this._getPropDefs(),this.worldview=b,this.maxUniformBufferBindings=S||24,this.uboSizeDwords=A||4096,this.featureVertexRangesFromId=new Map,this.allFeatures=[],this.ubos=[],this.featureCount=0,this.cachedHeader=null,this.maxFeaturesPerBatch=0,this.propertyHashToUBOIndex=new Map,this.canDeduplicate=this._checkIfAllPropertiesAreConstant(l,x),this.cachedParams=null,this.cachedParamsNext=null,this.cachedBrightness=void 0,this.cachedConstantUniforms=null,this.cachedConstantRenderZoom=null,this.cachedConstantBrightness=void 0,this.activeAppearanceByVtIndex=new Map}_getPropDefs(){const l=this.isText?"text":"icon";return[{name:`${l}-color`,useThemeName:`${l}-color-use-theme`,isColor:!0},{name:`${l}-halo-color`,useThemeName:`${l}-halo-color-use-theme`,isColor:!0},{name:`${l}-opacity`,useThemeName:null,isColor:!1},{name:`${l}-halo-width`,useThemeName:null,isColor:!1},{name:`${l}-halo-blur`,useThemeName:null,isColor:!1},{name:`${l}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${l}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${l}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const l=this.layer.paint,u=this.propDefs;let m=0,x=0,b=0,S=0;const A=[0,0,0,0,0,0,0,0,0];for(let N=0;N<9;N++){const{name:O,isColor:$,isVec2:U}=u[N],q=l.get(O),K=!(!q||typeof q.isConstant!="function"||q.isConstant()),X=this._appearancesHavePaintProperties(O),te=K||X,ie=!(!q||!q.value||q.value.kind!=="composite"),ae=this.layer._transitionablePaint._values[O],he=!te&&(ae&&ae.value&&ae.value.expression&&ae.value.expression.kind)==="camera";te?(m|=1<u.hasPaintProperty(l):this.isText?u=>u.hasTextPaintProperties():u=>u.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(l,u){const m=l.paint,x=u?"text":"icon",b=[`${x}-color`,`${x}-halo-color`,`${x}-opacity`,`${x}-halo-width`,`${x}-halo-blur`,`${x}-emissive-strength`,`${x}-occlusion-opacity`,"symbol-z-offset",`${x}-translate`];for(const S of b){const A=m.get(S);if(A&&typeof A=="object"&&"isConstant"in A&&!A.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(l,u){if(u.dataDrivenMask===0)return"";const m=[];for(let x=0;x<9;x++){if(!(u.dataDrivenMask&1<=X){$r(`Too many symbol features: batch ${q} requires binding points up to ${3*q+2}, device limit ${X}. Some features will render incorrectly.`);const ie={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:u,featureId:N};return this.allFeatures.push(ie),N!=null&&(this.featureVertexRangesFromId.has(N)||this.featureVertexRangesFromId.set(N,[]),this.featureVertexRangesFromId.get(N).push(ie)),0}this.ubos[q]||(this.ubos[q]=new W4(A,q,this.uboSizeDwords),this.ubos[q].writeHeader(O)),this.ubos[q].writeDataDrivenBlock($,K,O);const te={batchIndex:q,localFeatureIndex:K,vtFeatureIndex:u,featureId:N};return this.allFeatures.push(te),N!=null&&(this.featureVertexRangesFromId.has(N)||this.featureVertexRangesFromId.set(N,[]),this.featureVertexRangesFromId.get(N).push(te)),K}updateFeatures(l,u,m,x,b,S,A){if(this.layer=u,this.cachedConstantUniforms=null,!this.cachedHeader)return;const N=this.cachedHeader;for(const O of l){const $=this.featureVertexRangesFromId.get(O);if(!$)continue;const U=S[O]||{};for(const q of $){if(!m)continue;const K=m.feature(q.vtFeatureIndex);if(!K)continue;const X={type:K.type,id:O,properties:K.properties||{},geometry:[]},te=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(q.vtFeatureIndex):void 0,ie=this.evaluateAllProperties(X,U,x,b,A,void 0,te);this.ubos[q.batchIndex]&&this.ubos[q.batchIndex].writeDataDrivenBlock(ie,q.localFeatureIndex,N)}}}updateDynamicExpressions(l,u,m,x,b,S){if(this.layer=l,this.cachedConstantUniforms=null,!this.cachedHeader)return;const A=this.cachedHeader;for(const N of this.allFeatures){if(!u)continue;const O=u.feature(N.vtFeatureIndex);if(!O)continue;const $=N.featureId!=null&&b[N.featureId]||{},U={type:O.type,id:N.featureId,properties:O.properties||{},geometry:[]},q=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(N.vtFeatureIndex):void 0,K=this.evaluateAllProperties(U,$,m,x,S,void 0,q);this.ubos[N.batchIndex]&&this.ubos[N.batchIndex].writeDataDrivenBlock(K,N.localFeatureIndex,A)}}updateFeaturePaintForAppearance(l,u,m,x,b,S,A){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(l,A||null),!this.cachedHeader))return!1;const N=this.cachedHeader;if(N.dataDrivenMask===0)return!1;let O=!1;for(const $ of this.allFeatures){if($.vtFeatureIndex!==l)continue;const U=this.evaluateAllProperties(u,m,x,b,S,void 0,A);this.ubos[$.batchIndex]&&(this.ubos[$.batchIndex].writeDataDrivenBlock(U,$.localFeatureIndex,N),O=!0)}return O}getConstantUniformValues(l,u){const m=this.cachedHeader,x=!(!m||!m.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===u&&(!x||this.cachedConstantRenderZoom===l))return this.cachedConstantUniforms;const b=this.layer.paint,S=this.propDefs,A=x?new si(l,{brightness:u,worldview:this.worldview}):null,N={type:1,id:void 0,properties:{},geometry:[]},O=q=>{const K=S[q],X=b.get(K.name);if(!X)return[0,0,0,1];const te=K.useThemeName?b.get(K.useThemeName):void 0,ie=lX(te&&typeof te!="string"?te.value:void 0,N,{},[],void 0,u,void 0,this.worldview)?null:this.lut;let ae;ae=m&&m.cameraMask&1<{const X=b.get(S[q].name);if(!X)return K;if(m&&m.cameraMask&1<{m.text=function(x,b,S){const A=b.layout.get("text-transform").evaluate(S,{});return A==="uppercase"?x=x.toLocaleUpperCase():A==="lowercase"&&(x=x.toLocaleLowerCase()),jh.applyArabicShaping&&(x=jh.applyArabicShaping(x)),x}(m.text,l,u)}),h}const Ej={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function YCe(h){return h==="︶"||h==="﹈"||h==="︸"||h==="﹄"||h==="﹂"||h==="︾"||h==="︼"||h==="︺"||h==="︘"||h==="﹀"||h==="︐"||h==="︓"||h==="︔"||h==="`"||h===" ̄"||h==="︑"||h==="︒"}function ZCe(h){return h==="︵"||h==="﹇"||h==="︷"||h==="﹃"||h==="﹁"||h==="︽"||h==="︻"||h==="︹"||h==="︗"||h==="︿"}const Z4=4294967296,cX=1/Z4,uX=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let eP=class{constructor(h=new Uint8Array(16)){this.buf=ArrayBuffer.isView(h)?h:new Uint8Array(h),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(h,l,u=this.length){for(;this.pos>3,b=this.pos;this.type=7&m,h(x,l,this),this.pos===b&&this.skip(m)}return l}readMessage(h,l){return this.readFields(h,l,this.readVarint()+this.pos)}readFixed32(){const h=this.dataView.getUint32(this.pos,!0);return this.pos+=4,h}readSFixed32(){const h=this.dataView.getInt32(this.pos,!0);return this.pos+=4,h}readFixed64(){const h=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*Z4;return this.pos+=8,h}readSFixed64(){const h=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*Z4;return this.pos+=8,h}readFloat(){const h=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,h}readDouble(){const h=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,h}readVarint(h){const l=this.buf;let u,m;return m=l[this.pos++],u=127&m,m<128?u:(m=l[this.pos++],u|=(127&m)<<7,m<128?u:(m=l[this.pos++],u|=(127&m)<<14,m<128?u:(m=l[this.pos++],u|=(127&m)<<21,m<128?u:(m=l[this.pos],u|=(15&m)<<28,function(x,b,S){const A=S.buf;let N,O;if(O=A[S.pos++],N=(112&O)>>4,O<128||(O=A[S.pos++],N|=(127&O)<<3,O<128)||(O=A[S.pos++],N|=(127&O)<<10,O<128)||(O=A[S.pos++],N|=(127&O)<<17,O<128)||(O=A[S.pos++],N|=(127&O)<<24,O<128)||(O=A[S.pos++],N|=(1&O)<<31,O<128))return Vb(x,N,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&&uX?uX.decode(this.buf.subarray(l,h)):function(u,m,x){let b="",S=m;for(;S239?4:A>223?3:A>191?2:1;if(S+q>x)break;q===1?A<128&&(U=A):q===2?(N=u[S+1],(192&N)==128&&(U=(31&A)<<6|63&N,U<=127&&(U=null))):q===3?(N=u[S+1],O=u[S+2],(192&N)==128&&(192&O)==128&&(U=(15&A)<<12|(63&N)<<6|63&O,(U<=2047||U>=55296&&U<=57343)&&(U=null))):q===4&&(N=u[S+1],O=u[S+2],$=u[S+3],(192&N)==128&&(192&O)==128&&(192&$)==128&&(U=(15&A)<<18|(63&N)<<12|(63&O)<<6|63&$,(U<=65535||U>=1114112)&&(U=null))),U===null?(U=65533,q=1):U>65535&&(U-=65536,b+=String.fromCharCode(U>>>10&1023|55296),U=56320|1023&U),b+=String.fromCharCode(U),S+=q}return b}(this.buf,l,h)}readBytes(){const h=this.readVarint()+this.pos,l=this.buf.subarray(this.pos,h);return this.pos=h,l}readPackedVarint(h=[],l){const u=this.readPackedEnd();for(;this.pos127;);else if(l===2)this.pos=this.readVarint()+this.pos;else if(l===5)this.pos+=4;else{if(l!==1)throw new Error(`Unimplemented type: ${l}`);this.pos+=8}}writeTag(h,l){this.writeVarint(h<<3|l)}realloc(h){let l=this.length||16;for(;l268435455||h<0?function(l,u){let m,x;if(l>=0?(m=l%4294967296|0,x=l/4294967296|0):(m=~(-l%4294967296),x=~(-l/4294967296),4294967295^m?m=m+1|0:(m=0,x=x+1|0)),l>=18446744073709552e3||l<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");u.realloc(10),function(b,S,A){A.buf[A.pos++]=127&b|128,b>>>=7,A.buf[A.pos++]=127&b|128,b>>>=7,A.buf[A.pos++]=127&b|128,b>>>=7,A.buf[A.pos++]=127&b|128,A.buf[A.pos]=127&(b>>>=7)}(m,0,u),function(b,S){const A=(7&b)<<4;S.buf[S.pos++]|=A|((b>>>=3)?128:0),b&&(S.buf[S.pos++]=127&b|((b>>>=7)?128:0),b&&(S.buf[S.pos++]=127&b|((b>>>=7)?128:0),b&&(S.buf[S.pos++]=127&b|((b>>>=7)?128:0),b&&(S.buf[S.pos++]=127&b|((b>>>=7)?128:0),b&&(S.buf[S.pos++]=127&b)))))}(x,u)}(h,this):(this.realloc(4),this.buf[this.pos++]=127&h|(h>127?128:0),h<=127||(this.buf[this.pos++]=127&(h>>>=7)|(h>127?128:0),h<=127||(this.buf[this.pos++]=127&(h>>>=7)|(h>127?128:0),h<=127||(this.buf[this.pos++]=h>>>7&127))))}writeSVarint(h){this.writeVarint(h<0?2*-h-1:2*h)}writeBoolean(h){this.writeVarint(+h)}writeString(h){h=String(h),this.realloc(4*h.length),this.pos++;const l=this.pos;this.pos=function(m,x,b){for(let S,A,N=0;N55295&&S<57344){if(!A){S>56319||N+1===x.length?(m[b++]=239,m[b++]=191,m[b++]=189):A=S;continue}if(S<56320){m[b++]=239,m[b++]=191,m[b++]=189,A=S;continue}S=A-55296<<10|S-56320|65536,A=null}else A&&(m[b++]=239,m[b++]=191,m[b++]=189,A=null);S<128?m[b++]=S:(S<2048?m[b++]=S>>6|192:(S<65536?m[b++]=S>>12|224:(m[b++]=S>>18|240,m[b++]=S>>12&63|128),m[b++]=S>>6&63|128),m[b++]=63&S|128)}return b}(this.buf,h,this.pos);const u=this.pos-l;u>=128&&dX(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&&dX(u,m,this),this.pos=u-1,this.writeVarint(m),this.pos+=m}writeMessage(h,l,u){this.writeTag(h,2),this.writeRawMessage(l,u)}writePackedVarint(h,l){l.length&&this.writeMessage(h,XCe,l)}writePackedSVarint(h,l){l.length&&this.writeMessage(h,QCe,l)}writePackedBoolean(h,l){l.length&&this.writeMessage(h,tNe,l)}writePackedFloat(h,l){l.length&&this.writeMessage(h,JCe,l)}writePackedDouble(h,l){l.length&&this.writeMessage(h,eNe,l)}writePackedFixed32(h,l){l.length&&this.writeMessage(h,rNe,l)}writePackedSFixed32(h,l){l.length&&this.writeMessage(h,nNe,l)}writePackedFixed64(h,l){l.length&&this.writeMessage(h,iNe,l)}writePackedSFixed64(h,l){l.length&&this.writeMessage(h,sNe,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 Vb(h,l,u){return u?4294967296*l+(h>>>0):4294967296*(l>>>0)+(h>>>0)}function dX(h,l,u){const m=l<=16383?1:l<=2097151?2:l<=268435455?3:Math.floor(Math.log(l)/(7*Math.LN2));u.realloc(m);for(let x=u.pos-1;x>=h;x--)u.buf[x+m]=u.buf[x]}function XCe(h,l){for(let u=0;u=0&&m>=l&&tP[this.text.charCodeAt(m)];m--)u--;this.text=this.text.substring(l,u),this.sectionIndex=this.sectionIndex.slice(l,u)}substring(l,u){const m=new qb;return m.text=this.text.substring(l,u),m.sectionIndex=this.sectionIndex.slice(l,u),m.sections=this.sections,m}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((l,u)=>Math.max(l,this.sections[u].scale),0)}addTextSection(l,u){this.text+=l.text,this.sections.push(jj.forText(l.scale,l.fontStack||u));const m=this.sections.length-1;for(let x=0;x=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function X4(h,l,u,m,x,b,S,A,N,O,$,U,q,K,X,te=1,ie=1){const ae=qb.fromFeature(h,x,te,ie);U===Fc.vertical&&ae.verticalizePunctuation(q);let he=[];const ue=function(ze,Ge,Ue,Ve,yt,wt,At=1){if(!ze)return[];const It=[],kt=function(Ct,Dt,Ut,Yt,vr,sr,ir=1){let Zt=0;for(let pr=0;pr=0;let mt=0;for(let Ct=0;Ct0&&nl>Sn&&(Sn=nl)}else{const Ka=Ue[cs.fontStack];if(!Ka)continue;Ka[us]&&(ws=Ka[us]);const jl=Ge[cs.fontStack];if(!jl)continue;const Ao=jl.glyphs[us];if(!Ao)continue;if(Ys=Ao.metrics,Ba=us!==8203?Oa:0,ir){const ms=jl.ascender!==void 0?Math.abs(jl.ascender):0,nl=jl.descender!==void 0?Math.abs(jl.descender):0,Ya=(ms+nl)*bs;fs-u/2;){if(S--,S<0)return!1;A-=h[S].dist(b),b=h[S]}A+=h[S].dist(h[S+1]),S++;const N=[];let O=0;for(;Am;)O-=N.shift().angleDelta;if(O>x)return!1;S++,A+=$.dist(U)}return!0}function bX(h){let l=0;for(let u=0;uO){const X=(O-N)/K,te=Qr(U.x,q.x,X),ie=Qr(U.y,q.y,X),ae=new hp(te,ie,0,q.angleTo(U),$);return!S||_X(h,ae,A,S,l)?ae:void 0}N+=K}}function hNe(h,l,u,m,x,b,S,A,N){const O=wX(m,b,S),$=SX(m,x),U=$*S,q=h[0].x===0||h[0].x===N||h[0].y===0||h[0].y===N;return l-U=0&&ve=0&&ke=0&&q+O<=$){const Ie=new hp(ve,ke,0,he,X);m&&!_X(h,Ie,b,m,x)||K.push(Ie)}}U+=ae}return A||K.length||S||(K=TX(h,U/2,u,m,x,b,S,!0,N)),K}function EX(h){let l=0,u=0;for(const S of h)l+=S.w*S.h,u=Math.max(u,S.w);h.sort((S,A)=>A.h-S.h);const m=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(l/.95)),u),h:1/0}];let x=0,b=0;for(const S of h)for(let A=m.length-1;A>=0;A--){const N=m[A];if(!(S.w>N.w||S.h>N.h)){if(S.x=N.x,S.y=N.y,b=Math.max(b,S.y+S.h),x=Math.max(x,S.x+S.w),S.w===N.w&&S.h===N.h){const O=m.pop();O&&Al.id?1:h.versionl.version?1:h.sxl.sx?1:h.syl.sy?1:0}function rB(h){let l=0;for(let u=0;u0,jX(l,m,this.iconDescriptors,b),jX(u,m,this.patternDescriptors,b),this.iconDescriptors.sort(nP),this.patternDescriptors.sort(nP);let S=0;const A=x?x.data:"";A&&(S=Ph(S,rB(A))),S=Ph(S,1);for(const N of this.iconDescriptors)S=Ph(S,rB(N.id)),S=Ph(S,N.version),S=Ph(S,N.sx),S=Ph(S,N.sy);S=Ph(S,1);for(const N of this.patternDescriptors)S=Ph(S,rB(N.id)),S=Ph(S,N.version),S=Ph(S,N.sx),S=Ph(S,N.sy);this.hash=S}subsetOf(l){return this.isSubsetArray(this.iconDescriptors,l.iconDescriptors,nP)&&this.isSubsetArray(this.patternDescriptors,l.patternDescriptors,nP)}isSubsetArray(l,u,m){let x=0,b=0;if(l.length>u.length)return!1;for(;x{const S=x.variant.id.toString().localeCompare(b.variant.id.toString());return S!==0?S:x.variant.sx!==b.variant.sx?x.variant.sx-b.variant.sx:x.variant.sy!==b.variant.sy?x.variant.sy-b.variant.sy:0});const m=new Map;for(const x of u)m.set(x.key,x.value);return m}class AX{constructor(l){this.sourceAtlasHash=l}}class kX{constructor(l,u,m,x){const b=new Map,S=new Map;this.haveRenderCallbacks=[];const A=[],N=x!==void 0,O=N?new Map:void 0,$=N?sB(l,O):l,U=N?sB(u,O):u;this.addImages($,b,1,A),this.addImages(U,S,2,A);const{w:q,h:K}=EX(A),X=new $o({width:q||1,height:K||1});for(const[te,ie]of $.entries()){const ae=b.get(te).paddedRect;$o.copy(ie.data,X,{x:0,y:0},{x:ae.x+1,y:ae.y+1},ie.data,null,ie.sdf)}for(const[te,ie]of U.entries()){const ae=S.get(te),he=ae.paddedRect;let ue=ae.padding;const ve=he.x+ue,ke=he.y+ue,Ie=ie.data.width,We=ie.data.height;ue=ue>1?ue-1:ue,$o.copy(ie.data,X,{x:0,y:0},{x:ve,y:ke},ie.data,m),$o.copy(ie.data,X,{x:0,y:We-ue},{x:ve,y:ke-ue},{width:Ie,height:ue},m),$o.copy(ie.data,X,{x:0,y:0},{x:ve,y:ke+We},{width:Ie,height:ue},m),$o.copy(ie.data,X,{x:Ie-ue,y:0},{x:ve-ue,y:ke},{width:ue,height:We},m),$o.copy(ie.data,X,{x:0,y:0},{x:ve+Ie,y:ke},{width:ue,height:We},m),$o.copy(ie.data,X,{x:Ie-ue,y:We-ue},{x:ve-ue,y:ke-ue},{width:ue,height:ue},m),$o.copy(ie.data,X,{x:0,y:We-ue},{x:ve+Ie,y:ke-ue},{width:ue,height:ue},m),$o.copy(ie.data,X,{x:0,y:0},{x:ve+Ie,y:ke+We},{width:ue,height:ue},m),$o.copy(ie.data,X,{x:Ie-ue,y:0},{x:ve-ue,y:ke+We},{width:ue,height:ue},m)}this.lut=m,this.image=X,this.iconPositions=b,this.patternPositions=S,N&&(this.contentDescriptor=new nB($,U,x,m,O))}addImages(l,u,m,x){for(const[b,S]of l.entries()){const{bin:A,imagePosition:N,imageVariant:O}=iB(b,S,m);u.set(b,N),x.push(A),S.hasRenderCallback&&this.haveRenderCallbacks.push(O.id)}}patchUpdatedImages(l,u,m,x){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(b=>l.hasImage(b,m)),l.dispatchRenderCallbacks(this.haveRenderCallbacks,m);for(const b of l.getUpdatedImages(m)){for(const S of this.iconPositions.keys()){const A=gu.parse(S);if(hc.isEqual(A.id,b)){const N=l.getImage(b,m);this.patchUpdatedImage(this.iconPositions.get(S),N,u,null)}}for(const S of this.patternPositions.keys()){const A=gu.parse(S);if(hc.isEqual(A.id,b)){const N=l.getImage(b,m);this.patchUpdatedImage(this.patternPositions.get(S),N,u,x||this.lut)}}}}patchUpdatedImage(l,u,m,x=null){if(!l||!u||l.version===u.version)return;l.version=u.version;const[b,S]=l.tl,A=l.sdf;if(this.lut||A){const N={width:u.data.width,height:u.data.height},O=new $o(N);$o.copy(u.data,O,{x:0,y:0},{x:0,y:0},N,x,A),m.update(O,{position:{x:b,y:S},recreateWhenResize:!1})}else m.update(u.data,{position:{x:b,y:S},recreateWhenResize:!1})}}br(Aj,"ImagePosition"),br(kX,"ImageAtlas",{omit:["lut"]}),br(AX,"ImageAtlasReference");class kj{constructor(l){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!l||l.useServerFontComposition===void 0||l.useServerFontComposition}loadGlyphRange(l,u,m,x,b){if(this.useServerFontComposition)return void kj.loadGlyphRange(l,u,m,x,b);const S=l.split(",").map(A=>A.trim()).filter(A=>A.length>0);S.length!==0?S.length!==1?this._loadMultipleFonts(S,u,m,x,b):this._loadFont(S[0],u,m,x,b):b(new Error("Empty fontstack"))}_loadMultipleFonts(l,u,m,x,b){const S=l.map(()=>null),A={completed:0,firstError:null,callbackCalled:!1},N=(O,$,U)=>{if(!A.callbackCalled&&($&&!A.firstError&&(A.firstError=$),U&&(S[O]=U),A.completed++,A.completed===l.length)){A.callbackCalled=!0;const q=S.filter(X=>X!==null);if(q.length===0)return void b(A.firstError||new Error("All fonts failed to load"));const K=this._composeGlyphs(q);b(null,K)}};for(let O=0;O{N(O,$,U)})}_loadFont(l,u,m,x,b){const S=`${l}:${u}`;if(this.cachedRanges.has(S)){const N=this.cachedRanges.get(S);return void $l.frame(()=>b(null,N))}const A=this.pendingRequests.get(S);A?A.push(b):(this.pendingRequests.set(S,[b]),kj.loadGlyphRange(l,u,m,x,(N,O)=>{N||this.cachedRanges.set(S,O||null);const $=this.pendingRequests.get(S);if(this.pendingRequests.delete(S),$)for(const U of $)U(N,O)}))}_composeGlyphs(l){const u={};let m,x;for(const b of l)if(m===void 0&&b.ascender!==void 0&&(m=b.ascender),x===void 0&&b.descender!==void 0&&(x=b.descender),b.glyphs)for(const S in b.glyphs)u[S]===void 0&&(u[S]=b.glyphs[S]);return{glyphs:u,ascender:m,descender:x}}}kj.loadGlyphRange=function(h,l,u,m,x){const b=256*l,S=b+255,A=m.transformRequest(m.normalizeGlyphsURL(u).replace("{fontstack}",h).replace("{range}",`${b}-${S}`),Zx.Glyphs);Sg(A,(N,O)=>{if(N)x(N);else if(O){const $={},U=function(q){return new eP(q).readFields(aNe,{})}(O);for(const q of U.glyphs)$[q.id]=q;x(null,{glyphs:$,ascender:U.ascender,descender:U.descender})}})};const Cj=1e20;function CX(h,l,u,m,x,b,S,A,N){for(let O=l;O-1);N++,b[N]=A,S[N]=O,S[N+1]=Cj}for(let A=0,N=0;A{if(S){x.ascender=S.ascender,x.descender=S.descender;for(const A in S.glyphs)this._doesCharSupportLocalGlyph(+A)||(x.glyphs[+A]=S.glyphs[+A]);x.ranges[u]=!0}for(const A of x.requests[u]||[])A(b,S);delete x.requests[u]}))}getGlyphs(l,u){const m=[],x=this.url||Mn.GLYPHS_URL;for(const b in l)for(const S of l[b])m.push({stack:b,id:S});Je(m,({stack:b,id:S},A)=>{let N=this.entries[b];N||(N=this.entries[b]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let O=N.glyphs[S];if(O!==void 0)return void A(null,{stack:b,id:S,glyph:O});if(O=this._tinySDF(N,b,S),O)return N.glyphs[S]=O,void A(null,{stack:b,id:S,glyph:O});const $=Math.floor(S/256);if(256*$>65535)return $r("glyphs > 65535 not supported"),void A(null,{stack:b,id:S,glyph:O});if(N.ranges[$])return void A(null,{stack:b,id:S,glyph:O});let U=N.requests[$];U||(U=N.requests[$]=[],this.glyphLoader.loadGlyphRange(b,$,x,this.requestManager,(q,K)=>{if(K){N.ascender=K.ascender,N.descender=K.descender;for(const X in K.glyphs)this._doesCharSupportLocalGlyph(+X)||(N.glyphs[+X]=K.glyphs[+X]);N.ranges[$]=!0}for(const X of U)X(q,K);delete N.requests[$]})),U.push((q,K)=>{q?A(q):K&&A(null,{stack:b,id:S,glyph:K.glyphs[S]||null})})},(b,S)=>{if(b)u(b);else if(S){const A={};for(const{stack:N,id:O,glyph:$}of S)A[N]===void 0&&(A[N]={}),A[N].glyphs===void 0&&(A[N].glyphs={}),A[N].glyphs[O]=$&&{id:$.id,bitmap:$.bitmap.clone(),metrics:$.metrics},A[N].ascender=this.entries[N].ascender,A[N].descender=this.entries[N].descender;u(null,A)}})}_doesCharSupportLocalGlyph(l){return this.localGlyphMode!==aB.none&&(this.localGlyphMode===aB.all?!!this.localFontFamily:!!this.localFontFamily&&(gb(l)||wE(l)||A0(l)||Qm(l)||j0(l)||_E(l)||(u=l)>=131072&&u<=173791||(m=>m>=66736&&m<=66815)(l)));var u}_tinySDF(l,u,m){const x=this.localFontFamily;if(!x||!this._doesCharSupportLocalGlyph(m))return;let b=l.tinySDF;if(!b){let ie="400";/bold/i.test(u)?ie="900":/medium/i.test(u)?ie="500":/light/i.test(u)&&(ie="200"),b=l.tinySDF=new iP.TinySDF({fontFamily:x,fontWeight:ie,fontSize:48,buffer:6,radius:16}),b.fontWeight=ie}const S=b.fontWeight;if(this.localGlyphs[S][m])return this.localGlyphs[S][m];const A=String.fromCodePoint(m),{data:N,width:O,height:$,glyphWidth:U,glyphHeight:q,glyphLeft:K,glyphTop:X,glyphAdvance:te}=b.draw(A);return this.localGlyphs[S][m]={id:m,bitmap:new Zg({width:O,height:$},N),metrics:{width:U/2,height:q/2,left:K/2,top:X/2-27,advance:te/2,localGlyph:!0}}}}function IX(h,l){return h+l[1]-l[0]}function oB(h,l,u,m,x=1){const b=[],S=h.imagePrimary,A=S.pixelRatio,N=S.paddedRect.w-2,O=S.paddedRect.h-2,$=(h.right-h.left)*x,U=(h.bottom-h.top)*x,q=S.stretchX||[[0,N]],K=S.stretchY||[[0,O]],X=q.reduce(IX,0),te=K.reduce(IX,0),ie=N-X,ae=O-te;let he=0,ue=X,ve=0,ke=te,Ie=0,We=ie,ze=0,Ge=ae;if(S.content&&m){const Ve=S.content;he=sP(q,0,Ve[0]),ve=sP(K,0,Ve[1]),ue=sP(q,Ve[0],Ve[2]),ke=sP(K,Ve[1],Ve[3]),Ie=Ve[0]-he,ze=Ve[1]-ve,We=Ve[2]-Ve[0]-ue,Ge=Ve[3]-Ve[1]-ke}const Ue=(Ve,yt,wt,At)=>{const It=aP(Ve.stretch-he,ue,$,h.left*x),kt=oP(Ve.fixed-Ie,We,Ve.stretch,X),$t=aP(yt.stretch-ve,ke,U,h.top*x),mt=oP(yt.fixed-ze,Ge,yt.stretch,te),Ct=aP(wt.stretch-he,ue,$,h.left*x),Dt=oP(wt.fixed-Ie,We,wt.stretch,X),Ut=aP(At.stretch-ve,ke,U,h.top*x),Yt=oP(At.fixed-ze,Ge,At.stretch,te),vr=new Ot(It,$t),sr=new Ot(Ct,$t),ir=new Ot(Ct,Ut),Zt=new Ot(It,Ut),pr=new Ot(kt/A,mt/A),Cr=new Ot(Dt/A,Yt/A),zr=l*Math.PI/180;if(zr){const Sn=Math.sin(zr),fs=Math.cos(zr),ai=[fs,-Sn,Sn,fs];vr._matMult(ai),sr._matMult(ai),Zt._matMult(ai),ir._matMult(ai)}const Rr=Ve.stretch+Ve.fixed,cn=wt.stretch+wt.fixed,zn=yt.stretch+yt.fixed,un=At.stretch+At.fixed,qn=h.imageSecondary;return{tl:vr,tr:sr,bl:Zt,br:ir,texPrimary:{x:S.paddedRect.x+1+Rr,y:S.paddedRect.y+1+zn,w:cn-Rr,h:un-zn},texSecondary:qn?{x:qn.paddedRect.x+1+Rr,y:qn.paddedRect.y+1+zn,w:cn-Rr,h:un-zn}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:pr,pixelOffsetBR:Cr,minFontScaleX:We/A/$,minFontScaleY:Ge/A/U,isSDF:u}};if(S.stretchX||S.stretchY){const Ve=PX(q,ie,X),yt=PX(K,ae,te);for(let wt=0;wt0?[he,-ue]:ve<0?[-he,ue]:he===0?[ue,he]:[ue,-he]}(u);let K=Math.abs(l.top-l.bottom);for(const ae of l.positionedLines)K-=ae.lineOffset;const X=l.positionedLines.length,te=K/X;let ie=l.top-u[1];for(let ae=0;aeb)&&(b=X.x),(!K||X.y>S)&&(S=X.y)}const N=Math.min(b-m,S-x);let O=N/2;const $=new d0([],gNe);if(N===0)return new Ot(m,x);for(let K=m;KU.d||!U.d)&&(U=K,u&&console.log("found best %d after %d probes",Math.round(1e4*K.d)/1e4,q)),K.max-U.d<=l||(O=K.h/2,$.push(new Hb(K.p.x-O,K.p.y-O,O,h)),$.push(new Hb(K.p.x+O,K.p.y-O,O,h)),$.push(new Hb(K.p.x-O,K.p.y+O,O,h)),$.push(new Hb(K.p.x+O,K.p.y+O,O,h)),q+=4)}return u&&(console.log(`num probes: ${q}`),console.log(`best distance: ${U.d}`)),U.p}function gNe(h,l){return l.max-h.max}iP.TinySDF=class{constructor({fontSize:h=24,buffer:l=3,radius:u=8,cutoff:m=.25,fontFamily:x="sans-serif",fontWeight:b="normal",fontStyle:S="normal",lang:A=null}={}){this.buffer=l,this.cutoff=m,this.radius=u,this.lang=A;const N=this.size=h+4*l,O=this._createCanvas(N),$=this.ctx=O.getContext("2d",{willReadFrequently:!0});$.font=`${S} ${b} ${h}px ${x}`,$.textBaseline="alphabetic",$.textAlign="left",$.fillStyle="black",this.gridOuter=new Float64Array(N*N),this.gridInner=new Float64Array(N*N),this.f=new Float64Array(N),this.z=new Float64Array(N+1),this.v=new Uint16Array(N)}_createCanvas(h){const l=document.createElement("canvas");return l.width=l.height=h,l}draw(h){const{width:l,actualBoundingBoxAscent:u,actualBoundingBoxDescent:m,actualBoundingBoxLeft:x,actualBoundingBoxRight:b}=this.ctx.measureText(h),S=Math.ceil(u),A=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(b-x))),N=Math.min(this.size-this.buffer,S+Math.ceil(m)),O=A+2*this.buffer,$=N+2*this.buffer,U=Math.max(O*$,0),q=new Uint8ClampedArray(U),K={data:q,width:O,height:$,glyphWidth:A,glyphHeight:N,glyphTop:S,glyphLeft:0,glyphAdvance:l};if(A===0||N===0)return K;const{ctx:X,buffer:te,gridInner:ie,gridOuter:ae}=this;this.lang&&(X.lang=this.lang),X.clearRect(te,te,A,N),X.fillText(h,te,te+S);const he=X.getImageData(te,te,A,N);ae.fill(Cj,0,U),ie.fill(0,0,U);for(let ue=0;ue0?We*We:0,ie[Ie]=We<0?We*We:0}}CX(ae,0,0,O,$,O,this.f,this.v,this.z),CX(ie,te,te,A,N,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&&(A=!A),N=Math.min(N,Fd(b,X,te))}}return(A?1:-1)*Math.sqrt(N)}(this.p,x),this.max=this.d+this.h*Math.SQRT2}}const yNe=Object.keys,lB=Number.POSITIVE_INFINITY,xNe=Math.sqrt(2);function ey(h,l,u,m,x,b){const S=J4(h)&&h.collisionPadding?h.collisionPadding:[0,0,0,0],A={top:h.top-S[1],bottom:h.bottom+S[3],left:h.left-S[0],right:h.right+S[2],scaled:!1};return m!==void 0&&function(N,O){N.top*=O,N.bottom*=O,N.left*=O,N.right*=O,N.scaled=!0}(A,m),b&&(A.left+=b[0],A.right+=b[0],A.top+=b[1],A.bottom+=b[1]),u&&function(N,O,$){if(!O)return;const U=Zn(O),q=new Ot($?$[0]:0,$?$[1]:0),K=new Ot(N.left,N.top),X=new Ot(N.right,N.top),te=new Ot(N.left,N.bottom),ie=new Ot(N.right,N.bottom);K._rotateAround(U,q),X._rotateAround(U,q),te._rotateAround(U,q),ie._rotateAround(U,q),N.left=Math.min(K.x,X.x,te.x,ie.x),N.right=Math.max(K.x,X.x,te.x,ie.x),N.top=Math.min(K.y,X.y,te.y,ie.y),N.bottom=Math.max(K.y,X.y,te.y,ie.y)}(A,u,x),l?{top:Math.min(l.top,A.top),bottom:Math.max(l.bottom,A.bottom),left:Math.min(l.left,A.left),right:Math.max(l.right,A.right),scaled:l.scaled||A.scaled}:A}function DX(h,[l,u]){let m=0,x=0;if(u===lB){l<0&&(l=0);const b=l/xNe;switch(h){case"top-right":case"top-left":x=b-7;break;case"bottom-right":case"bottom-left":x=7-b;break;case"bottom":x=7-l;break;case"top":x=l-7}switch(h){case"top-right":case"bottom-right":m=-b;break;case"top-left":case"bottom-left":m=b;break;case"left":m=l;break;case"right":m=-l}}else{switch(l=Math.abs(l),u=Math.abs(u),h){case"top-right":case"top-left":case"top":x=u-7;break;case"bottom-right":case"bottom-left":case"bottom":x=7-u}switch(h){case"top-right":case"bottom-right":case"right":m=-l;break;case"top-left":case"bottom-left":case"left":m=l}}return[m,x]}function vNe(h,l,u,m,x,b,S,A,N,O,$,U,q,K,X){const te=h.layers[0],ie=te.appearances;if(ie.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const ae={iconBBox:null,iconVerticalBBox:null},he={textBBox:null,textVerticalBBox:null},{baseIconRotate:ue,baseTextRotate:ve,iconScaleFactor:ke}=function(We,ze,Ge){const Ue=We.get("icon-rotate").evaluate(ze,{},Ge),Ve=We.get("text-rotate").evaluate(ze,{},Ge),[yt,wt]=We.get("icon-size-scale-range");return{baseIconRotate:Ue,baseTextRotate:Ve,iconScaleFactor:fe(1,yt,wt)}}(m,x,b);l&&(ae.iconBBox=ey(l,ae.iconBBox,ue),u)&&(ae.iconVerticalBBox=ey(u,ae.iconVerticalBBox,ue+90));const Ie=cP(U.horizontal);Ie&&(he.textBBox=ey(Ie,he.textBBox,ve,1,K)),U.vertical&&(he.textVerticalBBox=ey(U.vertical,he.textVerticalBBox,ve+90,1,K));for(const We of ie)We.hasIconLayoutProperties()&&_Ne(ae,h,te,We,x,b,A,ue,S,N,l,O,ke,$,X),We.hasTextLayoutProperties()&&bNe(he,te,We,x,b,K,ve,q,Ie,U.vertical);return{iconBBox:ae.iconBBox,iconVerticalBBox:ae.iconVerticalBBox,textBBox:he.textBBox,textVerticalBBox:he.textVerticalBBox}}function _Ne(h,l,u,m,x,b,S,A,N,O,$,U,q,K,X){const{appearanceIconOffset:te,appearanceIconRotate:ie,appearanceIconSize:ae}=MX(m,u,x,b,S,A,N,O.iconScaleFactor);let he=null,ue=null,ve=null;m.hasLayoutProperty("icon-image")?ve=function(Ie,We,ze,Ge,Ue,Ve,yt,wt){let At=null;const It=We.getAppearanceValueAndResolveTokens(ze,"icon-image",Ge,Ue,wt);if(It){const kt=Ie.getResolvedImageFromTokens(It),$t=ze.hasLayoutProperty("icon-size")?ze.getUnevaluatedLayoutProperty("icon-size"):We._unevaluatedLayout._values["icon-size"],mt=Nj(kt,K0(Ie.zoom,$t,Ie.worldview,wt),$t,Ue,Ie.zoom,Ge,Ie.pixelRatio,yt,Ie.worldview,wt);At=Ve.get(mt.iconPrimary.toString())}return At}(l,u,m,x,b,U,q,X):$&&(ve=$.imagePrimary),ve&&(he=rP(ve,null,te,K),l.allowVerticalPlacement&&(ue=rP(ve,null,te,K)));const ke=N>0?ae/N:1;he&&(h.iconBBox=ey(he,h.iconBBox,ie,ke!==1?ke:void 0)),ue&&(h.iconVerticalBBox=ey(ue,h.iconVerticalBBox,ie+90,ke!==1?ke:void 0))}function MX(h,l,u,m,x,b,S,A){const N=h.hasLayoutProperty("icon-offset")?l.getAppearanceValueAndResolveTokens(h,"icon-offset",u,m,[]):null,O=N&&Array.isArray(N)?N:x,$=h.hasLayoutProperty("icon-rotate")?l.getAppearanceValueAndResolveTokens(h,"icon-rotate",u,m,[]):null,U=typeof $=="number"?$:b,q=h.hasLayoutProperty("icon-size")?l.getAppearanceValueAndResolveTokens(h,"icon-size",u,m,[]):null;return{appearanceIconOffset:O,appearanceIconRotate:U,appearanceIconSize:typeof q=="number"?q*A:S}}function bNe(h,l,u,m,x,b,S,A,N,O){const{appearanceTextOffset:$,appearanceTextRotate:U,appearanceTextSize:q}=OX(u,l,m,x,b,S,A),K=q/A,X=[($[0]-b[0])*K,($[1]-b[1])*K],te=X[0]!==0||X[1]!==0;N&&(h.textBBox=ey(N,h.textBBox,U,K,$,te?X:void 0)),O&&(h.textVerticalBBox=ey(O,h.textVerticalBBox,U+90,K,$,te?X:void 0))}function OX(h,l,u,m,x,b,S){const A=h.hasLayoutProperty("text-offset")?l.getAppearanceValueAndResolveTokens(h,"text-offset",u,m,[]):null,N=A&&Array.isArray(A)?[A[0]*Oa,A[1]*Oa]:x,O=h.hasLayoutProperty("text-rotate")?l.getAppearanceValueAndResolveTokens(h,"text-rotate",u,m,[]):null,$=typeof O=="number"?O:b,U=h.hasLayoutProperty("text-size")?l.getAppearanceValueAndResolveTokens(h,"text-size",u,m,[]):null;return{appearanceTextOffset:N,appearanceTextRotate:$,appearanceTextSize:typeof U=="number"?U:S}}function lP(h,l,u,m,x,b,S,A,N){if(!l||!l.usvg)return;const O=vX(m),$=vX(x),U=b!=="both"&&b!=="width"||!yX(m)?1:$.width/O.width,q=b!=="both"&&b!=="height"||!xX(m)?1:$.height/O.height;u.scaleSelf(U,q);const K=u.toString();S.set(K,u),A.set(K,l);const{imagePosition:X}=iB(K,l,1);N.set(K,X)}function FX(h,l,u,m,x,b,S,A,N,O){if(!h)return;const $=function(U,q,K,X,te,ie,ae){if(U.kind==="camera")return U.maxSize;if(U.kind==="composite"){const he=q.possiblyEvaluate(new si(U.maxZoom,{worldview:ie}),K,ae).evaluate(te,{},K,ae),ue=q.possiblyEvaluate(new si(U.minZoom,{worldview:ie}),K,ae).evaluate(te,{},K,ae);return Math.max(he,ue)}return q.possiblyEvaluate(new si(X,{worldview:ie}),K,ae).evaluate(te,{},K,ae)}(l,u,m,x,b,N,O);return h.scaleSelf($*A*S)}function Nj(h,l,u,m,x,b,S,A,N,O){return{iconPrimary:FX(h.getPrimary(),l,u,m,x,b,S,A,N,O),iconSecondary:FX(h.getSecondary(),l,u,m,x,b,S,A,N,O)}}function wNe(h,l,u){if(!l)return;const m=u.get(h.toString()),x=u.get(l.toString());m&&x&&(m.paddedRect.w===x.paddedRect.w&&m.paddedRect.h===x.paddedRect.h||$r(`Mismatch in icon variant sizes: ${h.toString()} and ${l.toString()}`),m.usvg!==x.usvg&&$r(`Mismatch in icon variant image types: ${h.id} and ${l.id}`))}function BX(h,l,u,m){if(!h)return;const x=l.get(u.toString());if(x&&(h.imagePrimary=x),m){const b=l.get(m.toString());h.imageSecondary=b}}function SNe(h,l){for(const u in h.horizontal)$X(h.horizontal[u],l);$X(h.vertical,l)}function $X(h,l){if(h){for(const u of h.positionedLines)for(const m of u.positionedGlyphs)if(m.image!==null){const x=m.image.toString();m.rect=l.get(x).paddedRect}}}function cB(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 TNe(h,l,u,m,x,b,S,A,N){const O=cP(b.horizontal)||b.vertical,$=u.get("icon-text-fit-padding").evaluate(m,{},x);let U,q=l;return l&&N!=="none"&&(h.allowVerticalPlacement&&b.vertical&&(U=eB(l,b.vertical,N,$,A,S)),O&&(q=eB(l,O,N,$,A,S))),{defaultShapedIcon:q,verticallyShapedIcon:U}}function zX(h,l){return h*l/24}function ENe(h,l,u,m,x,b,S,A,N,O,$,U,q,K,X,te,ie,ae,he,ue,ve,ke,Ie,We){let ze=S.textMaxSize.evaluate(l,{},q);ze===void 0?ze=A*S.textScaleFactor:ze*=S.textScaleFactor;const Ge=h.layers[0].layout,Ue=zX(A,S.textScaleFactor),Ve=cP(u.horizontal)||u.vertical,yt=h.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),wt=h.getAppearanceFeatureData(l.index);(ie!=="none"||yt)&&wt&&(wt.textShaping=Ve,wt.iconTextFitPadding=Ge.get("icon-text-fit-padding").evaluate(l,{},q),wt.fontScale=Ue,wt.textScaleFactor=S.textScaleFactor);const At=K.name==="globe",It=h.tilePixelRatio*ze/24,kt=(Yt=h.overscaling,h.zoom>18&&Yt>2&&(Yt>>=1),Math.max(lr/(512*Yt),1)*Ge.get("symbol-spacing")),$t=Ge.get("text-padding")*h.tilePixelRatio,mt=Ge.get("icon-padding")*h.tilePixelRatio,Ct=Zn(Ge.get("text-max-angle")),Dt=Ge.get("icon-rotation-alignment")==="map"&&ue!=="point",Ut=kt/2;var Yt;h.hasAnyIconTextFit===!1&&ie!=="none"&&(h.hasAnyIconTextFit=!0);const vr=l.properties?+l.properties[yn]:null,sr=vr&&h.elevationFeatureIdToIndex?h.elevationFeatureIdToIndex.get(vr):65535,ir=(Zt,pr,Cr)=>{if(pr.x<0||pr.x>=lr||pr.y<0||pr.y>=lr)return;let zr=null;if(At){const{x:Rr,y:cn,z:zn}=K.projectTilePoint(pr.x,pr.y,Cr);zr={anchor:new hp(Rr,cn,zn,0,void 0),up:K.upVector(Cr,pr.x,pr.y)}}(function(Rr,cn,zn,un,qn,Sn,fs,ai,Wn,Pi,cs,Fa,us,bs,Ys,ws,jo,Ba,jn,El,Is,Ka,jl,Ao,ms,nl,Ya,AP,ew,Vl,RB,tw){const fp=Rr.addToLineVertexArray(cn,un);let mp,Yu,Zu,ev,rw,Nn,Za,Ss=0,ka=0,Xu=0,Bc=0,$c=-1,zc=-1;const zd={};let kP=wf("");const Mh=zn?zn.anchor:cn,nw=AP!=="none";let iw=0,ma=0;if(Wn._unevaluatedLayout.getValue("text-radial-offset")===void 0){const Ps=Wn.layout.get("text-offset").evaluate(Is,{},ms);iw=Ps[0]*Oa,ma=Ps[1]*Oa}else iw=Wn.layout.get("text-radial-offset").evaluate(Is,{},ms)*Oa,ma=lB;if(Rr.allowVerticalPlacement&&qn.vertical){const Ps=qn.vertical;if(Ys)Nn=hB(Ps),ai&&(Za=hB(ai));else{const Al=Wn.layout.get("text-rotate").evaluate(Is,{},ms)+90;Zu=uP(Pi,Mh,cn,cs,Fa,us,Ps,bs,Al,ws,tw),ai&&(ev=uP(Pi,Mh,cn,cs,Fa,us,ai,Ba,Al,null,RB))}}if(Sn){const Ps=Wn.layout.get("icon-rotate").evaluate(Is,{},ms),Al=oB(Sn,Ps,jl,nw,Ka.iconScaleFactor),ql=ai?oB(ai,Ps,jl,nw,Ka.iconScaleFactor):void 0;Yu=uP(Pi,Mh,cn,cs,Fa,us,Sn,Ba,Ps,null,Vl);const Vd=function(Oh,Gj,sw,$Ie,zIe,lJ,cJ,UIe,rqt,DB){const uJ=Oh.layers[0],dJ=uJ.appearances;let aw=Gj.length;if(sw&&(aw=Math.max(aw,sw.length)),dJ.length===0)return aw;const[VIe,qIe]=$Ie.get("icon-size-scale-range"),GIe=fe(1,VIe,qIe);for(const PP of dJ)if(PP.hasLayoutProperty("icon-image")){const hJ=uJ.getAppearanceValueAndResolveTokens(PP,"icon-image",lJ,cJ,DB);if(hJ){const fJ=Oh.getResolvedImageFromTokens(hJ);if(fJ){const mJ=PP.hasLayoutProperty("icon-size")?PP.getUnevaluatedLayoutProperty("icon-size"):zIe._values["icon-size"],HIe=Nj(fJ,K0(Oh.zoom,mJ,Oh.worldview,DB),mJ,cJ,Oh.zoom,lJ,Oh.pixelRatio,GIe,Oh.worldview,DB),pJ=UIe.get(HIe.iconPrimary.toString());pJ&&(aw=Math.max(aw,fNe(pJ)))}}}return aw}(Rr,Al,ql,Wn.layout,Wn._unevaluatedLayout,Is,ms,Rr.iconAtlasPositions,0,Ao);Ss=4*Vd;const CP=Wn.layout.get("icon-size").evaluate(Is,{},ms,Ao),NP=Ka.compositeIconSizes?Ka.compositeIconSizes[0].evaluate(Is,{},ms,Ao):0,LB=Ka.compositeIconSizes?Ka.compositeIconSizes[1].evaluate(Is,{},ms,Ao):0,IP=dB(Rr.layerIds[0],Rr.iconSizeData,CP,Ka.iconScaleFactor,NP,LB);Rr.addSymbols(Rr.icon,Al,IP,El,jn,Is,void 0,zn,cn,fp.lineStartIndex,fp.lineLength,-1,Ao,ms,nl,Ya,Rr.symbolInstances.length,Vd),$c=Rr.icon.placedSymbolArray.length-1,ql&&(ka=4*Vd,Rr.addSymbols(Rr.icon,ql,IP,El,jn,Is,Fc.vertical,zn,cn,fp.lineStartIndex,fp.lineLength,-1,Ao,ms,nl,Ya,Rr.symbolInstances.length,Vd),zc=Rr.icon.placedSymbolArray.length-1)}for(const Ps in qn.horizontal){const Al=Ps,ql=qn.horizontal[Al];mp||(kP=wf(ql.text),Ys?rw=hB(ql):mp=uP(Pi,Mh,cn,cs,Fa,us,ql,bs,Wn.layout.get("text-rotate").evaluate(Is,{},ms),ws,tw));const Vd=ql.positionedLines.length===1;if(Xu+=UX(Rr,zn,cn,ql,fs,Wn,Ys,Is,ws,fp,qn.vertical?Fc.horizontal:Fc.horizontalOnly,Vd?yNe(qn.horizontal):[Al],zd,$c,Ka,Ao,ms,Rr.symbolInstances.length,nl),Vd)break}qn.vertical&&(Bc+=UX(Rr,zn,cn,qn.vertical,fs,Wn,Ys,Is,ws,fp,Fc.vertical,["vertical"],zd,zc,Ka,Ao,ms,Rr.symbolInstances.length,nl));let ra=-1;const Ca=(Ps,Al)=>Ps?Math.max(Ps,Al):Al;ra=Ca(rw,ra),ra=Ca(Nn,ra),ra=Ca(Za,ra);const Ud=ra>-1?1:0;Rr.glyphOffsetArray.length>=65535&&$r("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),Is.sortKey!==void 0&&Rr.addToSortKeyRanges(Rr.symbolInstances.length,Is.sortKey),Rr.symbolInstances.emplaceBack(cn.x,cn.y,Mh.x,Mh.y,Mh.z,zd.right>=0?zd.right:-1,zd.center>=0?zd.center:-1,zd.left>=0?zd.left:-1,zd.vertical>=0?zd.vertical:-1,$c,zc,kP,mp!==void 0?mp:Rr.collisionBoxArray.length,mp!==void 0?mp+1:Rr.collisionBoxArray.length,Zu!==void 0?Zu:Rr.collisionBoxArray.length,Zu!==void 0?Zu+1:Rr.collisionBoxArray.length,Yu!==void 0?Yu:Rr.collisionBoxArray.length,Yu!==void 0?Yu+1:Rr.collisionBoxArray.length,ev||Rr.collisionBoxArray.length,ev?ev+1:Rr.collisionBoxArray.length,cs,Xu,Bc,Ss,ka,Ud,0,iw,ma,ra,0,nw?1:0,ew)})(h,pr,zr,Zt,u,m,b,x,h.layers[0],h.collisionBoxArray,l.index,l.sourceLayerIndex,h.index,$t,he,O,0,mt,Dt,ae,l,S,$,U,q,X,te,ie,sr,ve,ke,Ie)};if(ue==="line")for(const Zt of VI(l.geometry,0,0,lr,lr)){const pr=hNe(Zt,kt,Ct,u.vertical||Ve,m,24,It,h.overscaling,lr);for(const Cr of pr)Ve&&jNe(h,Ve.text,Ut,Cr)||ir(Zt,Cr,q)}else if(ue==="line-center"){for(const Zt of l.geometry)if(Zt.length>1){const pr=dNe(Zt,Ct,u.vertical||Ve,m,24,It);pr&&ir(Zt,pr,q)}}else if(l.type==="Polygon")for(const Zt of hj(l.geometry,0)){const pr=pNe(Zt,16);ir(Zt[0],new hp(pr.x,pr.y,0,0,void 0),q)}else if(l.type==="LineString")for(const Zt of l.geometry)ir(Zt,new hp(Zt[0].x,Zt[0].y,0,0,void 0),q);else if(l.type==="Point")for(const Zt of l.geometry)for(const pr of Zt)ir([pr],new hp(pr.x,pr.y,0,0,void 0),q)}const uB=255,Y0=uB*dp;function UX(h,l,u,m,x,b,S,A,N,O,$,U,q,K,X,te,ie,ae,he){const ue=LX(0,m,N,b,S,A,x,h.allowVerticalPlacement,void 0,X.textScaleFactor),ve=b.layout.get("text-size").evaluate(A,{},ie),ke=X.compositeTextSizes?X.compositeTextSizes[0].evaluate(A,{},ie):0,Ie=X.compositeTextSizes?X.compositeTextSizes[1].evaluate(A,{},ie):0,We=dB(h.layerIds[0],h.textSizeData,ve,X.textScaleFactor,ke,Ie);h.addSymbols(h.text,ue,We,N,S,A,$,l,u,O.lineStartIndex,O.lineLength,K,te,ie,he,!1,ae,ue.length);for(const ze of U)q[ze]=h.text.placedSymbolArray.length-1;return 4*ue.length}function dB(h,l,u,m,x,b){const S=l;let A=null;return S.kind==="source"?(A=[dp*u*m],A[0]>Y0&&$r(`${h}: Value for "text-size" is >= ${uB}. Reduce your "text-size".`)):S.kind==="composite"&&(A=[dp*x*m,dp*b*m],(A[0]>Y0||A[1]>Y0)&&$r(`${h}: Value for "text-size" is >= ${uB}. Reduce your "text-size".`)),A}function cP(h){for(const l in h)return h[l];return null}function uP(h,l,u,m,x,b,S,A,N,O,$){let U,q,K,X;if(U=$?$.top:S.top,q=$?$.bottom:S.bottom,K=$?$.left:S.left,X=$?$.right:S.right,J4(S)&&S.collisionPadding){const te=S.collisionPadding;K-=te[0],U-=te[1],X+=te[2],q+=te[3]}if(N){const te=new Ot(K,U),ie=new Ot(X,U),ae=new Ot(K,q),he=new Ot(X,q),ue=Zn(N);let ve=new Ot(0,0);O&&(ve=new Ot(O[0],O[1])),te._rotateAround(ue,ve),ie._rotateAround(ue,ve),ae._rotateAround(ue,ve),he._rotateAround(ue,ve),K=Math.min(te.x,ie.x,ae.x,he.x),X=Math.max(te.x,ie.x,ae.x,he.x),U=Math.min(te.y,ie.y,ae.y,he.y),q=Math.max(te.y,ie.y,ae.y,he.y)}return h.emplaceBack(l.x,l.y,l.z,u.x,u.y,K,U,X,q,A,m,x,b),h.length-1}function hB(h){J4(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 jNe(h,l,u,m){const x=h.compareText;if(l in x){const b=x[l];for(let S=b.length-1;S>=0;S--)if(m.dist(b[S])ue&&(ve(Ie,At,ze,Ge,yt,wt),ve(At,We,yt,wt,Ue,Ve))}ve(U,q,m,b,x,b),ve(q,K,x,b,x,S),ve(K,X,x,S,m,S),ve(X,U,m,S,m,b),te-=ue,ie-=ue,ae+=ue,he+=ue;const ke=1/Math.max(ae-te,he-ie);return{scale:ke,x:te*ke,y:ie*ke,x2:ae*ke,y2:he*ke,projection:l}}function qX(h,{x:l,y:u},m=0){return new Ot(((l-m)*h.scale-h.x)*lr,(u*h.scale-h.y)*lr)}const ANe=R(new Float32Array(16));class ty{constructor(l){this.spec=l,this.name=l.name,this.wrap=!1,this.requiresDraping=!1,this.supportsWorldCopies=!1,this.supportsTerrain=!1,this.supportsFog=!1,this.supportsFreeCamera=!1,this.zAxisUnit="meters",this.isReprojectedInTileSpace=!0,this.unsupportedLayers=["custom"],this.center=[0,0],this.range=[3.5,7]}project(l,u){return{x:0,y:0,z:0}}unproject(l,u){return new Qe(0,0)}projectTilePoint(l,u,m){return{x:l,y:u,z:0}}locationPoint(l,u,m,x=!0){return l._coordinatePoint(l.locationCoordinate(u,m),x)}pixelsPerMeter(l,u){return ot(1,l)*u}pixelSpaceConversion(l,u,m){return 1}farthestPixelDistance(l){return VX(l,l.pixelsPerMeter)}pointCoordinate(l,u,m,x){const b=l.horizonLineFromTop(!1),S=new Ot(u,Math.max(b,m));return l.rayIntersectionCoordinate(l.pointRayIntersection(S,x))}pointCoordinate3D(l,u,m){const x=new Ot(u,m);if(l.elevation)return l.elevation.pointCoordinate(x);{const b=this.pointCoordinate(l,x.x,x.y,0);return[b.x,b.y,b.z]}}isPointAboveHorizon(l,u){if(l.elevation&&l.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(l,u.x,u.y);const m=l.horizonLineFromTop();return u.y0?u<-Wb+m&&(u=-Wb+m):u>Wb-m&&(u=Wb-m);const S=b/Math.pow(hP(u),x);let A=S*Math.sin(x*l),N=b-S*Math.cos(x*l);return A=.5*(A/Math.PI+.5),N=.5*(N/Math.PI+.5),{x:A,y:this.southernCenter?N:1-N,z:0}}unproject(l,u){l=(2*l-.5)*Math.PI,this.southernCenter&&(u=1-u),u=(2*(1-u)-.5)*Math.PI;const{n:m,f:x}=this,b=x-u,S=Math.sign(b),A=Math.sign(m)*Math.sqrt(l*l+b*b);let N=Math.atan2(l,Math.abs(b))*S;b*m<0&&(N-=Math.PI*Math.sign(l)*S);const O=fe(fo(N/m)+this.center[0],-180,180),$=fe(fo(2*Math.atan(Math.pow(x/A,1/m))-Wb),-85.051129,St);return new Qe(O,this.southernCenter?-$:$)}}class GX extends ty{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:Lt(l),y:Ft(u),z:0}}unproject(l,u){const m=et(l),x=gt(u);return new Qe(m,x)}}const HX=Zn(St);class PNe extends ty{project(l,u){const m=(u=Zn(u))*u,x=m*m;return{x:.5*((l=Zn(l))*(.8707-.131979*m+x*(x*(.003971*m-.001529*x)-.013791))/Math.PI+.5),y:1-.5*(u*(1.007226+m*(.015085+x*(.028874*m-.044475-.005916*x)))/Math.PI+1),z:0}}unproject(l,u){l=(2*l-.5)*Math.PI;let m=u=(2*(1-u)-1)*Math.PI,x=25,b=0,S=m*m;do{S=m*m;const O=S*S;b=(m*(1.007226+S*(.015085+O*(.028874*S-.044475-.005916*O)))-u)/(1.007226+S*(.045255+O*(.259866*S-.311325-.005916*11*O))),m=fe(m-b,-HX,HX)}while(Math.abs(b)>1e-6&&--x>0);S=m*m;const A=fe(fo(l/(.8707+S*(S*(S*S*S*(.003971-.001529*S)-.013791)-.131979))),-180,180),N=fo(m);return new Qe(A,N)}}const WX=Zn(St);class RNe extends ty{project(l,u){u=Zn(u),l=Zn(l);const m=Math.cos(u),x=2/Math.PI,b=Math.acos(m*Math.cos(l/2)),S=Math.sin(b)/b,A=.5*(l*x+2*m*Math.sin(l/2)/S)||0,N=.5*(u+Math.sin(u)/S)||0;return{x:.5*(A/Math.PI+.5),y:1-.5*(N/Math.PI+1),z:0}}unproject(l,u){let m=l=(2*l-.5)*Math.PI,x=u=(2*(1-u)-1)*Math.PI,b=25;const S=1e-6;let A=0,N=0;do{const O=Math.cos(x),$=Math.sin(x),U=2*$*O,q=$*$,K=O*O,X=Math.cos(m/2),te=Math.sin(m/2),ie=2*X*te,ae=te*te,he=1-K*X*X,ue=he?1/he:0,ve=he?Math.acos(O*X)*Math.sqrt(1/he):0,ke=.5*(2*ve*O*te+2*m/Math.PI)-l,Ie=.5*(ve*$+x)-u,We=.5*ue*(K*ae+ve*O*X*q)+1/Math.PI,ze=ue*(ie*U/4-ve*$*te),Ge=.125*ue*(U*te-ve*$*K*ie),Ue=.5*ue*(q*X+ve*ae*O)+.5,Ve=ze*Ge-Ue*We;A=(Ie*ze-ke*Ue)/Ve,N=(ke*Ge-Ie*We)/Ve,m=fe(m-A,-Math.PI,Math.PI),x=fe(x-N,-WX,WX)}while((Math.abs(A)>S||Math.abs(N)>S)&&--b>0);return new Qe(fo(m),fo(x))}}class KX extends ty{constructor(l){super(l),this.center=l.center||[0,0],this.parallels=l.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Zn(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(l,u){const{scale:m,cosPhi:x}=this;return{x:Zn(l)*x*m+.5,y:-Math.sin(Zn(u))/x*m+.5,z:0}}unproject(l,u){const{scale:m,cosPhi:x}=this,b=-(u-.5)/m,S=fe(fo((l-.5)/m)/x,-180,180),A=Math.asin(fe(b*x,-1,1)),N=fe(fo(A),-85.051129,St);return new Qe(S,N)}}class LNe extends GX{constructor(l){super(l),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(l,u,m){const x=sj(l,u,m);return cr(x,x,aj(Mf(m))),{x:x[0],y:x[1],z:x[2]}}locationPoint(l,u,m){const x=Be(u.lat,u.lng),b=pt([],x),S=m?l._centerAltitude+m:l.elevation?l.elevation.getAtPointOrZero(l.locationCoordinate(u),l._centerAltitude):l._centerAltitude;tt(x,x,b,ot(1,0)*lr*S);const A=R(new Float64Array(16));return M(A,l.pixelMatrix,l.globeMatrix),cr(x,x,A),new Ot(x[0],x[1])}pixelsPerMeter(l,u){return ot(1,0)*u}pixelSpaceConversion(l,u,m){const x=ot(1,l)*u,b=Qr(ot(1,45)*u,x,m);return this.pixelsPerMeter(l,u)/b}createTileMatrix(l,u,m){const x=a4(Mf(m.canonical));return M(new Float64Array(16),l.globeMatrix,x)}createInversionMatrix(l,u){const{center:m}=l,x=aj(Mf(u));return W(x,x,Zn(m.lng)),G(x,x,Zn(m.lat)),V(x,x,[l._pixelsPerMercatorPixel,l._pixelsPerMercatorPixel,1]),Float32Array.from(x)}pointCoordinate(l,u,m,x){return uY(l,u,m,!0)||new kr(0,0)}pointCoordinate3D(l,u,m){const x=this.pointCoordinate(l,u,m,0);return[x.x,x.y,x.z]}isPointAboveHorizon(l,u){return!uY(l,u.x,u.y,!1)}farthestPixelDistance(l){const u=function(x,b){const S=x.cameraToCenterDistance,A=x._centerAltitude*b,N=x._camera,O=x._camera.forward(),$=me([],He([],O,-S),[0,0,A]),U=x.worldSize/(2*Math.PI),q=[0,0,-U],K=x.width/x.height,X=Math.tan(x.fovAboveCenter),te=He([],N.up(),X),ie=He([],N.right(),X*K),ae=pt([],me([],me([],O,te),ie)),he=[];let ue;if(new In($,ae).closestPointOnSphere(q,U,he)){const ve=me([],he,q),ke=rr([],ve,$);ue=Math.cos(x.fovAboveCenter)*Le(ke)}else{const ve=rr([],$,q),ke=rr([],q,$);pt(ke,ke);const Ie=Le(ve)-U;ue=Math.sqrt(Ie*(Ie+2*U));const We=Math.acos(ue/(U+Ie))-Math.acos(Pt(O,ke));ue*=Math.cos(We)}return 1.01*ue}(l,this.pixelsPerMeter(l.center.lat,l.worldSize)),m=lp(l.zoom);if(m>0){const x=VX(l,ot(1,l.center.lat)*l.worldSize),b=l.worldSize/(2*Math.PI),S=Math.max(l.width,l.height)/l.worldSize*Math.PI;return Qr(u,x+b*(1-Math.cos(S)),Math.pow(m,10))}return u}upVector(l,u,m){return sj(u,m,l,1)}upVectorScale(l){return{metersToTile:EI(AI(Mf(l)))}}}function YX(h){const l=h.parallels,u=!!l&&Math.abs(l[0]+l[1])<.01;switch(h.name){case"mercator":return new GX(h);case"equirectangular":return new NNe(h);case"naturalEarth":return new PNe(h);case"equalEarth":return new CNe(h);case"winkelTripel":return new RNe(h);case"albers":return u?new KX(h):new kNe(h);case"lambertConformalConic":return u?new KX(h):new INe(h);case"globe":return new LNe(h)}throw new Error(`Invalid projection name: ${h.name}`)}class DNe{constructor(l,u){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=u,this.appearances=l;const m=l.map(x=>function(b){if(!b.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const S=b.condition.expression;return{featureDependent:!Km(S),stateDependent:!Lg(S),zoomDependent:!Pd(S,["zoom"]),pitchDependent:!Pd(S,["pitch"]),brightnessDependent:!Pd(S,["brightness","measure-light"]),worldviewDependent:!Pd(S,["worldview"])}}(x));this.anyFeatureDependent=m.some(x=>x.featureDependent),this.anyStateDependent=m.some(x=>x.stateDependent)}update(l,u){const m=this.lastParams,x=!m||m.zoom!==l.zoom||m.pitch!==(l.pitch||0)||m.brightness!==(l.brightness||0)||m.worldview!==l.worldview;this.lastParams={zoom:l.zoom,pitch:l.pitch||0,brightness:l.brightness||0,worldview:l.worldview};const b=u&&this.anyStateDependent;if(!x&&!b&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!b){const S=this.evaluateAllFeatures(l);return S===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=S,{kind:"all-features",appearanceIndex:S})}return{kind:"per-feature"}}evaluateAllFeatures(l){for(let u=0;u{for(let x=0;xS-A),b=new Map;for(const S of x){const A=m.get(S);b.set(S,new Ci(A))}return u&&(this.cachedBatchIndices=x,this.cachedBatchSegments=b),{batchIndices:x,batchSegments:b}}snapshotSymbolVertexData(l,u){const m=l*Yb;return this.layoutVertexArray.uint16.slice(m,m+u*Yb)}restoreSymbolVertexData(l,u){this.layoutVertexArray.uint16.set(u,l*Yb)}updateSymbolVertexData(l,u,m,x,b,S,A,N,O,$,U,q,K){const X=this.layoutVertexArray.uint16,te=l*Yb;X[te]=u,X[te+1]=m,X[te+2]=x,X[te+3]=b,X[te+4]=S,X[te+5]=A,X[te+6]=N,X[te+7]=O,X[te+8]=$,X[te+9]=U,X[te+10]=q,X[te+11]=K}upload(l,u,m,x,b,S){this.isEmpty()||(m&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,FCe.members,!!S),this.indexBuffer=l.createIndexBuffer(this.indexArray,u),this.dynamicLayoutVertexBuffer=l.createVertexBuffer(this.dynamicLayoutVertexArray,$Ce.members,!0),this.opacityVertexBuffer=l.createVertexBuffer(this.opacityVertexArray,ONe,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=l.createVertexBuffer(this.iconTransitioningVertexArray,qCe.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=l.createVertexBuffer(this.globeExtVertexArray,BCe.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||b)&&(this.zOffsetVertexBuffer=l.createVertexBuffer(this.zOffsetVertexArray,zCe.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=l.createVertexBuffer(this.orientationVertexArray,VCe.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=l.createVertexBuffer(this.featureIdArray,UCe.members,!1))),(m||x)&&(this.programConfigurations.upload(l),this.uboBinder&&this.uboBinder.upload(l)))}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy(),this.iconTransitioningVertexBuffer&&this.iconTransitioningVertexBuffer.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.orientationVertexBuffer&&this.orientationVertexBuffer.destroy(),this.featureIdBuffer&&this.featureIdBuffer.destroy(),this.uboBinder&&this.uboBinder.destroy())}}br(fB,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class mB{constructor(l,u,m){this.layoutVertexArray=new l,this.layoutAttributes=u,this.indexArray=new m,this.segments=new Ci,this.collisionVertexArray=new D0,this.collisionVertexArrayExt=new Ch}upload(l){this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=l.createVertexBuffer(this.collisionVertexArray,GCe.members,!0),this.collisionVertexBufferExt=l.createVertexBuffer(this.collisionVertexArrayExt,HCe.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}br(mB,"CollisionBuffers");class Rh{constructor(l){this.collisionBoxArray=l.collisionBoxArray,this.zoom=l.zoom,this.overscaling=l.overscaling,this.layers=l.layers,this.layerIds=this.layers.map(S=>S.fqid),this.index=l.index,this.pixelRatio=l.pixelRatio,this.sourceLayerIndex=l.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=R([]),this.placementViewportMatrix=R([]);const u=this.layers[0]._unevaluatedLayout._values;this.worldview=l.worldview,this.localizable=l.localizable,this.maxUniformBufferBindings=l.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=l.maxUniformBlockSizeDwords,this.disableSymbolUBO=l.disableSymbolUBO,this.textSizeData=K0(this.zoom,u["text-size"],this.worldview,l.availableImages),this.iconSizeData=K0(this.zoom,u["icon-size"],this.worldview,l.availableImages);const m=this.layers[0].layout,x=m.get("symbol-sort-key"),b=m.get("symbol-z-order");this.lut=l.lut,this.canOverlap=m.get("text-allow-overlap")||m.get("icon-allow-overlap")||m.get("text-ignore-placement")||m.get("icon-ignore-placement"),this.sortFeaturesByKey=b!=="viewport-y"&&x.constantOr(1)!==void 0,this.sortFeaturesByY=(b==="viewport-y"||b==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=m.get("text-writing-mode").map(S=>Fc[S]),this.stateDependentLayerIds=this.layers.filter(S=>S.isStateDependent()).map(S=>S.id),this.sourceID=l.sourceID,this.projection=l.projection,this.hasAnyZOffset=!1,this.zOffsetSortDirty=!1,this.zOffsetBuffersNeedUpload=!1,this.elevationType="none",this.elevationStateComplete=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.hasAnySecondaryIcon=!1,this.hasAppearances=null,this.featureAppearances=null,this.featureAppearanceData=new Map}hasAnyAppearanceLayoutProperty(l){const u=this.layers[0].getAppearances();if(!u||u.length===0)return!1;const m=Array.isArray(l)?l:[l];return u.some(x=>m.some(b=>x.hasLayoutProperty(b)))}getAppearanceFeatureData(l){return this.featureAppearanceData.get(l)}createArrays(){this.text=new fB(new se(this.layers,{zoom:this.zoom,lut:this.lut},l=>l.startsWith("text")||l.startsWith("symbol"))),this.icon=new fB(new se(this.layers,{zoom:this.zoom,lut:this.lut},l=>l.startsWith("icon")||l.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new Y4(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new Y4(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new vI,this.lineVertexArray=new F0,this.symbolInstances=new xI}calculateGlyphDependencies(l,u,m,x,b){for(const S of l){const A=S.codePointAt(0);if(A===void 0)break;if(u[A]=!0,x&&b&&A<=65535){const N=Ej[S];N&&(u[N.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(l,u,m,x,b,S,A){if(!l.hasLayoutProperty("icon-size"))return A*S;let N=1;const O=l.getUnevaluatedLayoutProperty("icon-size"),$=K0(this.zoom,O,this.worldview,b),U=Gb($,u);if($.kind!=="constant"&&$.kind!=="camera"||(N=U.uSize),$.kind==="composite"){const{minZoom:q,maxZoom:K}=$,X=O.possiblyEvaluate(new si(q,{worldview:this.worldview}),x),te=O.possiblyEvaluate(new si(K,{worldview:this.worldview}),x),ie=X.evaluate(m,{},x,b);N=ie+(te.evaluate(m,{},x,b)-ie)*U.uSizeT}return $.kind==="source"&&(N=O.possiblyEvaluate(new si(this.zoom,{worldview:this.worldview}),x).evaluate(m,{},x,b)),N*S}updateFootprints(l,u){}updateReplacement(l,u){if(u.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=u.updateTime;const m=u.getReplacementRegionsForTile(l.toUnwrapped(),!0);return!OI(this.activeReplacements,m)&&(this.activeReplacements=m,!0)}getResolvedImageFromTokens(l){return typeof l=="string"?zl.build(l):l}populate(l,u,m,x){const b=this.layers[0],S=b.layout,A=this.projection.name==="globe",N=S.get("text-font"),O=S.get("text-field"),$=S.get("icon-image"),[U,q]=S.get("icon-size-scale-range"),K=fe(u.scaleFactor||1,U,q),[X,te]=S.get("text-size-scale-range"),ie=fe(u.scaleFactor||1,X,te),ae=(O.value.kind!=="constant"||O.value.value instanceof Oo&&!O.value.value.isEmpty()||O.value.value.toString().length>0)&&(N.value.kind!=="constant"||N.value.value.length>0),he=$.value.kind!=="constant"||!!$.value.value||Object.keys($.parameters).length>0,ue=this.hasAnyAppearanceLayoutProperty("icon-image"),ve=S.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!ae&&!he&&!ue)return;const ke=u.iconDependencies,Ie=u.glyphDependencies,We=u.availableImages,ze=new si(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),Ge=Ue=>{const Ve=Ue.id.toString();ke.has(Ve)?ke.get(Ve).push(Ue):ke.set(Ve,[Ue])};for(const Ue of l){const{feature:Ve,id:yt,index:wt,sourceLayerIndex:At}=Ue,It=b._featureFilter.needGeometry,kt=wn(Ve,It);if(!b._featureFilter.filter(ze,kt,m))continue;if(It||(kt.geometry=Ur(Ve,m,x)),A&&Ve.type!==1&&m.z<=5){const sr=kt.geometry,ir=.98078528056,Zt=(pr,Cr)=>Pt(sj(pr.x,pr.y,m,1),sj(Cr.x,Cr.y,m,1)){if(!sr.getLayoutProperty("icon-image"))return;const ir=this.getCombinedIconPrimary(sr,Ct,kt,m,We,Yt,K);ir&&Ge(ir)}),$t){const sr=N.evaluate(kt,{},m).join(","),ir=S.get("text-rotation-alignment")==="map"&&S.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(Fc.vertical)>=0;for(const Zt of $t.sections)if(Zt.image){const pr=Zt.image.getPrimary().scaleSelf(this.pixelRatio*ie),Cr=pr.id.toString(),zr=ke.get(Cr)||[];zr.push(pr),ke.set(Cr,zr)}else{const pr=AE($t.toString()),Cr=Zt.fontStack||sr,zr=Ie[Cr]=Ie[Cr]||{};this.calculateGlyphDependencies(Zt.text,zr,ir,this.allowVerticalPlacement,pr)}}}if(S.get("symbol-placement")==="line"&&(this.features=function(Ue){const Ve={},yt={},wt=[];let At=0;function It(Ct){wt.push(Ue[Ct]),At++}function kt(Ct,Dt,Ut){const Yt=yt[Ct];return delete yt[Ct],yt[Dt]=Yt,wt[Yt].geometry[0].pop(),wt[Yt].geometry[0]=wt[Yt].geometry[0].concat(Ut[0]),Yt}function $t(Ct,Dt,Ut){const Yt=Ve[Dt];return delete Ve[Dt],Ve[Ct]=Yt,wt[Yt].geometry[0].shift(),wt[Yt].geometry[0]=Ut[0].concat(wt[Yt].geometry[0]),Yt}function mt(Ct,Dt,Ut){const Yt=Ut?Dt[0][Dt[0].length-1]:Dt[0][0];return`${Ct}:${Yt.x}:${Yt.y}`}for(let Ct=0;CtCt.geometry)}(this.features)),S.get("symbol-elevation-reference")==="hd-road-markup"){if(this.elevationType="road",u.elevationFeatures){!this.elevationFeatures&&u.elevationFeatures.length>0&&(this.elevationFeatures=[],this.elevationFeatureIdToIndex=new Map);for(const Ue of u.elevationFeatures)this.elevationFeatureIdToIndex.set(Ue.id,this.elevationFeatures.length),this.elevationFeatures.push(Ue)}}else S.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((Ue,Ve)=>Ue.sortKey-Ve.sortKey)}getCombinedIconPrimary(l,u,m,x,b,S,A){let N,O;if(l.hasLayoutProperty("icon-image")){const $=u.getAppearanceValueAndResolveTokens(l,"icon-image",m,x,b);N=this.getResolvedImageFromTokens($)}else{const $=u.getValueAndResolveTokens("icon-image",m,x,b);N=this.getResolvedImageFromTokens($)}if(N){const $=l.hasLayoutProperty("icon-size")?l.getUnevaluatedLayoutProperty("icon-size"):u._unevaluatedLayout._values["icon-size"];O=Nj(N,K0(this.zoom,$,this.worldview,b),$,x,this.zoom,S,this.pixelRatio,A,this.worldview,b).iconPrimary}return O}updateSymbolInstanceIconVertices(l,u,m,x,b,S){const{canonical:A,availableImages:N,globalProperties:O,layer:$,iconScaleFactor:U,featureState:q,layoutIconOffset:K,layoutIconSize:X,layoutIconRotate:te}=S;if(l.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(u.activeAppearanceIndex===m)return{vertexOffsetDelta:l.numIconVertices,hasChanges:!1};const ie=m>=0?$.appearances[m]:null;if(ie){const ae=this.getCombinedIconPrimary(ie,$,x,A,N,{sortKey:void 0,text:void 0,icon:null,index:l.featureIndex,sourceLayerIndex:l.featureIndex,geometry:[],properties:u.properties,type:"Point",id:u.id},U);if(!ae)return{vertexOffsetDelta:0,hasChanges:!1};const he=ae.toString(),ue=this.iconAtlasPositions&&this.iconAtlasPositions.get(he);if(ue){const{appearanceIconOffset:ve,appearanceIconRotate:ke}=MX(ie,$,x,A,K,te,X,U);let Ie=rP(ue,void 0,ve,$.layout.get("icon-anchor").evaluate(x,q,A));const We=ue.sdf,ze=$.layout.get("icon-text-fit").constantOr("none");ze!=="none"&&u.textShaping&&u.iconTextFitPadding&&u.fontScale&&(Ie=eB(Ie,u.textShaping,ze,u.iconTextFitPadding,ve,u.fontScale));const Ge=this.calculateEffectiveAppearanceIconSize(ie,O.zoom,x,A,N,U,X),Ue=0,Ve=1+(Math.min(Y0,Math.round(Ge*dp))<<1),yt=oB(Ie,ke,We,ze!=="none",U);u.isUsingAppearanceIconVertexData||(u.isUsingAppearanceIconVertexData=!0,u.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(b,l.numIconVertices));const wt=Math.floor(l.numIconVertices/4),At=Math.min(yt.length,wt);let It=b;for(let $t=0;$t0||l.numVerticalGlyphVertices>0;if(!ve)return{vertexOffsetDelta:ve?l.numHorizontalGlyphVertices+l.numVerticalGlyphVertices:0,hasChanges:!1};if(u.activeAppearanceIndex===m)return{vertexOffsetDelta:l.numHorizontalGlyphVertices+l.numVerticalGlyphVertices,hasChanges:!1};const ke=m>=0?N.appearances[m]:null;if(ke&&u.textShaping){const{appearanceTextOffset:Ie,appearanceTextRotate:We,appearanceTextSize:ze}=OX(ke,N,x,A,q,X,K);u.fontScale=zX(ze,u.textScaleFactor);const Ge=ke.getUnevaluatedLayoutProperty("text-size");let Ue=this.textSizeData,Ve=ae,yt=he;ke.hasLayoutProperty("text-size")&&(Ue=K0(this.zoom,Ge,this.worldview,ue),Ve=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,yt=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const wt=u.textShaping.bottom-q[1],At=u.textShaping.left-q[0],It=u.textShaping.right-q[0];u.textShaping.top=Ie[1]+(u.textShaping.top-q[1]),u.textShaping.bottom=Ie[1]+wt,u.textShaping.left=Ie[0]+At,u.textShaping.right=Ie[0]+It;const kt=LX(0,u.textShaping,Ie,N,!1,x,$,this.allowVerticalPlacement,We),$t=ze&&Ue.kind==="composite"?Ge.possiblyEvaluate(new si(Ve,{}),A).evaluate(x,U,A):te,mt=ze&&Ue.kind==="composite"?Ge.possiblyEvaluate(new si(yt,{}),A).evaluate(x,U,A):ie,Ct=dB(ke.name,Ue,ze,O,$t,mt),Dt=Array.isArray(Ct)?Ct[1]:ze,Ut=0,Yt=1+(Math.min(Y0,Math.round(Dt*dp))<<1);u.isUsingAppearanceTextVertexData||(u.isUsingAppearanceTextVertexData=!0,u.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(b,l.numHorizontalGlyphVertices+l.numVerticalGlyphVertices));for(let vr=0;vr0){const O=new Set(Object.keys(l).map($=>{const U=Number($);return!isNaN(U)&&Number.isSafeInteger(U)&&String(U)===$?U:$}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(O,b[0],u,N,m,l,A),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(O,b[0],u,N,m,l,A)}}}updateRoadElevation(l){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let u=!1;const m=Mt(l),x=1/m;let b=!1,S=!1;for(let A=0;A0||q>0,ie=K>0,ae=this.elevationFeatures[N.elevationFeatureIndex];if(ae){const he=new Ot(N.tileAnchorX,N.tileAnchorY),ue=.075+ae.pointElevation(he);N.zOffset!==ue&&(u=!0,N.zOffset=ue),ue!==0&&(this.hasAnyZOffset=!0);const ve=ae.computeSlopeNormal(he,x),ke=ca(Nt(),Ae(0,0,1),ve);sn(O,O,ke),sn($,$,ke),O[2]*=m,$[2]*=m,O[0]===1&&O[1]===0&&O[2]===0&&$[0]===0&&$[1]===1&&$[2]===0||(b=b||te,S=S||ie)}if(te&&(fP(this.text.orientationVertexArray,U,O,$),fP(this.text.orientationVertexArray,q,O,$)),ie){const{placedIconSymbolIndex:he,verticalPlacedIconSymbolIndex:ue}=N;he>=0&&fP(this.icon.orientationVertexArray,K,O,$),ue>=0&&fP(this.icon.orientationVertexArray,X,O,$)}}b||(this.text.orientationVertexArray=void 0),S||(this.icon.orientationVertexArray=void 0),u&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const l=(b,S,A)=>{m+=S,m>b.length&&b.resize(m);for(let N=-S;N<0;N++)b.emplace(N+m,A)},u=(b,S,A)=>{x+=S,x>b.length&&b.resize(x);for(let N=-S;N<0;N++)b.emplace(N+x,A)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let m=0,x=0;for(let b=0;b0;if((A>0||N>0)&&(l(this.text.zOffsetVertexArray,A,$),l(this.text.zOffsetVertexArray,N,$)),U){const{placedIconSymbolIndex:q,verticalPlacedIconSymbolIndex:K}=S;q>=0&&u(this.icon.zOffsetVertexArray,O,$),K>=0&&u(this.icon.zOffsetVertexArray,S.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,m,x,b){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(l),this.iconCollisionBox.upload(l)),this.text.upload(l,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(S=>S.appearances&&S.appearances.length>0)),this.icon.upload(l,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(l,u,m,x,b,S=!1){const A={hasLayoutChanges:!1,hasUboChanges:!1};if(!l||!m||!this.featureAppearanceData)return A;const N=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 A;const U=this.layers[0],q=U.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===U.appearancesVersion||(this.featureAppearances=new DNe(U.appearances,U.appearancesVersion));const K=this.featureAppearances.update(x,S);if(K.kind==="no-changes")return A;let X=1,te=0,ie=!1,ae=!1;if(O){const[Ie,We]=q.get("icon-size-scale-range");X=fe(1,Ie,We)}let he=1,ue=0,ve=!1;if($){const[Ie,We]=q.get("text-size-scale-range");he=fe(1,Ie,We)}const ke=new Map;if(b&&m)for(const Ie of m){const We=b.getImage(Ie,U.scope);if(We){const ze=new gu(Ie.toString());ke.set(ze.toString(),We)}}for(let Ie=0;IeIt.isActive({globals:x,feature:Ve,canonical:l,featureState:Ue})):-1;yt=At>=0?At:-1}const wt=ze.activeAppearanceIndex!==yt;if($){const At=q.get("text-size"),It=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,kt=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,$t={canonical:l,layer:U,featureState:Ue,availableImages:m,textScaleFactor:he,imageMap:ke,layoutTextOffset:q.get("text-offset").evaluate(Ve,Ue,l).map(Ct=>Ct*Oa),layoutTextSize:At.evaluate(Ve,Ue,l),layoutTextRotate:q.get("text-rotate").evaluate(Ve,Ue,l),layoutMinZoomSize:At.evaluate(Ve,{zoom:It},l),layoutMaxZoomSize:At.evaluate(Ve,{zoom:kt},l),layoutTextSizeMinZoom:It,layoutTextSizeMaxZoom:kt},mt=this.updateSymbolInstanceTextVertices(We,ze,yt,Ve,ue,$t);ue+=mt.vertexOffsetDelta,ve=ve||mt.hasChanges}if(O){const At={canonical:l,layer:U,featureState:Ue,availableImages:m,globalProperties:x,iconScaleFactor:X,layoutIconOffset:q.get("icon-offset").evaluate(Ve,Ue,l),layoutIconSize:q.get("icon-size").evaluate(Ve,Ue,l,m),layoutIconRotate:q.get("icon-rotate").evaluate(Ve,Ue,l)},It=this.updateSymbolInstanceIconVertices(We,ze,yt,Ve,te,At);te+=It.vertexOffsetDelta,ie=ie||It.hasChanges}if(wt){const At=We.featureIndex,It=x?x.brightness:null,kt=Ue||{},$t=yt>=0?U.appearances[yt]:null;this.text.uboBinder&&(this.text.uboBinder.layer=U,ae=this.text.uboBinder.updateFeaturePaintForAppearance(At,Ve,kt,l,m,It,$t)||ae),this.icon.uboBinder&&(this.icon.uboBinder.layer=U,ae=this.icon.uboBinder.updateFeaturePaintForAppearance(At,Ve,kt,l,m,It,$t)||ae)}ze.activeAppearanceIndex=yt}return ie&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),ve&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:ie||ve,hasUboChanges:ae}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=YX(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(l,u){const m=this.lineVertexArray.length;if(l.segment!==void 0)for(const{x,y:b}of u)this.lineVertexArray.emplaceBack(x,b);return{lineStartIndex:m,lineLength:this.lineVertexArray.length-m}}addSymbols(l,u,m,x,b,S,A,N,O,$,U,q,K,X,te,ie,ae,he){const ue=l.indexArray,ve=l.layoutVertexArray,ke=l.globeExtVertexArray,Ie=he,We=l.uboBinder?l.uboBinder.getCurrentBatchIndex():void 0,ze=l.segments.prepareSegment(4*Ie,ve,ue,this.canOverlap?S.sortKey:void 0,We),Ge=this.glyphOffsetArray.length,Ue=ze.vertexLength,Ve=this.allowVerticalPlacement&&A===Fc.vertical?Math.PI/2:0,yt=S.text&&S.text.sections;let wt=ve.length,At=-1;for(let $t=0;$t=0)){const $t=4*It;for(let mt=0;mt<$t;mt++)l.featureIdArray.emplaceBack(At)}const kt=N?N.anchor:O;l.placedSymbolArray.emplaceBack(kt.x,kt.y,kt.z,O.x,O.y,Ge,this.glyphOffsetArray.length-Ge,Ue,$,U,O.segment,m?m[0]:0,m?m[1]:0,x[0],x[1],A,0,0,0,q,0),l.symbolInstanceIndices.push(ae)}_addNullVertices(l,u,m,x,b,S,A,N,O){for(let $=0;$=0?u.rightJustifiedTextSymbolIndex:u.centerJustifiedTextSymbolIndex>=0?u.centerJustifiedTextSymbolIndex:u.leftJustifiedTextSymbolIndex>=0?u.leftJustifiedTextSymbolIndex:u.verticalPlacedTextSymbolIndex>=0?u.verticalPlacedTextSymbolIndex:x),S=tB(this.textSizeData,l,b)/Oa;return this.tilePixelRatio*S}getSymbolInstanceIconSize(l,u,m){const x=this.icon.placedSymbolArray.get(m),b=tB(this.iconSizeData,l,x);return this.tilePixelRatio*b}_commitDebugCollisionVertexUpdate(l,u,m,x){l.emplaceBack(u,-m,-m,x),l.emplaceBack(u,m,-m,x),l.emplaceBack(u,m,m,x),l.emplaceBack(u,-m,m,x)}_updateTextDebugCollisionBoxes(l,u,m,x,b,S,A){for(let N=x;N0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}hasIconTextFit(){return this.hasAnyIconTextFit}addIndicesForPlacedSymbol(l,u){const m=l.placedSymbolArray.get(u),x=m.vertexStartIndex+4*m.numGlyphs;for(let b=m.vertexStartIndex;bx[A]-x[N]||b[N]-b[A]),S}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let l=0;lthis.symbolInstances.get(u).zOffset-this.symbolInstances.get(l).zOffset)}addToSortKeyRanges(l,u){const m=this.sortKeyRanges[this.sortKeyRanges.length-1];m&&m.sortKey===u?m.symbolInstanceEnd=l+1:this.sortKeyRanges.push({sortKey:u,symbolInstanceStart:l,symbolInstanceEnd:l+1})}sortFeatures(l){if(this.sortFeaturesByY&&this.sortedAngle!==l)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(l),this.sortedAngle=l,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const u of this.symbolInstanceIndexes){const m=this.symbolInstances.get(u);this.featureSortOrder.push(m.featureIndex);const{rightJustifiedTextSymbolIndex:x,centerJustifiedTextSymbolIndex:b,leftJustifiedTextSymbolIndex:S,verticalPlacedTextSymbolIndex:A,placedIconSymbolIndex:N,verticalPlacedIconSymbolIndex:O}=m;x>=0&&this.addIndicesForPlacedSymbol(this.text,x),b>=0&&b!==x&&this.addIndicesForPlacedSymbol(this.text,b),S>=0&&S!==b&&S!==x&&this.addIndicesForPlacedSymbol(this.text,S),A>=0&&this.addIndicesForPlacedSymbol(this.text,A),N>=0&&this.addIndicesForPlacedSymbol(this.icon,N),O>=0&&this.addIndicesForPlacedSymbol(this.icon,O)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(l,u){const m=(this.text.uboBinder&&this.text.uboBinder.maxFeaturesPerBatch>0?this.text.uboBinder:this.icon.uboBinder&&this.icon.uboBinder.maxFeaturesPerBatch>0?this.icon.uboBinder:null).maxFeaturesPerBatch;if(this.symbolsByBatch)for(const x of this.symbolsByBatch.values())for(const b of x){const S=this.symbolInstances.get(b.index);b.rotatedY=0|Math.round(l*S.tileAnchorX+u*S.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let x=0;xb.rotatedY-S.rotatedY||S.featureIndex-b.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(l,u){for(const m of l){const x=m.batchIndex;if(x===void 0)continue;const b=u.get(x);if(!b){m.primitiveOffset=this.text.indexArray.length,m.primitiveLength=0;continue}m.primitiveOffset=this.text.indexArray.length;const S=this.text.indexArray.length;for(const{index:A}of b){const N=this.symbolInstances.get(A),{rightJustifiedTextSymbolIndex:O,centerJustifiedTextSymbolIndex:$,leftJustifiedTextSymbolIndex:U,verticalPlacedTextSymbolIndex:q}=N;O>=0&&this.addIndicesForPlacedSymbol(this.text,O),$>=0&&$!==O&&this.addIndicesForPlacedSymbol(this.text,$),U>=0&&U!==$&&U!==O&&this.addIndicesForPlacedSymbol(this.text,U),q>=0&&this.addIndicesForPlacedSymbol(this.text,q)}m.primitiveLength=this.text.indexArray.length-S}}rebuildIconSegmentIndices(l,u){for(const m of l){const x=m.batchIndex;if(x===void 0)continue;const b=u.get(x);if(!b){m.primitiveOffset=this.icon.indexArray.length,m.primitiveLength=0;continue}m.primitiveOffset=this.icon.indexArray.length;const S=this.icon.indexArray.length;for(const{index:A}of b){const N=this.symbolInstances.get(A),{placedIconSymbolIndex:O,verticalPlacedIconSymbolIndex:$}=N;O>=0&&this.addIndicesForPlacedSymbol(this.icon,O),$>=0&&this.addIndicesForPlacedSymbol(this.icon,$)}m.primitiveLength=this.icon.indexArray.length-S}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const l=Math.sin(this.sortedAngle),u=Math.cos(this.sortedAngle),m=this.getOrCreateSortedSymbolsByBatch(l,u),x=Array.from(m.keys()).sort((b,S)=>b-S);for(const b of x){const S=m.get(b);for(const{index:A}of S){const N=this.symbolInstances.get(A);this.featureSortOrder.push(N.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),m),this.rebuildIconSegmentIndices(this.icon.segments.get(),m),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(l){const u=this.symbolInstances.get(this.text.symbolInstanceIndices[l]).elevationFeatureIndex;let m;return this.elevationFeatures&&um in h?String(h[m]):"")}let XX,QX,pB;br(Rh,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),Rh.addDynamicAttributes=Kb;class JX{constructor(l){this.type=l.property.overrides?l.property.overrides.runtimeType:bh,this.defaultValue=l}evaluate(l){if(l.formattedSection){const u=this.defaultValue.property.overrides;if(u&&u.hasOverride(l.formattedSection))return u.getOverride(l.formattedSection)}return l.feature&&l.featureState?this.defaultValue.evaluate(l.feature,l.featureState):this.defaultValue.property.specification.default}eachChild(l){this.defaultValue.isConstant()||l(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}br(JX,"FormatSectionOverride",{omit:["defaultValue"]});const gB=()=>pB||(pB={layout:XX||(XX=new rs({"symbol-placement":new Qt(nt.layout_symbol["symbol-placement"]),"symbol-spacing":new Qt(nt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Qt(nt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Ht(nt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Qt(nt.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new Qt(nt.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new Qt(nt.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new Qt(nt.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new Qt(nt.layout_symbol["icon-ignore-placement"]),"icon-optional":new Qt(nt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Qt(nt.layout_symbol["icon-rotation-alignment"]),"icon-size":new Ht(nt.layout_symbol["icon-size"]),"icon-size-scale-range":new Qt(nt.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new Ht(nt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Ht(nt.layout_symbol["icon-text-fit-padding"]),"icon-image":new Ht(nt.layout_symbol["icon-image"]),"icon-image-use-theme":new Qt({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new Ht(nt.layout_symbol["icon-rotate"]),"icon-padding":new Qt(nt.layout_symbol["icon-padding"]),"icon-keep-upright":new Qt(nt.layout_symbol["icon-keep-upright"]),"icon-offset":new Ht(nt.layout_symbol["icon-offset"]),"icon-anchor":new Ht(nt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Qt(nt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Qt(nt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Qt(nt.layout_symbol["text-rotation-alignment"]),"text-field":new Ht(nt.layout_symbol["text-field"]),"text-font":new Ht(nt.layout_symbol["text-font"]),"text-size":new Ht(nt.layout_symbol["text-size"]),"text-size-scale-range":new Qt(nt.layout_symbol["text-size-scale-range"]),"text-max-width":new Ht(nt.layout_symbol["text-max-width"]),"text-line-height":new Ht(nt.layout_symbol["text-line-height"]),"text-letter-spacing":new Ht(nt.layout_symbol["text-letter-spacing"]),"text-justify":new Ht(nt.layout_symbol["text-justify"]),"text-radial-offset":new Ht(nt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Qt(nt.layout_symbol["text-variable-anchor"]),"text-anchor":new Ht(nt.layout_symbol["text-anchor"]),"text-max-angle":new Qt(nt.layout_symbol["text-max-angle"]),"text-writing-mode":new Qt(nt.layout_symbol["text-writing-mode"]),"text-rotate":new Ht(nt.layout_symbol["text-rotate"]),"text-padding":new Qt(nt.layout_symbol["text-padding"]),"text-keep-upright":new Qt(nt.layout_symbol["text-keep-upright"]),"text-transform":new Ht(nt.layout_symbol["text-transform"]),"text-offset":new Ht(nt.layout_symbol["text-offset"]),"text-allow-overlap":new Qt(nt.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new Qt(nt.layout_symbol["text-ignore-placement"]),"text-optional":new Qt(nt.layout_symbol["text-optional"]),visibility:new Qt(nt.layout_symbol.visibility)})),paint:QX||(QX=new rs({"icon-opacity":new Ht(nt.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new Ht(nt.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new Ht(nt.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new Ht(nt.paint_symbol["text-emissive-strength"]),"icon-color":new Ht(nt.paint_symbol["icon-color"]),"icon-halo-color":new Ht(nt.paint_symbol["icon-halo-color"]),"icon-halo-width":new Ht(nt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Ht(nt.paint_symbol["icon-halo-blur"]),"icon-translate":new Qt(nt.paint_symbol["icon-translate"]),"icon-translate-anchor":new Qt(nt.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new Qt(nt.paint_symbol["icon-image-cross-fade"]),"text-opacity":new Ht(nt.paint_symbol["text-opacity"]),"text-occlusion-opacity":new Ht(nt.paint_symbol["text-occlusion-opacity"]),"text-color":new Ht(nt.paint_symbol["text-color"],{runtimeType:Sl,getOverride:h=>h.textColor,hasOverride:h=>!!h.textColor}),"text-halo-color":new Ht(nt.paint_symbol["text-halo-color"]),"text-halo-width":new Ht(nt.paint_symbol["text-halo-width"]),"text-halo-blur":new Ht(nt.paint_symbol["text-halo-blur"]),"text-translate":new Qt(nt.paint_symbol["text-translate"]),"text-translate-anchor":new Qt(nt.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new Qt(nt.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new Qt(nt.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new Qt(nt.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new Qt(nt.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new Ht(nt.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"})}))},pB);class mP extends rl{constructor(l,u,m,x){super(l,gB(),u,m,x,l.layout?l.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=R([]),this.hasOcclusionOpacityProperties=l.paint!==void 0&&("icon-occlusion-opacity"in l.paint||"text-occlusion-opacity"in l.paint)}_handleSpecialPaintPropertyUpdate(l){l!=="icon-occlusion-opacity"&&l!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(l,u){super.recalculate(l,u),this.appearances&&this.appearances.forEach(x=>{x.recalculate(l,u,this.iconImageUseTheme)}),this.layout.get("icon-rotation-alignment")==="auto"&&(this.layout._values["icon-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-rotation-alignment")==="auto"&&(this.layout._values["text-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-pitch-alignment")==="auto"&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),this.layout.get("icon-pitch-alignment")==="auto"&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment"));const m=this.layout.get("text-writing-mode");if(m){const x=[];for(const b of m)x.indexOf(b)<0&&x.push(b);this.layout._values["text-writing-mode"]=x}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(l,u,m,x){return this._saturation===l&&this._contrast===u&&this._brightnessMin===m&&this._brightnessMax===x||(this._colorAdjustmentMatrix=function(b,S,A,N){b=os(b),S=Mi(S);const O=k(),$=b/3,U=1-2*$,q=[U,$,$,0,$,U,$,0,$,$,U,0,0,0,0,1],K=.5-.5*S,X=N-A;return M(O,[X,0,0,0,0,X,0,0,0,0,X,0,A,A,A,1],[S,0,0,0,0,S,0,0,0,0,S,0,K,K,K,1]),M(O,O,q),O}(l,u,m,x),this._saturation=l,this._contrast=u,this._brightnessMin=m,this._brightnessMax=x),this._colorAdjustmentMatrix}getValueAndResolveTokens(l,u,m,x){const b=this.layout.get(l).evaluate(u,{},m,x),S=this._unevaluatedLayout._values[l];return S.isDataDriven()||S0(S.value)||!b?b:ZX(u.properties,b)}getAppearanceValueAndResolveTokens(l,u,m,x,b){const S=l.getLayoutProperty(u);if(!S)return;const A=S.evaluate(m,{},x,b),N=l.getUnevaluatedLayoutProperties()._values[u];return N.isDataDriven()||S0(N.value)||!A||typeof A!="string"?A:ZX(m.properties,A)}createBucket(l){return new Rh(l)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const l of gB().paint.overridableProperties){if(!mP.hasPaintOverride(this.layout,l))continue;const u=this.paint.get(l),m=new JX(u),x=new ub(m,u.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let b=null;b=u.value.kind==="constant"||u.value.kind==="source"?new $g("source",x):new Zm("composite",x,u.value.zoomStops,u.value.interpolationType),this.paint._values[l]=new ep(u.property,b,u.parameters)}}_handleOverridablePaintPropertyUpdate(l,u,m){return!(!this.layout||u.isDataDriven()||m.isDataDriven())&&mP.hasPaintOverride(this.layout,l)}static hasPaintOverride(l,u){const m=l.get("text-field"),x=gB().paint.properties[u];let b=!1;const S=A=>{for(const N of A)if(x.overrides&&x.overrides.hasOverride(N))return void(b=!0)};if(m.value.kind==="constant"&&m.value.value instanceof Oo)S(m.value.value.sections);else if(m.value.kind==="source"){const A=O=>{b||(O instanceof Ir&&Cs(O.value)===Jx?S(O.value.sections):O instanceof Vm?S(O.sections):O.eachChild(A))},N=m.value;N._styleExpression&&A(N._styleExpression.expression)}return b}getProgramIds(){return["symbol"]}getDefaultProgramParams(l,u,m){return{config:new re(this,{zoom:u,lut:m}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let eQ,tQ,rQ,nQ;var pP=Rn([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function gP(h,l,u,m,x,b,S,A){const N=[h,l,1,u,m,1,x,b,1],O=[S,A,1],$=T([],N),[U,q,K]=Tr(O,O,$);return E(N,N,[U,0,0,0,q,0,0,0,K])}function iQ(h,l,u,m,x,b,S,A){const N=function(O,$,U,q,K,X,te,ie){const ae=gP(0,0,1,0,1,1,0,1),he=gP(O,$,U,q,K,X,te,ie);return E(he,he,T([],ae))}(h,l,u,m,x,b,S,A);return[N[2]/N[8]/lr,N[5]/N[8]/lr]}function yP(h){return[h[0],Math.min(Math.max(h[1],-85.051129),St)]}class sQ extends Qx{constructor(l,u,m,x){super(),this.id=l,this.dispatcher=m,this.coordinates=u.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.onNorthPole=!1,this.onSouthPole=!1,this.setEventedParent(x),this.options=u,this._dirty=!1}load(l,u){if(this._loaded=u||!1,this.fire(new Uu("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return l&&(this.coordinates=l),this._loaded=!0,void this._finishLoading();this._imageRequest=Tg(this.map._requestManager.transformRequest(this.url,Zx.Image),(m,x)=>{this._imageRequest=null,this._loaded=!0,m?this.fire(new Eg(m)):x&&(this.image=x,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,l&&(this.coordinates=l),this._finishLoading())})}loaded(){return this._loaded}updateImage(l){return l.url?(this._imageRequest&&l.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=l.url,this.load(l.coordinates,this._loaded),this):this}setTexture(l){if(!(l.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new wj(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 Uu("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 wj||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(l){if(this.coordinates=l,this._boundsArray=void 0,this._unsupportedCoords=!1,!l.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let u=l[0][1],m=l[0][1];for(const b of l)b[1]>m&&(m=b[1]),b[1]St?this.onNorthPole=!0:x<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const b=l.map(kr.fromLngLat);this.tileID=function(S){let A=1/0,N=1/0,O=-1/0,$=-1/0;for(const te of S)A=Math.min(A,te.x),N=Math.min(N,te.y),O=Math.max(O,te.x),$=Math.max($,te.y);const U=Math.max(O-A,$-N),q=Math.max(0,Math.floor(-Math.log2(U))),K=Math.pow(2,q);let X=Math.floor((A+O)/2*K);return X>1&&(X-=1),new V0(q,X,Math.floor((N+$)/2*K))}(b),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new Uu("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof wj||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(l){for(const ie in this.tiles){const ae=this.tiles[ie];ae.state!=="loaded"&&(ae.state="loaded",ae.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const u=Z0(new V0(0,0,0),this.map.transform.projection),m=[u.projection.project(this.coordinates[0][0],this.coordinates[0][1]),u.projection.project(this.coordinates[1][0],this.coordinates[1][1]),u.projection.project(this.coordinates[2][0],this.coordinates[2][1]),u.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(ie){const ae=ie[1].x-ie[0].x,he=ie[1].y-ie[0].y,ue=ie[2].x-ie[1].x,ve=ie[2].y-ie[1].y,ke=ie[3].x-ie[2].x,Ie=ie[3].y-ie[2].y,We=ie[0].x-ie[3].x,ze=ie[0].y-ie[3].y,Ge=ae*ve-ue*he,Ue=ue*Ie-ke*ve,Ve=ke*ze-We*Ie,yt=We*he-ae*ze;return Ge>0&&Ue>0&&Ve>0&&yt>0||Ge<0&&Ue<0&&Ve<0&&yt<0}(m))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const x=Z0(this.tileID,this.map.transform.projection),[b,S,A,N]=this.coordinates.map(ie=>{const ae=x.projection.project(ie[0],ie[1]);return qX(x,ae)._round()});this.perspectiveTransform=iQ(b.x,b.y,S.x,S.y,A.x,A.y,N.x,N.y);const O=this._boundsArray=new To;O.emplaceBack(b.x,b.y,0,0),O.emplaceBack(S.x,S.y,lr,0),O.emplaceBack(N.x,N.y,0,lr),O.emplaceBack(A.x,A.y,lr,lr),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=l.createVertexBuffer(O,pP.members),this.boundsSegments=Ci.simpleSegment(0,0,4,2);const $=[],U=function(ie){return[yP(ie[0]),yP(ie[1]),yP(ie[2]),yP(ie[3])]}(this.coordinates),[q,K,X,te]=function(ie){let ae=ie[0][0],he=ae,ue=ie[0][1],ve=ue;for(let ke=1;kehe&&(he=ie[ke][0]),ie[ke][1]ve&&(ve=ie[ke][1]);return[ae,ue,he-ae,ve-ue]}(U);{const ie=new To,[ae,he,ue,ve]=function(kt){let $t=kt[0].x,mt=$t,Ct=kt[0].y,Dt=Ct;for(let Ut=1;Utmt&&(mt=kt[Ut].x),kt[Ut].yDt&&(Dt=kt[Ut].y);return[$t,Ct,mt-$t,Dt-Ct]}(m),ke=kt=>[(kt.x-ae)/ue,(kt.y-he)/ve],[Ie,We,ze,Ge]=m.map(ke),Ue=function(kt,$t,mt,Ct,Dt,Ut,Yt,vr){const sr=gP(0,0,1,0,1,1,0,1);return E(sr,sr,T([],gP(kt,$t,mt,Ct,Dt,Ut,Yt,vr)))}(Ie[0],Ie[1],We[0],We[1],ze[0],ze[1],Ge[0],Ge[1]);this.elevatedGlobePerspectiveTransform=iQ(Ie[0],Ie[1],We[0],We[1],ze[0],ze[1],Ge[0],Ge[1]);const Ve=(kt,$t)=>{$.push(kt.lng);const mt=Math.round((kt.lng-q)/X*lr),Ct=Math.round((kt.lat-K)/te*lr),Dt=ke($t),Ut=Tr([],[Dt[0],Dt[1],1],Ue),Yt=Math.round(Ut[0]/Ut[2]*lr),vr=Math.round(Ut[1]/Ut[2]*lr);ie.emplaceBack(mt,Ct,Yt,vr)},yt=m[3].x-m[0].x,wt=m[3].y-m[0].y,At=m[2].x-m[1].x,It=m[2].y-m[1].y;for(let kt=0;kt<65;kt++){const $t=kt/64,mt=[m[0].x+$t*yt,m[0].y+$t*wt],Ct=[m[1].x+$t*At,m[1].y+$t*It],Dt=Ct[0]-mt[0],Ut=Ct[1]-mt[1];for(let Yt=0;Yt<65;Yt++){const vr=Yt/64,sr={x:mt[0]+Dt*vr,y:mt[1]+Ut*vr};Ve(u.projection.unproject(sr.x,sr.y),sr)}}this.elevatedGlobeVertexBuffer=l.createVertexBuffer(ie,pP.members)}{this.maxLongitudeTriangleSize=0;let ie=[],ae=new _s;const he=(ue,ve,ke)=>{ae.emplaceBack(ue,ve,ke);const Ie=$[ue],We=$[ve],ze=$[ke],Ge=Math.min(Math.min(Ie,We),ze),Ue=Math.max(Math.max(Ie,We),ze)-Ge;Ue>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=Ue),ie.push(Ge+Ue/2)};for(let ue=0;ue<64;ue++)for(let ve=0;ve<64;ve++){const ke=65*ue+ve,Ie=ke+1,We=ke+65,ze=We+1;he(ke,We,Ie),he(Ie,We,ze)}[ie,ae]=function(ue,ve){const ke=Array.from({length:ue.length},(ze,Ge)=>Ge);ke.sort((ze,Ge)=>ue[ze]-ue[Ge]);const Ie=[],We=new _s;for(let ze=0;ze{S.segments.push({vertexOffset:0,primitiveOffset:U,vertexLength:u.segments[0].vertexLength,primitiveLength:q,sortKey:void 0,vaos:{}})},N=.51*this.maxLongitudeTriangleSize;if(Math.abs(m[0]-x)<=N){const U=ua(m,0,m.length,x+N);return U===m.length||A(U,as(m,U+1,m.length,x+360-N)-U),S}x0}}let oQ,lQ,cQ,uQ,dQ,hQ,fQ;class mQ extends rl{constructor(l,u,m,x){super(l,{layout:oQ||(oQ=new rs({visibility:new Qt(nt["layout_raster-particle"].visibility)})),paint:lQ||(lQ=new rs({"raster-particle-array-band":new Qt(nt["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new Qt(nt["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new qg(nt["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new Qt(nt["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new Qt(nt["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new Qt(nt["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new Qt(nt["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new Qt(nt["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"})}))},u,m,x),this._updateColorRamp(),this.lastInvalidatedAt=$l.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=oj({expression:l,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:u}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=$l.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class $Ne extends rl{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 xB(h,l,u){const m=[0,0,1],x=gr([]);return ni(x,x,u?-Zn(h)+Math.PI:Zn(h)),En(x,x,-Zn(l)),sn(m,m,x),pt(m,m)}class xP{constructor(l,u,m,x){this.message=(l?`${l}: `:"")+m,x&&(this.identifier=x),u!=null&&u.__line__&&(this.line=u.__line__)}}function vB(h,l){const u=h.indexOf("://")===-1;try{return new URL(h,u&&l?"http://example.com":void 0),!0}catch{return!1}}class pQ{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 gQ{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new QE,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(l){const u=16*l,m=this.instancedDataArray.float32;let x=Math.floor(m[u+2]);const b=1.05*(m[u+2]-x);return x/=100,[m[u]%1*1.05,m[u+1]%1*1.05,b,x]}tileCoordinatesForInstance(l){const u=16*l,m=this.instancedDataArray.float32;let x=m[u+0];return x=x>lr?x-lr:x,new Ot(Math.trunc(x),Math.trunc(m[u+1]))}translationForInstance(l){const u=16*l,m=this.instancedDataArray.float32;return[m[u+4],m[u+5],m[u+6]]}rotationScaleForInstance(l){const u=16*l,m=this.instancedDataArray.float32;return[m[u+7],m[u+8],m[u+9],m[u+10],m[u+11],m[u+12],m[u+13],m[u+14],m[u+15]]}transformForInstance(l){const u=16*l,m=this.instancedDataArray.float32;return[m[u+7],m[u+8],m[u+9],m[u+4],m[u+10],m[u+11],m[u+12],m[u+5],m[u+13],m[u+14],m[u+15],m[u+6],0,0,0,1]}}class _B{constructor(l){this.zoom=l.zoom,this.canonical=l.canonical,this.overscaledZ=this.canonical.z+Math.log2(l.overscaling),this.layers=l.layers,this.layerIds=this.layers.map(u=>u.fqid),this.projection=l.projection,this.index=l.index,this.worldview=l.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.hasPattern=!1,this.instancesPerModel={},this.validForExaggeration=0,this.maxVerticalOffset=0,this.maxScale=0,this.maxHeight=0,this.lookupDim=this.zoom>this.canonical.z+1?0:this.zoom>this.canonical.z?256:this.zoom>15?75:100,this.instanceCount=0,this.terrainElevationMin=0,this.terrainElevationMax=0,this.validForDEMTile={id:null,timestamp:0},this.modelUris=[],this.modelsRequested=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.styleDefinedModelURLs=l.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,m,x){this.tileToMeter=Mt(m);const b=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const S=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?u.elevationFeatures:void 0;for(const{feature:A,id:N,index:O,sourceLayerIndex:$}of l){const U=N??(A.properties&&A.properties.hasOwnProperty("id")?A.properties.id:void 0),q=wn(A,b);if(!this.layers[0]._featureFilter.filter(new si(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),q,m))continue;const K={id:U,sourceLayerIndex:$,index:O,geometry:b?q.geometry:Ur(A,m,x),properties:A.properties,type:A.type,patterns:{}},X=this.addFeature(K,K.geometry,q,S,m);X&&u.featureIndex.insert(A,K.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 m=0;for(const x of this.modelUris){const b=l.getModel(x,u);if(!b)continue;const S=this.instancesPerModel[x];if(S){const A=.5*at(b.aabb.max,b.aabb.min)*S.maxScale+S.maxXYTranslationDistance,N=Math.min(lr,Math.max(A/this.tileToMeter,256));m=Math.max(N,m)}}return m}update(l,u,m,x){for(const b in this.instancesPerModel){const S=this.instancesPerModel[b];for(const A in l)S.idToFeaturesIndex.hasOwnProperty(A)&&(this.evaluate(S.features[S.idToFeaturesIndex[A]],l[A],S,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let l=!1;for(const u in this.instancesPerModel){const m=this.instancesPerModel[u];for(const x of m.features){const b=this.layers[0],S=x.feature,A=this.canonical,N=b.paint.get("model-rotation").evaluate(S,{},A),O=b.paint.get("model-scale").evaluate(S,{},A),$=b.paint.get("model-translation").evaluate(S,{},A);xr(x.rotation,N)&&xr(x.scale,O)&&xr(x.translation,$)||(this.evaluate(x,x.featureStates,m,!0),l=!0)}}return l}updateReplacement(l,u,m,x){if(u.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=u.updateTime;const b=u.getReplacementRegionsForTile(l.toUnwrapped(),!0);if(OI(this.activeReplacements,b))return!1;this.activeReplacements=b;let S=!1;for(const A in this.instancesPerModel){const N=this.instancesPerModel[A],O=N.instancedDataArray;for(const $ of N.features){const U=$.instancedDataOffset,q=$.instancedDataCount;for(let K=0;Klr;te=ie?te-lr:te;const ae=Math.floor(te),he=Math.floor(O.float32[X+1]);let ue=!1;for(const ve of this.activeReplacements)if(!XY(ve,m,FI.Model,x)&&!(ve.min.x>ae||ae>ve.max.x||ve.min.y>he||he>ve.max.y)&&(ue=rZ(tZ(ae,he,l.canonical,ve.footprintTileId.canonical),ve.footprint),ue))break;O.float32[X]=ue?te+lr:te,S=S||ue!==ie}}}return S}isEmpty(){for(const l in this.instancesPerModel)if(this.instancesPerModel[l].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(l){if(!this.uploaded)for(const u in this.instancesPerModel){const m=this.instancesPerModel[u];m.instancedDataArray.length<0||m.instancedDataArray.length===0||(m.instancedDataBuffer?m.instancedDataBuffer.updateData(m.instancedDataArray):m.instancedDataBuffer=l.createVertexBuffer(m.instancedDataArray,sCe.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(l){for(const m in this.instancesPerModel){const x=this.instancesPerModel[m];x.instancedDataArray.length!==0&&x.instancedDataBuffer&&x.instancedDataBuffer.destroy()}const u=this.layers[0].modelManager;if(l&&u&&this.modelUris&&this.modelsRequested)for(const m of this.modelUris)u.removeModel(m,"",!0)}addFeature(l,u,m,x,b){const S=this.layers[0],A=S.layout.get("model-id"),N=S.layout.get("model-allow-density-reduction"),O=A.evaluate(m,{},this.canonical);if(!O)return $r(`modelId is not evaluated for layer ${S.id} and it is not going to get rendered.`),O;(vB(O,!1)||this.styleDefinedModelURLs[O]!==void 0)&&(this.modelUris.includes(O)||this.modelUris.push(O)),this.instancesPerModel[O]||(this.instancesPerModel[O]=new gQ);const $=this.instancesPerModel[O],U=$.instancedDataArray,q=new pQ(m,U.length);let K;x&&(K=Oi.getElevationFeature(l,x));for(const X of u)for(const te of X){if(te.x<0||te.x>=lr||te.y<0||te.y>=lr)continue;if(this.lookupDim!==0&&N){const ae=(this.lookupDim-1)/lr,he=this.lookupDim*(te.y*ae|0)+te.x*ae|0;if(this.lookup){if(this.lookup[he]!==0)continue;this.lookup[he]=1}}this.instanceCount++;const ie=U.length;if(U.resize(ie+1),x){$.instancesRoadElevation||($.instancesRoadElevation=[]);const ae=K?K.pointElevation(new Ot(te.x,te.y)):0;$.instancesRoadElevation.push(ae)}$.instancesEvaluatedElevation.push(0),U.float32[16*ie]=te.x,U.float32[16*ie+1]=te.y}return q.instancedDataCount=$.instancedDataArray.length-q.instancedDataOffset,q.instancedDataCount>0&&(l.id&&($.idToFeaturesIndex[l.id]=$.features.length),$.features.push(q),this.evaluate(q,{},$,!1)),O}getModelUris(){return this.modelUris}evaluate(l,u,m,x){const b=this.layers[0],S=l.feature,A=this.canonical,N=l.rotation=b.paint.get("model-rotation").evaluate(S,u,A),O=l.scale=b.paint.get("model-scale").evaluate(S,u,A),$=l.translation=b.paint.get("model-translation").evaluate(S,u,A),U=Object.assign({},b.paint.get("model-color").evaluate(S,u,A));U.a=b.paint.get("model-color-mix-intensity").evaluate(S,u,A);const q=[];this.maxVerticalOffset<$[2]&&(this.maxVerticalOffset=$[2]);const K=$[0]*$[0]+$[1]*$[1],X=K>0?Math.sqrt(K):0;m.maxScale=Math.max(Math.max(m.maxScale,O[0]),Math.max(O[1],O[2])),m.maxXYTranslationDistance=Math.max(m.maxXYTranslationDistance,X),this.maxScale=Math.max(Math.max(this.maxScale,O[0]),Math.max(O[1],O[2])),$Z(q,N,O);const te=Math.round(100*U.a)+U.b/1.05;for(let ie=0;ie10?this.tileToMeter:Mt(A,ke)),ue[he+4]=$[0],ue[he+5]=$[1],ue[he+6]=$[2]+(m.instancesRoadElevation?m.instancesRoadElevation[ae]:0)+ve,ue[he+7]=q[0],ue[he+8]=q[1],ue[he+9]=q[2],ue[he+10]=q[4],ue[he+11]=q[5],ue[he+12]=q[6],ue[he+13]=q[8],ue[he+14]=q[9],ue[he+15]=q[10],m.instancesEvaluatedElevation[ae]=$[2]}}}br(_B,"ModelBucket",{omit:["layers"]}),br(gQ,"PerModelAttributes"),br(pQ,"ModelFeature");class Zb{constructor(l,u,m){this._demTile=l,this._dem=this._demTile.dem,this._scale=u,this._offset=m}static create(l,u,m){const x=m||l.findDEMTileFor(u);if(!x||!x.dem)return;const b=x.dem,S=x.tileID,A=1<O.fqid),this.stateDependentLayerIds=this.layers.filter(O=>O.isStateDependent()).map(O=>O.id),this.modelTraits|=Ub.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,x&&(this.modelTraits|=Ub.HasMapboxMeshFeatures),b&&(this.modelTraits|=Ub.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=S,this.worldview=N,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const O of u)this.nodesInfo.push(new _Q(O)),xQ(O,A.featureIndexArray.length,A.grid),A.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,A.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(l,u){for(const m of this.getNodesInfo()){const x=m.node;x.footprint&&u.push({footprint:x.footprint,id:l})}}updateAppearances(l,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(l){const u=Object.keys(l).length!==0;if(u&&!this.stateDependentLayers.length)return;const m=u?this.stateDependentLayers:this.layers;if(!Mo(l,this.states))for(const x of m)this.evaluate(x,l);this.states=structuredClone(l)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(l){if(!this.needsUpload)return;const u=this.getNodesInfo();for(const m of u){const x=m.node;this.uploaded?this.updatePbrBuffer(x):F4(x,l,!0)}for(const m of u)XI(m.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(l){let u=!1;if(!l.meshes)return u;for(const m of l.meshes)m.pbrBuffer&&(m.pbrBuffer.updateData(m.featureArray),u=!0);return u}needsReEvaluation(l,u,m){const x=l.transform.projectionOptions,b=l.style.getBrightness(),S=this.brightness!==b;if(!this.uploaded||this.dirty||x.name!==this.projection.name||Fj(m.paint.get("model-color").value,S)||Fj(m.paint.get("model-color-mix-intensity").value,S)||Fj(m.paint.get("model-roughness").value,S)||Fj(m.paint.get("model-emissive-strength").value,S)||Fj(m.paint.get("model-height-based-emissive-strength-multiplier").value,S)){this.projection=x,this.brightness=b;const A=this.getNodesInfo();for(const N of A)N.state=null;return!0}return!1}evaluateTransform(l,u){if(l.transform.zoom===this.zoom)return;this.zoom=l.transform.zoom;const m=this.getNodesInfo(),x=this.id.canonical;for(const b of m){const S=b.feature;b.evaluatedTranslation=u.paint.get("model-translation").evaluate(S,{},x),b.evaluatedScale=u.paint.get("model-scale").evaluate(S,{},x)}}evaluate(l,u){const m=this.getNodesInfo();for(const x of m){if(!x.node.meshes)continue;const b=x.feature,S=u&&u[b.id];if(Mo(S,x.state))continue;x.state=structuredClone(S);const A=x.node.meshes&&x.node.meshes[0].featureData,N=x.evaluatedColor[2],O=x.evaluatedRMEA[2],$=this.id.canonical;if(x.hasTranslucentParts=!1,A){for(let U=0;U=Ie)continue;const $t=bB[kt],mt=Math.abs($t);mt>Ve&&(Ue=$t,Ve=mt,yt=It,wt=At)}if(Ve>.1){const At=1-(Ie+.5*Math.abs(yt*wt))/X;let It=u._dem.get(ze,We)+Ue*At;const kt=u._dem.get(ze+yt,We+wt),$t=u._dem.get(ze-yt,We-wt,!0);(It-kt)*(It-$t)>0&&(It=(kt+$t)/2),bB[Ge]=u._dem.set(ze,We,It),X0[Ge]=Ie}}}}}A&&(u._demTile.needsDEMTextureUpload=!0,u._dem._timestamp=$l.now())}setFilter(l){this.filter=l?wb(l):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(l=>this.filter.filter(new si(this.id.overscaledZ,{worldview:this.worldview}),l.feature,this.id.canonical)):this.nodesInfo}destroy(){const l=this.getNodesInfo();for(const u of l)XI(u.node),B4(u.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(l,u){if(u.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=u.updateTime;const m=u.getReplacementRegionsForTile(l.toUnwrapped());for(const x of this.getNodesInfo()){const b=x.node.footprint;x.hiddenByReplacement=!!b&&!m.find(S=>S.footprint===b)}}getHeightAtTileCoord(l,u){const m=[],x=[0,0,0],b=R([]);for(const S of this.getNodesInfo()){const A=S.node.meshes[0],N=A.transformedAabb;if(lN.max[0]||u>N.max[1])continue;if(S.node.hidden===!0)return{height:1/0,maxHeight:S.feature.properties.height,hidden:!1,verticalScale:S.evaluatedScale[2]};D(b,S.node.globalMatrix),x[0]=l,x[1]=u,cr(x,x,b);const O=(x[0]-A.aabb.min[0])/(A.aabb.max[0]-A.aabb.min[0])*H0|0,$=Math.min(63,(x[1]-A.aabb.min[1])/(A.aabb.max[1]-A.aabb.min[1])*H0|0)*H0+Math.min(63,O),U=A.heightmap[$];if(!(U<0&&S.node.footprint))return S.hiddenByReplacement?void 0:{height:U,maxHeight:S.feature.properties.height,hidden:!1,verticalScale:S.evaluatedScale[2]};if(S.node.footprint.grid.query(new Ot(l,u),new Ot(l,u),m),m.length>0)return{height:void 0,maxHeight:S.feature.properties.height,hidden:S.hiddenByReplacement,verticalScale:S.evaluatedScale[2]}}}}function Fj(h,l){return h instanceof $g&&!h.isLightConstant&&l}function zNe(h,l,u,m,x,b,S,A){let N=(61440&l|(61440&l)>>4)>>8,O=(3840&l|(3840&l)>>4)>>4,$=240&l|(240&l)>>4;u[3]>0&&(N=Qr(N,255*u[0],u[3]),O=Qr(O,255*u[1],u[3]),$=Qr($,255*u[2],u[3]));const U=N<<8|O,q=$<<8|Math.floor(255*m[3]),K=function(Ie){const We=fe(Ie,0,2);return Math.min(Math.round(.5*We*255),255)}(m[2])<<8|15*m[0]<<4|15*m[1],X=fe(x[0],0,1),te=fe(x[1],0,1),ie=fe(x[2],0,1),ae=fe(x[3],0,1);let he,ue,ve,ke;if(X!==te&&S!==b&&te!==X){const Ie=S-b;ue=1/(Ie*(te-X)),ve=-(b+Ie*X)/(Ie*(te-X));const We=fe(x[4],-1,1);ke=Math.pow(10,We),he=255*ie<<8|255*ae}else he=65535,ue=0,ve=1,ke=1;if(h.emplaceBack(U,q,K,he,ue,ve,ke),A){const Ie=A.length;A.clear();for(let We=0;We>16&65535,$=b?N>>16&65535:65535&N,U=(15&$)<8?15&$:0,q=h.evaluatedRMEA[U],K=h.evaluatedColor[U],X=h.emissionHeightBasedParams[U];let te;if(A&&U===2&&m.lights&&(te=new Nb,te.resize(10*m.lights.length)),zNe(S.featureArray,O,K,q,X,S.aabb.min[2],S.aabb.max[2],te),te&&A){A=!1;const ie=m.meshes[m.lightMeshIndex];ie.featureArray=te,ie.featureArray._trim()}}S.featureArray._trim(),x++}}br(vP,"Tiled3dModelBucket",{omit:["layers"]}),br(_Q,"Tiled3dModelFeature");const VNe=["id","tile","layer","source","sourceLayer","state"];class Q0{constructor(l,u,m,x,b){this.type="Feature",this._vectorTileFeature=l,this._z=u,this._x=m,this._y=x,this.properties=l?l.properties:{},this.id=b}clone(){const l=new Q0(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 VNe)this[u]!==void 0&&(l[u]=this[u]);return l}}class J0 extends Qx{constructor(l,u,m,x){super(),this.id=l,this.type="model",this.models=[],this._options=u,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}loadGLTFFromURI(l,u){return MZ(this.map._requestManager.transformRequest(l,Zx.Model).url,u)}async loadModel(l,u,m){try{const x=await this.loadGLTFFromURI(u.uri,m);if(m.aborted)return;const b=this._modelsInfo.get(l);if(!b)return;const S=z4(x),A=b.modelSpec,N=new zZ(l,A.uri,A.position,A.orientation,S);J0.applyModelSpecification(N,A),N.computeBoundsAndApplyParent(),this.models.push(N),b.model=N}catch(x){if(x instanceof Error&&x.name==="AbortError")return;const b=x instanceof Error?x.message:"Unknown error";this.fire(new Eg(new Error(`Could not load model ${l} from ${u.uri}: ${b}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const l=this._abortController.signal,u=[];for(const m in this._options.models){const x=this._options.models[m],b=this._modelsInfo.get(m);if(b&&b.model){b.modelSpec=x;const S=b.model;S.position=x.position!=null?new Qe(x.position[0],x.position[1]):new Qe(0,0),S.orientation=x.orientation!=null?x.orientation:[0,0,0],J0.applyModelSpecification(S,x),S.computeBoundsAndApplyParent(),this.models.push(S)}else b?b.modelSpec=x:(this._modelsInfo.set(m,{modelSpec:x,model:null}),u.push(this.loadModel(m,x,l)))}u.length!==0?(await Promise.allSettled(u),l.aborted||this.fire(new Uu("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new Uu("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(l,u){u.nodeOverrides&&J0.convertNodeOverrides(l,u.nodeOverrides),u.materialOverrides&&J0.convertMaterialOverrides(l,u.materialOverrides),u.nodeOverrideNames&&(l.nodeOverrideNames=[...u.nodeOverrideNames]),u.materialOverrideNames&&(l.materialOverrideNames=[...u.materialOverrideNames]),u.featureProperties&&(l.featureProperties=u.featureProperties)}static convertNodeOverrides(l,u){if(Array.isArray(u)&&u.every(m=>typeof m=="string")){l.nodeOverrideNames=[];for(const m of u)l.nodeOverrideNames.push(m)}else Object.entries(u).forEach(([m,x])=>{const b={orientation:[0,0,0]};if(x.hasOwnProperty("orientation")){const S=x.orientation;S&&(b.orientation=S)}l.nodeOverrides.set(m,b)})}static convertMaterialOverrides(l,u){if(Array.isArray(u)&&u.every(m=>typeof m=="string")){l.materialOverrideNames=[];for(const m of u)l.materialOverrideNames.push(m)}else Object.entries(u).forEach(([m,x])=>{const b={color:new Xn(1,1,1),colorMix:0,emissionStrength:0,opacity:1},S=x["model-color"];S!==void 0&&(b.color.r=S[0],b.color.g=S[1],b.color.b=S[2]);const A=x["model-color-mix-intensity"];A!==void 0&&(b.colorMix=A);const N=x["model-emissive-strength"];N!==void 0&&(b.emissionStrength=N);const O=x["model-opacity"];O!==void 0&&(b.opacity=O),l.materialOverrides.set(m,b)})}onAdd(l){this.map=l,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const l of this._modelsInfo.values())if(l.model==null)return!1;return!0}getModels(){return this.models}loadTile(l,u){}serialize(){return this._options}setProperty(l,u){return!1}reload(){this.cancelModelRequests();const l=tp(this.id,this.scope);this.map.style.clearSource(l),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(l){this.cancelModelRequests()}setModels(l){this.models=[];const u=new Map;for(const m in l){const x=l[m],b=this._modelsInfo.get(m);b&&b.modelSpec.uri===x.uri&&u.set(m,b)}if(this._modelsInfo.size!==u.size){this.cancelModelRequests();for(const[m,x]of u)x.model||u.delete(m)}this._modelsInfo=u,this._options.models=l,this.load()}}function wB(h,l,u,m){const x=1<N>=ke.vertexArrayOffset&&Nve.polygon).flat());const ie=K?A:null,[ae,he]=bZ(b,m,U,$,O,S,ie,q,X,b.center.lat,h.tileID.canonical),ue=h.queryGeometry;return _Z(ae,he,ue.isPointQuery()?ue.screenBounds:ue.screenGeometry)}},building:class extends rl{constructor(h,l,u,m){super(h,{layout:KZ||(KZ=new rs({visibility:new Qt(nt.layout_building.visibility),"building-facade":new Ht(nt.layout_building["building-facade"]),"building-facade-floors":new Ht(nt.layout_building["building-facade-floors"]),"building-facade-unit-width":new Ht(nt.layout_building["building-facade-unit-width"]),"building-facade-window":new Ht(nt.layout_building["building-facade-window"]),"building-roof-shape":new Ht(nt.layout_building["building-roof-shape"]),"building-height":new Ht(nt.layout_building["building-height"]),"building-base":new Ht(nt.layout_building["building-base"]),"building-flood-light-wall-radius":new Ht(nt.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new Ht(nt.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new Ht(nt.layout_building["building-flip-roof-orientation"])})),paint:YZ||(YZ=new rs({"building-opacity":new Qt(nt.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new Qt(nt.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new Qt(nt.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new Qt(nt.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new Qt(nt.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new Qt(nt.paint_building["building-vertical-scale"]),"building-cast-shadows":new Qt(nt.paint_building["building-cast-shadows"]),"building-color":new Ht(nt.paint_building["building-color"]),"building-emissive-strength":new Ht(nt.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new Qt(nt.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new Qt(nt.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new Qt(nt.paint_building["building-front-cutoff"]),"building-flood-light-color":new Qt(nt.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new Qt(nt.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new Qt(nt.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new Ht({type:"string",default:"default","property-type":"data-driven"})}))},l,u,m),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(h){return new WZ(h)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(h){return!0}queryRadius(h){return 0}queryIntersectsFeature(h,l,u,m,x,b,S,A,N,O){let $=this.layout.get("building-height").evaluate(l,u);const U=this.layout.get("building-base").evaluate(l,u),q=h.tile.getBucket(this).getFootprint(l);if(q){if(q.hiddenFlags!==0)return!1;$=q.height}const[K,X]=bZ(b,m,U,$,new Ot(0,0),S,null,[0,0],1,b.center.lat,h.tileID.canonical),te=h.queryGeometry;return _Z(K,X,te.isPointQuery()?te.screenBounds:te.screenGeometry)}},line:class extends rl{constructor(h,l,u,m){const x=sX();super(h,x,l,u,m),x.layout&&(this.layout=new Ah(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 f0,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(Tj)return Tj;const u=sX();return Tj=new OCe(u.paint.properties["line-width"].specification),Tj.useIntegerZoom=!0,Tj})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,h)}createBucket(h){return new JI(h)}getProgramIds(){const h=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&h.push("lineBlendComposite"),h}getDefaultProgramParams(h,l,u){if(h==="lineBlendComposite")return{};const m=nX(this);return{config:new re(this,{zoom:l,lut:u}),defines:m,overrideFog:!1}}queryRadius(h){const l=h,u=aX(Yg("line-width",this,l),Yg("line-gap-width",this,l)),m=Yg("line-offset",this,l);return u/2+Math.abs(m)+SI(this.paint.get("line-translate"))}queryIntersectsFeature(h,l,u,m,x,b){if(h.queryGeometry.isAboveHorizon)return!1;const S=iY(h.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),b.angle,h.pixelToTileUnitsFactor),A=h.pixelToTileUnitsFactor/2*aX(this.paint.get("line-width").evaluate(l,u),this.paint.get("line-gap-width").evaluate(l,u)),N=this.paint.get("line-offset").evaluate(l,u);return N&&(m=function(O,$){const U=[],q=new Ot(0,0);for(let K=0;K=3){for(let X=0;X{this._triggered=!1,this._callback()})}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout(()=>{this._triggered=!1,this._callback()},0))}remove(){this._channel=void 0,this._callback=()=>{}}}class bQ{constructor(l){this._stringToNumber={},this._numberToString=[];for(let u=0;u=0&&q[3]>=0&&O.insert(N,q[0],q[1],q[2],q[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new ei(new eP(this.rawTileData)).layers,this.sourceLayerCoder=new bQ(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const l in this.vtLayers)this.vtFeatures[l]=[]}return this.vtLayers}query(l,u){const{tilespaceGeometry:m,transform:x,tileTransform:b,pixelPosMatrix:S,availableImages:A,worldview:N}=u;this.loadVTLayers(),this.serializedLayersCache.clear();const O=u.queryRadius?u.queryRadius:0,$=m.bufferedTilespaceBounds,U=this.grid.query($.min.x,$.min.y,$.max.x,$.max.y,(te,ie,ae,he)=>Rf(m.bufferedTilespaceGeometry,te-O,ie-O,ae+O,he+O));U.sort(WNe);let q=null;x.elevation&&U.length>0&&(q=Zb.create(x.elevation,this.tileID));const K={};let X;for(let te=0;te(he||(he=Ur(ue,this.tileID.canonical,b)),ve.queryIntersectsFeature(m,ue,ke,he,this.z,x,S,q,Ie,u.scope)))}return K}loadMatchingFeature(l,u,m,x,b,S){const{featureIndex:A,bucketIndex:N,sourceLayerIndex:O,layoutVertexArrayOffset:$}=u,U=this.bucketLayerIDs[N],q=m.layers,K=Object.keys(q);if(K.length&&!Fr(K,U))return;const X=m.sourceCache,te=this.sourceLayerCoder.decode(O),ie=this.vtLayers[te].feature(A),ae=this.getId(ie,te);for(let he=0;he`${A.key}: ${A.message}`).join(", ");return void $r(`Failed to create expression for promoteId: ${S}`)}this.promoteIdExpression=b.value}m=this.promoteIdExpression.evaluate({zoom:0},l)}else m=l.properties[x];typeof m=="boolean"&&(m=Number(m))}return m}}function SQ(h,l,u,m,x){return zt(h,(b,S)=>{const A=l instanceof Ah?l.get(S):null;return A&&A.evaluate?A.evaluate(u,m,void 0,x):A})}function WNe(h,l){return l-h}function TQ(h,l){const u={};if(!l)return u;for(const m of h){const x=m.layerIds.map(b=>l.getLayer(b)).filter(Boolean);if(x.length!==0){m.layers=x,m.stateDependentLayerIds&&(m.stateDependentLayers=m.stateDependentLayerIds.map(b=>x.filter(S=>S.id===b)[0]));for(const b of x)u[b.fqid]=m}}return u}br(wQ,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const Bd=32,$f=33,ry=new Uint16Array(8184);for(let h=0;h<2046;h++){let l=h+2,u=0,m=0,x=0,b=0,S=0,A=0;for(1&l?x=b=S=Bd:u=m=A=Bd;(l>>=1)>1;){const O=u+x>>1,$=m+b>>1;1&l?(x=u,b=m,u=S,m=A):(u=x,m=b,x=S,b=A),S=O,A=$}const N=4*h;ry[N+0]=u,ry[N+1]=m,ry[N+2]=x,ry[N+3]=b}const zf=new Uint16Array(2178),ny=new Uint8Array(1089),_P=new Uint16Array(1089);function EQ(h){return h===0?-.03125:h===32?.03125:0}const jQ={Other:0,Symbol:1,FillExtrusion:2},AQ={type:2,extent:lr,loadGeometry:()=>[[new Ot(0,0),new Ot(8193,0),new Ot(8193,8193),new Ot(0,8193),new Ot(0,0)]]};class KNe{constructor(){this.tasks={},this.taskQueue=[],ht(["process"],this),this.invoker=new HNe(this.process),this.nextId=0}add(l,u){const m=this.nextId++,x=function({type:b,renderSourceType:S,zoom:A}){A=A||0;const N=S===jQ.Symbol;return b==="message"?0:b!=="maybePrepare"||N?b!=="parseTile"||N?b==="parseTile"&&N?300-A:b==="maybePrepare"&&N?400-A:500:200-A:100-A}(u);if(x===0){try{l()}finally{}return null}return this.tasks[m]={fn:l,metadata:u,priority:x,id:m},this.taskQueue.push(m),this.invoker.trigger(),{cancel:()=>{delete this.tasks[m]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(m=>!!this.tasks[m]),!this.taskQueue.length)return;const l=this.pick();if(l===null)return;const u=this.tasks[l];if(delete this.tasks[l],this.taskQueue.length&&this.invoker.trigger(),!u)return;u.fn()}finally{}}pick(){let l=null,u=1/0;for(let x=0;x>16&255)/255,(h>>8&255)/255,(255&h)/255,1)}function aIe(h,l,u){h===1?(l.rgb_color=SP(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 oIe(h,l,u){h===1?l.transform=wP(u,u.readVarint()+u.pos):h===2?l.spread_method=u.readVarint():h===3?l.stops.push(NQ(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 NQ(h,l){return h.readFields(lIe,{offset:0,opacity:255,rgb_color:SB},l)}function lIe(h,l,u){h===1?l.offset=u.readFloat():h===2?l.opacity=u.readVarint():h===3&&(l.rgb_color=SP(u.readVarint()))}function cIe(h,l,u){h===1?l.transform=wP(u,u.readVarint()+u.pos):h===2?l.spread_method=u.readVarint():h===3?l.stops.push(NQ(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 uIe(h,l,u){h===1?l.transform=wP(u,u.readVarint()+u.pos):h===2?l.clip_path_idx=u.readVarint():h===3&&l.children.push(bP(u,u.readVarint()+u.pos))}function dIe(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(bP(u,u.readVarint()+u.pos))}class hIe{static calculate(l={},u=[]){const m=new Map,x=new Map;if(Object.keys(l).length===0)return m;u.forEach(b=>{x.set(b.name,b.rgb_color||new Xn(0,0,0))});for(const[b,S]of Object.entries(l))x.has(b)?m.set(x.get(b).toString(),S):console.warn(`Ignoring unknown image variable "${b}"`);return m}}function Xb(h,l=255,u){const m=l/255,x=h.toString(),b=u.has(x)?u.get(x).clone():h.clone();return b.a*=m,b.toString()}function Bj(h,l){if(!hu()){const u=document.createElement("canvas");return u.width=h,u.height=l,u}return new OffscreenCanvas(h,l)}let TB,$j=null;function EB(h,l,u,m,x){for(const b of m.children)IQ(h,l,u,b,x)}function IQ(h,l,u,m,x){m.group?(h.save(),function(b,S,A,N,O){const $=N.mask_idx!=null?A.masks[N.mask_idx]:null,U=N.clip_path_idx!=null?A.clip_paths[N.clip_path_idx]:null;if(N.transform&&(S=Qb(N.transform).preMultiplySelf(S)),!function(X,te,ie){return X.opacity!==255||te||ie}(N,U!=null,$!=null))return void EB(b,S,A,N,O);const q=Bj(b.canvas.width,b.canvas.height),K=q.getContext("2d");EB(K,S,A,N,O),U&&FQ(K,S,A,U),$&&BQ(K,S,A,$,O),b.globalAlpha=N.opacity/255,b.drawImage(q,0,0)}(h,l,u,m.group,x),h.restore()):m.path&&(h.save(),function(b,S,A,N,O){b.setTransform(S),N.paint_order===1?(PQ(b,A,N,O),LQ(b,A,N,O)):(LQ(b,A,N,O),PQ(b,A,N,O))}(h,l,u,m.path,x),h.restore())}function PQ(h,l,u,m){const x=u.fill;if(!x)return;const b=x.opacity/255;switch(h.save(),h.beginPath(),$Q(u,h),x.paint){case"rgb_color":h.fillStyle=Xb(x.rgb_color,x.opacity,m);break;case"linear_gradient_idx":{const S=l.linear_gradients[x.linear_gradient_idx];S.transform&&h.setTransform(Qb(S.transform).preMultiplySelf(h.getTransform())),h.fillStyle=DQ(h,S,b,m);break}case"radial_gradient_idx":{const S=l.radial_gradients[x.radial_gradient_idx];S.transform&&h.setTransform(Qb(S.transform).preMultiplySelf(h.getTransform())),h.fillStyle=MQ(h,S,b,m)}}h.fill(RQ(u)),h.restore()}function RQ(h){return h.rule===1?"nonzero":h.rule===2?"evenodd":void 0}function LQ(h,l,u,m){const x=u.stroke;if(!x)return;const b=zQ(u);h.lineWidth=x.width,h.miterLimit=x.miterlimit,h.setLineDash(x.dasharray),h.lineDashOffset=x.dashoffset;const S=x.opacity/255;switch(x.paint){case"rgb_color":h.strokeStyle=Xb(x.rgb_color,x.opacity,m);break;case"linear_gradient_idx":h.strokeStyle=DQ(h,l.linear_gradients[x.linear_gradient_idx],S,m,!0);break;case"radial_gradient_idx":h.strokeStyle=MQ(h,l.radial_gradients[x.radial_gradient_idx],S,m,!0)}switch(x.linejoin){case 2:case 1:h.lineJoin="miter";break;case 3:h.lineJoin="round";break;case 4:h.lineJoin="bevel"}switch(x.linecap){case 1:h.lineCap="butt";break;case 2:h.lineCap="round";break;case 3:h.lineCap="square"}h.stroke(b)}function DQ(h,l,u,m,x=!1){if(l.stops.length===1){const q=l.stops[0];return Xb(q.rgb_color,q.opacity*u,m)}const{x1:b,y1:S,x2:A,y2:N}=l;let O=new DOMPoint(b,S),$=new DOMPoint(A,N);if(x){const q=Qb(l.transform);O=q.transformPoint(O),$=q.transformPoint($)}const U=h.createLinearGradient(O.x,O.y,$.x,$.y);for(const q of l.stops)U.addColorStop(q.offset,Xb(q.rgb_color,q.opacity*u,m));return U}function MQ(h,l,u,m,x=!1){if(l.stops.length===1){const ae=l.stops[0];return Xb(ae.rgb_color,ae.opacity*u,m)}const b=Qb(l.transform),{fx:S,fy:A,fr:N,cx:O,cy:$,r:U}=l;let q=new DOMPoint(S,A),K=new DOMPoint(O,$),X=N,te=U;if(x){q=b.transformPoint(q),K=b.transformPoint(K);const ae=(b.a+b.d)/2;X=N*ae,te=l.r*ae}const ie=h.createRadialGradient(q.x,q.y,X,K.x,K.y,te);for(const ae of l.stops)ie.addColorStop(ae.offset,Xb(ae.rgb_color,ae.opacity*u,m));return ie}function OQ(h,l,u,m){const x=m.transform?Qb(m.transform).preMultiplySelf(l):l,b=Bj(h.canvas.width,h.canvas.height),S=b.getContext("2d");for(const N of m.children)if(N.group)OQ(S,x,u,N.group);else if(N.path){const O=N.path,$=new Path2D;$.addPath(zQ(O),x),S.fill($,RQ(O))}const A=m.clip_path_idx!=null?u.clip_paths[m.clip_path_idx]:null;A&&FQ(S,x,u,A),h.globalCompositeOperation="source-over",h.drawImage(b,0,0)}function FQ(h,l,u,m){const x=Bj(h.canvas.width,h.canvas.height);OQ(x.getContext("2d"),l,u,m),h.globalCompositeOperation="destination-in",h.drawImage(x,0,0)}function BQ(h,l,u,m,x){if(m.children.length===0)return;const b=m.mask_idx!=null?u.masks[m.mask_idx]:null;b&&BQ(h,l,u,b,x);const S=h.canvas.width,A=h.canvas.height,N=Bj(S,A),O=N.getContext("2d"),$=m.width,U=m.height,q=m.left,K=m.top,X=new Path2D,te=new Path2D;te.rect(q,K,$,U),X.addPath(te,l),O.clip(X);for(const he of m.children)IQ(O,l,u,he,x);const ie=O.getImageData(0,0,S,A),ae=ie.data;if(m.mask_type===1)for(let he=0;hel[S])return null}else{const A=1/m[S];let N=(h[S]-u[S])*A,O=(l[S]-u[S])*A;if(N>O){const $=N;N=O,O=$}if(N>x&&(x=N),Ob)return null}return x}function qQ(h,l,u,m,x,b,S,A,N,O,$){const U=m-h,q=x-l,K=b-u,X=S-h,te=A-l,ie=N-u,ae=$[1]*ie-$[2]*te,he=$[2]*X-$[0]*ie,ue=$[0]*te-$[1]*X,ve=U*ae+q*he+K*ue;if(Math.abs(ve)<1e-15)return null;const ke=1/ve,Ie=O[0]-h,We=O[1]-l,ze=O[2]-u,Ge=(Ie*ae+We*he+ze*ue)*ke;if(Ge<0||Ge>1)return null;const Ue=We*K-ze*q,Ve=ze*U-Ie*K,yt=Ie*q-We*U,wt=($[0]*Ue+$[1]*Ve+$[2]*yt)*ke;return wt<0||Ge+wt>1?null:(X*Ue+te*Ve+ie*yt)*ke}function GQ(h,l,u){return(h-l)/(u-l)}function HQ(h,l,u,m,x,b,S,A,N){const O=1<{const he=ie?1:0,ue=(K+1)*te-he,ve=X*te,ke=(X+1)*te-he;ae[0]=K*te,ae[1]=ve,ae[2]=ue,ae[3]=ke};let U=new UQ(N);const q=[];for(let K=0;K=1;N/=2){const K=A[A.length-1];U=new UQ(N);for(let X=0;X0;){const{idx:X,t:te,nodex:ie,nodey:ae,depth:he}=K.pop();if(this.leaves[X]){HQ(ie,ae,he,l,u,m,x,U,q);const ve=1<=kt[2])return te}continue}let ue=0;for(let ve=0;ve=O[$[ze]]&&($.splice(ze,0,ve),We=!0);We||($[ue]=ve),ue++}}for(let ve=0;ve=this.dim+1||u<-1||u>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(u+1)*this.stride+(l+1)}static pack(l,u){const m=[0,0,0,0],x=EP.getUnpackVector(u);let b=Math.floor((l+x[3])/x[2]);return m[2]=b%256,b=Math.floor(b/256),m[1]=b%256,b=Math.floor(b/256),m[0]=b,m}getPixels(){return new CY({width:this.stride,height:this.stride},this.pixels)}backfillBorder(l,u,m){if(this.dim!==l.dim)throw new Error("dem dimension mismatch");let x=u*this.dim,b=u*this.dim+this.dim,S=m*this.dim,A=m*this.dim+this.dim;switch(u){case-1:x=b-1;break;case 1:b=x+1}switch(m){case-1:S=A-1;break;case 1:A=S+1}const N=-u*this.dim,O=-m*this.dim;for(let $=S;$=1;m--){const x=m===1?1:0,b=m===2?1:0;for(let S=0;S>>1^-(1&h[l]);return h}function jIe(h,l){switch(l){case"uint32":return h;case"uint16":for(let u=0;u>4|(61440&m)>>8|(240&x)<<4|61440&x,h[u+1]=15&m|(3840&m)>>4|(15&x)<<8|(3840&x)<<4}return h;case"uint8":for(let u=0;u>6|(192&x)>>4|(192&b)>>2|192&S,h[u+1]=(48&m)>>4|(48&x)>>2|48&b|(48&S)<<2,h[u+2]=(12&m)>>2|12&x|(12&b)<<2|(12&S)<<4,h[u+3]=3&m|(3&x)<<2|(3&b)<<4|(3&S)<<6}return h;default:throw new Error(`Invalid pixel format, "${l}"`)}}br(EP,"DEMData"),br(WQ,"DemMinMaxQuadTree",{omit:["dem"]});var Ku=Uint8Array,zj=Uint16Array,AIe=Int32Array,YQ=new Ku([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]),ZQ=new Ku([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]),kIe=new Ku([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),XQ=function(h,l){for(var u=new zj(31),m=0;m<31;++m)u[m]=l+=1<>1|(21845&Aa)<<1;eJ[Aa]=((65280&(Jb=(61680&(Jb=(52428&Jb)>>2|(13107&Jb)<<2))>>4|(3855&Jb)<<4))>>8|(255&Jb)<<8)>>1}var Uj=function(h,l,u){for(var m=h.length,x=0,b=new zj(l);x>N]=O;return S},Vj=new Ku(288);for(Aa=0;Aa<144;++Aa)Vj[Aa]=8;for(Aa=144;Aa<256;++Aa)Vj[Aa]=9;for(Aa=256;Aa<280;++Aa)Vj[Aa]=7;for(Aa=280;Aa<288;++Aa)Vj[Aa]=8;var tJ=new Ku(32);for(Aa=0;Aa<32;++Aa)tJ[Aa]=5;var IIe=Uj(Vj,9),PIe=Uj(tJ,5),AB=function(h){for(var l=h[0],u=1;ul&&(l=h[u]);return l},Lh=function(h,l,u){var m=l/8|0;return(h[m]|h[m+1]<<8)>>(7&l)&u},kB=function(h,l){var u=l/8|0;return(h[u]|h[u+1]<<8|h[u+2]<<16)>>(7&l)},RIe=function(h){return(h+7)/8|0},LIe=["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"],Dh=function(h,l,u){var m=new Error(l||LIe[h]);if(m.code=h,Error.captureStackTrace&&Error.captureStackTrace(m,Dh),!u)throw m;return m},DIe=new Ku(0),MIe=typeof TextDecoder<"u"&&new TextDecoder;try{MIe.decode(DIe,{stream:!0})}catch{}const OIe={gzip_data:"gzip"};class $d extends Error{constructor(l){super(l),this.name="MRTError"}}const FIe={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},rJ={uint32:1,uint16:2,uint8:4},BIe={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let CB;class jP{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 $d(`Layer '${l}' not found`);return u}getHeaderLength(l){const u=new Uint8Array(l),m=new DataView(l);if(u[0]!==13)throw new $d("File is not a valid MRT.");return m.getUint32(1,!0)}parseHeader(l){const u=new Uint8Array(l),m=this.getHeaderLength(l);if(u.length= ${m} but got buffer of length ${u.length}`);const x=new CB(u.subarray(0,m)).readFields(gIe,{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 $d(`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 nJ(b,{cacheSize:this._cacheSize});return this}createDecodingTask(l){const u=[],m=this.getLayer(l.layerName);for(let x of l.blockIndices){const b=m.dataIndex[x],S=b.firstByte-l.firstByte,A=b.lastByte-l.firstByte;if(m._blocksInProgress.has(x))continue;const N={layerName:m.name,firstByte:S,lastByte:A,pixelFormat:m.pixelFormat,blockIndex:x,blockShape:[b.bands.length].concat(m.bandShape),buffer:m.buffer,codec:b.codec.codec,filters:b.filters.map(O=>O.filter)};m._blocksInProgress.add(x),u.push(N)}return new iJ(u,()=>{u.forEach(x=>m._blocksInProgress.delete(x.blockIndex))},(x,b)=>{if(u.forEach(S=>m._blocksInProgress.delete(S.blockIndex)),x)throw x;b.forEach(S=>{this.getLayer(S.layerName).processDecodedData(S)})})}}class nJ{constructor({version:l,name:u,units:m,tileSize:x,pixelFormat:b,buffer:S,dataIndex:A},N){if(this.version=l,this.version!==1)throw new $d(`Cannot parse raster layer encoded with MRT version ${l}`);this.name=u,this.units=m,this.tileSize=x,this.buffer=S,this.pixelFormat=FIe[b],this.dataIndex=A,this.bandShape=[x+2*S,x+2*S,rJ[this.pixelFormat]],this._decodedBlocks=new TP(N?N.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return rJ[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:l})=>l).flat()}processDecodedData(l){const u=l.blockIndex.toString();this._decodedBlocks.get(u)||this._decodedBlocks.put(u,l.data)}getBlockForBand(l){let u=0;switch(typeof l){case"string":for(const[m,x]of this.dataIndex.entries()){for(const[b,S]of x.bands.entries())if(S===l)return{bandIndex:u+b,blockIndex:m,blockBandIndex:b};u+=x.bands.length}break;case"number":for(const[m,x]of this.dataIndex.entries()){if(l>=u&&lthis.cacheSize)throw new $d(`Number of blocks to decode (${b.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:u,lastByte:m,blockIndices:x}}hasBand(l){const{blockIndex:u}=this.getBlockForBand(l);return u>=0}hasDataForBand(l){const{blockIndex:u}=this.getBlockForBand(l);return u>=0&&!!this._decodedBlocks.get(u.toString())}getBandView(l){const{blockIndex:u,blockBandIndex:m}=this.getBlockForBand(l);if(u<0)throw new $d(`Band not found: ${JSON.stringify(l)}`);const x=this._decodedBlocks.get(u.toString());if(!x)throw new $d(`Data for band ${JSON.stringify(l)} of layer "${this.name}" not decoded.`);const b=this.dataIndex[u],S=this.bandShape.reduce((O,$)=>O*$,1),A=m*S,N=x.subarray(A,A+S);return{data:N,bytes:new Uint8Array(N.buffer).subarray(N.byteOffset,N.byteOffset+N.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:b.offset,scale:b.scale}}}jP.setPbf=function(h){CB=h};class iJ{constructor(l,u,m){this.tasks=l,this._onCancel=u,this._onComplete=m,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(l,u){this._finalized||(this._onComplete(l,u),this._finalized=!0)}}jP.performDecoding=function(h,l){const u=new Uint8Array(h);return Promise.all(l.tasks.map(m=>{const{layerName:x,firstByte:b,lastByte:S,pixelFormat:A,blockShape:N,blockIndex:O,filters:$,codec:U}=m,q=u.subarray(b,S+1),K=new Uint32Array(N[0]*N[1]*N[2]);let X;if(U!=="gzip_data")throw new $d(`Unhandled codec: ${U}`);return X=function(te,ie){if(!globalThis.DecompressionStream&&ie==="gzip_data")return Promise.resolve((ke=function(ze){ze[0]==31&&ze[1]==139&&ze[2]==8||Dh(6,"invalid gzip data");var Ge=ze[3],Ue=10;4&Ge&&(Ue+=2+(ze[10]|ze[11]<<8));for(var Ve=(Ge>>3&1)+(Ge>>4&1);Ve>0;Ve-=!ze[Ue++]);return Ue+(2&Ge)}(ae=te),ke+8>ae.length&&Dh(6,"invalid gzip data"),function(ze,Ge,Ue,Ve){var yt=ze.length;if(!yt||Ge.f&&!Ge.l)return Ue||new Ku(0);var wt=!Ue,At=wt||Ge.i!=2,It=Ge.i;wt&&(Ue=new Ku(3*yt));var kt=function(ms){var nl=Ue.length;if(ms>nl){var Ya=new Ku(Math.max(2*nl,ms));Ya.set(Ue),Ue=Ya}},$t=Ge.f||0,mt=Ge.p||0,Ct=Ge.b||0,Dt=Ge.l,Ut=Ge.d,Yt=Ge.m,vr=Ge.n,sr=8*yt;do{if(!Dt){$t=Lh(ze,mt,1);var ir=Lh(ze,mt+1,3);if(mt+=3,!ir){var Zt=ze[(ai=RIe(mt)+4)-4]|ze[ai-3]<<8,pr=ai+Zt;if(pr>yt){It&&Dh(0);break}At&&kt(Ct+Zt),Ue.set(ze.subarray(ai,pr),Ct),Ge.b=Ct+=Zt,Ge.p=mt=8*pr,Ge.f=$t;continue}if(ir==1)Dt=IIe,Ut=PIe,Yt=9,vr=5;else if(ir==2){var Cr=Lh(ze,mt,31)+257,zr=Lh(ze,mt+10,15)+4,Rr=Cr+Lh(ze,mt+5,31)+1;mt+=14;for(var cn=new Ku(Rr),zn=new Ku(19),un=0;un>4)<16)cn[un++]=ai;else{var Pi=0,cs=0;for(ai==16?(cs=3+Lh(ze,mt,3),mt+=2,Pi=cn[un-1]):ai==17?(cs=3+Lh(ze,mt,7),mt+=3):ai==18&&(cs=11+Lh(ze,mt,127),mt+=7);cs--;)cn[un++]=Pi}}var Fa=cn.subarray(0,Cr),us=cn.subarray(Cr);Yt=AB(Fa),vr=AB(us),Dt=Uj(Fa,Yt),Ut=Uj(us,vr)}else Dh(1);if(mt>sr){It&&Dh(0);break}}At&&kt(Ct+131072);for(var bs=(1<>4;if((mt+=15&Pi)>sr){It&&Dh(0);break}if(Pi||Dh(2),jo<256)Ue[Ct++]=jo;else{if(jo==256){ws=mt,Dt=null;break}var Ba=jo-254;jo>264&&(Ba=Lh(ze,mt,(1<<(Is=YQ[un=jo-257]))-1)+JQ[un],mt+=Is);var jn=Ut[kB(ze,mt)&Ys],El=jn>>4;if(jn||Dh(3),mt+=15&jn,us=NIe[El],El>3){var Is=ZQ[El];us+=kB(ze,mt)&(1<sr){It&&Dh(0);break}At&&kt(Ct+131072);var Ka=Ct+Ba;if(Ctms.length)&&(Ya=ms.length),new Ku(ms.subarray(0,Ya))}(Ue,0,Ct):Ue.subarray(0,Ct)}(ae.subarray(ke,-8),{i:2},new Ku(((ue=ae)[(ve=ue.length)-4]|ue[ve-3]<<8|ue[ve-2]<<16|ue[ve-1]<<24)>>>0),he)));var ae,he,ue,ve,ke;const Ie=OIe[ie];if(!Ie)throw new Error(`Unhandled codec: ${ie}`);const We=new globalThis.DecompressionStream(Ie);return new Response(new Blob([te]).stream().pipeThrough(We)).arrayBuffer().then(ze=>new Uint8Array(ze))}(q,U).then(te=>(function(ie,ae){ie.readFields(wIe,ae)}(new CB(te),K),new BIe[A](K.buffer))),X.then(te=>{for(let ie=$.length-1;ie>=0;ie--)switch($[ie]){case"delta_filter":TIe(te,N);break;case"zigzag_filter":EIe(te);break;case"bitshuffle_filter":jIe(te,A);break;default:throw new $d(`Unhandled filter "${$[ie]}"`)}return{layerName:x,blockIndex:O,data:te}}).catch(te=>{throw te})}))},br(iJ,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),br(jP,"MapboxRasterTile"),br(nJ,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const sJ=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class NB{static from(l){if(!(l instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[u,m]=new Uint8Array(l,0,2);if(u!==219)throw new Error("Data does not appear to be in a KDBush format.");const x=m>>4;if(x!==1)throw new Error(`Got v${x} data when expected v1.`);const b=sJ[15&m];if(!b)throw new Error("Unrecognized array type.");const[S]=new Uint16Array(l,2,1),[A]=new Uint32Array(l,4,1);return new NB(A,S,b,l)}constructor(l,u=64,m=Float64Array,x){if(isNaN(l)||l<0)throw new Error(`Unpexpected numItems value: ${l}.`);this.numItems=+l,this.nodeSize=Math.min(Math.max(+u,2),65535),this.ArrayType=m,this.IndexArrayType=l<65536?Uint16Array:Uint32Array;const b=sJ.indexOf(this.ArrayType),S=2*l*this.ArrayType.BYTES_PER_ELEMENT,A=l*this.IndexArrayType.BYTES_PER_ELEMENT,N=(8-A%8)%8;if(b<0)throw new Error(`Unexpected typed array class: ${m}.`);x&&x instanceof ArrayBuffer?(this.data=x,this.ids=new this.IndexArrayType(this.data,8,l),this.coords=new this.ArrayType(this.data,8+A+N,2*l),this._pos=2*l,this._finished=!0):(this.data=new ArrayBuffer(8+S+A+N),this.ids=new this.IndexArrayType(this.data,8,l),this.coords=new this.ArrayType(this.data,8+A+N,2*l),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+b]),new Uint16Array(this.data,2,1)[0]=u,new Uint32Array(this.data,4,1)[0]=l)}add(l,u){const m=this._pos>>1;return this.ids[m]=m,this.coords[this._pos++]=l,this.coords[this._pos++]=u,m}finish(){const l=this._pos>>1;if(l!==this.numItems)throw new Error(`Added ${l} items when expected ${this.numItems}.`);return IB(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(l,u,m,x){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:b,coords:S,nodeSize:A}=this,N=[0,b.length-1,0],O=[];for(;N.length;){const $=N.pop()||0,U=N.pop()||0,q=N.pop()||0;if(U-q<=A){for(let ie=q;ie<=U;ie++){const ae=S[2*ie],he=S[2*ie+1];ae>=l&&ae<=m&&he>=u&&he<=x&&O.push(b[ie])}continue}const K=q+U>>1,X=S[2*K],te=S[2*K+1];X>=l&&X<=m&&te>=u&&te<=x&&O.push(b[K]),($===0?l<=X:u<=te)&&(N.push(q),N.push(K-1),N.push(1-$)),($===0?m>=X:x>=te)&&(N.push(K+1),N.push(U),N.push(1-$))}return O}within(l,u,m){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:x,coords:b,nodeSize:S}=this,A=[0,x.length-1,0],N=[],O=m*m;for(;A.length;){const $=A.pop()||0,U=A.pop()||0,q=A.pop()||0;if(U-q<=S){for(let ie=q;ie<=U;ie++)oJ(b[2*ie],b[2*ie+1],l,u)<=O&&N.push(x[ie]);continue}const K=q+U>>1,X=b[2*K],te=b[2*K+1];oJ(X,te,l,u)<=O&&N.push(x[K]),($===0?l-m<=X:u-m<=te)&&(A.push(q),A.push(K-1),A.push(1-$)),($===0?l+m>=X:u+m>=te)&&(A.push(K+1),A.push(U),A.push(1-$))}return N}}function IB(h,l,u,m,x,b){if(x-m<=u)return;const S=m+x>>1;aJ(h,l,S,m,x,b),IB(h,l,u,m,S-1,1-b),IB(h,l,u,S+1,x,1-b)}function aJ(h,l,u,m,x,b){for(;x>m;){if(x-m>600){const O=x-m+1,$=u-m+1,U=Math.log(O),q=.5*Math.exp(2*U/3),K=.5*Math.sqrt(U*q*(O-q)/O)*($-O/2<0?-1:1);aJ(h,l,u,Math.max(m,Math.floor(u-$*q/O+K)),Math.min(x,Math.floor(u+(O-$)*q/O+K)),b)}const S=l[2*u+b];let A=m,N=x;for(qj(h,l,m,u),l[2*x+b]>S&&qj(h,l,m,x);AS;)N--}l[2*m+b]===S?qj(h,l,m,N):(N++,qj(h,l,N,x)),N<=u&&(m=N+1),u<=N&&(x=N-1)}}function qj(h,l,u,m){PB(h,u,m),PB(l,2*u,2*m),PB(l,2*u+1,2*m+1)}function PB(h,l,u){const m=h[l];h[l]=h[u],h[u]=m}function oJ(h,l,u,m){const x=h-u,b=l-m;return x*x+b*b}a.$=Lg,a.A=class{constructor(h,l,u){this.target=h,this.parent=l,this.mapId=u,this.callbacks={},this.cancelCallbacks={},ht(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new KNe}send(h,l,u,m,x=!1,b){const S=Math.round(1e18*Math.random()).toString(36).substring(0,10);u&&(u.metadata=b,this.callbacks[S]=u);const A=new Set;return this.target.postMessage({id:S,type:h,hasCallback:!!u,targetMapId:m,mustQueue:x,sourceMapId:this.mapId,data:Th(l,A)},A),{cancel:()=>{u&&delete this.callbacks[S],this.target.postMessage({id:S,type:"",targetMapId:m,sourceMapId:this.mapId})}}}receive(h){const l=h.data;if(!l)return;const u=l.id;if(u&&(!l.targetMapId||this.mapId===l.targetMapId))if(l.type===""){const m=this.cancelCallbacks[u];delete this.cancelCallbacks[u],m&&m.cancel()}else if(l.mustQueue||Di(self)){const m=this.callbacks[u],x=this.scheduler.add(()=>this.processTask(u,l),m&&m.metadata||{type:"message"});x&&(this.cancelCallbacks[u]=x)}else this.processTask(u,l)}processTask(h,l){if(delete this.cancelCallbacks[h],l.type===""){const u=this.callbacks[h];delete this.callbacks[h],u&&(l.error?u(If(l.error)):u(null,If(l.data)))}else{const u=new Set,m=l.hasCallback?(b,S)=>{this.target.postMessage({id:h,type:"",sourceMapId:this.mapId,error:b?Th(b):null,data:Th(S,u)},u)}:()=>{},x=If(l.data);if(this.parent[l.type])this.parent[l.type](l.sourceMapId,x,m);else if(this.parent.getWorkerSource){const b=l.type.split("."),{source:S,scope:A}=x;this.parent.getWorkerSource(l.sourceMapId,{type:b[0],source:S,scope:A,uid:0})[b[1]](x,m)}else m(new Error(`Could not find function ${l.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},a.B=Eg,a.C=Uu,a.D=gu,a.E=Qx,a.F=tp,a.G=2,a.H=Aj,a.I=hc,a.J=EX,a.K=z_,a.L=oI,a.M=n0,a.N=i0,a.O=cb,a.P=Ot,a.Q=lb,a.R=Zx,a.S=mE,a.T=Bf,a.U=S0,a.V=xP,a.W=bb,a.X=Nf,a.Y=gE,a.Z=Pd,a._=Km,a.a=function(h){return Mn.API_CDN_URL_REGEX.test(h)},a.a$=eP,a.a0=Ma,a.a1=s0,a.a2=U_,a.a3=qT,a.a4=DE,a.a5=class extends xP{},a.a6=pE,a.a7=qN,a.a8=nt,a.a9=function(h){const l=h.value;return l?U_(l)?vB(l,!0)?[]:[new xP(h.key,l,`invalid url "${l}"`)]:[new xP(h.key,l,`string expected, "${n0(l)}" found`)]:[]},a.aA=JZ,a.aB=function(h){let l=1/0,u=1/0,m=-1/0,x=-1/0;for(const b of h)l=Math.min(l,b.x),u=Math.min(u,b.y),m=Math.max(m,b.x),x=Math.max(x,b.y);return{min:new Ot(l,u),max:new Ot(m,x)}},a.aC=fe,a.aD=M,a.aE=ar,a.aF=De,a.aG=Ul,a.aH=Lt,a.aI=yr,a.aJ=function(h,l){const u={};for(let m=0;m=0?l.slice(u+1):""}catch{return""}},a.aN=class{constructor(h){this.entries={},this.scheduler=h}request(h,l,u,m){const x=this.entries[h]=this.entries[h]||{callbacks:[]};if(x.result){const[b,S]=x.result;return this.scheduler?this.scheduler.add(()=>{m(b,S)},l):m(b,S),()=>{}}return x.callbacks.push(m),x.cancel||(x.cancel=u((b,S)=>{x.result=[b,S];for(const A of x.callbacks)this.scheduler?this.scheduler.add(()=>{A(b,S)},l):A(b,S);setTimeout(()=>delete this.entries[h],3e3)})),()=>{x.result||(x.callbacks=x.callbacks.filter(b=>b!==m),x.callbacks.length||(x.cancel(),delete this.entries[h]))}}},a.aO=function(h,l,u){const m=JSON.stringify(h.request);return h.data&&(this.deduped.entries[m]={result:[null,h.data]}),this.deduped.request(m,{type:"parseTile",renderSourceType:h.renderSourceType,zoom:h.tileZoom},x=>{const b=Sg(h.request,(S,A,N)=>{S?zT(S)?x(null,null):x(S):A&&x(null,{rawData:A,vectorTile:u?void 0:new ei(new eP(A)),responseHeaders:new Map(N.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){OT++,OT>P_&&(h.getActor().send("enforceCacheSizeLimit",I_),OT=0)},a.aR=Tl,a.aS=aQ,a.aT=mQ,a.aU=Qe,a.aV=sQ,a.aW=function(h,l){const u=document.createElement("video");u.muted=!0,u.onloadstart=function(){l(null,u)};for(let m=0;m{}}},a.aX=wj,a.aY=J0,a.aZ=ht,a.a_=jP,a.aa=_b,a.ab=rs,a.ac=Qt,a.ad=class{constructor(h){this.specification=h}possiblyEvaluate(h,l){return Ln(h.expression.evaluate(l))}interpolate(h,l,u){return{x:Qr(h.x,l.x,u),y:Qr(h.y,l.y,u),z:Qr(h.z,l.z,u),azimuthal:Qr(h.azimuthal,l.azimuthal,u),polar:Qr(h.polar,l.polar,u)}}},a.ae=si,a.af=Zm,a.ag=kr,a.ah=cr,a.ai=Le,a.aj=Oe,a.ak=Ah,a.al=lp,a.am=Qr,a.an=lr,a.ao=Vu,a.ap=Zn,a.aq=Xn,a.ar=class{constructor(h){this.specification=h}possiblyEvaluate(h,l){return function([u,m]){const x=Ln([1,u,m]);return{x:x.x,y:x.y,z:x.z}}(h.expression.evaluate(l))}interpolate(h,l,u){return{x:Qr(h.x,l.x,u),y:Qr(h.y,l.y,u),z:Qr(h.z,l.z,u)}}},a.as=function(h,l,u=0,m=!0){const x=new Ot(u,u),b=h.sub(x),S=l.add(x),A=[b,new Ot(S.x,b.y),S,new Ot(b.x,S.y)];return m&&A.push(b.clone()),A},a.at=function(h,l){const u=[];for(let m=0;mthis.buckets[U].layers.some(q=>S.has(q.fqid))),N=Object.keys(this.buckets).some(U=>this.buckets[U].layers.some(q=>q.hasTransition&&q.hasTransition())),O=this._firstPrepareComplete&&b!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(l));const $=this._lastUpdatedBrightness!==m;this._lastAvailableImagesCount=b,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||m||this._hasAppearances||A||N||O)&&(!(this._hasAppearances||A||N||O)&&this._lastUpdatedBrightness&&m&&Math.abs(this._lastUpdatedBrightness-m)<.001||(this.updateBuckets(l,$,void 0,O||A||N,S,x),this._lastUpdatedBrightness=m))}evaluateQueryRenderedFeaturePadding(){let h=0;for(const l in this.buckets){const u=this.buckets[l];u.evaluateQueryRenderedFeaturePadding&&(h=Math.max(h,u.evaluateQueryRenderedFeaturePadding()))}return h}queryRenderedFeatures(h,l,u,m,x,b,S){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const A=this.evaluateQueryRenderedFeaturePadding(),N=function(O,$){const U=J([],[.5*O.width,.5*-O.height,1]);return B(U,U,[1,-1,0]),M(U,U,O.calculateProjMatrix($.toUnwrapped())),Float32Array.from(U)}(x,this.tileID);return this.latestFeatureIndex.query(h,{tilespaceGeometry:l,pixelPosMatrix:N,transform:m,availableImages:u,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:A,scope:S})}querySourceFeatures(h,l){const u=this.latestFeatureIndex;if(!u||!u.rawTileData)return;const m=u.loadVTLayers(),x=l?l.sourceLayer:"",b=m._geojsonTileLayer||m[x];if(!b)return;const S=wb(l&&l.filter),{z:A,x:N,y:O}=this.tileID.canonical,$={z:A,x:N,y:O};for(let U=0;Uu)m=!1;else if(l)if(this.expirationTimeu.appearances&&u.appearances.length>0))return!0;return!1}updateBuckets(h,l,u,m,x,b){if(!this.latestFeatureIndex||!h.style)return;const S=b||h.style.listImages(),A=h.style.getBrightness(),N=x||new Set;for(const O in this.buckets){if(!h.style.hasLayer(O))continue;const $=this.buckets[O],U=$.layers[0],q=U.sourceLayer||"_geojsonTileLayer",K=h.style.getLayerSourceCache(U),X=$.layers.some(ke=>N.has(ke.fqid)),te=(m||X)&&$ instanceof Rh?h.style.getOwnLayer(O):void 0;let ie=u&&u[q]||{};K&&!u&&(ie=K._state.getState(q,void 0));const ae=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},he=Object.keys(ie).length>0&&!l;$.hasAppearances=$.layers.some(ke=>ke.appearances&&ke.appearances.length>0);const ue=he?$.stateDependentLayers:$.layers;if(he&&$.stateDependentLayers.length!==0||l||X||m){const ke=this.latestFeatureIndex.loadVTLayers()[q];if($.update(ie,ke,S,ae,ue,l,A,this.tileID.canonical),(m||X)&&!l&&$ instanceof Rh&&te&&te.type==="symbol"){const Ie=$;Ie.text&&Ie.text.uboBinder&&Ie.text.uboBinder.updateDynamicExpressions(te,ke,this.tileID.canonical,S,ie,A),Ie.icon&&Ie.icon.uboBinder&&Ie.icon.uboBinder.updateDynamicExpressions(te,ke,this.tileID.canonical,S,ie,A)}if($ instanceof Rh){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(he&&$.stateDependentLayers.length!==0||l||$.hasAppearances){const ke={zoom:h.transform.zoom,pitch:h.transform.pitch,brightness:h.style.getBrightness()||0,worldview:h.worldview},Ie=$.updateAppearances(this.tileID.canonical,ie,S,ke,h.imageManager,he&&$.stateDependentLayers.length!==0);if(Ie&&Ie.hasUboChanges){const We=h.context;$ instanceof Rh&&$.text&&$.text.uboBinder&&$.text.uboBinder.upload(We),$ instanceof Rh&&$.icon&&$.icon.uboBinder&&$.icon.uboBinder.upload(We)}}($ instanceof JI||$ instanceof LI)&&h._terrain&&h._terrain.enabled&&K&&$.uploadPending()&&h._terrain._clearRenderCacheForTile(K.id,this.tileID);const ve=h&&h.style&&h.style.getOwnLayer(O);ve&&(this.queryPadding=Math.max(this.queryPadding,ve.queryRadius($)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil<$l.now()}clearFadeHold(){this.symbolFadeHoldUntil=void 0}setHoldDuration(h){this.symbolFadeHoldUntil=$l.now()+h}setTexture(h,l){const u=l.context,m=u.gl;this.texture=this.texture||l.getTileTexture(h.width),this.texture&&this.texture instanceof Bf?this.texture.update(h):(this.texture=new Bf(u,h,m.RGBA8,{useMipmap:!0}),this.texture.bind(m.LINEAR,m.CLAMP_TO_EDGE))}setDependencies(h,l){const u={};for(const m of l)u[m]=!0;this.dependencies[h]=u}hasDependency(h,l){for(const u of h){const m=this.dependencies[u];if(m){for(const x of l)if(m[x])return!0}}return!1}clearQueryDebugViz(){}_makeDebugTileBoundsBuffers(h,l){if(!l||l.name==="mercator"||this._tileDebugBuffer)return;const u=Ur(AQ,this.tileID.canonical,this.tileTransform)[0],m=new mc,x=new ip;for(let b=0;b=0;te--){const ie=4*te,ae=ry[ie+0],he=ry[ie+1],ue=ry[ie+2],ve=ry[ie+3],ke=ae+ue>>1,Ie=he+ve>>1,We=ke+Ie-he,ze=Ie+ae-ke,Ge=he*$f+ae,Ue=ve*$f+ue,Ve=Ie*$f+ke,yt=Math.hypot((zf[2*Ge+0]+zf[2*Ue+0])/2-zf[2*Ve+0],(zf[2*Ge+1]+zf[2*Ue+1])/2-zf[2*Ve+1])>=16;ny[Ve]=ny[Ve]||(yt?1:0),te<1022&&(ny[Ve]=ny[Ve]||ny[(he+ze>>1)*$f+(ae+We>>1)]||ny[(ve+ze>>1)*$f+(ue+We>>1)])}const $=new To,U=new _s;let q=0;function K(te,ie){const ae=ie*$f+te;return _P[ae]===0&&($.emplaceBack(zf[2*ae+0],zf[2*ae+1],te*lr/Bd,ie*lr/Bd),_P[ae]=++q),_P[ae]-1}function X(te,ie,ae,he,ue,ve){const ke=te+ae>>1,Ie=ie+he>>1;if(Math.abs(te-ue)+Math.abs(ie-ve)>1&&ny[Ie*$f+ke])X(ue,ve,te,ie,ke,Ie),X(ae,he,ue,ve,ke,Ie);else{const We=K(te,ie),ze=K(ae,he),Ge=K(ue,ve);U.emplaceBack(We,ze,Ge)}}return X(0,0,Bd,Bd,Bd,0),X(Bd,Bd,0,0,0,Bd),{vertices:$,indices:U}}(this.tileID.canonical,l);m=b.vertices,x=b.indices}else{m=new To,x=new _s;for(const{x:S,y:A}of u)m.emplaceBack(S,A,0,0);const b=Ob(m.int16.subarray(0,4*m.length),void 0,4);for(let S=0;S0&&(S=D(new Float64Array(16),l.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(h,m,l,x,S,b),this._makeGlobeTileDebugTextBuffer(h,m,l,x,S,b)}_globePoint(h,l,u,m,x,b,S){let A=sj(h,l,u);if(b){const N=1<.5?q=-1:U<-.5&&(q=1);let K=(h/lr+u.x)/N+q,X=(l/lr+u.y)/N;K=(K-O)*m._pixelsPerMercatorPixel+O,X=(X-$)*m._pixelsPerMercatorPixel+$;const te=[K*m.worldSize,X*m.worldSize,0];cr(te,te,b),A=op(A,te,S)}return cr(A,A,x)}_makeGlobeTileDebugBorderBuffer(h,l,u,m,x,b){const S=new mc,A=new ip,N=new Md,O=(U,q,K,X,te)=>{const ie=(K-U)/(te-1),ae=(X-q)/(te-1),he=S.length;for(let ue=0;ueO*U+q;for(let U=0;U1)return!1;const u=l.getSource().maxzoom,m=1<1)return l;const x=m.getSource().maxzoom,b=1<{const A=this.getAtTileOffset(h,x,b,S),N=m.upVector(h.canonical,x.x,x.y);return He(N,N,A*m.upVectorScale(h.canonical,l,u).metersToTile),N}}getForTilePoints(h,l,u,m){if(this.isUsingMockSource())return!1;const x=Zb.create(this,h,m);return!!x&&(l.forEach(b=>{b[2]=this.exaggeration()*x.getElevationAt(b[0],b[1],u)}),!0)}getMinMaxForTile(h){if(this.isUsingMockSource())return null;const l=this.findDEMTileFor(h);if(!l||!l.dem)return null;const u=l.dem.tree,m=l.tileID,x=1<0&&(m+=(h[x]-0)*(h[x]-0)),l[x]<0&&(m+=(0-l[x])*(0-l[x]));return m},a.cL=function(h){return h*h*h*h*h},a.cM=ft,a.cN=45,a.cO=Lb,a.cP=function(h,l,u){const m=Math.sqrt(h*h+l*l+u*u),x=m>0?Math.acos(u/m)*As:0;let b=h!==0||l!==0?Math.atan2(-l,-h)*As+90:0;return b<0&&(b+=360),[m,b,x]},a.cQ=Ae,a.cR=Ln,a.cS=Mt,a.cT=me,a.cU=li,a.cV=Te,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=MZ,a.cY=z4,a.cZ=zZ,a.c_=vB,a.ca=2,a.cb=7,a.cc=6,a.cd=_t,a.ce=Se,a.cf=je,a.cg=0,a.ch=1,a.ci=4,a.cj=5,a.ck=Mb,a.cl=pc,a.cm=FZ,a.cn=V0,a.co=fY,a.cp=function(h,l,u,m,x,b,S,A,N){if(N.name==="globe")return fY(h,l,new V0(u,m,x),!1);const O=Z0({z:u,x:m,y:x},N);return new li([(b+O.x/O.scale)*l,l*(O.y/O.scale),S],[(b+O.x2/O.scale)*l,l*(O.y2/O.scale),A])},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 du[l]},a.ct=St,a.cu=er,a.cv=6,a.cw=function(h){const l=R(new Float64Array(16));M(l,h.pixelMatrix,h.globeMatrix);const u=[0,$e,0],m=[0,Ke,0];return cr(u,u,l),cr(m,m,l),[u[0]>0&&u[0]<=h.width&&u[1]>0&&u[1]<=h.height&&!l4(h,new Qe(h.center.lat,90)),m[0]>0&&m[0]<=h.width&&m[1]>0&&m[1]<=h.height&&!l4(h,new Qe(h.center.lat,-90))]},a.cx=function(h,l){const{scale:u}=h.tileTransform,m=u*lr/(h.tileSize*Math.pow(2,l.zoom-h.tileID.overscaledZ+h.tileID.canonical.z));return function(x,b,S){var A=b[1],N=b[2],O=b[3],$=S[0],U=S[1];return x[0]=b[0]*$,x[1]=A*$,x[2]=N*U,x[3]=O*U,x}(new Float32Array(4),l.inverseAdjustmentMatrix,[m,m])},a.cy=WI,a.cz=pe,a.d=function(h){return Mn.API_TILEJSON_REGEX.test(h)},a.d$=KAe,a.d0=hs,a.d1=class{static calculate(h,l,u){const m=new Set,x=new Map,b=new Set,S=new Set;for(const N of Object.values(h))for(const[O,$]of Object.entries(N.floors)){b.add(O),$.isDefault&&S.add(O),$.conflicts&&x.set(O,$.conflicts);const U=O===l,q=$.connections&&l&&$.connections.has(l);(U||q)&&m.add(O)}const A=N=>{const O=x.get(N)||new Set;for(const $ of m)if((x.get($)||new Set).has(N)||O.has($))return!0;return!1};if(u)for(const N of u)b.has(N)&&(A(N)||m.add(N));for(const N of S)m.has(N)||A(N)||m.add(N);return m}},a.d2=iP,a.d3=aB,a.d4=Jn,a.d5=function(){return{API_URL:Mn.API_URL,DRACO_URL:Mn.DRACO_URL,MESHOPT_URL:Mn.MESHOPT_URL,MESHOPT_SIMD_URL:Mn.MESHOPT_SIMD_URL,BUILDING_GEN_URL:Mn.BUILDING_GEN_URL}},a.d6=iI,a.d7=DT,a.d8=wf,a.d9=hr,a.dA=EI,a.dB=mc,a.dC=_s,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),m=Math.cos(l);return h[0]=m,h[1]=u,h[2]=0,h[3]=-u,h[4]=m,h[5]=0,h[6]=0,h[7]=0,h[8]=1,h},a.dG=Tr,a.dH=pY,a.dI=Mi,a.dJ=os,a.dK=yB,a.dL=function(h,l){const u=[0,0,0];return cr(u,u,aj(Mf(l.canonical))),cr(u,u,h),u},a.dM=h=>({u_matrix:new d(h),u_texsize:new bu(h),u_pixels_to_tile_units:new j(h),u_device_pixel_ratio:new ha(h),u_width_scale:new ha(h),u_floor_width_scale:new ha(h),u_image:new z0(h),u_units_to_pixels:new bu(h),u_tile_units_to_pixels:new ha(h),u_alpha_discard_threshold:new ha(h),u_trim_offset:new bu(h),u_trim_fade_range:new bu(h),u_trim_gradient_mix_range:new bu(h),u_trim_color:new Lb(h),u_zbias_factor:new ha(h),u_tile_to_meter:new ha(h),u_ground_shadow_factor:new U0(h),u_pattern_transition:new ha(h)}),a.dN=h=>({u_matrix:new d(h),u_pixels_to_tile_units:new j(h),u_device_pixel_ratio:new ha(h),u_width_scale:new ha(h),u_floor_width_scale:new ha(h),u_units_to_pixels:new bu(h),u_dash_image:new z0(h),u_gradient_image:new z0(h),u_image_height:new ha(h),u_texsize:new bu(h),u_tile_units_to_pixels:new ha(h),u_alpha_discard_threshold:new ha(h),u_trim_offset:new bu(h),u_trim_fade_range:new bu(h),u_trim_gradient_mix_range:new bu(h),u_trim_color:new Lb(h),u_zbias_factor:new ha(h),u_tile_to_meter:new ha(h),u_ground_shadow_factor:new U0(h)}),a.dO=h=>({u_camera_to_center_distance:new ha(h),u_extrude_scale:new j(h),u_device_pixel_ratio:new ha(h),u_matrix:new d(h),u_inv_rot_matrix:new d(h),u_merc_center:new bu(h),u_tile_id:new U0(h),u_zoom_transition:new ha(h),u_up_dir:new U0(h),u_emissive_strength:new ha(h)}),a.dP=WE,a.dQ=WCe,a.dR=class{constructor(h,l,u,m){this.context=h,this.format=m,this.size=u,this.texture=h.gl.createTexture();const[x,b,S]=this.size,{gl:A}=h;A.bindTexture(A.TEXTURE_3D,this.texture),h.pixelStoreUnpackFlipY.set(!1),h.pixelStoreUnpack.set(1),h.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in l&&l.data&&A.texImage3D(A.TEXTURE_3D,0,this.format,x,b,S,0,L4(this.format),D4(this.format),l.data)}bind(h,l){const{context:u}=this,{gl:m}=u;m.bindTexture(m.TEXTURE_3D,this.texture),h!==this.minFilter&&(m.texParameteri(m.TEXTURE_3D,m.TEXTURE_MAG_FILTER,h),m.texParameteri(m.TEXTURE_3D,m.TEXTURE_MIN_FILTER,h),this.minFilter=h),l!==this.wrapS&&(m.texParameteri(m.TEXTURE_3D,m.TEXTURE_WRAP_S,l),m.texParameteri(m.TEXTURE_3D,m.TEXTURE_WRAP_T,l),this.wrapS=l)}destroy(){const{gl:h}=this.context;h.deleteTexture(this.texture),this.texture=null}},a.dS=vY,a.dT=(h,l,u,m,x,b)=>{const S=h.transform,A=S.projection.name==="globe";let N;if(b.paint.get("circle-pitch-alignment")==="map")if(A){const $=pY(S.zoom,l.canonical)*S._pixelsPerMercatorPixel;N=Float32Array.from([$,0,0,$])}else N=S.calculatePixelsToTileUnitsMatrix(u);else N=new Float32Array([S.pixelsToGLUnits[0],0,0,S.pixelsToGLUnits[1]]);const O={u_camera_to_center_distance:h.transform.getCameraToCenterDistance(S.projection),u_matrix:h.translatePosMatrix(l.projMatrix,u,b.paint.get("circle-translate"),b.paint.get("circle-translate-anchor")),u_device_pixel_ratio:$l.devicePixelRatio,u_extrude_scale:N,u_inv_rot_matrix:eke,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:b.paint.get("circle-emissive-strength")};if(A){O.u_inv_rot_matrix=m,O.u_merc_center=x,O.u_tile_id=[l.canonical.x,l.canonical.y,1<{const $=h.transform,U=$.pitch<15?eX(.07,.7,fe((14-$.zoom)/5,0,1)):.07,q=u.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:rX(h,l,u,m),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:S,u_image:0,u_tile_units_to_pixels:tX(l,$),u_units_to_pixels:[1/$.pixelsToGLUnits[0],1/$.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:A,u_trim_fade_range:u.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:u.paint.get("line-trim-color").toPremultipliedRenderColor(q?null:u.lut).toArray01(),u_zbias_factor:U,u_tile_to_meter:Mt(l.tileID.canonical,0),u_ground_shadow_factor:N,u_pattern_transition:O}},a.dX=(h,l,u,m,x,b,S,A,N,O)=>{const $=h.transform,U=$.calculatePixelsToTileUnitsMatrix(l),q=u.paint.get("line-trim-color-use-theme").constantOr("default")==="none",K=$.pitch<15?eX(.07,.7,fe((14-$.zoom)/5,0,1)):.07;return{u_matrix:rX(h,l,u,m),u_pixels_to_tile_units:U,u_device_pixel_ratio:b,u_width_scale:S,u_floor_width_scale:A,u_units_to_pixels:[1/$.pixelsToGLUnits[0],1/$.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:x,u_texsize:iX(u)&&l.lineAtlasTexture?l.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:tX(l,h.transform),u_alpha_discard_threshold:0,u_trim_offset:N,u_trim_fade_range:u.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:u.paint.get("line-trim-color").toPremultipliedRenderColor(q?null:u.lut).toArray01(),u_zbias_factor:K,u_tile_to_meter:Mt(l.tileID.canonical,0),u_ground_shadow_factor:O}},a.dY=it,a.dZ=oj,a.d_=bt,a.da=function(h){const l=h.indexOf(N0);return l>=0?h.slice(0,l):h},a.db=function(h){return h.indexOf(N0)>=0},a.dc=function(h){const l=h.lastIndexOf(N0);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,m){return h.type==="custom"?new $Ne(h,l):new GNe[h.type](h,l,u,m)},a.df=Rt,a.dg=wb,a.dh=hI,a.di=class extends Q0{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=IE,a.dk=function(h){return h({pluginStatus:tl,pluginURL:Ic}),IE.on("pluginStateChange",h),h},a.dl=n4,a.dm=class extends _u{constructor(h){super(h),this.current=g}set(h,l,u){if(this.fetchUniformLocation(h,l)){for(let m=0;m<9;m++)if(u[m]!==this.current[m]){this.current=u,this.gl.uniformMatrix3fv(this.location,!1,u);break}}}},a.dn=Kx,a.dp=function(h,l,u){const m=lp(u.zoom),x=h.style.map._antialias,b=h.terrain&&h.terrain.exaggeration()>0;return m===0&&!x&&!b},a.dq=function(h){const l=h.pixelsPerMeter,u=l/ot(1,h.center.lat),m=R(new Float64Array(16));return B(m,m,[h.point.x,h.point.y,0]),V(m,m,[u,u,l]),Float32Array.from(m)},a.dr=jI,a.ds=function(h){const l=80.051129;h=fe(h,-80.051129,l)/l*90;const u=Math.pow(Math.abs(Math.sin(Zn(h))),3);return Math.round(u*(Ze.length-1))},a.dt=function(h,l,u,m){const x=l.getNorth(),b=l.getSouth(),S=l.getWest(),A=l.getEast(),N=1<0){const X=180/m;E(K,K,[X/O+1,0,0,0,X/$+1,0,-.5*X/U,.5*X/q,1])}return K[2]=N,K[5]=h.x,K[8]=h.y,K},a.du=aj,a.dv=Mf,a.dw=function(h,l,u){const m=R(new Float64Array(16)),x=(l/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(h,l=!1){const u=JY(new Ot(0,0),new Ot(lr,lr),h),m=[];if(l&&!S4(u,this._globalClipBounds))return m;for(const x of this._activeRegions){if(x.hiddenByOverlap||!S4(u,x))continue;const b=Mke(x.min,x.max,h);m.push({min:b.min,max:b.max,sourceId:this._sourceIds[x.priority],footprint:x.footprint,footprintTileId:x.tileId,order:x.order,clipMask:x.clipMask,clipScope:x.clipScope})}return m}setSources(h){this._setSources(h.map(l=>({getSourceId:()=>l.cache.id,getFootprints:()=>{const u=[];for(const m of l.cache.getVisibleCoordinates()){const x=l.cache.getTile(m).buckets[l.layer];x&&x.updateFootprints(m.toUnwrapped(),u)}return u},getOrder:()=>l.order,getClipMask:()=>l.clipMask,getClipScope:()=>l.clipScope})))}_addSource(h){const l=h.getFootprints();if(l.length===0)return;const u=h.getOrder(),m=h.getClipMask(),x=h.getClipScope();for(const b of l){if(!b.footprint)continue;const S=JY(b.footprint.min,b.footprint.max,b.id);this._activeRegions.push({min:S.min,max:S.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:b.id,footprint:b.footprint,order:u,clipMask:m,clipScope:x})}this._sourceIds.push(h.getSourceId())}_computeReplacement(){this._activeRegions.sort((l,u)=>l.priority-u.priority||MI(l.min,u.min)||MI(l.max,u.max)||l.order-u.order||l.clipMask-u.clipMask||function(m,x){const b=(S,A)=>S+A;return m.length-x.length||m.reduce(b,"").localeCompare(x.reduce(b,""))}(l.clipScope,u.clipScope));let h=this._activeRegions.length!==this._prevRegions.length;if(!h){let l=0;for(;!h&&l!==this._activeRegions.length;){const u=this._activeRegions[l],m=this._prevRegions[l];h=u.priority!==m.priority||!QY(u,m)||u.order!==m.order||u.clipMask!==m.clipMask||!Mo(u.clipScope,m.clipScope),this._activeRegions[l].hiddenByOverlap=m.hiddenByOverlap,++l}}if(h){++this._updateTime;for(const u of this._activeRegions)u.order!==pj&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,u.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,u.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,u.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,u.max.y));const l=u=>{const m=this._activeRegions;if(u>=m.length)return u;const x=m[u].priority;for(;u1){let u=0,m=l(u);for(;u!==m;){let x=u;const b=u;for(;x!==m;){const S=this._activeRegions[x];S.hiddenByOverlap=!1;for(let A=0;A=0;l--)this._addSource(h[l]);this._computeReplacement()}},a.eH=To,a.eI=pP,a.eJ=ip,a.eK=pj,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 mc,m=new _s,x=[],b=h+1+2,S=l[0]+1,A=l[0]+1+(1+l.length),N=(O,$,U)=>{let q=O===b-1?O-2:O===0?O:O-1;return q+=U?24575:0,[q,$]};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=dY,a.ed=a4,a.ee=xu,a.ef=W,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=rp,a.ei=M0,a.ej=function(h,l,u,m,x){return fe((h-l)/(u-l)*(x-m)+m,m,x)},a.ek=ni,a.el=function(h,l){var u=l[0],m=l[1],x=l[2],b=l[3],S=l[4],A=l[5],N=l[6],O=l[7],$=l[8],U=$*S-A*O,q=-$*b+A*N,K=O*b-S*N,X=u*U+m*q+x*K;return X?(h[0]=U*(X=1/X),h[1]=(-$*m+x*O)*X,h[2]=(A*m-x*S)*X,h[3]=q*X,h[4]=($*u-x*N)*X,h[5]=(-A*u+x*b)*X,h[6]=K*X,h[7]=(-O*u+m*N)*X,h[8]=(S*u-m*b)*X,h):null},a.em=$N,a.en=2,a.eo=Gt,a.ep=Nt,a.eq=ee,a.er=function(h,l){var u=new p(3);ee(u,l);var m=1/u[0],x=1/u[1],b=1/u[2],S=l[0]*m,A=l[1]*x,N=l[2]*b,O=l[4]*m,$=l[5]*x,U=l[6]*b,q=l[8]*m,K=l[9]*x,X=l[10]*b,te=S+$+X,ie=0;return te>0?(ie=2*Math.sqrt(te+1),h[3]=.25*ie,h[0]=(U-K)/ie,h[1]=(q-N)/ie,h[2]=(A-O)/ie):S>$&&S>X?(ie=2*Math.sqrt(1+S-$-X),h[3]=(U-K)/ie,h[0]=.25*ie,h[1]=(A+O)/ie,h[2]=(q+N)/ie):$>X?(ie=2*Math.sqrt(1+$-S-X),h[3]=(q-N)/ie,h[0]=(A+O)/ie,h[1]=.25*ie,h[2]=(U+K)/ie):(ie=2*Math.sqrt(1+X-S-$),h[3]=(A-O)/ie,h[0]=(q+N)/ie,h[1]=(U+K)/ie,h[2]=.25*ie),h},a.es=function(h,l){var u=2*Math.acos(l[3]),m=Math.sin(u/2);return m>f?(h[0]=l[0]/m,h[1]=l[1]/m,h[2]=l[2]/m):(h[0]=1,h[1]=0,h[2]=0),u},a.et=wB,a.eu=ZI,a.ev=YI,a.ew=[1,1,1],a.ex=Zb,a.ey=function(h,l,u,m){var x=l[0],b=l[1],S=l[2],A=l[3];return h[0]=x+m*(u[0]-x),h[1]=b+m*(u[1]-b),h[2]=S+m*(u[2]-S),h[3]=A+m*(u[3]-A),h},a.ez=Ub,a.f=cc,a.f0=yY,a.f1=function(h){const l=[0,0,0],u=R(new Float64Array(16));return M(u,h.pixelMatrix,h.globeMatrix),cr(l,l,u),new Ot(l[0],l[1])},a.f2=PE,a.f3=function(h,l,u=!1){if(tl===fc.deferred||tl===fc.loading||tl===fc.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");Ic=$l.resolveURL(h),tl=fc.deferred,Dd=l,NE(),u||sI()},a.f4=mo,a.f5=So,a.f6=ja,a.f7=function(h){const l=fN();if(!l)return;const u=l.delete(Fm);h&&u.then(()=>h()).catch(h)},a.f8=br,a.f9=Zg,a.fA=rn,a.fB=function(h){let l=0;if(new Uint32Array(h,0,1)[0]!==IZ){const u=new Uint32Array(h,0,7),[,,m,x,b,S]=u;l=u.byteLength+x+b+S+b,(m!==h.byteLength||l>=h.byteLength)&&$r("Invalid b3dm header information.")}return DZ(h,l)},a.fC=function(h,l){const u=z4(h);for(const m of u){for(const x of m.meshes)fCe(x);m.lights&&(m.lightMeshIndex=m.meshes.length,m.meshes.push(mCe(m.lights,l)))}return u},a.fD=vP,a.fE=Di,a.fF=jh,a.fG=fc,a.fH=function(h){R_(),Id!=null&&Id.then(l=>{l.keys().then(u=>{for(let m=0;m$r(x.message))}).catch(u=>$r(u.message))}).catch(l=>$r(l.message))},a.fa=2,a.fb=Sh,a.fc=Z0,a.fd=JE,a.fe=bQ,a.ff=wQ,a.fg=ZZ,a.fh=yn,a.fi="hd_road_elevation",a.fj=Oi,a.fk=zt,a.fl=LI,a.fm=cp,a.fn=iB,a.fo=1,a.fp=Rh,a.fq=function(h,l,u,m,x,b,S,A=1,N,O,$,U){h.createArrays(),h.tilePixelRatio=lr/(512*h.overscaling),h.compareText={},h.iconsNeedLinear=!1;const q=h.layers[0].layout,K=h.layers[0]._unevaluatedLayout._values,X={};X.scaleFactor=A,X.textSizeScaleRange=q.get("text-size-scale-range"),X.iconSizeScaleRange=q.get("icon-size-scale-range");const[te,ie]=X.textSizeScaleRange,[ae,he]=X.iconSizeScaleRange;X.textScaleFactor=fe(X.scaleFactor,te,ie),X.iconScaleFactor=fe(X.scaleFactor,ae,he);const ue=K["text-size"],ve=K["icon-size"];if(h.textSizeData.kind==="composite"){const{minZoom:Ue,maxZoom:Ve}=h.textSizeData;X.compositeTextSizes=[ue.possiblyEvaluate(new si(Ue,{worldview:$}),b),ue.possiblyEvaluate(new si(Ve,{worldview:$}),b)]}if(h.iconSizeData.kind==="composite"){const{minZoom:Ue,maxZoom:Ve}=h.iconSizeData;X.compositeIconSizes=[ve.possiblyEvaluate(new si(Ue,{worldview:$}),b,U),ve.possiblyEvaluate(new si(Ve,{worldview:$}),b,U)]}X.layoutTextSize=ue.possiblyEvaluate(new si(S+1,{worldview:$}),b),X.layoutIconSize=ve.possiblyEvaluate(new si(S+1,{worldview:$}),b,U),X.textMaxSize=ue.possiblyEvaluate(new si(18,{worldview:$}),b);const ke=q.get("symbol-placement"),Ie=q.get("text-rotation-alignment")==="map"&&ke!=="point",We=q.get("text-size");let ze=!1;const Ge=[];for(const Ue of h.features){const Ve=q.get("text-font").evaluate(Ue,{},b).join(","),yt=We.evaluate(Ue,{},b)*X.textScaleFactor,wt=X.layoutTextSize.evaluate(Ue,{},b)*X.textScaleFactor,At=X.layoutIconSize.evaluate(Ue,{},b,U)*X.iconScaleFactor,It={horizontal:{},vertical:void 0},kt=Ue.text;let $t,mt=[0,0];if(kt){const Sn=kt.toString(),fs=q.get("text-letter-spacing").evaluate(Ue,{},b)*Oa,ai=q.get("text-line-height").evaluate(Ue,{},b)*Oa,Wn=V5(Sn)?fs:0,Pi=q.get("text-anchor").evaluate(Ue,{},b),cs=q.get("text-variable-anchor");if(!cs){const ws=q.get("text-radial-offset").evaluate(Ue,{},b);if(ws)mt=DX(Pi,[ws*Oa,lB]);else{const jo=q.get("text-offset").evaluate(Ue,{},b);mt=[jo[0]*Oa,jo[1]*Oa]}}let Fa=Ie?"center":q.get("text-justify").evaluate(Ue,{},b);const us=ke==="point",bs=us?q.get("text-max-width").evaluate(Ue,{},b)*Oa:1/0,Ys=ws=>{h.allowVerticalPlacement&&AE(Sn)&&(It.vertical=X4(kt,l,u,x,Ve,bs,ai,Pi,ws,Wn,mt,Fc.vertical,!0,wt,yt,N,X.textScaleFactor))};if(!Ie&&cs){const ws=Fa==="auto"?cs.map(Ba=>cB(Ba)):[Fa];let jo=!1;for(let Ba=0;Ba=0||!AE(Sn)){const ws=X4(kt,l,u,x,Ve,bs,ai,Pi,Fa,Wn,mt,Fc.horizontal,!1,wt,yt,N,X.textScaleFactor);ws&&(It.horizontal[Fa]=ws)}Ys(us?"left":Fa)}}let Ct,Dt,Ut,Yt,vr,sr,ir=!1;const Zt=q.get("icon-text-fit").evaluate(Ue,{},b);if(Ue.icon&&Ue.icon.hasPrimary()){const Sn=Nj(Ue.icon,h.iconSizeData,K["icon-size"],b,h.zoom,Ue,N,X.iconScaleFactor,$,U);Ct=Sn.iconPrimary,Ut=Sn.iconSecondary;const fs=Ct.toString();if(Dt=m.get(fs),Dt&&(vr=q.get("icon-offset").evaluate(Ue,{},b),sr=q.get("icon-anchor").evaluate(Ue,{},b),$t=rP(x.get(fs),Ut?x.get(Ut.toString()):void 0,vr,sr),ir=Dt.sdf,h.sdfIcons===void 0?h.sdfIcons=Dt.sdf:h.sdfIcons!==Dt.sdf&&$r("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(Dt.pixelRatio!==h.pixelRatio||q.get("icon-rotate").constantOr(1)!==0)&&(h.iconsNeedLinear=!0)),Ut){const ai=Ut.toString();Yt=m.get(ai)}}ze=ze||!(!Ue.icon||!Ue.icon.hasSecondary());const pr=cP(It.horizontal)||It.vertical;h.iconsInText||(h.iconsInText=!!pr&&pr.iconsInText);const Cr=wt*X.textScaleFactor/Oa,{defaultShapedIcon:zr,verticallyShapedIcon:Rr}=TNe(h,$t,q,Ue,b,It,Cr,vr,Zt);Zt!=="none"&&$t&&(yX($t)||xX($t))&&(lP(0,Dt,Ct,$t,zr,Zt,O,m,x),lP(0,Yt,Ut,$t,zr,Zt,O,m,x),Rr&&(lP(0,Dt,Ct,$t,Rr,Zt,O,m,x),lP(0,Yt,Ut,$t,Rr,Zt,O,m,x))),$t=zr;const{iconBBox:cn,iconVerticalBBox:zn,textBBox:un,textVerticalBBox:qn}=vNe(h,$t,Rr,q,Ue,b,At,vr,X,x,sr,It,wt,mt,U);Ge.push({feature:Ue,shapedTextOrientations:It,shapedText:pr,shapedIcon:$t,iconPrimary:Ct,iconSecondary:Ut,iconOffset:vr,iconAnchor:sr,verticallyShapedIcon:Rr,layoutTextSize:wt,layoutIconSize:At,textOffset:mt,isSDFIcon:ir,iconTextFit:Zt,iconCollisionBounds:cn,iconVerticalCollisionBounds:zn,textCollisionBounds:un,textVerticalCollisionBounds:qn})}return{featureData:Ge,sizes:X,hasAnySecondaryIcon:ze,textAlongLine:Ie,symbolPlacement:ke}},a.fr=sB,a.fs=nB,a.ft=AX,a.fu=kX,a.fv=function(h,l,u,m,x,b,S,A,N,O){h.iconAtlasPositions=O.iconPositions;const{featureData:$,hasAnySecondaryIcon:U,sizes:q,textAlongLine:K,symbolPlacement:X}=l;for(const te of $){const{shapedIcon:ie,verticallyShapedIcon:ae,feature:he,shapedTextOrientations:ue,shapedText:ve,layoutTextSize:ke,textOffset:Ie,isSDFIcon:We,iconPrimary:ze,iconSecondary:Ge,iconTextFit:Ue,iconOffset:Ve,iconCollisionBounds:yt,iconVerticalCollisionBounds:wt,textCollisionBounds:At}=te;BX(ie,O.iconPositions,ze,Ge),BX(ae,O.iconPositions,ze,Ge),SNe(ue,O.iconPositions),wNe(ze,Ge,O.iconPositions),(ve||ie)&&ENe(h,he,ue,ie,ae,N,q,ke,0,Ie,We,m,x,S,A,U,Ue,Ve,K,X,yt,wt,At)}u&&h.generateCollisionDebugBuffers(b,h.collisionBoxArray,q.textScaleFactor)},a.fw=JI,a.fx=ei,a.fy=function(h){return h<=1?1:Math.pow(2,Math.floor(Math.log2(h)))},a.fz=EP,a.g=Mn,a.h=function(h,l){return wg(Object.assign(h,{method:"GET"}),l)},a.i=function(h){return Mn.API_STYLE_REGEX.test(h)&&!uc(h)},a.j=function(h){return btoa(encodeURIComponent(h).replace(/%([0-9A-F]{2})/g,(l,u)=>String.fromCharCode(+("0x"+u))))},a.k=L_,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 wg(Object.assign(h,{type:"json"}),l)},a.n=Tg,a.o=$l,a.p=function(h,l){return wg(Object.assign(h,{method:"POST"}),l)},a.q=$o,a.r=dt,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=Je,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=$r,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[m]of this.textures.entries()){const x=this.textureAccessTimes.get(m)||0;xthis._layers[hr.id]),dt=rt[0];if(dt.visibility==="none")continue;const it=dt.source||"";let ht=this.familiesBySource[it];ht||(ht=this.familiesBySource[it]=Object.create(null));const zt=dt.sourceLayer||"_geojsonTileLayer";let Rt=ht[zt];Rt||(Rt=ht[zt]=[]),Rt.push(rt)}}}const k=1*f.fa;class P{constructor(de){const fe={},Oe=[];for(const dt in de){const it=de[dt],ht=fe[dt]={};for(const zt in it.glyphs){const Rt=it.glyphs[+zt];if(!Rt||Rt.bitmap.width===0||Rt.bitmap.height===0)continue;const hr=Rt.metrics.localGlyph?k:1,Fr={x:0,y:0,w:Rt.bitmap.width+2*hr,h:Rt.bitmap.height+2*hr};Oe.push(Fr),ht[zt]=Fr}}const{w:Ye,h:Je}=f.J(Oe),rt=new f.f9({width:Ye||1,height:Je||1});for(const dt in de){const it=de[dt];for(const ht in it.glyphs){const zt=it.glyphs[+ht];if(!zt||zt.bitmap.width===0||zt.bitmap.height===0)continue;const Rt=fe[dt][ht],hr=zt.metrics.localGlyph?k:1;f.f9.copy(zt.bitmap,rt,{x:0,y:0},{x:Rt.x+hr,y:Rt.y+hr},zt.bitmap)}}this.image=rt,this.positions=fe}}function R(ut,de,fe){ut[de]?fe&&(ut[de].center=fe):ut[de]={floorIds:new Set,center:fe||[0,0],floors:{}}}function D(ut,de,fe,Oe){for(const Ye of de)R(ut,Ye),ut[Ye].floors[fe]=Oe,ut[Ye].floorIds.add(fe)}function M(ut){return{id:ut.properties.id.toString(),center:[ut.properties.center_lon||0,ut.properties.center_lat||0]}}function B(ut,de){const fe=ut.properties.id.toString(),Oe=!!ut.properties.is_default&&ut.properties.is_default,Ye=ut.properties.connected_floor_ids?new Set(ut.properties.connected_floor_ids.toString().split(";")):new Set,Je=ut.properties.conflicted_floor_ids?new Set(ut.properties.conflicted_floor_ids.toString().split(";")):new Set,rt=ut.properties.structure_ids?new Set(ut.properties.structure_ids.toString().split(";")):new Set,dt=ut.properties.name.toString(),it=ut.properties.z_index,ht=function(zt,Rt){const hr=zt.loadGeometry();if(!hr||hr.length===0)return;const Fr=hr.map(qr=>qr.map($r=>f.fb($r,Rt,zt.extent)));return Fr.length===0?void 0:{type:"Polygon",coordinates:[Fr[0]]}}(ut,de);return{id:fe,isDefault:Oe,connections:Ye,conflicts:Je,buildings:rt,name:dt,zIndex:it,geometry:ht}}function V(ut,de){return de.every(fe=>ut.properties&&ut.properties[fe]!=null)}function G(ut){return V(ut,["type","id","name"])&&ut.properties.type==="structure"}function W(ut){return V(ut,["type","id","name","z_index"])&&ut.properties.type==="floor"}f.f8(P,"GlyphAtlas");class Y{constructor(de){this.tileID=new f.aR(de.tileID.overscaledZ,de.tileID.wrap,de.tileID.canonical.z,de.tileID.canonical.x,de.tileID.canonical.y),this.tileZoom=de.tileZoom,this.uid=de.uid,this.zoom=de.zoom,this.lut=de.lut,this.canonical=de.tileID.canonical,this.pixelRatio=de.pixelRatio,this.tileSize=de.tileSize,this.source=de.source,this.scope=de.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=de.showCollisionBoxes,this.collectResourceTiming=!!de.request&&de.request.collectResourceTiming,this.promoteId=de.promoteId,this.renderSourceType=de.renderSourceType,this.tileTransform=f.fc(de.tileID.canonical,de.projection),this.projection=de.projection,this.worldview=de.worldview,this.localizableLayerIds=de.localizableLayerIds,this.brightness=de.brightness,this.extraShadowCaster=!!de.extraShadowCaster,this.tessellationStep=de.tessellationStep,this.scaleFactor=de.scaleFactor,this.worldview=de.worldview,this.indoor=de.indoor}parse(de,fe,Oe,Ye,Je,rt){this.status="parsing",this.data=de,this.collisionBoxArray=new f.fd;const dt=new f.fe(Object.keys(de.layers).sort()),it=new f.ff(this.tileID,this.promoteId);it.bucketLayerIDs=[];const ht={},zt=new f.fg(256,256),Rt={featureIndex:it,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:zt,availableImages:Oe,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(Rt.activeFloors=function($r,on,Cn,Ln){const Di=on.indoorState.activeFloorsVisible;if(!on.sourceLayers)return Di?on.indoorState.activeFloors:void 0;const Fs=function(bi,as){if(!bi)return f.w("No source layers defined in indoor specification"),as;if(bi.size===0)return as;const ua=bi.difference(as);for(const Mi of ua)f.w(`Missing source layer required in indoor specification: ${Mi}`);return as.intersection(as)}(on.sourceLayers,new Set(Object.keys($r.layers))),ks=on.indoorState,gs=function(bi,as,ua,Mi,os){const ys={};for(const Mn of as){const ja=bi.layers[Mn];if(ja)for(let So=0;So=Mi.maxzoom||Mi.visibility==="none")continue;J(ua,this.zoom,Rt.brightness,Oe,this.worldview,Rt.activeFloors);const os=ht[Mi.id]=Mi.createBucket({index:it.bucketLayerIDs.length,layers:ua,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:ks,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:Ye,worldview:this.worldview,localizable:bi,availableImages:Oe,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});it.bucketLayerIDs.push(ua.map(Mn=>f.F(Mn.id,Mn.scope)));let ys=os.prepare?os.prepare():null;ys!=null?(ys=ys.then(()=>os.populate(gs,Rt,this.tileID.canonical,this.tileTransform)),hr.push(ys)):os.populate(gs,Rt,this.tileID.canonical,this.tileTransform)}}const qr=()=>{zt.trim();const $r=!(!Rt.elevationFeatures||!Rt.elevationFeatures.some(Mi=>Mi.heightRange.min<0));let on,Cn,Ln,Di,Fs,ks,gs;const bi={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},as=()=>{if(on)return this.status="done",rt(on);if(this.extraShadowCaster)this.status="done",rt(null,{buckets:Object.values(ht).filter(Mi=>!Mi.isEmpty()),featureIndex:it,collisionBoxArray:null,hasTunnelGeometry:$r,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:Rt.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(Cn&&Ln&&Di&&gs){const os=new P(Cn),ys=new Map;for(const[So,mo]of Ln.entries()){const{imagePosition:cc}=f.fn(So,mo,f.fo);ys.set(So,cc)}const Mn={};for(const So in ht){const mo=ht[So];mo instanceof f.fp&&(J(mo.layers,this.zoom,Rt.brightness,Oe,this.worldview,Rt.activeFloors),Mn[So]=f.fq(mo,Cn,os.positions,Ln,ys,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,Fs,this.worldview,Oe))}const ja={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(Je,Ln,Fs,()=>{ja.iconsPending=!1,ua(Mn,os,ja,void 0,gs)}),this.rasterizeIfNeeded(Je,Di,ks,()=>{ja.patternsPending=!1,ua(Mn,os,ja,void 0,gs)})}},ua=(Mi,os,ys,Mn,ja)=>{if(ys.iconsPending||ys.patternsPending)return;const So=Ln.size>0||Di.size>0,mo=Object.keys(Mi).length>0;if(!So&&!mo)return this.status="done",void rt(null,{buckets:Object.values(ht).filter(uc=>!uc.isEmpty()),featureIndex:it,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:$r,glyphAtlasImage:os.image,lineAtlas:zt,imageAtlas:null,brightness:Rt.brightness});const cc=(uc,kd)=>{for(const wl in ht){const dc=ht[wl];if(wl in Mi)f.fv(dc,Mi[wl],this.showCollisionBoxes,Oe,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,Ln,kd);else if(dc.hasPattern&&(dc instanceof f.fw||dc instanceof f.fl||dc instanceof f.e0)){J(dc.layers,this.zoom,Rt.brightness,Oe,this.worldview,Rt.activeFloors);const Cd=Object.fromEntries(kd.patternPositions);dc.addFeatures(Rt,this.tileID.canonical,Cd,Oe,this.tileTransform,this.brightness)}}this.status="done",rt(null,{buckets:Object.values(ht).filter(wl=>!wl.isEmpty()),featureIndex:it,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:$r,glyphAtlasImage:os.image,lineAtlas:zt,imageAtlas:uc,brightness:Rt.brightness})};if(So){const uc=new Map,kd=f.fr(Ln,uc),wl=f.fr(Di,uc),dc=new f.fs(kd,wl,ja,this.lut,uc);Je.send("checkAtlasCache",{descriptor:dc,scope:this.scope},(Cd,kc)=>{let Nd,hu;if(Cd&&f.w(`[Worker] Error checking atlas cache: ${Cd.message}`),kc)Nd=new f.ft(kc.sourceHash),hu=kc;else{const $l=new f.fu(Ln,Di,this.lut,ja);Nd=$l,hu=$l}cc(Nd,hu)})}else cc(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const Mi=f.fk(Rt.glyphDependencies,Mn=>Object.keys(Mn).map(Number));Object.keys(Mi).length?Je.send("getGlyphs",{uid:this.uid,stacks:Mi},(Mn,ja)=>{on||(on=Mn,Cn=ja,as())},void 0,!1,bi):Cn={},gs=new Map;const os=Array.from(Rt.iconDependencies.keys()).map(Mn=>f.I.parse(Mn));os.length?Je.send("getImages",{images:os,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(Mn,ja)=>{if(!on){on=Mn,Ln=new Map,Fs=this.updateImageMapAndGetImageTaskQueue(Ln,ja.images,Rt.iconDependencies);for(const[So,mo]of ja.versions.entries())gs.set(So,mo);as()}},void 0,!1,bi):(Ln=new Map,Fs=new Map);const ys=Array.from(Rt.patternDependencies.keys()).map(Mn=>f.I.parse(Mn));ys.length?Je.send("getImages",{images:ys,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(Mn,ja)=>{if(!on){on=Mn,Di=new Map,ks=this.updateImageMapAndGetImageTaskQueue(Di,ja.images,Rt.patternDependencies);for(const[So,mo]of ja.versions.entries())gs.set(So,mo);as()}},void 0,!1,bi):(Di=new Map,ks=new Map)}if(Rt.elevationFeatures&&Rt.elevationFeatures.length>0){const Mi=[];for(const ys of Object.values(ht))if(ys instanceof f.fl){const Mn=ys.getUnevaluatedPortalGraph();Mn&&Mi.push(Mn)}const os=f.fm.evaluate(Mi);for(const ys of Object.values(ht))if(ys instanceof f.fl){const Mn=de.layers[dt.decode(ys.sourceLayerIndex)];ys.setEvaluatedPortalGraph(os,Mn,this.tileID.canonical,Rt.availableImages,Rt.brightness)}}as()};hr.length>0?Promise.allSettled(hr).then(qr).catch(rt):qr()}updateParameters(de){this.scaleFactor=de.scaleFactor,this.showCollisionBoxes=de.showCollisionBoxes,this.projection=de.projection,this.brightness=de.brightness,this.tileTransform=f.fc(de.tileID.canonical,de.projection),this.extraShadowCaster=de.extraShadowCaster,this.lut=de.lut,this.worldview=de.worldview,this.indoor=de.indoor}rasterizeIfNeeded(de,fe,Oe,Ye){Array.from(fe.values()).some(Je=>Je.usvg)?this.rasterize(de,fe,Oe,Ye):Ye()}updateImageMapAndGetImageTaskQueue(de,fe,Oe){const Ye=new Map;for(const Je of fe.keys()){const rt=Oe.get(Je)||[];for(const dt of rt){const it=dt.toString(),ht=fe.get(dt.id.toString());ht.usvg?Ye.has(it)||(Ye.set(it,dt),de.set(it,Object.assign({},ht))):de.set(it,ht)}}return Ye}rasterize(de,fe,Oe,Ye){this.rasterizeTask=de.send("rasterizeImages",{scope:this.scope,tasks:Oe},(Je,rt)=>{if(!Je)for(const[dt,it]of rt.entries()){const ht=Object.assign(fe.get(dt),{data:it});fe.set(dt,ht)}Ye()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function J(ut,de,fe,Oe,Ye,Je){const rt=new f.ae(de,{brightness:fe,worldview:Ye,activeFloors:Je});for(const dt of ut)dt.recalculate(rt,Oe)}class Q extends f.E{constructor({actor:de,layerIndex:fe,availableImages:Oe,availableModels:Ye,isSpriteLoaded:Je,tileProvider:rt,brightness:dt,maxUniformBufferBindings:it,maxUniformBlockSizeDwords:ht,disableSymbolUBO:zt}){super(),this.actor=de,this.layerIndex=fe,this.availableImages=Oe,this.availableModels=Ye,this.loadVectorData=f.aO,this.tileProvider=rt,this.loading={},this.loaded={},this.deduped=new f.aN(de.scheduler),this.isSpriteLoaded=Je,this.scheduler=de.scheduler,this.brightness=dt,this.maxUniformBufferBindings=it,this.maxUniformBlockSizeDwords=ht,this.disableSymbolUBO=zt}loadTileData(de,fe){if(!this.tileProvider)return this.loadVectorData(de,fe);const Oe=new AbortController,{z:Ye,x:Je,y:rt}=de.tileID.canonical;return this.tileProvider.loadTile({z:Ye,x:Je,y:rt},{request:de.request,signal:Oe.signal}).then(dt=>{if(Oe.signal.aborted)return;if(dt==null){const ht=new Error("Tile not found");return ht.status=404,fe(ht)}if(dt.data===null)return fe(null,null);const it=new Map;dt.expires&&it.set("expires",dt.expires),dt.cacheControl&&it.set("cache-control",dt.cacheControl),fe(null,{rawData:dt.data,responseHeaders:it})}).catch(dt=>{Oe.signal.aborted||fe(dt instanceof Error?dt:new Error(String(dt)))}),()=>Oe.abort()}loadTile(de,fe){const Oe=de.uid,Ye=de&&de.request,Je=Ye&&Ye.collectResourceTiming,rt=this.loading[Oe]=new Y(de);rt.maxUniformBufferBindings=this.maxUniformBufferBindings,rt.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,rt.disableSymbolUBO=this.disableSymbolUBO,rt.abort=this.loadTileData(de,(dt,it)=>{const ht=!this.loading[Oe];if(delete this.loading[Oe],rt.cancelRasterize(),ht||dt||!it)return rt.status="done",ht||(this.loaded[Oe]=rt),fe(dt);const zt=it.rawData,Rt={},hr=f.aP(it.responseHeaders);hr&&hr.expires&&(Rt.expires=hr.expires),hr&&hr.cacheControl&&(Rt.cacheControl=hr.cacheControl),rt.vectorTile=it.vectorTile||new f.fx(new f.a$(zt));const Fr=()=>{rt.parse(rt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(qr,$r)=>{if(qr||!$r)return fe(qr);const on={};if(Je){const Cn=p(Ye);Cn.length>0&&(on.resourceTiming=JSON.parse(JSON.stringify(Cn)))}fe(null,Object.assign({rawTileData:zt.slice(0),responseHeaders:it.responseHeaders},$r,Rt,on))})};this.isSpriteLoaded?Fr():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(Fr,{type:"parseTile",renderSourceType:de.renderSourceType,zoom:de.tileZoom}):Fr()}),this.loaded=this.loaded||{},this.loaded[Oe]=rt})}reloadTile(de,fe){const Oe=this.loaded,Ye=de.uid;if(Oe&&Oe[Ye]){const Je=Oe[Ye];Je.updateParameters(de);const rt=(dt,it)=>{const ht=Je.reloadCallback;ht&&(delete Je.reloadCallback,Je.parse(Je.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,ht)),fe(dt,it)};Je.status==="parsing"?Je.reloadCallback=rt:Je.status==="done"&&(Je.vectorTile?Je.parse(Je.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,rt):rt())}else fe(null,void 0)}abortTile(de,fe){const Oe=de.uid,Ye=this.loading[Oe];Ye&&(Ye.abort&&Ye.abort(),delete this.loading[Oe]),fe()}removeTile(de,fe){const Oe=this.loaded,Ye=de.uid;Oe&&Oe[Ye]&&delete Oe[Ye],fe()}}class ee{constructor(de){this.loading={}}loadTile(de,fe){const Oe=de.uid,{cancel:Ye}=f.b1(de.request,(Je,rt,dt)=>{const it=!this.loading[Oe];if(delete this.loading[Oe],it||Je||!rt)return fe(Je);this.decodeTile(Oe,rt,de.encoding).then(ht=>{const{expires:zt,cacheControl:Rt}=f.aP(dt);fe(null,Object.assign(ht,{expires:zt,cacheControl:Rt}))}).catch(ht=>fe(ht))});this.loading[Oe]={cancel:Ye}}async decodeTile(de,fe,Oe){const Ye=await createImageBitmap(new Blob([new Uint8Array(fe)],{type:"image/png"})),Je=1-(Ye.width-f.fy(Ye.width))/2,rt=Je<1,dt=this.getImageData(Ye,Je);return Ye.close(),{dem:new f.fz(de,dt,Oe,rt),borderReady:rt}}reloadTile(de,fe){fe(null,null)}abortTile(de,fe){const Oe=de.uid,Ye=this.loading[Oe];Ye&&(Ye.cancel(),delete this.loading[Oe]),fe()}removeTile(de,fe){fe()}getImageData(de,fe){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(de.width,de.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=de.width,this.offscreenCanvas.height=de.height,this.offscreenCanvasContext.drawImage(de,0,0,de.width,de.height);const Oe=this.offscreenCanvasContext.getImageData(-fe,-fe,de.width+2*fe,de.height+2*fe);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),Oe}}f.a_.setPbf(f.a$);class le{constructor(de){this._mrt=new f.a_(de.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=de.uid,this.tileID=de.tileID,this.source=de.source}parse(de,fe){const Oe=this._mrt;this.status="parsing",this._entireBuffer=de;try{Oe.parseHeader(de),this._isHeaderLoaded=!0;const Ye=[];for(const Je in Oe.layers){const rt=Oe.getLayer(Je),dt=rt.getDataRange(rt.getBandList()),it=Oe.createDecodingTask(dt),ht=de.slice(dt.firstByte,dt.lastByte+1),zt=f.a_.performDecoding(ht,it).then(Rt=>it.complete(null,Rt)).catch(Rt=>it.complete(Rt,null));Ye.push(zt)}Promise.allSettled(Ye).then(()=>fe(null,Oe)).catch(Je=>fe(Je))}catch(Ye){fe(Ye)}}}class pe{constructor({actor:de}){this.actor=de,this.loading={},this.loaded={}}loadTile(de,fe){const Oe=de.uid,Ye=de.request,Je=this.loading[Oe]=new le(de),{cancel:rt}=f.b1(Ye,(dt,it,ht)=>{const zt=!this.loading[Oe];if(delete this.loading[Oe],zt||dt||!it)return Je.status="done",zt||(this.loaded[Oe]=Je),fe(dt);Je.parse(it,(Rt,hr)=>{if(Rt||!hr)return fe(Rt);fe(null,hr,ht)}),this.loaded[Oe]=Je});Je.abort=rt}reloadTile(de,fe){fe(null,void 0)}abortTile(de,fe){const Oe=de.uid,Ye=this.loading[Oe];Ye&&(Ye.abort&&Ye.abort(),delete this.loading[Oe]),fe()}removeTile(de,fe){const Oe=de.uid;this.loaded[Oe]&&delete this.loaded[Oe],fe()}decodeRasterArray(de,fe){f.a_.performDecoding(de.buffer,de.task).then(Oe=>fe(null,Oe)).catch(Oe=>fe(Oe))}}const Se=f.fA.prototype.toGeoJSON;class je{constructor(de){this._feature=de,this.extent=f.an,this.type=de.type,this.properties=de.tags,"id"in de&&!isNaN(de.id)&&(this.id=parseInt(de.id,10))}loadGeometry(){if(this._feature.type===1){const de=[];for(const fe of this._feature.geometry)de.push([new f.P(fe[0],fe[1])]);return de}{const de=[];for(const fe of this._feature.geometry){const Oe=[];for(const Ye of fe)Oe.push(new f.P(Ye[0],Ye[1]));de.push(Oe)}return de}}toGeoJSON(de,fe,Oe){return Se.call(this,de,fe,Oe)}}class Le{constructor(de,fe){this.name=de,this.extent=f.an,this.length=fe.length,this._jsonFeatures=fe}feature(de){return new je(this._jsonFeatures[de])}}class Ae{constructor(de){this.layers={},this.extent=f.an;for(const fe of Object.keys(de))this.layers[fe]=new Le(fe,de[fe])}}const be=64/4096;class me{constructor(){this.features=new Map}clear(){this.features.clear()}load(de=[],fe){for(const Oe of de){const Ye=Oe.id;if(Ye==null)continue;let Je=this.features.get(Ye);Je&&this.updateCache(Je,fe),Oe.geometry?(Je=Ne(Oe),this.updateCache(Je,fe),this.features.set(Ye,Je)):this.features.delete(Ye),this.updateCache(Je,fe)}}updateCache(de,fe){for(const{canonical:Oe,uid:Ye}of Object.values(fe)){const{z:Je,x:rt,y:dt}=Oe;Te(de,Math.pow(2,Je),rt,dt)&&delete fe[Ye]}}getTile(de,fe,Oe){const Ye=Math.pow(2,de),Je=[];for(const rt of this.features.values())Te(rt,Ye,fe,Oe)&&Je.push(tt(rt,Ye,fe,Oe));return{features:Je}}getFeatures(){return[...this.features.values()]}}function Te({minX:ut,minY:de,maxX:fe,maxY:Oe},Ye,Je,rt){return ut<(Je+1+be)/Ye&&de<(rt+1+be)/Ye&&fe>(Je-be)/Ye&&Oe>(rt-be)/Ye}function Ne(ut){const{id:de,geometry:fe,properties:Oe}=ut;if(!fe)return;if(fe.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:Ye,coordinates:Je}=fe,rt={id:de,type:1,geometry:[],tags:Oe,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},dt=rt.geometry;if(Ye==="Point")Ee(Je,dt,rt);else if(Ye==="MultiPoint")for(const it of Je)Ee(it,dt,rt);else if(Ye==="LineString")rt.type=2,we(Je,dt,rt);else if(Ye==="MultiLineString")rt.type=2,He(Je,dt,rt);else if(Ye==="Polygon")rt.type=3,He(Je,dt,rt,!0);else{if(Ye!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");rt.type=3;for(const it of Je)He(it,dt,rt,!0)}return rt}function Ee([ut,de],fe,Oe){const Ye=f.aH(ut);let Je=f.aL(de);Je=Je<0?0:Je>1?1:Je,fe.push(Ye,Je),Oe.minX=Math.min(Oe.minX,Ye),Oe.minY=Math.min(Oe.minY,Je),Oe.maxX=Math.max(Oe.maxX,Ye),Oe.maxY=Math.max(Oe.maxY,Je)}function we(ut,de,fe,Oe=!1,Ye=!1){const Je=[];for(const rt of ut)Ee(rt,Je,fe);de.push(Je),Oe&&function(rt,dt){let it=0;for(let ht=0,zt=rt.length,Rt=zt-2;ht0===dt)for(let ht=0,zt=rt.length;ht=rt&&Rt>=rt||(ht>=rt?(zt+=Math.round(qr*((rt-ht)/Fr)),ht=rt):Rt>=rt&&(hr=zt+Math.round(qr*((rt-ht)/Fr)),Rt=rt),zt>=rt&&hr>=rt||(zt>=rt?(ht+=Math.round(Fr*((rt-zt)/qr)),zt=rt):hr>=rt&&(Rt=ht+Math.round(Fr*((rt-zt)/qr)),hr=rt),dt&&ht===dt[dt.length-1][0]&&zt===dt[dt.length-1][1]||(dt=[[ht,zt]],Ye.push(dt)),dt.push([Rt,hr])))))}}function Et(ut,de,fe,Oe,Ye){const Je=(fe-be)/de,rt=(Oe-be)/de,dt=(fe+1+be)/de,it=(Oe+1+be)/de;function ht(hr,Fr){let qr=0;return hrdt&&(qr|=2),Frit&&(qr|=8),qr}let zt=[];for(let hr=1;hr<=8;hr*=2){let Fr=ut[ut.length-2],qr=ut[ut.length-1],$r=!(ht(Fr,qr)&hr);for(let on=0;on>31}function _t(ut,de){const{geometry:fe,type:Oe}=ut;let Ye=0,Je=0;if(Oe===1){de.writeVarint(Pt(1,fe.length));for(const rt of fe){const dt=rt[0]-Ye,it=rt[1]-Je;de.writeVarint(tr(dt)),de.writeVarint(tr(it)),Ye+=dt,Je+=it}}else for(const rt of fe){if(rt.length===0)continue;de.writeVarint(Pt(1,1));const dt=rt.length-(Oe===3?1:0);for(let it=0;itut},sn=Math.fround||(ur=new Float32Array(1),ut=>(ur[0]=+ut,ur[0]));var ur;class xr{constructor(de){this.options=Object.assign(Object.create(Tr),de),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(de){const{log:fe,minZoom:Oe,maxZoom:Ye}=this.options;fe&&console.time("total time");const Je=`prepare ${de.length} points`;fe&&console.time(Je),this.points=de;const rt=[];for(let it=0;it=Oe;it--){const ht=+Date.now();dt=this.trees[it]=this._createTree(this._cluster(dt,it)),fe&&console.log("z%d: %d clusters in %dms",it,dt.numItems,+Date.now()-ht)}return fe&&console.timeEnd("total time"),this}getClusters(de,fe){let Oe=((de[0]+180)%360+360)%360-180;const Ye=Math.max(-90,Math.min(90,de[1]));let Je=de[2]===180?180:((de[2]+180)%360+360)%360-180;const rt=Math.max(-90,Math.min(90,de[3]));if(de[2]-de[0]>=360)Oe=-180,Je=180;else if(Oe>Je){const Rt=this.getClusters([Oe,Ye,180,rt],fe),hr=this.getClusters([-180,Ye,Je,rt],fe);return Rt.concat(hr)}const dt=this.trees[this._limitZoom(fe)],it=dt.range(ct(Oe),jt(rt),ct(Je),jt(Ye)),ht=dt.data,zt=[];for(const Rt of it){const hr=this.stride*Rt;zt.push(ht[hr+5]>1?rr(ht,hr,this.clusterProps):this.points[ht[hr+3]])}return zt}getChildren(de){const fe=this._getOriginId(de),Oe=this._getOriginZoom(de),Ye="No cluster with the specified id.",Je=this.trees[Oe];if(!Je)throw new Error(Ye);const rt=Je.data;if(fe*this.stride>=rt.length)throw new Error(Ye);const dt=this.options.radius/(this.options.extent*Math.pow(2,Oe-1)),it=Je.within(rt[fe*this.stride],rt[fe*this.stride+1],dt),ht=[];for(const zt of it){const Rt=zt*this.stride;rt[Rt+4]===de&&ht.push(rt[Rt+5]>1?rr(rt,Rt,this.clusterProps):this.points[rt[Rt+3]])}if(ht.length===0)throw new Error(Ye);return ht}getLeaves(de,fe,Oe){const Ye=[];return this._appendLeaves(Ye,de,fe=fe||10,Oe=Oe||0,0),Ye}getTile(de,fe,Oe){const Ye=this.trees[this._limitZoom(de)],Je=Math.pow(2,de),{extent:rt,radius:dt}=this.options,it=dt/rt,ht=(Oe-it)/Je,zt=(Oe+1+it)/Je,Rt={features:[]};return this._addTileFeatures(Ye.range((fe-it)/Je,ht,(fe+1+it)/Je,zt),Ye.data,fe,Oe,Je,Rt),fe===0&&this._addTileFeatures(Ye.range(1-it/Je,ht,1,zt),Ye.data,Je,Oe,Je,Rt),fe===Je-1&&this._addTileFeatures(Ye.range(0,ht,it/Je,zt),Ye.data,-1,Oe,Je,Rt),Rt.features.length?Rt:null}getClusterExpansionZoom(de){let fe=this._getOriginZoom(de)-1;for(;fe<=this.options.maxZoom;){const Oe=this.getChildren(de);if(fe++,Oe.length!==1)break;de=Oe[0].properties.cluster_id}return fe}_appendLeaves(de,fe,Oe,Ye,Je){const rt=this.getChildren(fe);for(const dt of rt){const it=dt.properties;if(it&&it.cluster?Je+it.point_count<=Ye?Je+=it.point_count:Je=this._appendLeaves(de,it.cluster_id,Oe,Ye,Je):Je1;let zt,Rt,hr;if(ht)zt=vn(fe,it,this.clusterProps),Rt=fe[it],hr=fe[it+1];else{const $r=this.points[fe[it+3]];zt=$r.properties;const[on,Cn]=$r.geometry.coordinates;Rt=ct(on),hr=jt(Cn)}const Fr={type:1,geometry:[[Math.round(this.options.extent*(Rt*Je-Oe)),Math.round(this.options.extent*(hr*Je-Ye))]],tags:zt};let qr;qr=ht||this.options.generateId?fe[it+3]:this.points[fe[it+3]].id,qr!==void 0&&(Fr.id=qr),rt.features.push(Fr)}}_limitZoom(de){return Math.max(this.options.minZoom,Math.min(Math.floor(+de),this.options.maxZoom+1))}_cluster(de,fe){const{radius:Oe,extent:Ye,reduce:Je,minPoints:rt}=this.options,dt=Oe/(Ye*Math.pow(2,fe)),it=de.data,ht=[],zt=this.stride;for(let Rt=0;Rtfe&&(on+=it[Ln+5])}if(on>$r&&on>=rt){let Cn,Ln=hr*$r,Di=Fr*$r,Fs=-1;const ks=(Rt/zt<<5)+(fe+1)+this.points.length;for(const gs of qr){const bi=gs*zt;if(it[bi+2]<=fe)continue;it[bi+2]=fe;const as=it[bi+5];Ln+=it[bi]*as,Di+=it[bi+1]*as,it[bi+4]=ks,Je&&(Cn||(Cn=this._map(it,Rt,!0),Fs=this.clusterProps.length,this.clusterProps.push(Cn)),Je(Cn,this._map(it,bi)))}it[Rt+4]=ks,ht.push(Ln/on,Di/on,1/0,ks,-1,on),Je&&ht.push(Fs)}else{for(let Cn=0;Cn1)for(const Cn of qr){const Ln=Cn*zt;if(!(it[Ln+2]<=fe)){it[Ln+2]=fe;for(let Di=0;Di>5}_getOriginZoom(de){return(de-this.points.length)%32}_map(de,fe,Oe){if(de[fe+5]>1){const rt=this.clusterProps[de[fe+6]];return Oe?Object.assign({},rt):rt}const Ye=this.points[de[fe+3]].properties,Je=this.options.map(Ye);return Oe&&Je===Ye?Object.assign({},Je):Je}}function rr(ut,de,fe){return{type:"Feature",id:ut[de+3],properties:vn(ut,de,fe),geometry:{type:"Point",coordinates:[(Oe=ut[de],360*(Oe-.5)),er(ut[de+1])]}};var Oe}function vn(ut,de,fe){const Oe=ut[de+5],Ye=Oe>=1e4?`${Math.round(Oe/1e3)}k`:Oe>=1e3?Math.round(Oe/100)/10+"k":Oe,Je=ut[de+6],rt=Je===-1?{}:Object.assign({},fe[Je]);return Object.assign(rt,{cluster:!0,cluster_id:ut[de+3],point_count:Oe,point_count_abbreviated:Ye})}function ct(ut){return ut/360+.5}function jt(ut){const de=Math.sin(ut*Math.PI/180),fe=.5-.25*Math.log((1+de)/(1-de))/Math.PI;return fe<0?0:fe>1?1:fe}function er(ut){const de=(180-360*ut)*Math.PI/180;return 360*Math.atan(Math.exp(de))/Math.PI-90}function Pr(ut,de,fe,Oe){let Ye=Oe;const Je=de+(fe-de>>1);let rt,dt=fe-de;const it=ut[de],ht=ut[de+1],zt=ut[fe],Rt=ut[fe+1];for(let hr=de+3;hrYe)rt=hr,Ye=Fr;else if(Fr===Ye){const qr=Math.abs(hr-Je);qrOe&&(rt-de>3&&Pr(ut,de,rt,Oe),ut[rt+2]=Ye,fe-rt>3&&Pr(ut,rt,fe,Oe))}function dr(ut,de,fe,Oe,Ye,Je){let rt=Ye-fe,dt=Je-Oe;if(rt!==0||dt!==0){const it=((ut-fe)*rt+(de-Oe)*dt)/(rt*rt+dt*dt);it>1?(fe=Ye,Oe=Je):it>0&&(fe+=rt*it,Oe+=dt*it)}return rt=ut-fe,dt=de-Oe,rt*rt+dt*dt}function ar(ut,de,fe,Oe){const Ye={id:ut??null,type:de,geometry:fe,tags:Oe,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(de==="Point"||de==="MultiPoint"||de==="LineString")Nt(Ye,fe);else if(de==="Polygon")Nt(Ye,fe[0]);else if(de==="MultiLineString")for(const Je of fe)Nt(Ye,Je);else if(de==="MultiPolygon")for(const Je of fe)Nt(Ye,Je[0]);return Ye}function Nt(ut,de){for(let fe=0;fe0&&(rt+=Oe?(Ye*zt-ht*Je)/2:Math.sqrt(Math.pow(ht-Ye,2)+Math.pow(zt-Je,2))),Ye=ht,Je=zt}const dt=de.length-3;de[2]=1,Pr(de,0,dt,fe),de[dt+2]=1,de.size=Math.abs(rt),de.start=0,de.end=de.size}function ii(ut,de,fe,Oe){for(let Ye=0;Ye1?1:fe}function vi(ut,de,fe,Oe,Ye,Je,rt,dt){if(Oe/=de,Je>=(fe/=de)&&rt=Oe)return null;const it=[];for(const ht of ut){const zt=ht.geometry;let Rt=ht.type;const hr=Ye===0?ht.minX:ht.minY,Fr=Ye===0?ht.maxX:ht.maxY;if(hr>=fe&&Fr=Oe)continue;let qr=[];if(Rt==="Point"||Rt==="MultiPoint")ca(zt,qr,fe,Oe,Ye);else if(Rt==="LineString")Nr(zt,qr,fe,Oe,Ye,!1,dt.lineMetrics);else if(Rt==="MultiLineString")Ks(zt,qr,fe,Oe,Ye,!1);else if(Rt==="Polygon")Ks(zt,qr,fe,Oe,Ye,!0);else if(Rt==="MultiPolygon")for(const $r of zt){const on=[];Ks($r,on,fe,Oe,Ye,!0),on.length&&qr.push(on)}if(qr.length){if(dt.lineMetrics&&Rt==="LineString"){for(const $r of qr)it.push(ar(ht.id,Rt,$r,ht.tags));continue}Rt!=="LineString"&&Rt!=="MultiLineString"||(qr.length===1?(Rt="LineString",qr=qr[0]):Rt="MultiLineString"),Rt!=="Point"&&Rt!=="MultiPoint"||(Rt=qr.length===3?"Point":"MultiPoint"),it.push(ar(ht.id,Rt,qr,ht.tags))}}return it.length?it:null}function ca(ut,de,fe,Oe,Ye){for(let Je=0;Je=fe&&rt<=Oe&&Ea(de,ut[Je],ut[Je+1],ut[Je+2])}}function Nr(ut,de,fe,Oe,Ye,Je,rt){let dt=Vn(ut);const it=Ye===0?wo:Zr;let ht,zt,Rt=ut.start;for(let on=0;onfe&&(zt=it(dt,Cn,Ln,Fs,ks,fe),rt&&(dt.start=Rt+ht*zt)):gs>Oe?bi=fe&&(zt=it(dt,Cn,Ln,Fs,ks,fe),as=!0),bi>Oe&&gs<=Oe&&(zt=it(dt,Cn,Ln,Fs,ks,Oe),as=!0),!Je&&as&&(rt&&(dt.end=Rt+ht*zt),de.push(dt),dt=Vn(ut)),rt&&(Rt+=ht)}let hr=ut.length-3;const Fr=ut[hr],qr=ut[hr+1],$r=Ye===0?Fr:qr;$r>=fe&&$r<=Oe&&Ea(dt,Fr,qr,ut[hr+2]),hr=dt.length-3,Je&&hr>=3&&(dt[hr]!==dt[0]||dt[hr+1]!==dt[1])&&Ea(dt,dt[0],dt[1],dt[2]),dt.length&&de.push(dt)}function Vn(ut){const de=[];return de.size=ut.size,de.start=ut.start,de.end=ut.end,de}function Ks(ut,de,fe,Oe,Ye,Je){for(const rt of ut)Nr(rt,de,fe,Oe,Ye,Je,!1)}function Ea(ut,de,fe,Oe){ut.push(de,fe,Oe)}function wo(ut,de,fe,Oe,Ye,Je){const rt=(Je-de)/(Oe-de);return Ea(ut,Je,fe+(Ye-fe)*rt,1),rt}function Zr(ut,de,fe,Oe,Ye,Je){const rt=(Je-fe)/(Ye-fe);return Ea(ut,de+(Oe-de)*rt,Je,1),rt}function fn(ut,de){const fe=[];for(let Oe=0;Oe0&&de.size<(Ye?rt:Oe))return void(fe.numPoints+=de.length/3);const dt=[];for(let it=0;itrt)&&(fe.numSimplified++,dt.push(de[it],de[it+1])),fe.numPoints++;Ye&&function(it,ht){let zt=0;for(let Rt=0,hr=it.length,Fr=hr-2;Rt0===ht)for(let Rt=0,hr=it.length;Rt
24)throw new Error("maxZoom should be in the 0-24 range");if(fe.promoteId&&fe.generateId)throw new Error("promoteId and generateId cannot be used together.");let Ye=function(Je,rt){const dt=[];if(Je.type==="FeatureCollection")for(let it=0;it1&&console.time("creation"),Fr=this.tiles[hr]=en(de,fe,Oe,Ye,ht),this.tileCoords.push({z:fe,x:Oe,y:Ye}),zt)){zt>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",fe,Oe,Ye,Fr.numFeatures,Fr.numPoints,Fr.numSimplified),console.timeEnd("creation"));const as=`z${fe}`;this.stats[as]=(this.stats[as]||0)+1,this.total++}if(Fr.source=de,Je==null){if(fe===ht.indexMaxZoom||Fr.numPoints<=ht.indexMaxPoints)continue}else{if(fe===ht.maxZoom||fe===Je)continue;if(Je!=null){const as=Je-fe;if(Oe!==rt>>as||Ye!==dt>>as)continue}}if(Fr.source=null,de.length===0)continue;zt>1&&console.time("clipping");const qr=.5*ht.buffer/ht.extent,$r=.5-qr,on=.5+qr,Cn=1+qr;let Ln=null,Di=null,Fs=null,ks=null,gs=vi(de,Rt,Oe-qr,Oe+on,0,Fr.minX,Fr.maxX,ht),bi=vi(de,Rt,Oe+$r,Oe+Cn,0,Fr.minX,Fr.maxX,ht);de=null,gs&&(Ln=vi(gs,Rt,Ye-qr,Ye+on,1,Fr.minY,Fr.maxY,ht),Di=vi(gs,Rt,Ye+$r,Ye+Cn,1,Fr.minY,Fr.maxY,ht),gs=null),bi&&(Fs=vi(bi,Rt,Ye-qr,Ye+on,1,Fr.minY,Fr.maxY,ht),ks=vi(bi,Rt,Ye+$r,Ye+Cn,1,Fr.minY,Fr.maxY,ht),bi=null),zt>1&&console.timeEnd("clipping"),it.push(Ln||[],fe+1,2*Oe,2*Ye),it.push(Di||[],fe+1,2*Oe,2*Ye+1),it.push(Fs||[],fe+1,2*Oe+1,2*Ye),it.push(ks||[],fe+1,2*Oe+1,2*Ye+1)}}getTile(de,fe,Oe){de=+de,fe=+fe,Oe=+Oe;const Ye=this.options,{extent:Je,debug:rt}=Ye;if(de<0||de>24)return null;const dt=1<1&&console.log("drilling down to z%d-%d-%d",de,fe,Oe);let ht,zt=de,Rt=fe,hr=Oe;for(;!ht&&zt>0;)zt--,Rt>>=1,hr>>=1,ht=this.tiles[Ot(zt,Rt,hr)];return ht&&ht.source?(rt>1&&(console.log("found parent tile z%d-%d-%d",zt,Rt,hr),console.time("drilling down")),this.splitTile(ht.source,zt,Rt,hr,de,fe,Oe),rt>1&&console.timeEnd("drilling down"),this.tiles[it]?Xr(this.tiles[it],Je):null):null}}function Ot(ut,de,fe){return 32*((1<ht.tags&&"3d_elevation_id"in ht.tags&&"source"in ht.tags&&ht.tags.source==="elevation",Je=Oe.features.filter(ht=>Ye(ht));let rt={_geojsonTileLayer:Oe.features};Je.length>0&&(rt={_geojsonTileLayer:Oe.features.filter(ht=>!Ye(ht)),hd_road_elevation:Je});const dt=new Ae(rt),it=function(ht){const zt=new f.a$;for(const Rt of Object.keys(ht))zt.writeMessage(3,vt,{name:Rt,features:ht[Rt]});return zt.finish()}(rt).buffer;de(null,{vectorTile:dt,rawData:it})}class Ei extends Q{constructor(de){super(de),this.loadVectorData=Mo,this._dynamicIndex=new me}loadData(de,fe){const Oe=de&&de.request,Ye=Oe&&Oe.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(de,(Je,rt)=>{if(Je||!rt)return fe(Je);if(typeof rt!="object")return fe(new Error(`Input data given to '${de.source}' is not a valid GeoJSON object.`));{try{if(de.filter){const it=f.X(de.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(it.result==="error")throw new Error(it.value.map(ht=>`${ht.key}: ${ht.message}`).join(", "));rt.features=rt.features.filter(ht=>it.value.evaluate({zoom:0},ht))}de.dynamic?(rt.type==="Feature"&&(rt={type:"FeatureCollection",features:[rt]}),de.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(rt.features,this.loaded),de.cluster&&(rt.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=de.cluster?new xr(function({superclusterOptions:it,clusterProperties:ht}){if(!ht||!it)return it;const zt={},Rt={},hr={accumulated:null,zoom:0},Fr={properties:null},qr=Object.keys(ht);for(const $r of qr){const[on,Cn]=ht[$r],Ln=f.X(Cn),Di=f.X(typeof on=="string"?[on,["accumulated"],["get",$r]]:on);zt[$r]=Ln.value,Rt[$r]=Di.value}return it.map=$r=>{Fr.properties=$r;const on={};for(const Cn of qr)on[Cn]=zt[Cn].evaluate(hr,Fr);return on},it.reduce=($r,on)=>{Fr.properties=on;for(const Cn of qr)hr.accumulated=$r[Cn],$r[Cn]=Rt[Cn].evaluate(hr,Fr)},it}(de)).load(rt.features):de.dynamic?this._dynamicIndex:function(it,ht){return new Jo(it,ht)}(rt,de.geojsonVtOptions)}catch(it){return fe(it)}const dt={};if(Ye){const it=p(Oe);it&&(dt.resourceTiming={},dt.resourceTiming[de.source]=JSON.parse(JSON.stringify(it)))}fe(null,dt)}})}reloadTile(de,fe){const Oe=this.loaded;return Oe&&Oe[de.uid]?de.partial?fe(null,void 0):super.reloadTile(de,fe):this.loadTile(de,fe)}loadGeoJSON(de,fe){if(de.request)f.m(de.request,fe);else{if(typeof de.data!="string")return fe(new Error(`Input data given to '${de.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return fe(null,JSON.parse(de.data))}catch{return fe(new Error(`Input data given to '${de.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(de,fe){try{fe(null,this._geoJSONIndex.getClusterExpansionZoom(de.clusterId))}catch(Oe){fe(Oe)}}getClusterChildren(de,fe){try{fe(null,this._geoJSONIndex.getChildren(de.clusterId))}catch(Oe){fe(Oe)}}getClusterLeaves(de,fe){try{fe(null,this._geoJSONIndex.getLeaves(de.clusterId,de.limit,de.offset))}catch(Oe){fe(Oe)}}}class As{constructor(de,fe,Oe){this.tileID=new f.aR(de.tileID.overscaledZ,de.tileID.wrap,de.tileID.canonical.z,de.tileID.canonical.x,de.tileID.canonical.y),this.tileZoom=de.tileZoom,this.uid=de.uid,this.zoom=de.zoom,this.canonical=de.tileID.canonical,this.pixelRatio=de.pixelRatio,this.tileSize=de.tileSize,this.source=de.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=de.projection,this.brightness=fe,this.worldview=Oe}parse(de,fe,Oe,Ye){this.status="parsing";const Je=new f.aR(Oe.tileID.overscaledZ,Oe.tileID.wrap,Oe.tileID.canonical.z,Oe.tileID.canonical.x,Oe.tileID.canonical.y),rt=[],dt=fe.familiesBySource[Oe.source],it=new f.ff(Je,Oe.promoteId);it.bucketLayerIDs=[],it.is3DTile=!0,f.fB(de).then(ht=>{const zt=ht.json.extensionsUsed&&ht.json.extensionsUsed.includes("MAPBOX_mesh_features")||ht.json.asset.extras&&ht.json.asset.extras.MAPBOX_mesh_features,Rt=ht.json.extensionsUsed&&ht.json.extensionsUsed.includes("EXT_meshopt_compression"),hr=new f.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const Fr in dt)for(const qr of dt[Fr]){const $r=qr[0];it.bucketLayerIDs.push(qr.map(Ln=>f.F(Ln.id,Ln.scope))),$r.recalculate(hr,[]);const on=f.fC(ht,1/f.cS(Oe.tileID.canonical)),Cn=new f.fD(qr,on,Je,zt,Rt,this.brightness,it,this.worldview);zt||(Cn.needsUpload=!0),rt.push(Cn),Cn.evaluate($r)}this.status="done",Ye(null,{buckets:rt,featureIndex:it,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(ht=>Ye(new Error(ht.message)))}}class Zn{constructor({actor:de,layerIndex:fe,availableImages:Oe,availableModels:Ye,brightness:Je,worldview:rt}){this.actor=de,this.layerIndex=fe,this.availableImages=Oe,this.availableModels=Ye,this.brightness=Je,this.loading={},this.loaded={},this.worldview=rt}loadTile(de,fe){const Oe=de.uid,Ye=this.loading[Oe]=new As(de,this.brightness,this.worldview);f.b1(de.request,(Je,rt)=>{const dt=!this.loading[Oe];return delete this.loading[Oe],dt||Je?(Ye.status="done",dt||(this.loaded[Oe]=Ye),fe(Je)):rt&&rt.byteLength!==0?void Ye.parse(rt,this.layerIndex,de,(it,ht)=>{Ye.status="done",this.loaded=this.loaded||{},this.loaded[Oe]=Ye,it||!ht?fe(it):fe(null,ht)}):(Ye.status="done",this.loaded[Oe]=Ye,fe())})}reloadTile(de,fe){const Oe=this.loaded,Ye=de.uid;if(Oe&&Oe[Ye]){const Je=Oe[Ye];Je.projection=de.projection,Je.brightness=de.brightness;const rt=(dt,it)=>{Je.reloadCallback&&(delete Je.reloadCallback,this.loadTile(de,fe)),fe(dt,it)};Je.status==="parsing"?Je.reloadCallback=rt:Je.status==="done"&&this.loadTile(de,fe)}}abortTile(de,fe){const Oe=de.uid;this.loading[Oe]&&delete this.loading[Oe],fe()}removeTile(de,fe){const Oe=this.loaded,Ye=de.uid;Oe&&Oe[Ye]&&delete Oe[Ye],fe()}}const fo=new Map,du=new Map;class Kx{constructor(de){this.self=de,this.actor=new f.A(de,this),this.layerIndexes={},this.availableImages={},this.availableModels={},this.isSpriteLoaded={},this.imageRasterizer=new f.z,this.rtlPluginParsingListeners=[],this.projections={},this.defaultProjection=f.c0({name:"mercator"}),this.workerSourceTypes={vector:Q,geojson:Ei,"raster-dem":ee,"raster-array":pe,"batched-model":Zn},this.workerSources={},this.self.registerWorkerSource=(fe,Oe)=>{if(this.workerSourceTypes[fe])throw new Error(`Worker source with name "${fe}" already registered.`);this.workerSourceTypes[fe]=Oe},this.self.registerRTLTextPlugin=fe=>{if(f.fF.isParsed())throw new Error("RTL text plugin already registered.");f.fF.setState({pluginStatus:f.fG.parsed,pluginURL:f.fF.getPluginURL()}),f.fF.applyArabicShaping=fe.applyArabicShaping,f.fF.processBidirectionalText=fe.processBidirectionalText,f.fF.processStyledBidirectionalText=fe.processStyledBidirectionalText;for(const Oe of this.rtlPluginParsingListeners)Oe(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(de,fe,Oe){delete this.layerIndexes[de],delete this.availableImages[de],delete this.availableModels[de],delete this.workerSources[de],Oe()}checkIfReady(de,fe,Oe){Oe()}setReferrer(de,fe){this.referrer=fe}spriteLoaded(de,fe){this.isSpriteLoaded[de]||(this.isSpriteLoaded[de]={});const{scope:Oe,isLoaded:Ye}=fe;if(this.isSpriteLoaded[de][Oe]=Ye,this.workerSources[de]&&this.workerSources[de][Oe])for(const Je in this.workerSources[de][Oe]){const rt=this.workerSources[de][Oe][Je];for(const dt in rt){const it=rt[dt];it instanceof Q&&(it.isSpriteLoaded=Ye,it.fire(new f.C("isSpriteLoaded")))}}}setImages(de,fe,Oe){this.availableImages[de]||(this.availableImages[de]={});const{scope:Ye,images:Je}=fe;if(this.availableImages[de][Ye]=Je,this.workerSources[de]&&this.workerSources[de][Ye]){for(const rt in this.workerSources[de][Ye]){const dt=this.workerSources[de][Ye][rt];for(const it in dt)dt[it].availableImages=Je}Oe()}else Oe()}setModels(de,{scope:fe,models:Oe},Ye){if(this.availableModels[de]||(this.availableModels[de]={}),this.availableModels[de][fe]=Oe,this.workerSources[de]&&this.workerSources[de][fe]){for(const Je in this.workerSources[de][fe]){const rt=this.workerSources[de][fe][Je];for(const dt in rt)rt[dt].availableModels=Oe}Ye()}else Ye()}setProjection(de,fe){this.projections[de]=f.c0(fe)}setBrightness(de,fe,Oe){this.brightness=fe,Oe()}setContextParams(de,fe,Oe){this.maxUniformBufferBindings=fe.maxBindingPoints,this.maxUniformBlockSizeDwords=fe.maxUniformBlockSizeDwords,this.disableSymbolUBO=fe.disableSymbolUBO,Oe()}setWorldview(de,fe,Oe){this.worldview=fe,Oe()}setLayers(de,fe,Oe){this.getLayerIndex(de,fe.scope).replace(fe.layers,fe.options),Oe()}updateLayers(de,fe,Oe){this.getLayerIndex(de,fe.scope).update(fe.layers,fe.removedIds,fe.options),Oe()}loadTile(de,fe,Oe){fe.projection=this.projections[de]||this.defaultProjection,this.getWorkerSource(de,fe).loadTile(fe,Oe)}decodeRasterArray(de,fe,Oe){this.getWorkerSource(de,fe).decodeRasterArray(fe,Oe)}reloadTile(de,fe,Oe){fe.projection=this.projections[de]||this.defaultProjection,this.getWorkerSource(de,fe).reloadTile(fe,Oe)}abortTile(de,fe,Oe){this.getWorkerSource(de,fe).abortTile(fe,Oe)}removeTile(de,fe,Oe){this.getWorkerSource(de,fe).removeTile(fe,Oe)}removeSource(de,fe,Oe){if(!(this.workerSources[de]&&this.workerSources[de][fe.scope]&&this.workerSources[de][fe.scope][fe.type]&&this.workerSources[de][fe.scope][fe.type][fe.source]))return;const Ye=this.workerSources[de][fe.scope][fe.type][fe.source];delete this.workerSources[de][fe.scope][fe.type][fe.source],Ye.removeSource!==void 0?Ye.removeSource(fe,Oe):Oe()}loadTileProvider(de,fe,Oe){(async function(Ye,Je){const rt=du.get(Ye);if(rt)return rt;const dt=fo.get(Ye);if(dt!==void 0)return dt;const it=import(Je).then(ht=>{const zt=ht.default;if(typeof zt!="function")throw new Error(`TileProvider "${Ye}" module must default-export a class`);if(typeof zt.prototype.loadTile!="function")throw new Error(`TileProvider "${Ye}" class must have a loadTile method`);return du.set(Ye,zt),zt}).finally(()=>{fo.delete(Ye)});return fo.set(Ye,it),it})(fe.name,fe.url).then(Ye=>{const Je=new Ye(fe.options);return this.getWorkerSource(de,{type:fe.type,source:fe.source,scope:fe.scope},Je),Je.load&&fe.request?Je.load({request:fe.request}):null}).then(Ye=>Oe(null,Ye)).catch(Ye=>Oe(Ye instanceof Error?Ye:new Error(typeof Ye=="string"?Ye:"Unknown error")))}loadWorkerSource(de,fe,Oe){try{this.self.importScripts(fe.url),Oe()}catch(Ye){Oe(Ye)}}syncRTLPluginState(de,fe,Oe){if(f.fF.isParsed())Oe(null,!0);else if(f.fF.isParsing())this.rtlPluginParsingListeners.push(Oe);else try{f.fF.setState(fe);const Ye=f.fF.getPluginURL();!f.fF.isLoaded()||f.fF.isParsed()||f.fF.isParsing()||Ye==null||(f.fF.setState({pluginStatus:f.fG.parsing,pluginURL:f.fF.getPluginURL()}),this.self.importScripts(Ye),f.fF.isParsed()?Oe(null,!0):this.rtlPluginParsingListeners.push(Oe))}catch(Ye){Oe(Ye)}}setConfig(de,fe){Object.assign(f.g,fe)}getAvailableImages(de,fe){this.availableImages[de]||(this.availableImages[de]={});let Oe=this.availableImages[de][fe];return Oe||(Oe=[]),Oe}getAvailableModels(de,fe){this.availableModels[de]||(this.availableModels[de]={});let Oe=this.availableModels[de][fe];return Oe||(Oe={}),Oe}getLayerIndex(de,fe){this.layerIndexes[de]||(this.layerIndexes[de]={});let Oe=this.layerIndexes[de][fe];return Oe||(Oe=this.layerIndexes[de][fe]=new E,Oe.scope=fe),Oe}getWorkerSource(de,fe,Oe){const{type:Ye,source:Je,scope:rt}=fe,dt=this.workerSources;if(dt[de]||(dt[de]={}),dt[de][rt]||(dt[de][rt]={}),dt[de][rt][Ye]||(dt[de][rt][Ye]={}),this.isSpriteLoaded[de]||(this.isSpriteLoaded[de]={}),!dt[de][rt][Ye][Je]){const it={send:(zt,Rt,hr,Fr,qr,$r)=>this.actor.send(zt,Rt,hr,de,qr,$r),scheduler:this.actor.scheduler},ht=this.workerSourceTypes[Ye];if(!ht)throw new Error(`Unknown worker source type "${Ye}".`);dt[de][rt][Ye][Je]=new ht({actor:it,layerIndex:this.getLayerIndex(de,rt),availableImages:this.getAvailableImages(de,rt),availableModels:this.getAvailableModels(de,rt),isSpriteLoaded:this.isSpriteLoaded[de][rt],tileProvider:Oe,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return dt[de][rt][Ye][Je]}rasterizeImagesWorker(de,fe,Oe){const Ye=new Map;for(const[Je,{image:rt,imageVariant:dt}]of fe.tasks.entries()){const it=this.imageRasterizer.rasterize(dt,rt,fe.scope,de);Ye.set(Je,it)}Oe(void 0,Ye)}removeRasterizedImages(de,fe,Oe){this.imageRasterizer.removeImagesFromCacheByIds(fe.imageIds,fe.scope,de),Oe()}enforceCacheSizeLimit(de,fe){f.fH(fe)}getWorkerPerformanceMetrics(de,fe,Oe){Oe(void 0,void 0)}}return f.fE(self)&&(self.worker=new Kx(self)),Kx}),o(["./shared"],function(a){var f="3.22.0";const p={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 T,E={},k=function(){if(T)return E;function _(w){return!d(w)}function d(w){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var I,L,F=new Blob([""],{type:"text/javascript"}),z=URL.createObjectURL(F);try{L=new Worker(z),I=!0}catch{I=!1}return L&&L.terminate(),URL.revokeObjectURL(z),I}()?function(){var I=document.createElement("canvas");I.width=I.height=1;var L=I.getContext("2d");if(!L)return!1;var F=L.getImageData(0,0,1,1);return F&&F.width===I.width}()?(g[j=w&&w.failIfMajorPerformanceCaveat]===void 0&&(g[j]=function(I){var L,F=function(z){var H=document.createElement("canvas"),Z=Object.create(_.webGLContextAttributes);return Z.failIfMajorPerformanceCaveat=z,H.getContext("webgl2",Z)}(I);if(!F)return!1;try{L=F.createShader(F.VERTEX_SHADER)}catch{return!1}return!(!L||F.isContextLost())&&(F.shaderSource(L,"void main() {}"),F.compileShader(L),F.getShaderParameter(L,F.COMPILE_STATUS)===!0)}(j)),g[j]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var j}T=1,E.supported=_,E.notSupportedReason=d;var g={};return _.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},E}();function P(_,d,g){const w=document.createElement(_);return d!=null&&(w.className=d),g&&g.appendChild(w),w}function R(_,d,g){const w=document.createElementNS("http://www.w3.org/2000/svg",_);for(const j of Object.keys(d))w.setAttributeNS(null,j,String(d[j]));return g&&g.appendChild(w),w}const D=typeof document<"u"?document.documentElement&&document.documentElement.style:null,M=D&&D.userSelect!==void 0?"userSelect":"WebkitUserSelect";let B;function V(){D&&M&&(B=D[M],D[M]="none")}function G(){D&&M&&(D[M]=B)}function W(_){_.preventDefault(),_.stopPropagation(),window.removeEventListener("click",W,!0)}function Y(){window.addEventListener("click",W,!0),window.setTimeout(()=>{window.removeEventListener("click",W,!0)},0)}function J(_,d){const g=_.getBoundingClientRect();return le(_,g,d)}function Q(_,d){const g=_.getBoundingClientRect(),w=[];for(let j=0;jthis._skuTokenExpiresAt}transformRequest(d,g){return this._transformRequestFn&&this._transformRequestFn(d,g)||{url:d}}normalizeStyleURL(d,g){if(!a.e(d))return d;const w=Ae(d);return w.params.push(`sdk=js-${f}`),w.path=`/styles/v1${w.path}`,this._makeAPIURL(w,this._customAccessToken||g)}normalizeGlyphsURL(d,g){if(!a.e(d))return d;const w=Ae(d);return w.path=`/fonts/v1${w.path}`,this._makeAPIURL(w,this._customAccessToken||g)}normalizeModelURL(d,g){if(!a.e(d))return d;const w=Ae(d);return w.path=`/models/v1${w.path}`,this._makeAPIURL(w,this._customAccessToken||g)}normalizeSourceURL(d,g,w,j){if(!a.e(d))return d;const I=Ae(d);return I.path=`/v4/${I.authority}.json`,I.params.push("secure"),w&&I.params.push(`language=${w}`),j&&I.params.push(`worldview=${j}`),this._makeAPIURL(I,this._customAccessToken||g)}normalizeIconsetURL(d,g){const w=Ae(d);return a.e(d)?(w.path=`/styles/v1${w.path}/iconset.pbf`,this._makeAPIURL(w,this._customAccessToken||g)):be(w)}normalizeSpriteURL(d,g,w,j){const I=Ae(d);return a.e(d)?(I.path=`/styles/v1${I.path}/sprite${g}${w}`,this._makeAPIURL(I,this._customAccessToken||j)):(I.path+=`${g}${w}`,be(I))}normalizeTileURL(d,g,w){if(this._isSkuTokenExpired()&&this._createSkuToken(),d&&!a.e(d))return d;const j=Ae(d);j.path=j.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${g||w&&j.authority!=="raster"&&w===512?"@2x":""}${a.k.supported?".webp":"$1"}`),j.authority==="raster"?j.path=`/${a.g.RASTER_URL_PREFIX}${j.path}`:j.authority==="rasterarrays"?j.path=`/${a.g.RASTERARRAYS_URL_PREFIX}${j.path}`:j.authority==="3dtiles"?j.path=`/${a.g.TILES3D_URL_PREFIX}${j.path}`:(j.path=j.path.replace(/^.+\/v4\//,"/"),j.path=`/${a.g.TILE_URL_VERSION}${j.path}`);const I=this._customAccessToken||function(L){for(const F of L){const z=F.match(/^access_token=(.*)$/);if(z)return z[1]}return null}(j.params)||a.g.ACCESS_TOKEN;return a.g.REQUIRE_ACCESS_TOKEN&&I&&this._skuToken&&j.params.push(`sku=${this._skuToken}`),this._makeAPIURL(j,I)}canonicalizeTileURL(d,g){const w=Ae(d);if(!w.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!w.path.match(/\.[\w]+$/))return d;let j="mapbox://";w.path.match(/^\/raster\/v1\//)?j+=`raster/${w.path.replace(`/${a.g.RASTER_URL_PREFIX}/`,"")}`:w.path.match(/^\/rasterarrays\/v1\//)?j+=`rasterarrays/${w.path.replace(`/${a.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:j+=`tiles/${w.path.replace(`/${a.g.TILE_URL_VERSION}/`,"")}`;let I=w.params;return g&&(I=I.filter(L=>!L.match(/^access_token=/))),I.length&&(j+=`?${I.join("&")}`),j}canonicalizeTileset(d,g){const w=!!g&&a.e(g),j=[];for(const I of d.tiles||[])a.f(I)?j.push(this.canonicalizeTileURL(I,w)):j.push(I);return j}_makeAPIURL(d,g){const w="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",j=Ae(a.g.API_URL);if(d.protocol=j.protocol,d.authority=j.authority,d.protocol==="http"){const I=d.params.indexOf("secure");I>=0&&d.params.splice(I,1)}if(j.path!=="/"&&(d.path=`${j.path}${d.path}`),!a.g.REQUIRE_ACCESS_TOKEN)return be(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. ${w}`);if(g[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${w}`)}return d.params=d.params.filter(I=>I.indexOf("access_token")===-1),d.params.push(`access_token=${g||""}`),be(d)}}const Le=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function Ae(_){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 be(_){const d=_.params.length?`?${_.params.join("&")}`:"";return`${_.protocol}://${_.authority}${_.path}${d}`}const me="mapbox.eventData";function Te(_){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 Ne(_){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=Te(a.g.ACCESS_TOKEN);let w="";return w=g&&g.u?a.j(g.u):a.g.ACCESS_TOKEN||"",d?`${me}.${d}:${w}`:`${me}:${w}`}fetchEventData(){const d=a.s("localStorage"),g=this.getStorageKey(),w=this.getStorageKey("uuid"),j=this.getStorageKey("uuidTimestamp");if(d)try{const I=localStorage.getItem(g);I&&(this.eventData=JSON.parse(I));const L=localStorage.getItem(w);L&&(this.anonId=L);const F=localStorage.getItem(j);F&&(this.anonIdTimestamp=Number(F));const z=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(g,JSON.stringify(this.eventData)),L&&localStorage.setItem(j,L.toString())}catch{a.w("Unable to write to LocalStorage")}}processRequests(d){}postEvent(d,g,w,j){if(!a.g.EVENTS_URL)return;const I=Ae(a.g.EVENTS_URL);I.params.push(`access_token=${j||a.g.ACCESS_TOKEN||""}`);const L={event:this.type,created:new Date(d).toISOString()},F=g?Object.assign(L,g):L,z={url:be(I),headers:{"Content-Type":"text/plain"},body:JSON.stringify([F])};this.pendingRequest=a.p(z,H=>{this.pendingRequest=null,w(H),this.saveEventData(),this.processRequests(j)})}queueRequest(d,g){this.queue.push(d),this.processRequests(g)}}class we extends Ee{constructor(d){super("metrics"),d&&(this.data=d)}postMetricsEvent(d){if(!Ne(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:w}=this.queue.shift();this.postEvent(g,w,()=>{},d)}}const He=new class extends Ee{constructor(_){super("appUserTurnstile"),this._customAccessToken=_}postTurnstileEvent(_,d){Ne(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=Te(a.g.ACCESS_TOKEN),g=d?d.u:a.g.ACCESS_TOKEN;let w=g!==this.eventData.tokenU;a.v(this.anonId)||(this.refreshUUID(),w=!0);const j=this.queue.shift();if(this.eventData.lastSuccess){const I=new Date(this.eventData.lastSuccess),L=new Date(j),F=(j-this.eventData.lastSuccess)/864e5;w=w||F>=1||F<-1||I.getDate()!==L.getDate()}else w=!0;w?this.postEvent(j,{sdkIdentifier:"mapbox-gl-js",sdkVersion:f,skuId:pe,"enabled.telemetry":!1,userId:this.anonId},I=>{I||(this.eventData.lastSuccess=j,this.eventData.tokenU=g)},_):this.processRequests()}},tt=He.postTurnstileEvent.bind(He),at=new class extends Ee{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(_,d,g,w){this.skuToken=d,this.errorCb=w,a.g.EVENTS_URL&&(g||a.g.ACCESS_TOKEN?this.queueRequest({id:_,timestamp:Date.now()},g):this.errorCb(new Error(Se)))}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:pe,skuToken:this.skuToken,userId:this.anonId},w=>{w?this.errorCb(w):d&&(this.success[d]=!0)},_))}remove(){this.errorCb=null}},Et=at.postMapLoadEvent.bind(at),vt=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:w,importedStyles:j}=d;if(!Ne(_))return;const I=this.getMapInstanceId(g),L={mapInstanceId:I,eventId:this.getEventId(I),style:w};j.length&&(L.importedStyles=j),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=vt.postStyleLoadEvent.bind(vt),pt=new we({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Pt=pt.postMetricsEvent.bind(pt),tr=new we({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),_t=tr.postMetricsEvent.bind(tr),cr=new class extends Ee{constructor(){super("gljs.performance")}postPerformanceEvent(_,d){Ne(_)&&this.queueRequest({timestamp:Date.now(),performanceData:d},_)}processRequests(_){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:d,performanceData:g}=this.queue.shift(),w=function(j){const I=performance.getEntriesByType("resource"),L=performance.getEntriesByType("mark"),F=function(se){const ce={};if(se){for(const oe in se)if(oe!=="other")for(const ye of se[oe]){const ge=`${oe}ResolveRangeMin`,Pe=`${oe}ResolveRangeMax`,De=`${oe}RequestCount`,_e=`${oe}RequestCachedCount`;ce[ge]=Math.min(ce[ge]||1/0,ye.startTime),ce[Pe]=Math.max(ce[Pe]||-1/0,ye.responseEnd);const Ze=$e=>{ce[$e]===void 0&&(ce[$e]=0),++ce[$e]};ye.transferSize!==void 0&&ye.transferSize===0&&Ze(_e),Ze(De)}}return ce}(function(se,ce){const oe={};if(se)for(const ye of se){const ge=ce(ye);oe[ge]===void 0&&(oe[ge]=[]),oe[ge].push(ye)}return oe}(I,v)),z=window.devicePixelRatio,H=navigator.connection||navigator.mozConnection||navigator.webkitConnection,Z=H?H.effectiveType:void 0,ne={counters:[],metadata:[],attributes:[]},re=(se,ce,oe)=>{oe!=null&&se.push({name:ce,value:oe.toString()})};for(const se in F)re(ne.counters,se,F[se]);if(j.interactionRange[0]!==1/0&&j.interactionRange[1]!==-1/0&&(re(ne.counters,"interactionRangeMin",j.interactionRange[0]),re(ne.counters,"interactionRangeMax",j.interactionRange[1])),L)for(const se of Object.values(p)){const ce=L.find(oe=>oe.name===se);ce&&re(ne.counters,se,ce.startTime)}return re(ne.counters,"visibilityHidden",j.visibilityHidden),re(ne.attributes,"style",function(se){if(se)for(const ce of se){const oe=ce.name.split("?")[0];if(a.i(oe)){const ye=oe.split("/").slice(-2);if(ye.length===2)return`mapbox://styles/${ye[0]}/${ye[1]}`}}}(I)),re(ne.attributes,"terrainEnabled",j.terrainEnabled?"true":"false"),re(ne.attributes,"fogEnabled",j.fogEnabled?"true":"false"),re(ne.attributes,"projection",j.projection),re(ne.attributes,"zoom",j.zoom),re(ne.metadata,"devicePixelRatio",z),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",j.width/z),re(ne.metadata,"mapHeight",j.height/z),re(ne.metadata,"webglRenderer",j.renderer),re(ne.metadata,"webglVendor",j.vendor),re(ne.metadata,"sdkVersion",f),re(ne.metadata,"sdkIdentifier","mapbox-gl-js"),ne}(g);for(const j of w.metadata);for(const j of w.counters);for(const j of w.attributes);this.postEvent(d,w,()=>{},_)}},Tr=cr.postPerformanceEvent.bind(cr),sn=new class extends Ee{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(_,d,g,w){if(!a.g.API_URL||!a.g.SESSION_PATH)return;const j=Ae(a.g.API_URL+a.g.SESSION_PATH);j.params.push(`sku=${d||""}`),j.params.push(`access_token=${w||a.g.ACCESS_TOKEN||""}`);const I={url:be(j),headers:{"Content-Type":"text/plain"}};this.pendingRequest=a.h(I,L=>{this.pendingRequest=null,g(L),this.saveEventData(),this.processRequests(w)})}getSessionAPI(_,d,g,w){this.skuToken=d,this.errorCb=w,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(Se)))}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,w=>{w?this.errorCb(w):d&&(this.success[d]=!0)},_)}remove(){this.errorCb=null}},ur=sn.getSessionAPI.bind(sn),xr=new Set;function rr(_,d){d?xr.add(_):xr.delete(_)}class vn{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 ct(_){const{userImage:d}=_;return!!(d&&d.render&&d.render())&&(_.data.replace(new Uint8Array(d.data.buffer)),!0)}const jt={workerUrl:"",workerClass:null,workerParams:void 0};function er(_){return jt.workerClass!=null?new jt.workerClass:new self.Worker(jt.workerUrl,Object.assign({name:_},jt.workerParams))}const Pr="mapboxgl_preloaded_worker_pool";class dr{constructor(d){this.active={},this.name=d}acquire(d,g=dr.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{g.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[Pr]}numActive(){return Object.keys(this.active).length}}dr.workerCount=2;class ar{constructor(d,g,w="Worker",j=dr.workerCount){this.workerPool=d,this.actors=[],this.currentActor=0,this.id=a.r();const I=this.workerPool.acquire(this.id,j);for(let L=0;L{this.ready=!0})}broadcast(d,g,w){a.t(this.actors,(j,I)=>{j.send(d,g,I)},w=w||function(){})}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(d=>{d.remove()}),this.actors=[],this.workerPool.release(this.id)}}let Nt,gr;function En(){return Nt||(Nt=new dr),Nt}ar.Actor=a.A;class ni 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 ar((gr||(gr=new dr("ImageRasterizer")),gr),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 w of g.values())w.hasPendingRequests()&&d.push(w);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:w,callback:j}of this.requestors)this._notify(w,g,j);this.requestors=[]}}hasImage(d,g){return!!this.getImage(d,g)}getImage(d,g){return this.images.get(g).get(d.toString())}addImage(d,g,w){if(this._validate(d,w)){this.images.get(g).set(d.toString(),w);const j=this.imageVersions.get(g),I=j.get(d.toString())||0;j.set(d.toString(),I+1)}}_validate(d,g){let w=!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`))),w=!1),this._validateStretch(g.stretchY,g.data&&g.data.height)||(this.fire(new a.B(new Error(`Image "${d.name}" has invalid "stretchY" value`))),w=!1),this._validateContent(g.content,g)||(this.fire(new a.B(new Error(`Image "${d.name}" has invalid "content" value`))),w=!1),w}_validateStretch(d,g){if(!d)return!0;let w=0;for(const j of d){if(j[0]a.I.from(g))}getImageVersions(d){const g=this.imageVersions.get(d);if(g)return g}getImages(d,g,w){const j=[],I=[],L=this.imageProviders.get(g);for(const Z of d){if(!Z.iconsetId){j.push(Z);continue}const ne=L.get(Z.iconsetId);ne&&(this.getImage(Z,g)?I.push(Z):ne.addPendingRequest(Z))}if(j.length===0)return void this._notify(I,g,w);let F=!0;const z=!!this.loaded.get(g),H=this.images.get(g);if(!z)for(const Z of j)H.has(Z.toString())||(F=!1);z||F?this._notify(j,g,w):this.requestors.push({ids:j,scope:g,callback:w})}rasterizeImages(d,g){const w=new Map,{tasks:j,scope:I}=d;for(const[L,F]of j.entries()){const z=this.getImage(F.id,I);z&&w.set(L,{image:z,imageVariant:F})}this._rasterizeImages(I,w,g)}_rasterizeImages(d,g,w){if(a.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:g,scope:d},w);else{const j=new Map;for(const[I,{image:L,imageVariant:F}]of g.entries())j.set(I,this.imageRasterizer.rasterize(F,L,d,0));w(void 0,j)}}getUpdatedImages(d){return this.updatedImages.get(d)||new Set}_notify(d,g,w){const j=this.images.get(g),I=new Map;for(const L of d){if(!j.get(L.toString())){if(L.iconsetId)continue;this.fire(new a.C("styleimagemissing",{id:L.name}))}const F=j.get(L.toString());if(!F){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 z={data:F.usvg?null:F.data.clone(),pixelRatio:F.pixelRatio,sdf:F.sdf,usvg:F.usvg,stretchX:F.stretchX,stretchY:F.stretchY,content:F.content,hasRenderCallback:!!(F.userImage&&F.userImage.render)};F.usvg&&Object.assign(z,{width:F.icon.usvg_tree.width,height:F.icon.usvg_tree.height}),I.set(a.I.toString(L),z)}w(null,{images:I,versions:this.getImageVersions(g)})}getPixelSize(d){const{width:g,height:w}=this.atlasImage.get(d);return{width:g,height:w}}getPattern(d,g,w){const j=d.toString(),I=this.patterns.get(g),L=I.get(j),F=this.getImage(d,g);if(!F)return null;if(L){if(L.position.version===F.version)return L.position;L.position.version=F.version}else{if(F.usvg&&!F.data){const z=this.getPatternInFlightId(j,g);if(this.patternsInFlight.has(z))return null;this.patternsInFlight.add(z);const H=new a.D(d).scaleSelf(a.o.devicePixelRatio),Z=new Map([[H.toString(),{image:F,imageVariant:H}]]);return this._rasterizeImages(g,Z,(ne,re)=>this.storePatternImage(H,g,F,w,re)),null}this.storePattern(d,g,F)}return this._updatePatternAtlas(g,w),I.get(j).position}getPatternInFlightId(d,g){return a.F(d,g)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(d,g,w,j,I){const L=d.toString(),F=I?I.get(L):void 0;F&&(w.data=F,this.storePattern(d.id,g,w),this._updatePatternAtlas(g,j),this.patternsInFlight.delete(this.getPatternInFlightId(d.id.toString(),g)))}storePattern(d,g,w){const j={w:w.data.width+2*a.G,h:w.data.height+2*a.G,x:0,y:0},I=new a.H(j,w,a.G);this.patterns.get(g).set(d.toString(),{bin:j,position:I})}destroyAtlasTextures(){for(const d of this.atlasTexture.values())d&&d.destroy();this.atlasTexture.clear()}bind(d,g){const w=d.gl;let j=this.atlasTexture.get(g);j?this.dirty&&(j.update(this.atlasImage.get(g)),this.dirty=!1):(j=new a.T(d,this.atlasImage.get(g),w.RGBA8),this.atlasTexture.set(g,j)),j.bind(w.LINEAR,w.CLAMP_TO_EDGE)}_updatePatternAtlas(d,g){const w=this.patterns.get(d),j=Array.from(w.values()).map(({bin:H})=>H),{w:I,h:L}=a.J(j),F=this.atlasImage.get(d);F.resize({width:I||1,height:L||1});const z=this.images.get(d);for(const[H,{bin:Z,position:ne}]of w.entries()){let re=ne.padding;const se=Z.x+re,ce=Z.y+re,oe=z.get(H).data,ye=oe.width,ge=oe.height;re=re>1?re-1:re,a.q.copy(oe,F,{x:0,y:0},{x:se,y:ce},{width:ye,height:ge},g),a.q.copy(oe,F,{x:0,y:ge-re},{x:se,y:ce-re},{width:ye,height:re},g),a.q.copy(oe,F,{x:0,y:0},{x:se,y:ce+ge},{width:ye,height:re},g),a.q.copy(oe,F,{x:ye-re,y:0},{x:se-re,y:ce},{width:re,height:ge},g),a.q.copy(oe,F,{x:0,y:0},{x:se+ye,y:ce},{width:re,height:ge},g),a.q.copy(oe,F,{x:ye-re,y:ge-re},{x:se-re,y:ce-re},{width:re,height:re},g),a.q.copy(oe,F,{x:0,y:ge-re},{x:se+ye,y:ce-re},{width:re,height:re},g),a.q.copy(oe,F,{x:0,y:0},{x:se+ye,y:ce+ge},{width:re,height:re},g),a.q.copy(oe,F,{x:ye-re,y:0},{x:se-re,y:ce+ge},{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 w=this.images.get(g);for(const j of d){if(this.callbackDispatchedThisFrame.get(g).has(j.toString()))continue;this.callbackDispatchedThisFrame.get(g).add(j.toString());const I=w.get(j.toString());ct(I)&&this.updateImage(j,g,I)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function ii(_){const d=_.value,g=_.valueSpec,w=_.style,j=_.styleSpec,I=_.key,L=_.arrayElementValidator||Ei;if(!Array.isArray(d))return[new a.V(I,d,`array expected, ${a.M(d)} found`)];if(g.length&&d.length!==g.length)return[new a.V(I,d,`array length ${g.length} expected, length ${d.length} found`)];if(g["min-length"]&&d.lengthj)return[new a.V(d,g,`${g} is greater than the maximum value ${j}`)]}return[]}function Ta(_){const d=_.key,g=_.value;if(!a.K(g))return[new a.V(d,g,`object expected, ${a.M(g)} found`)];const w=_.valueSpec,j=a.L(g.type);let I,L,F,z={};const H=j!=="categorical"&&g.property===void 0,Z=!H,ne=function(oe){const ye=oe.stops;return Array.isArray(ye)&&Array.isArray(ye[0])&&a.K(ye[0][0])}(g),re=As({key:_.key,value:_.value,valueSpec:_.styleSpec.function,style:_.style,styleSpec:_.styleSpec,objectElementValidators:{stops:function(oe){if(j==="identity")return[new a.V(oe.key,oe.value,'identity function may not have a "stops" property')];let ye=[];const ge=oe.value;return ye=ye.concat(ii({key:oe.key,value:ge,valueSpec:oe.valueSpec,style:oe.style,styleSpec:oe.styleSpec,arrayElementValidator:se})),Array.isArray(ge)&&ge.length===0&&ye.push(new a.V(oe.key,ge,"array must have at least one stop")),ye},default:function(oe){return Ei({key:oe.key,value:oe.value,valueSpec:w,style:oe.style,styleSpec:oe.styleSpec})}}});return j==="identity"&&H&&re.push(new a.V(_.key,_.value,'missing required property "property"')),j==="identity"||g.stops||re.push(new a.V(_.key,_.value,'missing required property "stops"')),j==="exponential"&&w.expression&&!a.O(w)&&re.push(new a.V(_.key,_.value,"exponential functions not supported")),_.styleSpec.$version>=8&&(Z&&!a.Q(w)?re.push(new a.V(_.key,_.value,"property functions not supported")):H&&!a.S(w)&&re.push(new a.V(_.key,_.value,"zoom functions not supported"))),j!=="categorical"&&!ne||g.property!==void 0||re.push(new a.V(_.key,_.value,'"property" property is required')),re;function se(oe){let ye=[];const ge=oe.value,Pe=oe.key;if(!Array.isArray(ge))return[new a.V(Pe,ge,`array expected, ${a.M(ge)} found`)];if(ge.length!==2)return[new a.V(Pe,ge,`array length 2 expected, length ${ge.length} found`)];if(ne){if(!a.K(ge[0]))return[new a.V(Pe,ge,`object expected, ${a.M(ge[0])} found`)];const De=ge[0];if(De.zoom===void 0)return[new a.V(Pe,ge,"object stop key must have zoom")];if(De.value===void 0)return[new a.V(Pe,ge,"object stop key must have value")];const _e=a.L(De.zoom);if(typeof _e!="number")return[new a.V(Pe,De.zoom,"stop zoom values must be numbers")];if(F&&F>_e)return[new a.V(Pe,De.zoom,"stop zoom values must appear in ascending order")];_e!==F&&(F=_e,L=void 0,z={}),ye=ye.concat(As({key:`${Pe}[0]`,value:ge[0],valueSpec:{zoom:{}},style:oe.style,styleSpec:oe.styleSpec,objectElementValidators:{zoom:Ui,value:ce}}))}else ye=ye.concat(ce({key:`${Pe}[0]`,value:ge[0],style:oe.style,styleSpec:oe.styleSpec},ge));return a.U(a.W(ge[1]))?ye.concat([new a.V(`${Pe}[1]`,ge[1],"expressions are not allowed in function stops.")]):ye.concat(Ei({key:`${Pe}[1]`,value:ge[1],valueSpec:w,style:oe.style,styleSpec:oe.styleSpec}))}function ce(oe,ye){const ge=a.M(oe.value),Pe=a.L(oe.value),De=oe.value!==null?oe.value:ye;if(I){if(ge!==I)return[new a.V(oe.key,De,`${ge} stop domain type must match previous stop domain type ${I}`)]}else I=ge;if(ge!=="number"&&ge!=="string"&&ge!=="boolean"&&typeof Pe!="number"&&typeof Pe!="string"&&typeof Pe!="boolean")return[new a.V(oe.key,De,"stop domain value must be a number, string, or boolean")];if(ge!=="number"&&j!=="categorical"){let _e=`number expected, ${ge} found`;return a.Q(w)&&j===void 0&&(_e+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new a.V(oe.key,De,_e)]}return j!=="categorical"||ge!=="number"||typeof Pe=="number"&&isFinite(Pe)&&Math.floor(Pe)===Pe?j!=="categorical"&&ge==="number"&&typeof Pe=="number"&&typeof L=="number"&&L!==void 0&&Penew a.V(`${_.key}${w.key}`,_.value,w.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 ca(g,_);if(_.expressionContext==="appearance")return Nr(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 ca(_,d){const g=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(d.valueSpec&&d.valueSpec.expression)for(const j of d.valueSpec.expression.parameters)g.delete(j);if(g.size===0)return[];const w=[];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(j=>{w.push(...ca(j,d))}),w)}function Nr(_,d){const g=new Set;if(d.valueSpec&&d.valueSpec.expression)for(const j of d.valueSpec.expression.parameters)g.add(j);if(g.size===0)return[];const w=[];return _ instanceof a.a0&&!g.has(_.name)?[new a.V(d.key,d.value,`["${_.name}"] is not an allowed parameter`)]:(_.eachChild(j=>{w.push(...Nr(j,d))}),w)}function Vn(_){const d=_.key,g=_.value,w=_.valueSpec,j=[];return Array.isArray(w.values)?w.values.indexOf(a.L(g))===-1&&j.push(new a.V(d,g,`expected one of [${w.values.join(", ")}], ${JSON.stringify(g)} found`)):Object.keys(w.values).indexOf(a.L(g))===-1&&j.push(new a.V(d,g,`expected one of [${Object.keys(w.values).join(", ")}], ${JSON.stringify(g)} found`)),j}function Ks(_){return a.a4(a.W(_.value))?vi(Object.assign({},_,{expressionContext:"filter",valueSpec:_.styleSpec[`filter_${_.layerType||"fill"}`]})):Ea(_)}function Ea(_){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 w=_.styleSpec;let j=Vn({key:`${g}[0]`,value:d[0],valueSpec:w.filter_operator});const I=()=>{d.length>=2&&(a.a2(d[1])||j.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"&&j.push(new a.V(g,d,`"$type" cannot be use with operator "${d[0]}"`)),d.length!==3&&j.push(new a.V(g,d,`filter array for operator "${d[0]}" must have 3 elements`)),I();break;case"==":case"!=":d.length!==3&&j.push(new a.V(g,d,`filter array for operator "${d[0]}" must have 3 elements`)),I();break;case"in":case"!in":I();break;case"any":case"all":case"none":for(let L=1;L{H in g&&d.push(new a.V(w,g[H],`"${H}" is prohibited for ref layers`))}),j.layers.forEach(H=>{a.L(H.id)===F&&(z=H)}),z?z.ref?d.push(new a.V(w,g.ref,"ref cannot reference another ref layer")):L=a.L(z.type):typeof F=="string"&&d.push(new a.V(w,g.ref,`ref layer "${F}" not found`))}else if(L!=="background"&&L!=="sky"&&L!=="slot")if(g.source)if(a.a2(g.source)){const z=j.sources&&j.sources[g.source],H=z&&a.L(z.type);z?H==="vector"&&L==="raster"?d.push(new a.V(w,g.source,`layer "${g.id}" requires a raster source`)):H==="raster"&&L!=="raster"?d.push(new a.V(w,g.source,`layer "${g.id}" requires a vector source`)):H!=="vector"||g["source-layer"]?H==="raster-dem"&&L!=="hillshade"?d.push(new a.V(w,g.source,"raster-dem source can only be used with layer type 'hillshade'.")):H!=="raster-array"||["raster","raster-particle"].includes(L)?L==="line"&&g.paint&&(g.paint["line-gradient"]||g.paint["line-trim-offset"])&&H==="geojson"&&!z.lineMetrics?d.push(new a.V(w,g,`layer "${g.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):L==="raster-particle"&&H!=="raster-array"&&d.push(new a.V(w,g.source,`layer "${g.id}" requires a 'raster-array' source.`)):d.push(new a.V(w,g.source,"raster-array source can only be used with layer type 'raster'.")):d.push(new a.V(w,g,`layer "${g.id}" must specify a "source-layer"`)):d.push(new a.V(w,g.source,`source "${g.source}" not found`))}else d.push(new a.V(`${w}.source`,g.source,'"source" must be a string'));else d.push(new a.V(w,g,'missing required property "source"'));return d=d.concat(As({key:w,value:g,valueSpec:I.layer,style:_.style,styleSpec:_.styleSpec,objectElementValidators:{"*":()=>[],type:()=>Ei({key:`${w}.type`,value:g.type,valueSpec:I.layer.type,style:_.style,styleSpec:_.styleSpec,object:g,objectKey:"type"}),filter:z=>Ks(Object.assign({layerType:L},z)),layout:z=>As({layer:g,key:z.key,value:z.value,valueSpec:{},style:z.style,styleSpec:z.styleSpec,objectElementValidators:{"*":H=>fn(Object.assign({layerType:L},H))}}),paint:z=>As({layer:g,key:z.key,value:z.value,valueSpec:{},style:z.style,styleSpec:z.styleSpec,objectElementValidators:{"*":H=>Zr(Object.assign({layerType:L,layer:g},H))}}),appearances(z){const H=ii({key:z.key,value:z.value,valueSpec:z.valueSpec,style:z.style,styleSpec:z.styleSpec,arrayElementValidator:re=>function(se){const{key:ce,layer:oe,layerType:ye}=se,ge=a.L(se.value),Pe=a.L(ge.name),De=a.L(ge.condition),_e=As({key:ce,value:ge,valueSpec:se.styleSpec.appearance,style:se.style,styleSpec:se.styleSpec,objectElementValidators:{condition:Ze=>function($e){const Ke=[];return Ke.push(...vi({key:$e.key,value:$e.object.condition,valueSpec:a.a8.appearance.condition,expressionContext:"appearance"})),Ke}(Object.assign({layer:oe,layerType:ye},Ze)),properties:Ze=>function($e){const Ke=[],{styleSpec:Me,layer:Be,layerType:qe}=$e,st=Me[`paint_${qe}`],Qe=Me[`layout_${qe}`],xt=$e.object[$e.objectKey];for(const ft in xt){const Lt=ft in st?"paint":ft in Qe?"layout":void 0;if(!Lt){Ke.push(new a.V($e.key,ft,`unknown property "${ft}" for layer type "${qe}"`));continue}const Ft=Object.assign({},$e,{key:`${$e.key}.${ft}`,object:xt,objectKey:ft,layer:Be,layerType:qe,value:xt[ft],valueSpec:Lt==="paint"?st[ft]:Qe[ft]});Ke.push(...wo(Ft,Lt))}return Ke}(Object.assign({layer:oe,layerType:ye},Ze))}});return Pe!=="hidden"&&De===void 0&&_e.push(new a.V(se.key,"name",'Appearance with name different than "hidden" must have a condition')),_e}(Object.assign({layerType:L,layer:g},re))}),Z=Array.isArray(z.value)?z.value:[],ne=new Set;return Z.forEach((re,se)=>{const ce=a.L(re.name);if(ce)if(ne.has(ce)){const oe=a.L(g.id);H.push(new a.V(z.key,ce,`Duplicated appearance name "${ce}" for layer "${oe}"`))}else ne.add(ce)}),H}}})),d}function Xr({key:_,value:d}){return a.a2(d)?[]:[new a.V(_,d,`string expected, ${a.M(d)} found`)]}const ui={promoteId:function _({key:d,value:g}){if(a.a2(g))return Xr({key:d,value:g});if(Array.isArray(g)){const j=[],I=a.W(g),L=a.X(I);return L.result==="error"?(L.value.forEach(F=>{j.push(new a.V(`${d}${F.key}`,null,`${F.message}`))}),j):(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"])||j.push(new a.V(`${d}`,null,"promoteId expression should be only feature dependent")),j)}if(!a.K(g))return[new a.V(d,g,`string, expression or object expected, "${a.M(g)}" found`)];const w=[];for(const j in g)w.push(..._({key:`${d}.${j}`,value:g[j]}));return w}};function en(_){const d=_.value,g=_.key,w=_.styleSpec,j=_.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 I=a.L(d.type);let L=[];switch(["vector","raster","raster-dem","raster-array"].includes(I)&&("url"in d||"tiles"in d||L.push(new a.a5(g,d,'Either "url" or "tiles" is required.'))),I){case"vector":case"raster":case"raster-dem":case"raster-array":return L=L.concat(As({key:g,value:d,valueSpec:w[`source_${I.replace("-","_")}`],style:_.style,styleSpec:w,objectElementValidators:ui})),L;case"geojson":if(L=As({key:g,value:d,valueSpec:w.source_geojson,style:j,styleSpec:w,objectElementValidators:ui}),"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 F in d.clusterProperties){const z=d.clusterProperties[F];if(!Array.isArray(z))return[new a.V(`${g}.clusterProperties.${F}`,z,"array expected")];const[H,Z]=z,ne=typeof H=="string"?[H,["accumulated"],["get",F]]:H;L.push(...vi({key:`${g}.${F}.map`,value:Z,expressionContext:"cluster-map"})),L.push(...vi({key:`${g}.${F}.reduce`,value:ne,expressionContext:"cluster-reduce"}))}}return L;case"video":return As({key:g,value:d,valueSpec:w.source_video,style:j,styleSpec:w});case"image":return As({key:g,value:d,valueSpec:w.source_image,style:j,styleSpec:w});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 Vn({key:`${g}.type`,value:d.type,valueSpec:{values:Fn(w)}})}}function Fn(_){return _.source.reduce((d,g)=>{const w=_[g];return w.type.type==="enum"&&(d=d.concat(Object.keys(w.type.values||{}))),d},[])}function ts(_){const d=_.value,g=_.styleSpec,w=g.light,j=_.style;if(d===void 0)return[];if(!a.K(d))return[new a.V("light",d,`object expected, ${a.M(d)} found`)];let I=[];for(const L in d){const F=L.match(/^(.*)-transition$/),z=L.match(/^(.*)-use-theme$/);I=I.concat(z&&w[z[1]]?Ei({key:L,value:d[L],valueSpec:{type:"string"},style:j,styleSpec:g}):F&&w[F[1]]&&w[F[1]].transition?Ei({key:L,value:d[L],valueSpec:g.transition,style:j,styleSpec:g}):w[L]?Ei({key:L,value:d[L],valueSpec:w[L],style:j,styleSpec:g}):[new a.V(L,d[L],`unknown property "${L}"`)])}return I}function bl(_){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 w=[];const j=_.styleSpec,I=j["light-3d"],L=_.style,F=_.style.lights;for(const Z of["type","id"])if(!(Z in d))return w=w.concat([new a.V(g,d,`missing property "${Z}"`)]),w;if(!a.a2(d.type))return w=w.concat([new a.V(`${g}.type`,d.type,"string expected")]),w;if(F)for(let Z=0;Z<_.arrayIndex;Z++){const ne=a.L(d.type),re=F[Z];a.L(re.type)===ne&&w.push(new a.V(g,d.id,`duplicate light type "${d.type}", previously defined at line ${re.id.__line__}`))}const z=`properties_light_${d.type}`;if(!(z in j))return w=w.concat([new a.V(`${g}.type`,d,`Invalid light type ${d.type}`)]),w;const H=j[z];for(const Z in d)if(Z==="properties"){const ne=d[Z];if(!a.K(ne))return w=w.concat([new a.V("properties",ne,`object expected, ${a.M(ne)} found`)]),w;for(const re in ne){const se=re.match(/^(.*)-transition$/),ce=re.match(/^(.*)-use-theme$/);w=w.concat(ce&&H[ce[1]]?Ei({key:Z,value:ne[re],valueSpec:{type:"string"},style:L,styleSpec:j}):se&&H[se[1]]&&H[se[1]].transition?Ei({key:Z,value:d[Z],valueSpec:j.transition,style:L,styleSpec:j}):H[re]?Ei({key:re,value:ne[re],valueSpec:H[re],style:L,styleSpec:j}):[new a.a5(_.key,ne[re],`unknown property "${re}"`)])}}else w=w.concat(I[Z]?Ei({key:Z,value:d[Z],valueSpec:I[Z],style:L,styleSpec:j}):[new a.a5(Z,d[Z],`unknown property "${Z}"`)]);return w}function Jo(_){const d=_.value,g=_.key,w=_.style,j=_.styleSpec,I=j.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 F in d){const z=F.match(/^(.*)-transition$/),H=F.match(/^(.*)-use-theme$/);L=L.concat(H&&I[H[1]]?Ei({key:F,value:d[F],valueSpec:{type:"string"},style:w,styleSpec:j}):z&&I[z[1]]&&I[z[1]].transition?Ei({key:F,value:d[F],valueSpec:j.transition,style:w,styleSpec:j}):I[F]?Ei({key:F,value:d[F],valueSpec:I[F],style:w,styleSpec:j}):[new a.a5(F,d[F],`unknown property "${F}"`)])}if(d.source)if(a.a2(d.source)){const F=w.sources&&w.sources[d.source],z=F&&a.L(F.type);F?z!=="raster-dem"&&L.push(new a.V(`${g}.source`,d.source,`terrain cannot be used with a source of type ${z}, 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 Ot(_){const d=_.value,g=_.style,w=_.styleSpec,j=w.fog;if(d===void 0)return[];if(!a.K(d))return[new a.V("fog",d,`object expected, ${a.M(d)} found`)];let I=[];for(const L in d){const F=L.match(/^(.*)-transition$/),z=L.match(/^(.*)-use-theme$/);I=I.concat(z&&j[z[1]]?Ei({key:L,value:d[L],valueSpec:{type:"string"},style:g,styleSpec:w}):F&&j[F[1]]&&j[F[1]].transition?Ei({key:L,value:d[L],valueSpec:w.transition,style:g,styleSpec:w}):j[L]?Ei({key:L,value:d[L],valueSpec:j[L],style:g,styleSpec:w}):[new a.a5(L,d[L],`unknown property "${L}"`)])}return I}const Mo={"*":()=>[],array:ii,boolean:function(_){const d=_.value,g=_.key;return a.a1(d)?[]:[new a.V(g,d,`boolean expected, ${a.M(d)} found`)]},number:Ui,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:Vn,filter:Ks,function:Ta,layer:xn,object:As,source:en,model:a.a9,light:ts,"light-3d":bl,terrain:Jo,fog:Ot,string:Xr,formatted:function(_){return Xr(_).length===0?[]:vi(_)},resolvedImage:function(_){return Xr(_).length===0?[]:vi(_)},projection:function(_){const d=_.value,g=_.styleSpec,w=g.projection,j=_.style;if(a.K(d)){let I=[];for(const L in d)I=I.concat(Ei({key:L,value:d[L],valueSpec:w[L],style:j,styleSpec:g}));return I}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:w}=_;if(!a.K(g))return[new a.V(d,g,"import must be an object")];const{data:j,...I}=g;Object.defineProperty(I,"__line__",{value:g.__line__,enumerable:!1});let L=As(Object.assign({},_,{value:I,valueSpec:w.import}));return a.L(I.id)===""&&L.push(new a.V(`${_.key}.id`,I,"import id can't be an empty string")),j&&(L=L.concat(fo(j,w,{key:`${_.key}.data`}))),L},iconset:function(_){const d=_.value,g=_.key,w=_.styleSpec,j=_.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 I=a.L(d.type);let L=[];if(L=L.concat(As({key:g,value:d,valueSpec:w[`iconset_${I}`],style:j,styleSpec:w})),function(F,z){return!(F!=="source"||!z.source)}(I,d)){const F=j.sources&&j.sources[d.source],z=F&&a.L(F.type);F?z!=="raster-array"&&L.push(new a.V(g,d.source,`iconset cannot be used with a source of type ${String(z)}, 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 Ei(_,d=!1){const g=_.value,w=_.valueSpec,j=_.styleSpec;if(w.expression){if(a.a6(a.L(g)))return Ta(_);if(a.U(a.W(g)))return vi(_)}if(w.type&&Mo[w.type]){const I=Mo[w.type](_);return d===!0&&I.length>0&&Array.isArray(_.value)?vi(_):I}return As(Object.assign({},_,{valueSpec:w.type?j[w.type]:w}))}function As(_){const d=_.key,g=_.value,w=_.valueSpec||{},j=_.objectElementValidators||{},I=_.style,L=_.styleSpec;if(!a.K(g))return[new a.V(d,g,`object expected, ${a.M(g)} found`)];let F=[];for(const z in g){const H=z.split(".")[0];let Z;j[H]?Z=j[H]:w[H]?Z=Ei:j["*"]?Z=j["*"]:w["*"]&&(Z=Ei),Z?F=F.concat(Z({key:(d&&`${d}.`)+z,value:g[z],valueSpec:w[H]||w["*"],style:I,styleSpec:L,object:g,objectKey:z},g)):F.push(new a.a5(d,g[z],`unknown property "${z}"`))}for(const z in w){if(j[z])continue;const H=w[z];H.required&&H.default===void 0&&g[z]===void 0&&F.push(new a.V(d,g,`missing required property "${z}"`))}return F}function Zn({key:_,value:d}){const g=Xr({key:_,value:d});if(g.length)return g;const w=d;return w.indexOf("{fontstack}")===-1&&g.push(new a.V(_,d,'"glyphs" url must include a "{fontstack}" token')),w.indexOf("{range}")===-1&&g.push(new a.V(_,d,'"glyphs" url must include a "{range}" token')),g}function fo(_,d=a.a8,g={}){return As({key:g.key||"",value:_,valueSpec:Object.assign(d.$root,{"*":{type:"*"}}),styleSpec:d,style:_,objectElementValidators:{glyphs:Zn}})}function du(_,d=a.a8){return Rt(fo(_,d))}const Kx=_=>Rt(en(_)),ut=_=>Rt(ts(_)),de=_=>Rt(bl(_)),fe=_=>Rt(Jo(_)),Oe=_=>Rt(Ot(_)),Ye=_=>Rt(function(d){const g=d.value,w=d.style,j=d.styleSpec,I=j.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 F in g){const z=F.match(/^(.*)-transition$/);L=L.concat(z&&I[z[1]]&&I[z[1]].transition?Ei({key:F,value:g[F],valueSpec:j.transition,style:w,styleSpec:j}):I[F]?Ei({key:F,value:g[F],valueSpec:I[F],style:w,styleSpec:j}):[new a.a5(F,g[F],`unknown property "${F}"`)])}return L}(_)),Je=_=>Rt(function(d){const g=d.value,w=d.style,j=d.styleSpec,I=j.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 F in g){const z=F.match(/^(.*)-transition$/);L=L.concat(z&&I[z[1]]&&I[z[1]].transition?Ei({key:F,value:g[F],valueSpec:j.transition,style:w,styleSpec:j}):I[F]?Ei({key:F,value:g[F],valueSpec:I[F],style:w,styleSpec:j}):[new a.a5(F,g[F],`unknown property "${F}"`)])}return L}(_)),rt=_=>Rt(xn(_)),dt=_=>Rt(Ks(_)),it=_=>Rt(Zr(_)),ht=_=>Rt(fn(_)),zt=_=>Rt(a.a9(_));function Rt(_){return _.slice().sort((d,g)=>d.line&&g.line?d.line-g.line:0)}function hr(_,d){let g=!1;if(d&&d.length)for(const w of d)w instanceof a.a5?a.w(w.message):(_.fire(new a.B(new Error(w.message))),g=!0);return g}const Fr=a.a8.light;let qr;class $r extends a.E{constructor(d,g="flat"){super(),this._transitionable=new a.aa(qr||(qr=new a.ab({anchor:new a.ac(Fr.anchor),position:new a.ad(Fr.position),color:new a.ac(Fr.color),intensity:new a.ac(Fr.intensity)}))),this.setLight(d,g),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(d,g,w={}){this._validate(ut,d,w)||(this._transitionable.setTransitionOrValue(d),this.id=g)}updateTransitions(d){this._transitioning=this._transitionable.transitioned(d,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(d){this.properties=this._transitioning.possiblyEvaluate(d)}_validate(d,g,w){return(!w||w.validate!==!1)&&hr(this,d.call(du,Object.assign({value:g,style:{glyphs:!0,sprite:!0},styleSpec:a.a8})))}}const on=a.a8.terrain;let Cn=class extends a.E{constructor(_,d,g,w,j){super(),this.scope=g,this._transitionable=new a.aa(new a.ab({source:new a.ac(on.source),exaggeration:new a.ac(on.exaggeration)}),g,w),this._transitionable.setTransitionOrValue(_,w),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=d,this.worldview=j}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,w=-1,j=1;for(const I of d.zoomStops)j=d.evaluate(new a.ae(I,{worldview:this.worldview})),j>.01?(g=I,w=-1):w=I;return j<.01&&g>0&&w>g?[g,w]:null}isZoomDependent(){const _=this._transitionable._values.exaggeration;return _!=null&&_.value!=null&&_.value.expression!=null&&_.value.expression instanceof a.af}};const Ln=.05;function Di(_,d,g,w){const j=a.aj(45,65,g),[I,L]=Fs(_,w);let F=1-Math.min(1,Math.exp((d-I)/(L-I)*-6));return F*=F*F,F=Math.min(1,1.00747*F),F*j*_.alpha}function Fs(_,d){const g=.5/Math.tan(.5*d);return[_.range[0]+g,_.range[1]+g]}function ks(_,d,g,w,j){const I=a.ah([],[d,g,w],j.mercatorFogMatrix);return Di(_,a.ai(I),j.pitch,j._fov)}function gs(_,d,g,w,j,I,L){const F=[[g,w,0],[j,w,0],[j,I,0],[g,I,0]];let z=Number.MAX_VALUE,H=-Number.MAX_VALUE;for(const Z of F){const ne=a.ah([],Z,d),re=a.ai(ne);z=Math.min(z,re),H=Math.max(H,re)}return[Di(_,z,L.pitch,L._fov),Di(_,H,L.pitch,L._fov)]}const bi=a.a8.fog;class as extends a.E{constructor(d,g,w,j){super();const I=new a.ab({range:new a.ac(bi.range),color:new a.ac(bi.color),"color-use-theme":new a.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new a.ac(bi["high-color"]),"high-color-use-theme":new a.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new a.ac(bi["space-color"]),"space-color-use-theme":new a.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new a.ac(bi["horizon-blend"]),"star-intensity":new a.ac(bi["star-intensity"]),"vertical-range":new a.ac(bi["vertical-range"])});this._transitionable=new a.aa(I,w,new Map(j)),this.set(d,j),this._transitioning=this._transitionable.untransitioned(),this._transform=g,this.properties=new a.ak(I),this.scope=w}get state(){const d=this._transform,g=d.projection.name==="globe",w=a.al(d.zoom),j=this.properties.get("range"),I=[.5,3];return{range:g?[a.am(I[0],j[0],w),a.am(I[1],j[1],w)]:j,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(d,g,w={}){if(this._validate(Oe,d,w))return;const j=Object.assign({},d);for(const I of Object.keys(bi))j[I]===void 0&&(j[I]=bi[I].default);this._options=j,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(w,j,I){const L=a.ag.fromLngLat(j),F=I.elevation?I.elevation.getAtPointOrZero(L):0;return ks(w,L.x,L.y,F,I)}(this.state,d,g):0}getOpacityForTile(d){if(!this._transform.projection.supportsFog)return[1,1];const g=this._transform.calculateFogTileMatrix(d.toUnwrapped());return gs(this.state,g,0,0,a.an,a.an,this._transform)}getOpacityForBounds(d,g,w,j,I){return this._transform.projection.supportsFog?gs(this.state,d,g,w,j,I,this._transform):[1,1]}getFovAdjustedRange(d){return this._transform.projection.supportsFog?Fs(this.state,d):[0,1]}isVisibleOnFrustum(d){if(!this._transform.projection.supportsFog)return!1;const g=[4,5,6,7];for(const w of g){const j=d.points[w];let I;if(j[2]>=0)I=j;else{const L=d.points[w-4];I=a.ao(L,j,L[2]/(L[2]-j[2]))}if(ks(this.state,I[0],I[1],0,this._transform)>=Ln)return!0}return!1}updateConfig(d){this._transitionable.setTransitionOrValue(this._options,new Map(d))}updateTransitions(d){this._transitioning=this._transitionable.transitioned(d,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(d){this.properties=this._transitioning.possiblyEvaluate(d)}_validate(d,g,w){return(!w||w.validate!==!1)&&hr(this,d.call(du,Object.assign({value:g,style:{glyphs:!0,sprite:!0},styleSpec:a.a8})))}}let ua,Mi,os,ys=class extends a.E{constructor(_,d,g,w){super();const j=ua||(ua=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(j,g,new Map(w)),this.set(_,w),this._transitioning=this._transitionable.untransitioned(),this.properties=new a.ak(j),this.scope=g}get state(){const _=this.properties.get("opacity"),d=this.properties.get("color"),g=this.properties.get("direction"),w=a.ap(g[0]),j=-Math.max(a.ap(g[1]),.01),I=[Math.cos(w)*Math.cos(j),Math.sin(w)*Math.cos(j),Math.sin(j)],L=this.properties.get("vignette"),F=this.properties.get("vignette-color");return F.a=L,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new a.aq(d.r,d.g,d.b,d.a*_),direction:I,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:F}}get(){return this._transitionable.serialize()}set(_,d,g={}){if(this._validate(Ye,_,g))return;const w=Object.assign({},_),j=a.a8.snow;for(const I of Object.keys(j))w[I]===void 0&&(w[I]=j[I].default);this._options=w,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)&&hr(this,_.call(du,Object.assign({value:d,style:{glyphs:!0,sprite:!0},styleSpec:a.a8})))}},Mn=class extends a.E{constructor(_,d,g,w){super();const j=Mi||(Mi=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(j,g,new Map(w)),this.set(_,w),this._transitioning=this._transitionable.untransitioned(),this.properties=new a.ak(j),this.scope=g}get state(){const _=this.properties.get("opacity"),d=this.properties.get("color"),g=this.properties.get("direction"),w=a.ap(g[0]),j=-Math.max(a.ap(g[1]),.01),I=[Math.cos(w)*Math.cos(j),Math.sin(w)*Math.cos(j),Math.sin(j)],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:I,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:L}}get(){return this._transitionable.serialize()}set(_,d,g={}){if(this._validate(Je,_,g))return;const w=Object.assign({},_),j=a.a8.rain;for(const I of Object.keys(j))w[I]===void 0&&(w[I]=j[I].default);this._options=w,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)&&hr(this,_.call(du,Object.assign({value:d,style:{glyphs:!0,sprite:!0},styleSpec:a.a8})))}};class ja extends a.E{constructor(d,g,w,j){super(),this.scope=w,this._options=d,this.properties=new a.ak(g),this._transitionable=new a.aa(g,w,new Map(j)),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 So=()=>os||(os=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 mo;const cc=()=>mo||(mo=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 uc{constructor(d,g,w){this.screenBounds=d,this.cameraPoint=w.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=g,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,w)}static createFromScreenPoints(d,g){let w,j;if(d instanceof a.P||typeof d[0]=="number"){const I=a.P.convert(d);w=[I],j=g.isPointAboveHorizon(I)}else{const I=a.P.convert(d[0]),L=a.P.convert(d[1]),F=I.add(L)._div(2);w=[I,L],j=a.as(I,L).every(z=>g.isPointAboveHorizon(z))&&g.isPointAboveHorizon(F)}return new uc(w,j,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],w=this.screenBounds.length===1?this.screenBounds[0].add(new a.P(1,1)):this.screenBounds[1],j=a.as(g,w,0,!1);return this.cameraPoint.y>w.y&&(this.cameraPoint.x>g.x&&this.cameraPoint.x=w.x?j[2]=this.cameraPoint:this.cameraPoint.x<=g.x&&(j[3]=this.cameraPoint)),a.at(j,d)}bufferedCameraGeometryGlobe(d){const g=this.screenBounds[0],w=this.screenBounds.length===1?this.screenBounds[0].add(new a.P(1,1)):this.screenBounds[1],j=a.as(g,w,d),I=this.cameraPoint.clone(),L=+(I.x>g.x)+ +(I.x>w.x);switch(3*(+(I.y>g.y)+ +(I.y>w.y))+L){case 0:j[0]=I,j[4]=I.clone();break;case 1:j.splice(1,0,I);break;case 2:j[1]=I;break;case 3:j.splice(4,0,I);break;case 5:j.splice(2,0,I);break;case 6:j[3]=I;break;case 7:j.splice(3,0,I);break;case 8:j[2]=I}return j}containsTile(d,g,w,j=0){const I=Math.max(d.queryPadding,d.evaluateQueryRenderedFeaturePadding())/g._pixelsPerMercatorPixel+1,L=w?this._bufferedCameraMercator(I,g):this._bufferedScreenMercator(I,g);let F=d.tileID.wrap+(L.unwrapped?j:0);const z=L.polygon.map(ye=>a.au(d.tileTransform,ye,F));if(!a.av(z,0,0,a.an,a.an))return;F=d.tileID.wrap+(this.screenGeometryMercator.unwrapped?j:0);const H=this.screenGeometryMercator.polygon.map(ye=>a.aw(d.tileTransform,ye,F)),Z=H.map(ye=>new a.P(ye[0],ye[1])),ne=g.getFreeCameraOptions().position||new a.ag(0,0,0),re=a.aw(d.tileTransform,ne,F),se=H.map(ye=>{const ge=a.ax(ye,ye,re);return a.ay(ge,ge),new a.az(re,ge)}),ce=a.aA(d,1,g.zoom)*g._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:Z,tilespaceRays:se,bufferedTilespaceGeometry:z,bufferedTilespaceBounds:(oe=a.aB(z),oe.min.x=a.aC(oe.min.x,0,a.an),oe.min.y=a.aC(oe.min.y,0,a.an),oe.max.x=a.aC(oe.max.x,0,a.an),oe.max.y=a.aC(oe.max.y,0,a.an),oe),tile:d,tileID:d.tileID,pixelToTileUnitsFactor:ce};var oe}_bufferedScreenMercator(d,g){const w=dc(d);if(this._screenRaycastCache[w])return this._screenRaycastCache[w];{let j;return j=g.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(d),g):{polygon:this.bufferedScreenGeometry(d).map(I=>g.pointCoordinate3D(I)),unwrapped:!0},this._screenRaycastCache[w]=j,j}}_bufferedCameraMercator(d,g){const w=dc(d);if(this._cameraRaycastCache[w])return this._cameraRaycastCache[w];{let j;return j=g.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(d),g):{polygon:this.bufferedCameraGeometry(d).map(I=>g.pointCoordinate3D(I)),unwrapped:!0},this._cameraRaycastCache[w]=j,j}}_projectAndResample(d,g){const w=function(I,L){const F=a.aD([],L.pixelMatrix,L.globeMatrix),z=[0,-a.aF,0,1],H=[0,a.aF,0,1],Z=[0,0,0,1];a.aE(z,z,F),a.aE(H,H,F),a.aE(Z,Z,F);const ne=new a.P(z[0]/z[3],z[1]/z[3]),re=new a.P(H[0]/H[3],H[1]/H[3]),se=a.aG(I,ne)&&z[3]1?kd(I.slice(0,ye),L):[],De=yenew a.P(wl(Ke.x),Ke.y)),De=De.map(Ke=>new a.P(wl(Ke.x),Ke.y));const _e=[...Pe];_e.length===0&&_e.push(De[De.length-1]);const Ze=a.am(_e[_e.length-1].y,(De.length===0?Pe[0]:De[0]).y,ge);let $e;return $e=se?[new a.P(0,Ze),new a.P(0,0),new a.P(1,0),new a.P(1,Ze)]:[new a.P(1,Ze),new a.P(1,1),new a.P(0,1),new a.P(0,Ze)],_e.push(...$e),De.length===0?_e.push(Pe[0]):_e.push(...De),{polygon:_e.map(Ke=>new a.ag(Ke.x,Ke.y)),unwrapped:!1}}(d,g);if(w)return w;const j=function(I,L){let F=!1,z=-1/0,H=0;for(let ne=0;nez&&(z=I[ne].x,H=ne);for(let ne=0;ne.5&&(se.x{ne.x-=1}),{polygon:I,unwrapped:F}}(kd(d,g).map(I=>new a.P(wl(I.x),I.y)),g);return{polygon:j.polygon.map(I=>new a.ag(I.x,I.y)),unwrapped:j.unwrapped}}}function kd(_,d){return a.aI(_,g=>{const w=d.pointCoordinate3D(g);g.x=w.x,g.y=w.y},1/256)}function wl(_){return _<0?1+_%1:_%1}function dc(_){return 100*_|0}function Cd(_,d,g){try{d=function(j){if(!j.variants)return j;if(!Array.isArray(j.variants))throw new Error("variants must be an array");for(const I of j.variants){if(I==null||typeof I!="object"||I.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(I.capabilities))throw new Error("capabilities must be an array");if(I.capabilities.length===1&&I.capabilities[0]==="meshopt")return Object.assign(j,I)}return j}(d)}catch(j){return new Error("Failed to process TileJSON variants",{cause:j})}const w=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&&(w.tiles=d.tiles),w.tiles=g.canonicalizeTileset(w,_.url),w}function kc(_,d,g,w,j){const I=function(F,z){if(F)return j(F);if(z){_.url&&z.tiles&&_.tiles&&delete _.tiles;const H=Cd(_,z,d);if(H instanceof Error)return j(H);j(null,H)}},L=function(F,z,H){if(!F)return null;if(!z&&!H)return F;H=H||F.worldview_default;const Z=Object.values(F.language||{});if(Z.length===0)return null;const ne=Object.values(F.worldview||{});if(ne.length===0)return null;const re=Z.every(ce=>ce===z),se=ne.every(ce=>ce===H);return re&&se?F:z in(F.language_options||{})||H in(F.worldview_options||{})?null:F.language_options&&F.worldview_options?F:null}(_.data,g,w);return L?a.o.frame(()=>I(null,L)):_.url?a.m(d.transformRequest(d.normalizeSourceURL(_.url,null,g,w),a.R.Source),I):a.o.frame(()=>{const{data:F,...z}=_;I(null,z)})}function Nd(_,d){const g=Math.pow(2,d.z),w=Math.floor(a.aH(_.getWest())*g),j=Math.floor(a.aL(_.getNorth())*g),I=Math.ceil(a.aH(_.getEast())*g),L=Math.ceil(a.aL(_.getSouth())*g);return d.x>=w&&d.x=j&&d.ythis.maxzoom||d.z{this._tileJSONRequest=null,this._loaded=!0,L?(g&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${g}`),w&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${w}`),this.fire(new a.B(L))):F&&(this._setTileJSON(F),tt(F.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 I=function(L){if("provider"in L&&!L.provider)return null;let F=L.provider;if(!F&&"url"in L&&L.url&&(F=a.aM(L.url)),!F)return null;const z=a.g.TILE_PROVIDER_URLS[F];if(!z)return null;let H;try{H=new URL(z,a.g.API_URL).href}catch{return a.w(`TileProvider "${F}" has an invalid URL: "${z}"`),null}return{name:F,url:H}}(this._options);if(this.provider&&!I)return this._loaded=!0,this.fire(new a.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(d&&d());this._tileJSONRequest=I?this._loadWithProvider(I,j):kc(this._options,this.map._requestManager,g,w,j)}_loadWithProvider(d,g){this.provider=d.name;const w=new AbortController,j=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,a.R.Source):void 0,I=j?Object.assign({},this._options,{url:j.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:d.name,url:d.url,source:this.id,scope:this.scope,type:this.type,options:I,request:j},(L,F)=>{if(w.signal.aborted)return;if(L)return void g(L);const z=F?F.find(H=>H!=null):null;if(z){const H=Cd(this._options,z,this.map._requestManager);H instanceof Error?g(H):g(null,H)}else g(null,{tiles:this._options.tiles})}),{cancel:()=>{w.abort()}}}_setTileJSON(d){if(Object.assign(this,d),this.hasWorldviews=!!d.worldview_options,d.worldview_default&&(this.worldviewDefault=d.worldview_default),d.vector_layers){this.vectorLayers=d.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const g of d.vector_layers)this.vectorLayerIds.push(g.id),d.worldview&&d.worldview[g.source]&&this.localizableLayerIds.add(g.id)}this.tileBounds=hu.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 w=d.tileID.canonical.url(this.tiles,this.scheme),j=this.map._requestManager.normalizeTileURL(w),I=this.map._requestManager.transformRequest(j,a.R.Tile),L=this.map.style?this.map.style.getLut(this.scope):null,F=L?{image:L.image.clone()}:null,z={request:I,data:void 0,uid:d.uid,tileID:d.tileID,tileZoom:d.tileZoom,zoom:d.tileID.overscaledZ,maxZoom:this.maxzoom,lut:F,tileSize:this.tileSize*d.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio: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(w)&&(z.localizableLayerIds=this.localizableLayerIds),z.request.collectResourceTiming=this._collectResourceTiming,d.actor&&d.state!=="expired")d.state==="loading"?d.reloadCallback=g:d.request=d.actor.send("reloadTile",z,H.bind(this));else if(d.actor=this._tileWorkers[j]=this._tileWorkers[j]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)d.request=d.actor.send("loadTile",z,H.bind(this),void 0,!0);else{const Z=a.aO.call({deduped:this._deduped},z,(ne,re)=>{if(ne||!re)H.call(this,ne);else{const se=a.aP(re.responseHeaders);z.data={rawData:re.rawData.slice(0),expires:se.expires,cacheControl:se.cacheControl},d.actor&&d.actor.send("loadTile",z,H.bind(this),void 0,!0)}},!0);d.request={cancel:Z}}function H(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 Yx extends a.E{constructor(d,g,w,j){super(),this.id=d,this.dispatcher=w,this.setEventedParent(j),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=kc(this._options,this.map._requestManager,null,g,(w,j)=>{this._tileJSONRequest=null,this._loaded=!0,w?this.fire(new a.B(w)):j&&(Object.assign(this,j),j.raster_layers&&(this.rasterLayers=j.raster_layers,this.rasterLayerIds=this.rasterLayers.map(I=>I.id)),this.tileBounds=hu.fromTileJSON(j),tt(j.tiles),this.fire(new a.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new a.C("data",{dataType:"source",sourceDataType:"content"}))),d&&d(w)})}loaded(){return this._loaded}onAdd(d){this.map=d,this.load()}reload(){this.cancelTileJSONRequest();const d=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 w=a.o.devicePixelRatio>=2,j=this.map._requestManager.normalizeTileURL(d.tileID.canonical.url(this.tiles,this.scheme),w,this.tileSize);d.request=a.n(this.map._requestManager.transformRequest(j,a.R.Tile),(I,L,F)=>{if(delete d.request,d.aborted)return d.state="unloaded",g(null);if(I)return d.state="errored",g(I);if(!L)return g(null);const z=a.aP(F);this.map._refreshExpiredTiles&&d.setExpiryData(z),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 DT([_,d],g,w,{scaled:j=!0}={}){const{tileSize:I,buffer:L}=w,{x:F,y:z,z:H}=g;if(!isFinite(F)||!isFinite(z)||!isFinite(H))throw new Error("Invalid MRT header");const Z=2**H,ne=Z*a.aH(_),re=Z*a.aL(d);return function([se,ce],oe,{scaled:ye=!0}={}){if(!oe)throw new Error("bandView is undefined");const{data:ge,tileSize:Pe,buffer:De,offset:_e,scale:Ze,dimension:$e}=oe;if(se<-De||se>Pe+De||ce<-De||ce>Pe+De)throw new Error(`Point (${se}, ${ce}) out of bounds for tileSize=${Pe}, buffer=${De}`);const Ke=(ce+De)*(Pe+2*De)+(se+De);if(new Uint32Array(ge.buffer)[Ke]===4294967295)return null;let Me=[];Me=ye?[]:new oe.data.constructor($e);for(let Be=0;Be<$e;Be++)Me[Be]=Math.round(1e12*(ge[$e*Ke+Be]*Ze+_e))/1e12;return Me}([Math.min(Math.max(-L,Math.floor((ne-F)*I)),I-1+L),Math.min(Math.max(-L,Math.floor((re-z)*I)),I-1+L)],w,{scaled:j})}class Fm extends Yx{constructor(d,g,w,j){super(d,g,w,j),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,w=this.map.style.getSourceCache(this.id);g&&g.enabled&&w&&g._clearRenderCacheForTile(w.id,d.tileID),this.map.triggerRepaint()}loadTile(d,g){const w=this.map._requestManager.normalizeTileURL(d.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),j=this.map._requestManager.transformRequest(w,a.R.Tile),I={request:j,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=j,d.actor||(d.actor=this.dispatcher.getActor());const L=(F,z,H)=>{if(delete d.request,d.aborted)return d.state="unloaded",g(null);if(F)return F.name==="AbortError"?void 0:(d.state="errored",g(F));if(this.map._refreshExpiredTiles&&z){const Z=a.aP(H);d.setExpiryData(Z)}if(this.partial&&d.state!=="expired")d.state="empty";else if(!this.partial){if(!z)return g(null);d.state="loaded",d._isHeaderLoaded=!0,d._mrt=z}g(null)};d.request=this.partial?d.fetchHeader(void 0,L.bind(this)):d.actor.send("loadTile",I,L.bind(this),void 0,!0)}abortTile(d){d.request&&(d.request.cancel(),delete d.request),d.actor&&d.actor.send("abortTile",{uid:d.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(d,g){const w=d.texturePerLayer;if(d.flushAllQueues(),w.size){d.destroy(!1);for(const j of w.values())this.map.painter.saveTileTexture(j)}else d.destroy()}prepareTile(d,g,w,j){d._isHeaderLoaded&&(d.state!=="empty"&&(d.state="reloading"),d.fetchBandForRender(g,w,j,(I,L)=>{I?(d.state="errored",this.fire(new a.B(I))):L&&(d._isHeaderLoaded=!0,d.setTexturePerLayer(w,L,this.map.painter),d.state="loaded"),this.triggerRepaint(d)}))}getInitialBand(d){if(!this.rasterLayers)return 0;const g=this.rasterLayers.find(({id:I})=>I===d),w=g&&g.fields,j=w&&w.bands&&w.bands;return j?j[0]:0}getTextureDescriptor(d,g,w){if(!d)return;const j=g.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!j)return;let I=null;g instanceof a.aS?I=g.paint.get("raster-array-band"):g instanceof a.aT&&(I=g.paint.get("raster-particle-array-band"));const L=I||this.getInitialBand(j);if(L==null)return;if(!d.textureDescriptorPerLayer.get(g.id))return void this.prepareTile(d,j,g.id,L);if(d.updateNeeded(g.id,L)&&!w)return;const F=d.textureDescriptorPerLayer.get(g.id);return Object.assign({},F,{texture:d.texturePerLayer.get(g.id)})}getImages(d,g){const w=new Map;for(const j of d)for(const I of g){const[L,F]=I.split("/"),z=j.getLayer(L);if(!z||!z.hasBand(F)||!z.hasDataForBand(F))continue;const{bytes:H,tileSize:Z,buffer:ne}=z.getBandView(F),re=Z+2*ne,se={data:new a.q({width:re,height:re},H),pixelRatio:2,sdf:!1,usvg:!1,version:0};w.set(I,se)}return w}queryRasterArrayValueByBandId(d,g,w){const j=g._mrt;return new Promise(I=>{const L={},F=new Set;for(const[z,H]of Object.entries(j.layers)){if(w.layerName&&z!==w.layerName)continue;const Z={};L[z]=Z;for(const{bands:ne}of H.dataIndex)for(const re of ne)w.bands&&!w.bands.includes(re)||(F.add(a.F(z,re)),g.fetchBand(z,null,re,se=>{a.o.frame(()=>{Z[re]=se?null:DT([d.lng,d.lat],j,H.getBandView(re)),F.delete(a.F(z,re)),F.size===0&&I(L)})},!1))}F.size===0&&I(L)})}_loadTileForQuery(d,g){if(this._loadTileLoaded[d.uid])return void g(null,d._mrt);if(this._loadTilePending[d.uid])return void this._loadTilePending[d.uid].push(g);this._loadTilePending[d.uid]=[g];const w=this.map._requestManager.normalizeTileURL(d.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),j=this.map._requestManager.transformRequest(w,a.R.Tile);d.actor.send("loadTile",{request:j,uid:d.uid,tileID:d.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(I,L,F)=>{if(I)return this._loadTilePending[d.uid].forEach(z=>z(I,null)),void delete this._loadTilePending[d.uid];if(!L)return this._loadTilePending[d.uid].forEach(z=>z(null,null)),void delete this._loadTilePending[d.uid];if(this.map._refreshExpiredTiles&&L){const z=a.aP(F);d.setExpiryData(z)}d._mrt=L,d._isHeaderLoaded=!0,d.state="loaded",this._loadTilePending[d.uid].forEach(z=>z(null,L)),this._loadTileLoaded[d.uid]=!0,delete this._loadTilePending[d.uid]},void 0,!0)}queryRasterArrayValueByAllBands(d,g,w){return new Promise((j,I)=>{this._loadTileForQuery(g,(L,F)=>{L?I(L):j(F?this.queryRasterArrayValueByBandId(d,g,w):null)})})}queryRasterArrayValue(d,g){const w=a.aU.convert(d),j=this.findLoadedParent(w);return j&&j._mrt?g.bands||!this.partial?this.queryRasterArrayValueByBandId(w,j,g):this.queryRasterArrayValueByAllBands(w,j,g):Promise.resolve(null)}findLoadedParent(d){const g=a.ag.fromLngLat(d,this.map.transform.tileSize),w=this.maxzoom+1,j=1<0&&(F[new a.aR(_.overscaledZ,j,d.z,w,d.y-1).key]={backfilled:!1},F[new a.aR(_.overscaledZ,_.wrap,d.z,d.x,d.y-1).key]={backfilled:!1},F[new a.aR(_.overscaledZ,L,d.z,I,d.y-1).key]={backfilled:!1}),d.y+1{if(this._loaded=!0,this._pendingLoad=null,w)this.fire(new a.B(w));else{const I={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&j&&j.resourceTiming&&j.resourceTiming[this.id]&&(I.resourceTiming=j.resourceTiming[this.id]),_&&(this._partialReload=!0),this.fire(new a.C("data",I)),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 w=this.map.style?this.map.style.getLut(this.scope):null,j=w?{image:w.image.clone()}:null,I=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:j,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:I,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};_.request=this.actor.send(g,L,(F,z)=>I&&!z?(_.state="loaded",d(null)):(delete _.request,_.destroy(!1),_.aborted?d(null):F?d(F):(_.loadVectorData(z,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,w){super(_,d,g,w),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,w){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(w)}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=kc(this._options,this.map._requestManager,d,g,(w,j)=>{this._tileJSONRequest=null,this._loaded=!0,w?(d&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${d}`),g&&g.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${g}`),this.fire(new a.B(w))):j&&(Object.assign(this,j),j.bounds&&(this.tileBounds=new hu(j.bounds,this.minzoom,this.maxzoom)),tt(j.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"}))),_&&_(w)})}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)),w={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 I=Object.values(_.buckets);for(const L of I)L.dirty=!0;return void(_.state="loaded")}_.request=_.actor.send("reloadTile",w,j.bind(this))}else _.actor=this.dispatcher.getActor(),_.request=_.actor.send("loadTile",w,j.bind(this),void 0,!0);function j(I,L){return _.aborted?d(null):I&&I.status!==404?d(I):(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,w){super(_,d,g,w),d.coordinates?Array.isArray(d.coordinates)&&d.coordinates.length===4&&!d.coordinates.some(j=>!Array.isArray(j)||j.length!==2||j.some(I=>typeof I!="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,w){super(),this.id=_,this.type="custom",this._dataType="raster",this._dispatcher=g,this._implementation=d,this.setEventedParent(w),this.scheme="xyz",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new 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 hu(this._implementation.bounds,this.minzoom,this.maxzoom));const j=d;j.update=this._update.bind(this),j.clearTiles=this._clearTiles.bind(this),j.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:w}=_.canonical;return this._implementation.hasTile({x:d,y:g,z:w})}return!this.tileBounds||this.tileBounds.contains(_.canonical)}loadTile(_,d){const{x:g,y:w,z:j}=_.tileID.canonical,I=new AbortController,L=Promise.resolve(this._implementation.loadTile({x:g,y:w,z:j},{signal:I.signal})).then((function(F){return delete _.request,_.aborted?(_.state="unloaded",d(null)):F===void 0?(_.state="errored",d(null)):F===null?(this.loadTileData(_,{width:this.tileSize,height:this.tileSize,data:null}),_.state="loaded",d(null)):function(z){return z instanceof ImageData||z instanceof HTMLCanvasElement||z instanceof ImageBitmap||z instanceof HTMLImageElement}(F)?(this.loadTileData(_,F),_.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(F=>{F.name!=="AbortError"&&(_.state="errored",d(F))});L.cancel=()=>I.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:w,z:j}=_.tileID.canonical;this._implementation.unloadTile({x:g,y:w,z:j})}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"}))}}},P_=function(_,d,g,w){const j=new I_[d.type](_,d,g,w);if(j.id!==_)throw new Error(`Expected Source id to be ${_} instead of ${j.id}`);return a.aZ(["load","abort","unload","serialize","prepare"],j),j};function MT(_,d,g=""){return`${g}:${d.id||""}:${d.layer.id}:${function(w){if("layerId"in w)return`layer:${w.layerId}`;{const{featuresetId:j,importId:I}=w;return`featureset:${j}${I?`:import:${I}`:""}`}}(_.target)}`}function Id(_,d,g,w=""){if(_.uniqueFeatureID){const j=MT(_,d,w);if(g.has(j))return!0;g.add(j)}return!1}function fN(_,d,g,w,j=!1,I=void 0){const L=d.sourceCache.transform,F=d.sourceCache.tilesIn(_,d.has3DLayers,j);F.sort(L_);const z=[];for(const H of F){const Z=H.tile.queryRenderedFeatures(d,H,g,w,L,j,I);Object.keys(Z).length&&z.push({wrappedTileID:H.tile.tileID.wrapped().key,queryResults:Z})}for(const H in d.layers){const Z=d.layers[H];if(Z.styleLayer){const ne=Z.styleLayer.queryRenderedFeatures(_,d.sourceCache,w);Object.keys(ne).length&&z.push({wrappedTileID:0,queryResults:ne})}}return z.length===0?{}:function(H){const Z={},ne={};for(const re of H){const se=re.queryResults,ce=re.wrappedTileID,oe=ne[ce]=ne[ce]||{};for(const ye in se){const ge=se[ye],Pe=oe[ye]=oe[ye]||{},De=Z[ye]=Z[ye]||[];for(const _e of ge)Pe[_e.featureIndex]||(Pe[_e.featureIndex]=!0,De.push(_e))}}return Z}(z)}function R_(_,d,g,w,j,I){const L={},F=w.queryRenderedSymbols(_),z=[];for(const H of Object.keys(F).map(Number))z.push(j[H]);z.sort(L_);for(const H of z){const Z=H.featureIndex.lookupSymbolFeatures(F[H.bucketInstanceId],H.bucketIndex,H.sourceLayerIndex,d,g,I);for(const ne in Z){const re=L[ne]=L[ne]||[],se=Z[ne];se.sort((ce,oe)=>{const ye=H.featureSortOrder;if(ye){const ge=ye.indexOf(ce.featureIndex);return ye.indexOf(oe.featureIndex)-ge}return oe.featureIndex-ce.featureIndex});for(const ce of se)re.push(ce)}}return L}function OT(_,d){const g=_.getRenderableIds().map(I=>_.getTileByID(I)),w=[],j={};for(let I=0;I{if(I)g(I);else try{const z=w.getHeaderLength(L);if(z>d)return void(this.request=this.fetchHeader(z,g));w.parseHeader(L),this._isHeaderLoaded=!0;let H=0;for(const Z of Object.values(w.layers))H=Math.max(H,Z.dataIndex[Z.dataIndex.length-1].lastByte);L.byteLength>=H&&(this.entireBuffer=L),g(null,this.entireBuffer||L,F)}catch(z){g(z)}}),this.request}fetchBandForRender(d,g,w,j){this.fetchBand(d,g,w,I=>{if(I)return void j(I);this.updateTextureDescriptor(d,g,w);const L=this.textureDescriptorPerLayer.get(g);j(null,L?L.img:null)})}fetchBand(d,g,w,j,I=!0){const L=this._mrt;if(!this._isHeaderLoaded||!L)return void j(new Error("Tile header is not ready"));const F=this.actor;if(!F)return void j(new Error("Can't fetch tile band without an actor"));let z;const H=a.F(String(w),a.F(this.tileID.key,d));let Z=this._taskQueue.get(H);Z?Z.add(j):(Z=new Set,Z.add(j),this._taskQueue.set(H,Z));const ne=(oe,ye)=>{z.complete(oe,ye),oe?j(oe):(Z.forEach(ge=>ge(null,ye)),this._taskQueue.delete(H))},re=(oe,ye)=>{if(oe)return j(oe);const ge=F.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:ye,task:z},ne,void 0,!0);if(g!==null){const Pe=this._workQueuePerLayer.get(g)||[];Pe.push(()=>{ge&&ge.cancel(),z.cancel()}),this._workQueuePerLayer.has(g)||this._workQueuePerLayer.set(g,Pe)}};let se;try{se=L.getLayer(d)}catch(oe){if(this.state==="reloading")return;throw oe}if(!se)return void j(new Error(`Unknown sourceLayer "${d}"`));if(se.hasDataForBand(w))return Z.forEach(oe=>oe(null,null)),void this._taskQueue.delete(H);const ce=se.getDataRange([w]);if(z=L.createDecodingTask(ce),!z||z.tasks.length)if(g!==null&&this.flushQueues(g),this.entireBuffer)re(null,this.entireBuffer.slice(ce.firstByte,ce.lastByte+1));else{const oe=Object.assign({},this.requestParams,{headers:{Range:`bytes=${ce.firstByte}-${ce.lastByte}`}}),ye=a.b1(oe,re);if(g!==null){const ge=this._fetchQueuePerLayer.get(g)||[];ge.push(()=>{ye.cancel(),z.cancel()}),this._fetchQueuePerLayer.has(g)||this._fetchQueuePerLayer.set(g,ge)}}}updateNeeded(d,g){return(!this.textureDescriptorPerLayer.get(d)||this.textureDescriptorPerLayer.get(d).band!==g||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(d,g,w){if(!this._mrt)return;const j=this._mrt.getLayer(d);if(!j||!j.hasBand(w)||!j.hasDataForBand(w))return;const{bytes:I,tileSize:L,buffer:F,offset:z,scale:H}=j.getBandView(w),Z=L+2*F,ne=new a.q({width:Z,height:Z},I),re=this.texturePerLayer.get(g);re&&re instanceof a.T&&re.update(ne,{premultiply:!1}),this.textureDescriptorPerLayer.set(g,{layer:d,band:w,img:ne,buffer:F,offset:z,tileSize:L,format:j.pixelFormat,mix:[H,256*H,65536*H,16777216*H]})}destroy(d=!1){if(super.destroy(d),delete this._mrt,!d)for(const g of this.texturePerLayer.values())g&&g instanceof 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 _g{constructor(d,g){this.max=d,this.onRemove=g,this.reset()}reset(){for(const d in this.data)for(const g of this.data[d])g.timeout&&clearTimeout(g.timeout),this.onRemove(g.value);return this.data={},this.order=[],this}add(d,g,w){const j=d.wrapped().key;this.data[j]===void 0&&(this.data[j]=[]);const I={value:g,timeout:void 0};if(w!==void 0&&(I.timeout=setTimeout(()=>{this.remove(d,I)},w)),this.data[j].push(I),this.order.push(j),this.order.length>this.max){const L=this._getAndRemoveByKey(this.order[0]);L&&this.onRemove(L)}return this}has(d){return d.wrapped().key in this.data}getAndRemove(d){return this.has(d)?this._getAndRemoveByKey(d.wrapped().key):null}_getAndRemoveByKey(d){const g=this.data[d].shift();return g.timeout&&clearTimeout(g.timeout),this.data[d].length===0&&delete this.data[d],this.order.splice(this.order.indexOf(d),1),g.value}getByKey(d){const g=this.data[d];return g?g[0].value:null}get(d){return this.has(d)?this.data[d.wrapped().key][0].value:null}remove(d,g){if(!this.has(d))return this;const w=d.wrapped().key,j=g===void 0?0:this.data[w].indexOf(g),I=this.data[w][j];return this.data[w].splice(j,1),I.timeout&&clearTimeout(I.timeout),this.data[w].length===0&&delete this.data[w],this.onRemove(I.value),this.order.splice(this.order.indexOf(w),1),this}setMaxSize(d){for(this.max=d;this.order.length>this.max;){const g=this._getAndRemoveByKey(this.order[0]);g&&this.onRemove(g)}return this}filter(d){const g=[];for(const w in this.data)for(const j of this.data[w])d(j.value)||g.push(j);for(const w of g)this.remove(w.value.tileID,w)}}class FT{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(d,g,w){const j=String(g);if(this.stateChanges[d]=this.stateChanges[d]||{},this.stateChanges[d][j]=this.stateChanges[d][j]||{},Object.assign(this.stateChanges[d][j],w),this.deletedStates[d]===null){this.deletedStates[d]={};for(const I in this.state[d])I!==j&&(this.deletedStates[d][I]=null)}else if(this.deletedStates[d]&&this.deletedStates[d][j]===null){this.deletedStates[d][j]={};for(const I in this.state[d][j])w[I]||(this.deletedStates[d][j][I]=null)}else for(const I in w)this.deletedStates[d]&&this.deletedStates[d][j]&&this.deletedStates[d][j][I]===null&&delete this.deletedStates[d][j][I]}removeFeatureState(d,g,w){if(this.deletedStates[d]===null)return;const j=String(g);if(this.deletedStates[d]=this.deletedStates[d]||{},w&&g!==void 0)this.deletedStates[d][j]!==null&&(this.deletedStates[d][j]=this.deletedStates[d][j]||{},this.deletedStates[d][j][w]=null);else if(g!==void 0)if(this.stateChanges[d]&&this.stateChanges[d][j])for(w in this.deletedStates[d][j]={},this.stateChanges[d][j])this.deletedStates[d][j][w]=null;else this.deletedStates[d][j]=null;else this.deletedStates[d]=null}getState(d,g){const w=this.state[d]||{},j=this.stateChanges[d]||{},I=this.deletedStates[d];if(I===null)return{};if(g!==void 0){const F=String(g),z=Object.assign({},w[F],j[F]);if(I){const H=I[g];if(H===null)return{};for(const Z in H)delete z[Z]}return z}const L=Object.assign({},w,j);if(I)for(const F in I)delete L[F];return L}initializeTileState(d,g){d.refreshFeatureState(g)}coalesceChanges(d,g){const w={};for(const j in this.stateChanges){this.state[j]=this.state[j]||{};const I={};for(const L in this.stateChanges[j])this.state[j][L]||(this.state[j][L]={}),Object.assign(this.state[j][L],this.stateChanges[j][L]),I[L]=this.state[j][L];w[j]=I}for(const j in this.deletedStates){this.state[j]=this.state[j]||{};const I={};if(this.deletedStates[j]===null)for(const L in this.state[j])I[L]={},this.state[j][L]={};else for(const L in this.deletedStates[j]){if(this.deletedStates[j][L]===null)this.state[j][L]={};else if(this.state[j][L])for(const F of Object.keys(this.deletedStates[j][L]))delete this.state[j][L][F];I[L]=this.state[j][L]}w[j]=w[j]||{},Object.assign(w[j],I)}if(this.stateChanges={},this.deletedStates={},Object.keys(w).length!==0)for(const j in d)d[j].refreshFeatureState(g,w)}}class fu extends a.E{constructor(d,g,w){super(),this.id=d,this._renderSourceType=w,this._maxzoomOverride=null,g.on("data",j=>{j.dataType==="source"&&j.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&j.dataType==="source"&&j.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),g.on("error",()=>{this._sourceErrored=!0}),this._source=g,this._tiles={},this._cache=new _g(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 FT,this._isRaster=this._source.type==="raster"||this._source.type==="raster-dem"||this._source.type==="raster-array"||this._source.type==="custom"&&"_dataType"in this._source&&this._source._dataType==="raster",this._supportsFading=this._source.type==="raster"||this._source.type==="raster-array"||this._source.type==="image"||this._source.type==="video"||this._source.type==="custom",this._isRasterElevatedOverTerrain=!1}onAdd(d){this.map=d,this._minTileCacheSize=this._minTileCacheSize===void 0&&d?d._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&d?d._maxTileCacheSize:this._maxTileCacheSize}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const d in this._tiles)if(!this._tiles[d].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const d=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,d&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(d){this._maxzoomOverride=d}_loadTile(d,g){return d.renderSourceType=this._renderSourceType,d.isExtraShadowCaster=this._shadowCasterTiles[d.tileID.key],this._source.loadTile(d,g)}_unloadTile(d){if(this._source.unloadTile)return this._source.unloadTile(d)}_abortTile(d){if(this._source.abortTile)return this._source.abortTile(d)}serialize(){return this._source.serialize()}prepare(d){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const g in this._tiles){const w=this._tiles[g];w.upload(d,this.map?this.map.painter:void 0),w.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(d=>d.tileID).sort(BT).map(d=>d.key)}getRenderableIds(d,g){const w=[];for(const j in this._tiles)this._isIdRenderable(+j,d,g)&&w.push(this._tiles[j]);return d?w.sort((j,I)=>{const L=j.tileID,F=I.tileID,z=new a.P(L.canonical.x,L.canonical.y)._rotate(this.transform.angle),H=new a.P(F.canonical.x,F.canonical.y)._rotate(this.transform.angle);return L.overscaledZ-F.overscaledZ||H.y-z.y||H.x-z.x}).map(j=>j.tileID.key):w.map(j=>j.tileID).sort(BT).map(j=>j.key)}hasRenderableParent(d){const g=this.findLoadedParent(d,0);return!!g&&this._isIdRenderable(g.tileID.key)}_isIdRenderable(d,g,w){return this._tiles[d]&&this._tiles[d].hasData()&&!this._coveredTiles[d]&&(g||!this._tiles[d].holdingForFade())&&(w||!this._shadowCasterTiles[d])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const d in this._tiles)this._tiles[d].state!=="errored"&&this._reloadTile(+d,"reloading")}}_reloadTile(d,g){const w=this._tiles[d];w&&(w.state!=="loading"&&(w.state=g),this._loadTile(w,this._tileLoaded.bind(this,w,d,g)))}_tileLoaded(d,g,w,j,I){if(j){if(d.state="errored",a.b2(j)){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 F=this.map.painter.terrain;this.update(this.transform,F.getScaledDemTileSize(),!0),F.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new a.B(j,{tile:d}));return}d.timeAdded=a.o.now(),w==="expired"&&(d.refreshedUponExpiration=!0),this._setTileReloadTimer(g,d),this._source.type==="raster-dem"&&d.dem&&this._backfillDEM(d),this._state.initializeTileState(d,this.map?this.map.painter:null);let L=new Map;I&&I.responseHeaders&&(L=I.responseHeaders),this._source.fire(new 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 j=0;j1||(Math.abs(L)>1&&(Math.abs(L+z)===1?L+=z:Math.abs(L-z)===1&&(L-=z)),I.dem&&j.dem&&(j.dem.backfillBorder(I.dem,L,F),j.neighboringTiles&&j.neighboringTiles[H]&&(j.neighboringTiles[H].backfilled=!0)))}}getTile(d){return this.getTileByID(d.key)}getTileByID(d){return this._tiles[d]}_retainLoadedChildren(d,g,w,j){for(const I in this._tiles){let L=this._tiles[I];if(j[I]||!L.hasData()||L.tileID.overscaledZ<=g||L.tileID.overscaledZ>w)continue;let F=L.tileID;for(;L&&L.tileID.overscaledZ>g+1;){const H=L.tileID.scaledTo(L.tileID.overscaledZ-1);L=this._tiles[H.key],L&&L.hasData()&&(F=H)}let z=F;for(;z.overscaledZ>g;)if(z=z.scaledTo(z.overscaledZ-1),d[z.key]){j[F.key]=F;break}}}findLoadedParent(d,g){if(d.key in this._loadedParentTiles){const w=this._loadedParentTiles[d.key];return w&&w.tileID.overscaledZ>=g?w:null}for(let w=d.overscaledZ-1;w>=g;w--){const j=d.scaledTo(w),I=this._getLoadedTile(j);if(I)return I}}_getLoadedTile(d){const g=this._tiles[d.key];return g&&g.hasData()?g:this._cache.getByKey(this._source.reparseOverscaled?d.wrapped().key:d.canonical.key)}updateCacheSize(d,g){g=g||this._source.tileSize;const w=Math.ceil(d.width/g)+1,j=Math.ceil(d.height/g)+1,I=Math.floor(w*j*5),L=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,I):I,F=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,L):L;this._cache.setMaxSize(F)}handleWrapJump(d){const g=Math.round((d-(this._prevLng===void 0?d:this._prevLng))/360);if(this._prevLng=d,g){const w={};for(const j in this._tiles){const I=this._tiles[j];I.tileID=I.tileID.unwrapTo(I.tileID.wrap+g),w[I.tileID.key]=I}this._tiles=w;for(const j in this._timers)clearTimeout(this._timers[j]),delete this._timers[j];for(const j in this._tiles)this._setTileReloadTimer(+j,this._tiles[j])}}update(d,g,w,j,I){if(this.transform=d,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!w)return;this.updateCacheSize(d,g),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const L=this._source.type==="batched-model";let F,z=this._source.maxzoom;this._maxzoomOverride!==null&&(z=Math.min(z,this._maxzoomOverride));const H=this.map&&this.map.painter?this.map.painter._terrain:null;if(H&&H.sourceCache===this&&H.attenuationRange()){const se=H.attenuationRange()[0],ce=Math.floor(se)-Math.log2(H.getDemUpscale());z>ce&&(z=ce)}const Z=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)F=d.getVisibleUnwrappedCoordinates(this._source.tileID).map(se=>new a.aR(se.canonical.z,se.wrap,se.canonical.z,se.canonical.x,se.canonical.y));else if(this.tileCoverLift!==0){const se=d.clone();se.tileCoverLift=this.tileCoverLift,F=se.coveringTiles({tileSize:g||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:z,roundZoom:this._source.roundZoom&&!w,reparseOverscaled:Z,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:L}),this._source.minzoom<=1&&d.projection.name==="globe"&&(F.push(new a.aR(1,0,1,0,0)),F.push(new a.aR(1,0,1,1,0)),F.push(new a.aR(1,0,1,0,1)),F.push(new a.aR(1,0,1,1,1)))}else if(F=d.coveringTiles({tileSize:g||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:z,roundZoom:this._source.roundZoom&&!w,reparseOverscaled:Z,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:L}),this._source.hasTile){const se=this._source.hasTile.bind(this._source);F=F.filter(ce=>se(ce))}}else F=[];if(F.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const se=d.coveringZoomLevel({tileSize:g||this._source.tileSize,roundZoom:this._source.roundZoom&&!w}),ce=Math.min(se,z);if(L){const oe=d.extendTileCover(F,ce);for(const ye of oe)F.push(ye)}else if(I){const oe=this.transform.getFrustum(ce),ye=d.extendTileCoverToNearPlane(F,oe,ce);for(const ge of ye)F.push(ge);if(ce>=18&&this._hasTunnelGeometry()){const ge=d.extendTileCoverForTunnels(F,oe,ce,20);for(const Pe of ge)F.push(Pe)}}else if(this.castsShadows&&j){const oe=d.extendTileCover(F,ce,j,16);for(const ye of oe)this._shadowCasterTiles[ye.key]=!0,F.push(ye)}}const ne=this._updateRetainedTiles(F);if(this._supportsFading&&F.length!==0){const se={},ce={},oe=a.o.now(),ye=Object.keys(ne);for(const Pe of ye){const De=ne[Pe],_e=this._tiles[Pe];if(!_e||_e.fadeEndTime!==void 0&&_e.fadeEndTime<=oe)continue;const Ze=this.findLoadedParent(De,Math.max(De.overscaledZ-fu.maxOverzooming,this._source.minzoom));Ze&&(this._addTile(Ze.tileID),se[Ze.tileID.key]=Ze.tileID),ce[Pe]=De}const ge=F[F.length-1].overscaledZ;for(const Pe in this._tiles){const De=this._tiles[Pe];if(ne[Pe]||!De.hasData())continue;let _e=De.tileID;for(;_e.overscaledZ>ge;){_e=_e.scaledTo(_e.overscaledZ-1);const Ze=this._tiles[_e.key];if(Ze&&Ze.hasData()&&ce[_e.key]){ne[Pe]=De.tileID;break}}}for(const Pe in se)ne[Pe]||(this._coveredTiles[Pe]=!0,ne[Pe]=se[Pe])}for(const se in ne)this._tiles[se].clearFadeHold();const re=a.b3(this._tiles,ne);for(const se of re){const ce=this._tiles[se];ce.hasSymbolBuckets&&!ce.holdingForFade()?ce.setHoldDuration(this.map._fadeDuration):ce.hasSymbolBuckets&&!ce.symbolFadeFinished()||this._removeTile(+se)}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 w={},j=d.reduce((H,Z)=>Math.min(H,Z.overscaledZ),1/0),I=d[0].overscaledZ,L=Math.max(I-fu.maxOverzooming,this._source.minzoom),F=Math.max(I+fu.maxUnderzooming,this._source.minzoom),z={};for(const H of d){const Z=this._addTile(H);g[H.key]=H,Z.hasData()||j=this._source.maxzoom){const re=H.children(this._source.maxzoom)[0],se=this.getTile(re);if(se&&se.hasData()){g[re.key]=re;continue}}else{const re=H.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=H.overscaledZ-1;re>=L;--re){const se=H.scaledTo(re);if(w[se.key]||(w[se.key]=!0,Z=this.getTile(se),!Z&&ne&&(Z=this._addTile(se)),Z&&(g[se.key]=se,ne=Z.wasRequested(),Z.hasData())))break}}return g}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const d in this._tiles){const g=[];let w,j=this._tiles[d].tileID;for(;j.overscaledZ>0;){if(j.key in this._loadedParentTiles){w=this._loadedParentTiles[j.key];break}g.push(j.key);const I=j.scaledTo(j.overscaledZ-1);if(w=this._getLoadedTile(I),w)break;j=I}for(const I of g)this._loadedParentTiles[I]=w}}_addTile(d){let g=this._tiles[d.key];if(g)return g.isExtraShadowCaster!==!0||this._shadowCasterTiles[d.key]||this._reloadTile(d.key,"reloading"),g;g=this._cache.getAndRemove(d),g&&(this._setTileReloadTimer(d.key,g),g.tileID=d,this._state.initializeTileState(g,this.map?this.map.painter:null),this._cacheTimers[d.key]&&(clearTimeout(this._cacheTimers[d.key]),delete this._cacheTimers[d.key],this._setTileReloadTimer(d.key,g)));const w=!!g;if(!w){const j=this.map?this.map.painter:null,I=this._source.tileSize*d.overscaleFactor();g=this._source.type==="raster-array"?new Bm(d,I,this.transform.tileZoom,j,this._isRaster):new a.b0(d,I,this.transform.tileZoom,j,this._isRaster,this._source.worldview),this._loadTile(g,this._tileLoaded.bind(this,g,d.key,g.state))}return g.uses++,this._tiles[d.key]=g,w||this._source.fire(new 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 w=g.getExpiryTimeout();w&&(this._timers[d]=setTimeout(()=>{this._reloadTile(d,"expired"),delete this._timers[d]},w))}_removeTile(d){const g=this._tiles[d];g&&(g.uses--,delete this._tiles[d],this._timers[d]&&(clearTimeout(this._timers[d]),delete this._timers[d]),g.uses>0||(g.hasData()&&g.state!=="reloading"||g.state==="empty"?this._cache.add(g.tileID,g,g.getExpiryTimeout()):(g.aborted=!0,this._abortTile(g),this._unloadTile(g))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const d in this._tiles)this._removeTile(+d);this._source._clear&&this._source._clear(),this._cache.reset(),this.map&&this.usedForTerrain&&this.map.painter.terrain&&this.map.painter.terrain.resetTileLookupCache(this.id)}tilesIn(d,g,w){const j=[],I=this.transform;if(!I)return j;const L=I.projection.name==="globe",F=a.aH(I.center.lng);for(const z in this._tiles){const H=this._tiles[z];if(w&&H.clearQueryDebugViz(),H.holdingForFade())continue;let Z;if(L){const ne=H.tileID.canonical;if(ne.z===0){const re=[Math.abs(a.aC(F,...bg(ne,-1))-F),Math.abs(a.aC(F,...bg(ne,1))-F)];Z=[0,2*re.indexOf(Math.min(...re))-1]}else{const re=[Math.abs(a.aC(F,...bg(ne,-1))-F),Math.abs(a.aC(F,...bg(ne,0))-F),Math.abs(a.aC(F,...bg(ne,1))-F)];Z=[re.indexOf(Math.min(...re))-1]}}else Z=[0];for(const ne of Z){const re=d.containsTile(H,I,g,ne);re&&j.push(re)}}return j}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(d){return this._getRenderableCoordinates(d)}_getRenderableCoordinates(d,g){const w=this.getRenderableIds(d,g).map(I=>this._tiles[I].tileID),j=this.transform.projection.name==="globe";for(const I of w)I.projMatrix=this.transform.calculateProjMatrix(I.toUnwrapped()),I.expandedProjMatrix=j?this.transform.calculateProjMatrix(I.toUnwrapped(),!1,!0):I.projMatrix;return w}sortCoordinatesByDistance(d){const g=d.slice(),w=this.transform._camera.position,j=this.transform._camera.forward(),I={};for(const L of g){const F=1/(1<I[L.key]-I[F.key]),g}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const d=a.o.now();for(const g in this._tiles){const w=this._tiles[g];if(w.fadeEndTime!==void 0&&w.fadeEndTime>=d)return!0}}return!1}setFeatureState(d,g,w){this._state.updateState(d=d||"_geojsonTileLayer",g,w)}removeFeatureState(d,g,w){this._state.removeFeatureState(d=d||"_geojsonTileLayer",g,w)}getFeatureState(d,g){return this._state.getState(d=d||"_geojsonTileLayer",g)}setDependencies(d,g,w){const j=this._tiles[d];j&&j.setDependencies(g,w)}reloadTilesForDependencies(d,g){for(const w in this._tiles)this._tiles[w].hasDependency(d,g)&&this._reloadTile(+w,"reloading");this._cache.filter(w=>!w.hasDependency(d,g))}_preloadTiles(d,g){if(!this._sourceLoaded){const z=()=>{this._sourceLoaded&&(this._source.off("data",z),this._preloadTiles(d,g))};return void this._source.on("data",z)}const w=new Map,j=Array.isArray(d)?d:[d],I=this.map.painter.terrain,L=this.usedForTerrain&&I?I.getScaledDemTileSize():this._source.tileSize;for(const z of j){const H=z.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 H)w.set(Z.key,Z);this.usedForTerrain&&z.updateElevation(!1)}const F=Array.from(w.values());a.t(F,(z,H)=>{const Z=new a.b0(z,this._source.tileSize*z.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),H(ne,Z)})},g)}}function BT(_,d){const g=Math.abs(2*_.wrap)-+(_.wrap<0),w=Math.abs(2*d.wrap)-+(d.wrap<0);return _.overscaledZ-d.overscaledZ||w-g||d.canonical.y-_.canonical.y||d.canonical.x-_.canonical.x}function bg(_,d){const g=1<<_.z;return[_.x/g+d,(_.x+1)/g+d]}fu.maxOverzooming=10,fu.maxUnderzooming=3;class Zx{constructor(d){this.style=d,this.layersGotHidden=!1,this.layers=[]}processLayersChanged(){this.layers=[];const d=!1,g=!1;for(const w in this.style._mergedLayers){const j=this.style._mergedLayers[w];if(j.type==="fill-extrusion"||j.type==="building")this.layers.push({layer:j,visible:d,visibilityChanged:g});else if(j.type==="model"){const I=this.style.getLayerSource(j);I&&I.type==="batched-model"&&this.layers.push({layer:j,visible:d,visibilityChanged:g})}}}onNewFrame(d){this.layersGotHidden=!1;for(const g of this.layers){const w=g.layer;let j=!1;w.type==="fill-extrusion"?j=!w.isHidden(d)&&w.paint.get("fill-extrusion-opacity")>0:w.type==="building"?j=!w.isHidden(d)&&w.paint.get("building-opacity")>0:w.type==="model"&&(j=!w.isHidden(d)&&w.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!j&&g.visible,g.visible=j}}updateZOffset(d,g){this.currentBuildingBuckets=[];for(const j of this.layers){const I=j.layer,L=this.style.getLayerSourceCache(I);let F=1;I.type==="fill-extrusion"?F=j.visible?I.paint.get("fill-extrusion-vertical-scale"):0:I.type==="building"&&(F=j.visible?I.paint.get("building-vertical-scale"):0);let z=L?L.getTile(g):null;if(!z&&L)for(const H in L._tiles){const Z=L._tiles[H];if(g.canonical.isChildOf(Z.tileID.canonical)){z=Z;break}}this.currentBuildingBuckets.push({bucket:z?z.getBucket(I):null,tileID:z?z.tileID:g,verticalScale:F})}d.hasAnyZOffset=!1;let w=!1;for(let j=0;j{w in d&&(g[w]=d[w])}),g}function zT(_){_=_.slice();const d=Object.create(null);for(const g of _)d[g.id]=g;for(let g=0;g<_.length;g++){const w=_[g];if(w&&"ref"in w){const j=d[w.ref];j&&(_[g]=$T(w,j))}}return _}const Jn={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 wg(_,d,g){g.push({command:Jn.addSource,args:[_,d[_]]})}function Sg(_,d,g){d.push({command:Jn.removeSource,args:[_]}),g[_]=!0}function w5(_,d,g,w){Sg(_,g,w),wg(_,d,g)}function D_(_,d,g){let w;for(w in _[g])if(_[g].hasOwnProperty(w)&&w!=="data"&&!a.b6(_[g][w],d[g][w]))return!1;for(w in d[g])if(d[g].hasOwnProperty(w)&&w!=="data"&&!a.b6(_[g][w],d[g][w]))return!1;return!0}function bf(_,d,g,w,j,I){let L;for(L in d=d||{},_=_||{})_.hasOwnProperty(L)&&(a.b6(_[L],d[L])||g.push({command:I,args:[w,L,d[L],j]}));for(L in d)d.hasOwnProperty(L)&&!_.hasOwnProperty(L)&&(a.b6(_[L],d[L])||g.push({command:I,args:[w,L,d[L],j]}))}function Tg(_){return _.id}function Xx(_,d){return _[d.id]=d,_}function M_(_,d,g){const w=d.createTileMatrix(_,_.worldSize,g.toUnwrapped());return a.aD(new Float32Array(16),_.projMatrix,w)}function mN(_,d,g){if(d.projection.name===g.projection.name)return _.projMatrix;const w=g.clone();return w.setProjection(d.projection),M_(w,d.getProjection(),_)}function $m(_,d,g){return d.name===g.projection.name?_.projMatrix:M_(g,d,_)}class pN{constructor(d,g){this.reset(d,g)}reset(d,g){this.points=d||[],this._distances=[0];for(let w=1;w0?(j-L)/F:0;return this.points[I].mult(1-z).add(this.points[g].mult(z))}}class UT{constructor(d,g,w){const j=this.boxCells=[],I=this.circleCells=[];this.xCellCount=Math.ceil(d/w),this.yCellCount=Math.ceil(g/w);for(let L=0;Lthis.width||j<0||g>this.height)return!I&&[];const F=[];if(d<=0&&g<=0&&this.width<=w&&this.height<=j){if(I)return!0;for(let z=0;z0:F}_queryCircle(d,g,w,j,I){const L=d-w,F=d+w,z=g-w,H=g+w;if(F<0||L>this.width||H<0||z>this.height)return!j&&[];const Z=[];return this._forEachCell(L,z,F,H,this._queryCellCircle,Z,{hitTest:j,circle:{x:d,y:g,radius:w},seenUids:{box:{},circle:{}}},I),j?Z.length>0:Z}query(d,g,w,j,I){return this._query(d,g,w,j,!1,I)}hitTest(d,g,w,j,I){return this._query(d,g,w,j,!0,I)}hitTestCircle(d,g,w,j){return this._queryCircle(d,g,w,!0,j)}_queryCell(d,g,w,j,I,L,F,z){const H=F.seenUids,Z=this.boxCells[I];if(Z!==null){const re=this.bboxes;for(const se of Z)if(!H.box[se]){H.box[se]=!0;const ce=4*se;if(d<=re[ce+2]&&g<=re[ce+3]&&w>=re[ce+0]&&j>=re[ce+1]&&(!z||z(this.boxKeys[se]))){if(F.hitTest)return L.push(!0),!0;L.push({key:this.boxKeys[se],x1:re[ce],y1:re[ce+1],x2:re[ce+2],y2:re[ce+3]})}}}const ne=this.circleCells[I];if(ne!==null){const re=this.circles;for(const se of ne)if(!H.circle[se]){H.circle[se]=!0;const ce=3*se;if(this._circleAndRectCollide(re[ce],re[ce+1],re[ce+2],d,g,w,j)&&(!z||z(this.circleKeys[se]))){if(F.hitTest)return L.push(!0),!0;{const oe=re[ce],ye=re[ce+1],ge=re[ce+2];L.push({key:this.circleKeys[se],x1:oe-ge,y1:ye-ge,x2:oe+ge,y2:ye+ge})}}}}}_queryCellCircle(d,g,w,j,I,L,F,z){const H=F.circle,Z=F.seenUids,ne=this.boxCells[I];if(ne!==null){const se=this.bboxes;for(const ce of ne)if(!Z.box[ce]){Z.box[ce]=!0;const oe=4*ce;if(this._circleAndRectCollide(H.x,H.y,H.radius,se[oe+0],se[oe+1],se[oe+2],se[oe+3])&&(!z||z(this.boxKeys[ce])))return L.push(!0),!0}}const re=this.circleCells[I];if(re!==null){const se=this.circles;for(const ce of re)if(!Z.circle[ce]){Z.circle[ce]=!0;const oe=3*ce;if(this._circlesCollide(se[oe],se[oe+1],se[oe+2],H.x,H.y,H.radius)&&(!z||z(this.circleKeys[ce])))return L.push(!0),!0}}}_forEachCell(d,g,w,j,I,L,F,z){const H=this._convertToXCellCoord(d),Z=this._convertToYCellCoord(g),ne=this._convertToXCellCoord(w),re=this._convertToYCellCoord(j);for(let se=H;se<=ne;se++)for(let ce=Z;ce<=re;ce++)if(I.call(this,d,g,w,j,this.xCellCount*ce+se,L,F,z))return}_convertToXCellCoord(d){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(d*this.xScale)))}_convertToYCellCoord(d){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(d*this.yScale)))}_circlesCollide(d,g,w,j,I,L){const F=j-d,z=I-g,H=w+L;return H*H>F*F+z*z}_circleAndRectCollide(d,g,w,j,I,L,F){const z=(L-j)/2,H=Math.abs(d-(j+z));if(H>z+w)return!1;const Z=(F-I)/2,ne=Math.abs(g-(I+Z));if(ne>Z+w)return!1;if(H<=z||ne<=Z)return!0;const re=H-z,se=ne-Z;return re*re+se*se<=w*w}}const S5=Math.tan(85*Math.PI/180);function wf(_,d,g,w,j,I,L){const F=a.bb();if(g)if(I.name==="globe"){const z=a.bc(j,d);a.aD(F,F,z)}else{const z=a.bd([],L);F[0]=z[0],F[1]=z[1],F[4]=z[2],F[5]=z[3],w||a.ba(F,F,j.angle)}else a.aD(F,j.labelPlaneMatrix,_);return F}function Uu(_,d,g,w,j,I,L){const F=wf(_,d,g,w,j,I,L);return I.name==="globe"&&g||(F[2]=F[6]=F[10]=F[14]=0),F}function Eg(_,d,g,w,j,I,L){if(g){if(I.name==="globe"){const F=wf(_,d,g,w,j,I,L);return a.b7(F,F),a.aD(F,_,F),F}{const F=a.b8(_),z=a.b9([]);return z[0]=L[0],z[1]=L[1],z[4]=L[2],z[5]=L[3],a.aD(F,F,z),w||a.ba(F,F,-j.angle),F}}return j.glCoordMatrix}function mu(_,d,g,w){const j=[_,d,g,1];g?a.aE(j,j,w):Qr(j,j,w);const I=j[3];return j[0]/=I,j[1]/=I,j[2]/=I,j}function O_(_,d){return Math.min(.5+_/d*.5,1.5)}function Qx(_,d){const g=_[0]/_[3],w=_[1]/_[3];return g>=-d[0]&&g<=d[0]&&w>=-d[1]&&w<=d[1]}function hc(_,d,g,w,j,I,L,F,z,H,Z=1){const ne=g.transform,re=w?_.textSizeData:_.iconSizeData,se=a.bj(re,g.transform.zoom,Z),ce=ne.projection.name==="globe",oe=[256/g.width*2+1,256/g.height*2+1],ye=w?_.text.dynamicLayoutVertexArray:_.icon.dynamicLayoutVertexArray;ye.clear();let ge=null;ce&&(ge=w?_.text.globeExtVertexArray:_.icon.globeExtVertexArray);const Pe=_.lineVertexArray,De=w?_.text.placedSymbolArray:_.icon.placedSymbolArray,_e=g.transform.width/g.transform.height;let Ze,$e=!1;for(let Ke=0;KeMath.abs(g)?{useVertical:!0}:_===a.bk.vertical?w>0?{needsFlipping:!0}:null:d!==0&&function(j,I){return j===0||Math.abs(I/j)>S5}(g,w)?d===1?{needsFlipping:!0}:null:g<0?{needsFlipping:!0}:null}function qT(_,d,g,w,j,I,L,F,z,H,Z,ne,re,se,ce,oe,ye,ge,Pe,De){const _e=d/24,Ze=_.lineOffsetX*_e,$e=_.lineOffsetY*_e,{lineStartIndex:Ke,glyphStartIndex:Me,numGlyphs:Be,segment:qe,writingMode:st,flipState:Qe}=_,xt=Ke+_.lineLength,ft=Lt=>{if(Z){const[gt,bt,St]=Lt.up,nr=H.length;a.bm(Z,nr+0,gt,bt,St),a.bm(Z,nr+1,gt,bt,St),a.bm(Z,nr+2,gt,bt,St),a.bm(Z,nr+3,gt,bt,St)}const[Ft,ot,et]=Lt.point;a.bn(H,Ft,ot,et,Lt.angle)};if(Be>1){const Lt=VT(_e,F,Ze,$e,g,ne,re,_,z,I,se,oe,!1,ye,ge,Pe,De);if(!Lt)return{notEnoughRoom:!0};if(w&&!g){let[Ft,ot,et]=Lt.first.point,[gt,bt,St]=Lt.last.point;[Ft,ot]=mu(Ft,ot,et,L),[gt,bt]=mu(gt,bt,St,L);const nr=F_(st,Qe,(gt-Ft)*ce,bt-ot);if(_.flipState=nr&&nr.needsFlipping?1:2,nr)return nr}ft(Lt.first);for(let Ft=Me+1;Ft0?gt:GT(re,et,Ft,1,j,void 0,ye,ge.canonical),St=F_(st,Qe,(bt[0]-Ft[0])*ce,bt[1]-Ft[1]);if(_.flipState=St&&St.needsFlipping?1:2,St)return St}const Lt=B_(_e*F.getoffsetX(Me),Ze,$e,g,ne,re,qe,Ke,xt,z,I,se,oe,!1,!1,ye,ge,Pe,De);if(!Lt)return{notEnoughRoom:!0};ft(Lt)}return{}}function Xn(_,d,g,w,j){const{x:I,y:L,z:F}=w.projectTilePoint(_.x,_.y,d);if(!j)return mu(I,L,F,g);const[z,H,Z]=j.getElevation(_,j.elevation,j.elevationFeature);return mu(I+z,L+H,F+Z,g)}function GT(_,d,g,w,j,I,L,F){const z=Xn(_.sub(d)._unit()._add(_),F,j,L,I);return a.ax(z,g,z),a.ay(z,z),a.bg(z,g,z,w)}function B_(_,d,g,w,j,I,L,F,z,H,Z,ne,re,se,ce,oe,ye,ge,Pe){const De=w?_-d:_+d;let _e=De>0?1:-1,Ze=0;w&&(_e*=-1,Ze=Math.PI),_e<0&&(Ze+=Math.PI);let $e=F+L+(_e>0?0:1)|0,Ke=j,Me=j,Be=0,qe=0;const st=Math.abs(De),Qe=[],xt=[];let ft=I,Lt=ft,Ft=a.be([]);const ot=()=>GT(Lt,ft,Me,st-Be+1,Z,re,oe,ye.canonical);for(;Be+qe<=st;){if($e+=_e,$e=z)return null;if(Me=Ke,Lt=ft,Qe.push(Me),se&&xt.push(Lt),ft=new a.P(H.getx($e),H.gety($e)),Ke=ne[$e],!Ke){const Lr=Xn(ft,ye.canonical,Z,oe,re);Ke=Lr[3]>0?ne[$e]=Lr:ot()}Be+=qe;const Mt=a.ax([],Ke,Me),kr=a.bf(Me,Ke);if(g&&kr>0&&qe>0&&a.bi(Ft,Mt)/(qe*kr)0,De),Ke=H*$e.perspectiveRatio,Me=(w.x1*g+F.x-w.padding)*Ke+$e.point.x,Be=(w.y1*g+F.y-w.padding)*Ke+$e.point.y,qe=(w.x2*g+F.x+w.padding)*Ke+$e.point.x,st=(w.y2*g+F.y+w.padding)*Ke+$e.point.y,Qe=$e.perspectiveRatio<=.55||$e.occluded;return!this.isInsideGrid(Me,Be,qe,st)||!z&&this.grid.hitTest(Me,Be,qe,st,ne)||Qe?{box:[],offscreen:!1,occluded:$e.occluded}:{box:[Me,Be,qe,st],offscreen:this.isOffscreen(Me,Be,qe,st),occluded:!1}}placeCollisionCircles(d,g,w,j,I,L,F,z,H,Z,ne,re,se,ce,oe,ye){const ge=[],Pe=this.transform.elevation,De=d.getProjection(),_e=d.elevationType==="road",Ze=!!Pe||_e,$e=a.bu.getAtTileOffsetFunc(ye,this.transform.center.lat,this.transform.worldSize,De),Ke=new a.P(w.tileAnchorX,w.tileAnchorY),Me=new a.P(w.tileAnchorX,w.tileAnchorY);let{x:Be,y:qe,z:st}=De.projectTilePoint(Me.x,Me.y,ye.canonical),Qe=null;if(Ze){const kr=_e?d.getElevationFeatureForText(j):null;Qe={getElevation:$e,elevation:Pe,elevationFeature:kr};const[Lr,yr,Er]=$e(Ke,Pe,kr);Be+=Lr,qe+=yr,st+=Er}const xt=De.name==="globe",ft=this.projectAndGetPerspectiveRatio(z,Be,qe,st,ye,xt||!!Pe||this.transform.pitch>0,De),{perspectiveRatio:Lt}=ft,Ft=(re?F/Lt:F*Lt)/a.by,ot=mu(Be,qe,st,H),et=w.lineOffsetX*Ft,gt=w.lineOffsetY*Ft,bt=a.ap(d.layers[0].layout.get("text-max-angle")),St=Math.cos(bt),nr=ft.signedDistanceFromCamera>0?VT(Ft,L,et,gt,_e&&w.flipState===1,ot,Me,w,I,H,{},Ze&&!re?Qe:null,re&&Ze,De,ye,re,St):null;let Wt=!1,Kt=!1,Mt=!0;if(nr&&!ft.occluded){const kr=.5*ce*Lt+oe,Lr=new a.P(-100,-100),yr=new a.P(this.screenRightBoundary,this.screenBottomBoundary),Er=new pN,{first:Hr,last:an}=nr,tn=Hr.path.length;let bn=[];for(let rn=tn-1;rn>=1;rn--)bn.push(Hr.path[rn]);for(let rn=1;rn(Ze&&!xt&&(wi=$e(Xirn[3]<=0)&&(bn=[]));let wn=[];if(bn.length>0){let rn=1/0,Gn=-1/0,wi=1/0,Xi=-1/0;for(const Ni of bn)rn=Math.min(rn,Ni[0]),wi=Math.min(wi,Ni[1]),Gn=Math.max(Gn,Ni[0]),Xi=Math.max(Xi,Ni[1]);Gn>=Lr.x&&rn<=yr.x&&Xi>=Lr.y&&wi<=yr.y&&(wn=[bn.map(Ni=>new a.P(Ni[0],Ni[1]))],(rnyr.x||wiyr.y)&&(wn=a.bv(wn,Lr.x,Lr.y,yr.x,yr.y)))}for(const rn of wn){Er.reset(rn,.25*kr);let Gn=0;Gn=Er.length<=.5*kr?1:Math.ceil(Er.paddedLength/Ur)+1;for(let wi=0;wi0?(a.aE(z,z,d),this.fogState&&I&&F.name!=="globe"&&(H=function(re,se,ce,oe,ye,ge){const Pe=ge.calculateFogTileMatrix(ye),De=[se,ce,oe];return a.ah(De,De,Pe),Di(re,a.ai(De),ge.pitch,ge._fov)}(this.fogState,g,w,j,I.toUnwrapped(),this.transform)>.9)):Qr(z,z,d);const Z=z[3];return{point:new a.P((z[0]/Z+1)/2*this.transform.width+Vu,(-z[1]/Z+1)/2*this.transform.height+Vu),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(F)/Z*.5,1.5),signedDistanceFromCamera:Z,occluded:L&&z[2]>Z||H}}isOffscreen(d,g,w,j){return w=this.screenRightBoundary||jthis.screenBottomBoundary}isInsideGrid(d,g,w,j){return w>=0&&d=0&&gw.collisionGroupID===g}}return this.collisionGroups[d]}}function Sl(_,d,g,w,j){const{horizontalAlign:I,verticalAlign:L}=a.bF(_),F=-(I-.5)*d,z=-(L-.5)*g,H=a.bG(_,w);return new a.P(F+H[0]*j,z+H[1]*j)}function Sf(_,d,g,w,j){const I=new a.P(_,d);return g&&I._rotate(w?j:-j),I}class gi{constructor(d,g,w,j,I,L){this.transform=d.clone(),this.projection=d.projection.name,this.collisionIndex=new $_(this.transform,I),this.buildingIndex=L,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=g,this.retainedQueryData={},this.collisionGroups=new pi(w),this.collisionCircleArrays={},this.prevPlacement=j,j&&(j.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(d,g,w,j,I=1){const L=w.getBucket(g),F=w.latestFeatureIndex;if(!L||!F||g.fqid!==L.layerIds[0])return;const z=L.layers[0].layout,H=L.layers[0].paint,Z=w.collisionBoxArray,ne=Math.pow(2,this.transform.zoom-w.tileID.overscaledZ),re=w.tileSize/a.an,se=w.tileID.toUnwrapped();this.transform.setProjection(L.projection);const ce=(oe=w.tileID,ye=L.getProjection(),ge=this.transform,ye.name===this.projection?ge.calculateProjMatrix(oe.toUnwrapped()):M_(ge,ye,oe));var oe,ye,ge;const Pe=z.get("text-pitch-alignment")==="map",De=z.get("text-rotation-alignment")==="map";g.compileFilter(g.options);const _e=g.dynamicFilter(),Ze=g.dynamicFilterNeedsFeature(),$e=g.dynamicFilterNeedsGeometry(),Ke=this.transform.calculatePixelsToTileUnitsMatrix(w),Me=Uu(ce,w.tileID.canonical,Pe,De,this.transform,L.getProjection(),Ke);let Be=null;const qe=L.getProjection().createInversionMatrix(this.transform,w.tileID.canonical);if(Pe){const gt=Eg(ce,w.tileID.canonical,Pe,De,this.transform,L.getProjection(),Ke);Be=a.aD([],this.transform.labelPlaneMatrix,gt)}let st=null;_e&&w.latestFeatureIndex&&(st={unwrappedTileID:se,dynamicFilter:_e,dynamicFilterNeedsFeature:Ze,needGeometry:$e}),this.retainedQueryData[L.bucketInstanceId]=new di(L.bucketInstanceId,F,L.sourceLayerIndex,L.index,w.tileID);const[Qe,xt]=L.layers[0].layout.get("text-size-scale-range"),ft=a.aC(I,Qe,xt),[Lt,Ft]=z.get("icon-size-scale-range"),ot=a.aC(I,Lt,Ft),et={bucket:L,layout:z,paint:H,posMatrix:ce,invMatrix:qe,mercatorCenter:[a.aH(this.transform.center.lng),a.aL(this.transform.center.lat)],textLabelPlaneMatrix:Me,labelToScreenMatrix:Be,clippingData:st,scale:ne,textPixelRatio:re,holdingForFade:w.holdingForFade(),collisionBoxArray:Z,partiallyEvaluatedTextSize:a.bj(L.textSizeData,this.transform.zoom,ft),partiallyEvaluatedIconSize:a.bj(L.iconSizeData,this.transform.zoom,ot),collisionGroup:this.collisionGroups.get(L.sourceID),latestFeatureIndex:w.latestFeatureIndex};if(j)for(const gt of L.sortKeyRanges){const{sortKey:bt,symbolInstanceStart:St,symbolInstanceEnd:nr}=gt;d.push({sortKey:bt,symbolInstanceStart:St,symbolInstanceEnd:nr,parameters:et})}else d.push({symbolInstanceStart:0,symbolInstanceEnd:L.symbolInstances.length,parameters:et})}attemptAnchorPlacement(d,g,w,j,I,L,F,z,H,Z,ne,re,se,ce,oe,ye,ge,Pe,De,_e,Ze){const{textOffset0:$e,textOffset1:Ke,crossTileID:Me}=oe,Be=[$e,Ke],qe=Sl(d,L,F,Be,z),st=this.collisionIndex.placeCollisionBox(ge,z,g,w,j,I,Sf(qe.x,qe.y,H,Z,this.transform.angle),ce,ne,re,se.predicate);if(De){const Qe=ge.getSymbolInstanceIconSize(Ze,this.transform.zoom,oe.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(ge,Qe,De,w,j,I,Sf(qe.x,qe.y,H,Z,this.transform.angle),ce,ne,re,se.predicate).box.length===0)return}if(st.box.length>0){let Qe;return this.prevPlacement&&this.prevPlacement.variableOffsets[Me]&&this.prevPlacement.placements[Me]&&this.prevPlacement.placements[Me].text&&(Qe=this.prevPlacement.variableOffsets[Me].anchor),this.variableOffsets[Me]={textOffset:Be,width:L,height:F,anchor:d,textScale:z,prevAnchor:Qe},this.markUsedJustification(ge,d,oe,Pe),ge.allowVerticalPlacement&&(this.markUsedOrientation(ge,Pe,oe),this.placedOrientations[Me]=Pe),{shift:qe,placedGlyphBoxes:st}}}placeLayerBucketPart(d,g,w,j,I=1){const{bucket:L,layout:F,paint:z,posMatrix:H,textLabelPlaneMatrix:Z,labelToScreenMatrix:ne,clippingData:re,textPixelRatio:se,mercatorCenter:ce,invMatrix:oe,holdingForFade:ye,collisionBoxArray:ge,partiallyEvaluatedTextSize:Pe,partiallyEvaluatedIconSize:De,collisionGroup:_e,latestFeatureIndex:Ze}=d.parameters,$e=F.get("text-optional"),Ke=F.get("icon-optional"),Me=F.get("text-allow-overlap"),Be=F.get("icon-allow-overlap"),qe=F.get("text-rotation-alignment")==="map",st=F.get("icon-rotation-alignment")==="map",Qe=F.get("text-pitch-alignment")==="map",xt=z.get("symbol-z-offset"),ft=F.get("symbol-elevation-reference")==="sea",Lt=F.get("symbol-placement"),[Ft,ot]=F.get("text-size-scale-range"),[et,gt]=F.get("icon-size-scale-range"),bt=a.aC(I,Ft,ot),St=a.aC(I,et,gt),nr=F.get("text-variable-anchor"),Wt=qe&&Lt!=="point",Kt=st&&Lt!=="point",Mt=nr&&L.hasTextData(),kr=L.hasIconTextFit()&&Mt&&L.hasIconData();this.transform.setProjection(L.projection);const Lr=Mt||Wt,yr=Kt||kr;let Er=Me&&(Be||!L.hasIconData()||Ke),Hr=Be&&(Me||!L.hasTextData()||$e);const an=!xt.isConstant();!L.collisionArrays&&ge&&L.deserializeCollisionBoxes(ge),w&&j&&L.updateCollisionDebugBuffers(this.transform.zoom,ge,bt,St);const tn=(Ur,wn,rn)=>{const{crossTileID:Gn,numVerticalGlyphVertices:wi}=Ur;let Xi=null;if(re&&re.dynamicFilterNeedsFeature||an){const Oi=this.retainedQueryData[L.bucketInstanceId],Vi=Ze.loadFeature({featureIndex:Ur.featureIndex,bucketIndex:Oi.bucketIndex,sourceLayerIndex:Oi.sourceLayerIndex,layoutVertexArrayOffset:0}),yi=Vi.properties?Vi.properties.worldview:null;if(L.localizable&&L.worldview&&typeof yi=="string")if(yi==="all")Vi.properties.$localized=!0;else{if(!yi.split(",").includes(L.worldview))return;Vi.properties.$localized=!0,Vi.properties.worldview=L.worldview}Xi=re&&re.needGeometry?a.bD(Vi,!0):Vi}if(re&&!(0,re.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:L.worldview},Xi,this.retainedQueryData[L.bucketInstanceId].tileID.canonical,new a.P(Ur.tileAnchorX,Ur.tileAnchorY),this.transform.calculateDistanceTileData(re.unwrappedTileID)))return this.placements[Gn]=new bh(!1,!1,!1,!0),void g.add(Gn);const Ni=xt.evaluate(Xi,{});if((Ur.zOffset||0)+(Ni||0)>0&&this.frontCutoffStart>0){const Oi=2*this.frontCutoffStart-1,Vi=[Ur.tileAnchorX,Ur.tileAnchorY,0,1],yi=a.aE(a.bE(),Vi,H);if(yi[1]/yi[3]{Oi.tileID=this.retainedQueryData[L.bucketInstanceId].tileID;const Vi=this.transform.elevation;Oi.elevation=ft?Ni:Ni+a.bu.getAtTileOffset(Oi.tileID,new a.P(Oi.tileAnchorX,Oi.tileAnchorY),Vi,fa),Oi.elevation+=Ur.zOffset},pc=rn.textBox;if(pc){Ha(pc);const Oi=yi=>{let Ns=a.bk.horizontal;if(L.allowVerticalPlacement&&!yi&&this.prevPlacement){const Bo=this.prevPlacement.placedOrientations[Gn];Bo&&(this.placedOrientations[Gn]=Bo,Ns=Bo,this.markUsedOrientation(L,Ns,Ur))}return Ns},Vi=(yi,Ns)=>{if(L.allowVerticalPlacement&&wi>0&&rn.verticalTextBox){for(const Bo of L.writingModes)if(Bo===a.bk.vertical?(ln=Ns(),Yi=ln):ln=yi(),ln&&ln.box&&ln.box.length)break}else ln=yi()};if(nr){let yi=nr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[Gn]){const hs=this.prevPlacement.variableOffsets[Gn];yi.indexOf(hs.anchor)>0&&(yi=yi.filter(gc=>gc!==hs.anchor),yi.unshift(hs.anchor))}const Ns=(hs,gc,Pf)=>{const sp=L.getSymbolInstanceTextSize(Pe,Ur,this.transform.zoom,wn),ap=(hs.x2-hs.x1)*sp+2*hs.padding,Wg=(hs.y2-hs.y1)*sp+2*hs.padding,Nh=Ur.hasIconTextFit&&!Be?gc:null;Nh&&Ha(Nh);let Fd={box:[],offscreen:!1,occluded:!1};const Kg=Me?2*yi.length:yi.length;for(let Ul=0;Ul=yi.length,Ur,wn,L,Pf,Nh,Pe,De);if(Rf&&(Fd=Rf.placedGlyphBoxes,Fd&&Fd.box&&Fd.box.length)){ei=!0,ti=Rf.shift;break}}return Fd};Vi(()=>Ns(pc,rn.iconBox,a.bk.horizontal),()=>{const hs=rn.verticalTextBox;return hs&&Ha(hs),L.allowVerticalPlacement&&!(ln&&ln.box&&ln.box.length)&&wi>0&&hs?Ns(hs,rn.verticalIconBox,a.bk.vertical):{box:null,offscreen:null,occluded:null}}),ln&&(ei=ln.box,yn=ln.offscreen,Ii=ln.occluded);const Bo=Oi(!(!ln||!ln.box));if(!ei&&this.prevPlacement){const hs=this.prevPlacement.variableOffsets[Gn];hs&&(this.variableOffsets[Gn]=hs,this.markUsedJustification(L,hs.anchor,Ur,Bo))}}else{const yi=(Ns,Bo)=>{const hs=L.getSymbolInstanceTextSize(Pe,Ur,this.transform.zoom,wn),gc=this.collisionIndex.placeCollisionBox(L,hs,Ns,ce,oe,Lr,new a.P(0,0),Me,se,H,_e.predicate);return gc&&gc.box&&gc.box.length&&(this.markUsedOrientation(L,Bo,Ur),this.placedOrientations[Gn]=Bo),gc};Vi(()=>yi(pc,a.bk.horizontal),()=>{const Ns=rn.verticalTextBox;return L.allowVerticalPlacement&&wi>0&&Ns?(Ha(Ns),yi(Ns,a.bk.vertical)):{box:null,offscreen:null,occluded:null}}),Oi(!!(ln&&ln.box&&ln.box.length))}}if(Si=ln,ei=Si&&Si.box&&Si.box.length>0,yn=Si&&Si.offscreen,Ii=Si&&Si.occluded,Ur.useRuntimeCollisionCircles){const Oi=Ur.centerJustifiedTextSymbolIndex>=0?Ur.centerJustifiedTextSymbolIndex:Ur.verticalPlacedTextSymbolIndex,Vi=L.text.placedSymbolArray.get(Oi),yi=a.bl(L.textSizeData,Pe,Vi),Ns=F.get("text-padding");Bs=this.collisionIndex.placeCollisionCircles(L,Me,Vi,Oi,L.lineVertexArray,L.glyphOffsetArray,yi,H,Z,ne,w,Qe,_e.predicate,Ur.collisionCircleDiameter*yi/a.by,Ns,this.retainedQueryData[L.bucketInstanceId].tileID),ei=Me||Bs.circles.length>0&&!Bs.collisionDetected,yn=yn&&Bs.offscreen,Ii=Bs.occluded}if(rn.iconFeatureIndex&&(Eo=rn.iconFeatureIndex),rn.iconBox){const Oi=Vi=>{Ha(Vi);const yi=Ur.hasIconTextFit&&ti?Sf(ti.x,ti.y,qe,Qe,this.transform.angle):new a.P(0,0),Ns=L.getSymbolInstanceIconSize(De,this.transform.zoom,Ur.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(L,Ns,Vi,ce,oe,yr,yi,Be,se,H,_e.predicate)};Yi&&Yi.box&&Yi.box.length&&rn.verticalIconBox?(In=Oi(rn.verticalIconBox),gn=In.box.length>0):(In=Oi(rn.iconBox),gn=In.box.length>0),yn=yn&&In.offscreen,ns=In.occluded}const li=$e||Ur.numHorizontalGlyphVertices===0&&wi===0,Lc=Ke||Ur.numIconVertices===0;if(li||Lc?Lc?li||(gn=gn&&ei):ei=gn&&ei:gn=ei=gn&&ei,ei&&Si&&Si.box&&this.collisionIndex.insertCollisionBox(Si.box,F.get("text-ignore-placement"),L.bucketInstanceId,Yi&&Yi.box&&ta?ta:ji,_e.ID),gn&&In&&this.collisionIndex.insertCollisionBox(In.box,F.get("icon-ignore-placement"),L.bucketInstanceId,Eo,_e.ID),Bs&&(ei&&this.collisionIndex.insertCollisionCircles(Bs.circles,F.get("text-ignore-placement"),L.bucketInstanceId,ji,_e.ID),w)){const Oi=L.bucketInstanceId;let Vi=this.collisionCircleArrays[Oi];Vi===void 0&&(Vi=this.collisionCircleArrays[Oi]=new Dr);for(let yi=0;yi=0;--wn){const rn=Ur[wn];tn(L.symbolInstances.get(rn),rn,L.collisionArrays[rn])}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 Ur=L.getSortedIndexesByZOffset();for(let wn=0;wn=0&&(d.text.placedSymbolArray.get(I).crossTileID=ne>=0&&I!==ne?0:H),L>=0&&(d.text.placedSymbolArray.get(L).crossTileID=ne>=0&&L!==ne?0:H),F>=0&&(d.text.placedSymbolArray.get(F).crossTileID=ne>=0&&F!==ne?0:H),z>=0&&(d.text.placedSymbolArray.get(z).crossTileID=ne>=0&&z!==ne?0:H)}markUsedOrientation(d,g,w){const j=g===a.bk.horizontal||g===a.bk.horizontalOnly?g:0,I=g===a.bk.vertical?g:0,{leftJustifiedTextSymbolIndex:L,centerJustifiedTextSymbolIndex:F,rightJustifiedTextSymbolIndex:z,verticalPlacedTextSymbolIndex:H}=w,Z=d.text.placedSymbolArray;L>=0&&(Z.get(L).placedOrientation=j),F>=0&&(Z.get(F).placedOrientation=j),z>=0&&(Z.get(z).placedOrientation=j),H>=0&&(Z.get(H).placedOrientation=I)}commit(d){this.commitTime=d,this.zoomAtLastRecencyCheck=this.transform.zoom;const g=this.prevPlacement;let w=!1;this.prevZoomAdjustment=g?g.zoomAdjustment(this.transform.zoom):0;const j=g?g.symbolFadeChange(d):1,I=g?g.opacities:{},L=g?g.variableOffsets:{},F=g?g.placedOrientations:{};for(const z in this.placements){const H=this.placements[z],Z=I[z];Z?(this.opacities[z]=new zm(Z,j,H.text,H.icon,null,H.clipped),w=w||H.text!==Z.text.placed||H.icon!==Z.icon.placed):(this.opacities[z]=new zm(null,j,H.text,H.icon,H.skipFade,H.clipped),w=w||H.text||H.icon)}for(const z in I){const H=I[z];if(!this.opacities[z]){const Z=new zm(H,j,!1,!1);Z.isHidden()||(this.opacities[z]=Z,w=w||H.text.placed||H.icon.placed)}}for(const z in L)this.variableOffsets[z]||!this.opacities[z]||this.opacities[z].isHidden()||(this.variableOffsets[z]=L[z]);for(const z in F)this.placedOrientations[z]||!this.opacities[z]||this.opacities[z].isHidden()||(this.placedOrientations[z]=F[z]);w?this.lastPlacementChangeTime=d:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=g?g.lastPlacementChangeTime:d)}updateLayerOpacities(d,g,w,j){j&&(this.lastReplacementSourceUpdateTime=j.updateTime);const I=new Set;for(const L of g){const F=L.getBucket(d);F&&L.latestFeatureIndex&&d.fqid===F.layerIds[0]&&(this.updateBucketOpacities(F,I,L,L.collisionBoxArray,w,j,L.tileID,d.scope),F.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(F,L.tileID),F.elevationType==="road"&&F.updateRoadElevation(L.tileID.canonical),F.updateZOffset())}}updateBucketOpacities(d,g,w,j,I,L,F,z){d.hasTextData()&&d.text.opacityVertexArray.clear(),d.hasIconData()&&d.icon.opacityVertexArray.clear(),d.hasIconCollisionBoxData()&&d.iconCollisionBox.collisionVertexArray.clear(),d.hasTextCollisionBoxData()&&d.textCollisionBox.collisionVertexArray.clear();const H=d.layers[0].layout,Z=d.layers[0].paint,ne=!!d.layers[0].dynamicFilter(),re=new zm(null,0,!1,!1,!0),se=H.get("text-allow-overlap"),ce=H.get("icon-allow-overlap"),oe=H.get("text-variable-anchor"),ye=H.get("text-rotation-alignment")==="map",ge=H.get("text-pitch-alignment")==="map",Pe=Z.get("symbol-z-offset"),De=H.get("symbol-elevation-reference")==="sea",_e=!Pe.isConstant(),Ze=new zm(null,0,se&&(ce||!d.hasIconData()||H.get("icon-optional")),ce&&(se||!d.hasTextData()||H.get("text-optional")),!0);!d.collisionArrays&&j&&(d.hasIconCollisionBoxData()||d.hasTextCollisionBoxData())&&d.deserializeCollisionBoxes(j);const $e=(Me,Be,qe)=>{for(let st=0;st0||st>0,nr=xt>0,Wt=this.placedOrientations[Qe],Kt=Wt===a.bk.vertical,Mt=Wt===a.bk.horizontal||Wt===a.bk.horizontalOnly;!St&&!nr||bt.isHidden()||Ke++;let kr=!1;if((St||nr)&&L)for(const Lr of d.activeReplacements){if(a.bz(Lr,I,a.bA.Symbol,z)||Lr.min.x>ft||ft>Lr.max.x||Lr.min.y>Lt||Lt>Lr.max.y)continue;const yr=a.bB(ft,Lt,F.canonical,Lr.footprintTileId.canonical);if(kr=a.bC(yr,Lr.footprint),kr)break}if(kr&&this.collisionIndex.markSymbolAsClipped(d.bucketInstanceId,Be.featureIndex),St){const Lr=kr?wh:Ag(bt.text);$e(d.text,qe,Kt?wh:Lr),$e(d.text,st,Mt?wh:Lr);const yr=bt.text.isHidden(),{leftJustifiedTextSymbolIndex:Er,centerJustifiedTextSymbolIndex:Hr,rightJustifiedTextSymbolIndex:an,verticalPlacedTextSymbolIndex:tn}=Be,bn=d.text.placedSymbolArray,Ur=yr||Kt?1:0;Er>=0&&(bn.get(Er).hidden=Ur),Hr>=0&&(bn.get(Hr).hidden=Ur),an>=0&&(bn.get(an).hidden=Ur),tn>=0&&(bn.get(tn).hidden=yr||Mt?1:0);const wn=this.variableOffsets[Qe];wn&&this.markUsedJustification(d,wn.anchor,Be,Wt);const rn=this.placedOrientations[Qe];rn&&(this.markUsedJustification(d,"left",Be,rn),this.markUsedOrientation(d,rn,Be))}if(nr){const Lr=kr?wh:Ag(bt.icon),{placedIconSymbolIndex:yr,verticalPlacedIconSymbolIndex:Er}=Be,Hr=d.icon.placedSymbolArray,an=bt.icon.isHidden()?1:0;yr>=0&&($e(d.icon,xt,Kt?wh:Lr),Hr.get(yr).hidden=an),Er>=0&&($e(d.icon,Be.numVerticalIconVertices,Mt?wh:Lr),Hr.get(Er).hidden=an)}if(d.hasIconCollisionBoxData()||d.hasTextCollisionBoxData()){const Lr=d.collisionArrays[Me];if(Lr){let yr=new a.P(0,0),Er=!0;if(Lr.textBox||Lr.verticalTextBox){if(oe){const an=this.variableOffsets[Qe];an?(yr=Sl(an.anchor,an.width,an.height,an.textOffset,an.textScale),ye&&yr._rotate(ge?this.transform.angle:-this.transform.angle)):Er=!1}ne&&(Er=!bt.clipped),Lr.textBox&&Um(d.textCollisionBox.collisionVertexArray,bt.text.placed,!Er||Kt,et,De,yr.x,yr.y),Lr.verticalTextBox&&Um(d.textCollisionBox.collisionVertexArray,bt.text.placed,!Er||Mt,et,De,yr.x,yr.y)}const Hr=Er&&!!(!Mt&&Lr.verticalIconBox);Lr.iconBox&&Um(d.iconCollisionBox.collisionVertexArray,bt.icon.placed,Hr,et,De,Be.hasIconTextFit?yr.x:0,Be.hasIconTextFit?yr.y:0),Lr.verticalIconBox&&Um(d.iconCollisionBox.collisionVertexArray,bt.icon.placed,!Hr,et,De,Be.hasIconTextFit?yr.x:0,Be.hasIconTextFit?yr.y:0)}}}if(d.fullyClipped=Ke===0,d.sortFeatures(this.transform.angle),this.retainedQueryData[d.bucketInstanceId]&&(this.retainedQueryData[d.bucketInstanceId].featureSortOrder=d.featureSortOrder),d.hasTextData()&&d.text.opacityVertexBuffer&&d.text.opacityVertexBuffer.updateData(d.text.opacityVertexArray),d.hasIconData()&&d.icon.opacityVertexBuffer&&d.icon.opacityVertexBuffer.updateData(d.icon.opacityVertexArray),d.hasIconCollisionBoxData()&&d.iconCollisionBox.collisionVertexBuffer&&d.iconCollisionBox.collisionVertexBuffer.updateData(d.iconCollisionBox.collisionVertexArray),d.hasTextCollisionBoxData()&&d.textCollisionBox.collisionVertexBuffer&&d.textCollisionBox.collisionVertexBuffer.updateData(d.textCollisionBox.collisionVertexArray),d.bucketInstanceId in this.collisionCircleArrays){const Me=this.collisionCircleArrays[d.bucketInstanceId];d.placementInvProjMatrix=Me.invProjMatrix,d.placementViewportMatrix=Me.viewportMatrix,d.collisionCircleArray=Me.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 Um(_,d,g,w,j,I,L){_.emplaceBack(d?1:0,g?1:0,I||0,L||0,w,j?1:0),_.emplaceBack(d?1:0,g?1:0,I||0,L||0,w,j?1:0),_.emplaceBack(d?1:0,g?1:0,I||0,L||0,w,j?1:0),_.emplaceBack(d?1:0,g?1:0,I||0,L||0,w,j?1:0)}const Jx=Math.pow(2,25),e0=Math.pow(2,24),el=Math.pow(2,17),da=Math.pow(2,16),T5=Math.pow(2,9),t0=Math.pow(2,8),HT=Math.pow(2,1);function Ag(_){if(_.opacity===0&&!_.placed)return 0;if(_.opacity===1&&_.placed)return 4294967295;const d=_.placed?1:0,g=Math.floor(127*_.opacity);return g*Jx+d*e0+g*el+d*da+g*T5+d*t0+g*HT+d}const wh=0;class WT{constructor(d){this._sortAcrossTiles=d.layout.get("symbol-z-order")!=="viewport-y"&&d.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(d,g,w,j,I,L){const F=this._bucketParts;for(;this._currentTileIndexz.sortKey-H.sortKey));this._currentPartIndex{const z=a.o.now()-L;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&z>2};for(;this._currentPlacementIndex>=0;){const z=g[d[this._currentPlacementIndex]],H=this.placement.collisionIndex.transform.zoom;if(z.type==="symbol"&&z.visibility!=="none"&&(!z.minzoom||z.minzoom<=H)&&(!z.maxzoom||z.maxzoom>H)){const Z=z,ne=Z.layout.get("symbol-z-elevate"),re=Z.layout.get("symbol-sort-key").constantOr(1)!==void 0,se=Z.layout.get("symbol-z-order"),ce=se==="viewport-y"||se==="auto"&&!(se!=="viewport-y"&&re),oe=Z.layout.get("text-allow-overlap")||Z.layout.get("icon-allow-overlap")||Z.layout.get("text-ignore-placement")||Z.layout.get("icon-ignore-placement"),ye=ce&&oe,ge=this._inProgressLayer=this._inProgressLayer||new WT(Z),Pe=a.F(z.source,z.scope);if(ge.continuePlacement(ne||ye?j[Pe]:w[Pe],this.placement,this._showCollisionBoxes,z,F,I))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(d){return this.placement.commit(d),this.placement}}const Oo=512/a.an/2;class gu{constructor(d,g,w){this.tileID=d,this.bucketInstanceId=w,this.index=new a.bI(g.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const j=d.canonical.x*a.an,I=d.canonical.y*a.an;for(let L=0;Lye-ge);for(const ye of oe){const ge=this.crossTileIDs[ye];if(this.keys[ye]===Z&&!w.has(ge)){w.add(ge),H.crossTileID=ge;break}}}}}class zl{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class gN{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(d){const g=Math.round((d-this.lng)/360);if(g!==0)for(const w in this.indexes){const j=this.indexes[w],I={};for(const L in j){const F=j[L];F.tileID=F.tileID.unwrapTo(F.tileID.wrap+g),I[F.tileID.key]=F}this.indexes[w]=I}this.lng=d}addBucket(d,g,w){if(this.indexes[d.overscaledZ]&&this.indexes[d.overscaledZ][d.key]){if(this.indexes[d.overscaledZ][d.key].bucketInstanceId===g.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(d.overscaledZ,this.indexes[d.overscaledZ][d.key])}for(let I=0;Id.overscaledZ)for(const F in L){const z=L[F];z.tileID.isChildOf(d)&&z.findMatches(g.symbolInstances,d,j)}else{const F=L[d.scaledTo(Number(I)).key];F&&F.findMatches(g.symbolInstances,d,j)}}for(let I=0;I{g[w]=!0});for(const w in this.layerIndexes)g[w]||delete this.layerIndexes[w]}}const Cs=771;class Yr{constructor(d,g,w,j){this.blendFunction=d,this.blendColor=g.toNonPremultipliedRenderColor(null),this.mask=w,this.blendEquation=j}}Yr.Replace=[1,0,1,0],Yr.disabled=new Yr(Yr.Replace,a.aq.transparent,[!1,!1,!1,!1]),Yr.unblended=new Yr(Yr.Replace,a.aq.transparent,[!0,!0,!0,!0]),Yr.alphaBlended=new Yr([1,Cs,1,Cs],a.aq.transparent,[!0,!0,!0,!0]),Yr.alphaBlendedNonPremultiplied=new Yr([770,Cs,770,Cs],a.aq.transparent,[!0,!0,!0,!0]),Yr.multiply=new Yr([774,0,774,0],a.aq.transparent,[!0,!0,!0,!0]),Yr.multiplyAccumulateAlpha=new Yr([774,0,1,Cs],a.aq.transparent,[!0,!0,!0,!0]),Yr.additive=new Yr([1,1,1,1],a.aq.transparent,[!0,!0,!0,!0]);class Ir{constructor(d,g,w){this.func=d,this.mask=g,this.range=w}}Ir.ReadOnly=!1,Ir.ReadWrite=!0,Ir.disabled=new Ir(519,Ir.ReadOnly,[0,1]);const ea=7680;class Jr{constructor(d,g,w,j,I,L){this.test=d,this.ref=g,this.mask=w,this.fail=j,this.depthFail=I,this.pass=L}}Jr.disabled=new Jr({func:519,mask:0},0,0,ea,ea,ea);const Cc=1029,Vm=2305;class Gr{constructor(d,g,w){this.enable=d,this.mode=g,this.frontFace=w}}function n0(_,d){const g=a.bO(_,3);a.bR(_,d),a.bW(_,3,g)}function z_(_,d){const g=a.bL([]);return a.bM(g,g,-d),a.bN(g,g,-_),g}function U_(_,d){const g=[_[0],_[1],0],w=[d[0],d[1],0];if(a.ai(g)>=1e-15){const L=a.ay([],g);a.bJ(w,L,a.bi(w,L)),d[0]=w[0],d[1]=w[1]}const j=a.bh([],d,_);if(a.bK(j)<1e-15)return null;const I=Math.atan2(-j[1],j[0]);return z_(Math.atan2(Math.sqrt(_[0]*_[0]+_[1]*_[1]),-_[2]),I)}Gr.disabled=new Gr(!1,Cc,Vm),Gr.backCCW=new Gr(!0,Cc,Vm),Gr.backCW=new Gr(!0,Cc,2304),Gr.frontCW=new Gr(!0,1028,2304),Gr.frontCCW=new Gr(!0,1028,Vm);class i0{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,w){if(this.orientation=null,!this.position)return;const j=this.position,I=w||(this._elevation?this._elevation.getAtPointOrZero(a.ag.fromLngLat(d)):0),L=a.ag.fromLngLat(d,I),F=[L.x-j.x,L.y-j.y,L.z-j.z];g||(g=[0,0,1]),g[2]=Math.abs(g[2]),this.orientation=U_(F,g)}setPitchBearing(d,g){this.orientation=z_(a.ap(d),a.ap(-g))}}class s0{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&&n0(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=z_(d,g),n0(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 w=new Float64Array(16);return a.b7(w,this.getWorldToCamera(d,g)),w}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(d,g,w){const j=this.position;a.bJ(j,j,-d);const I=new Float64Array(16);return a.bP(I,[w,w,w]),a.bx(I,I,j),I[10]*=g,I}getWorldToCamera(d,g){const w=new Float64Array(16),j=new Float64Array(4),I=this.position;return a.bQ(j,this._orientation),a.bJ(I,I,-d),a.bR(w,j),a.bx(w,w,I),w[1]*=-1,w[5]*=-1,w[9]*=-1,w[13]*=-1,w[8]*=g,w[9]*=g,w[10]*=g,w[11]*=g,w}getCameraToClipPerspective(d,g,w,j){const I=new Float64Array(16);return a.bS(I,d,g,w,j),I}getCameraToClipOrthographic(d,g,w,j,I,L){const F=new Float64Array(16);return a.bT(F,d,g,w,j,I,L),F}getDistanceToElevation(d,g=!1){const w=d===0?0:a.bU(d,g?a.bV(this.position[1]):this.position[1]),j=this.forward();return(w-this.position[2])/j[2]}clone(){return new s0([...this.position],[...this.orientation])}}const E5=(_,d)=>({u_matrix:_,u_ground_shadow_factor:d});class qu{constructor(d=0,g=0,w=0,j=0){if(isNaN(d)||d<0||isNaN(g)||g<0||isNaN(w)||w<0||isNaN(j)||j<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=d,this.bottom=g,this.left=w,this.right=j}interpolate(d,g,w){return g.top!=null&&d.top!=null&&(this.top=a.am(d.top,g.top,w)),g.bottom!=null&&d.bottom!=null&&(this.bottom=a.am(d.bottom,g.bottom,w)),g.left!=null&&d.left!=null&&(this.left=a.am(d.left,g.left,w)),g.right!=null&&d.right!=null&&(this.right=a.am(d.right,g.right,w)),this}getCenter(d,g){const w=a.aC((this.left+d-this.right)/2,0,d),j=a.aC((this.top+g-this.bottom)/2,0,g);return new a.P(w,j)}equals(d){return this.top===d.top&&this.bottom===d.bottom&&this.left===d.left&&this.right===d.right}clone(){return new qu(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const qm=15;class a0{constructor(d,g,w,j,I,L,F){this.tileSize=512,this._renderWorldCopies=I===void 0||I,this._minZoom=d||0,this._maxZoom=g||22,this._minPitch=w??0,this._maxPitch=j??60,this.setProjection(L),this.setMaxBounds(F),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 qu,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new s0,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 a0(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return d._elevation=this._elevation,d._centerAltitude=this._centerAltitude,d._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,d.tileSize=this.tileSize,d.mercatorFromTransition=this.mercatorFromTransition,d.width=this.width,d.height=this.height,d.cameraElevationReference=this.cameraElevationReference,d._center=this._center,d._setZoom(this.zoom),d._seaLevelZoom=this._seaLevelZoom,d.angle=this.angle,d._fov=this._fov,d._pitch=this._pitch,d._nearZ=this._nearZ,d._farZ=this._farZ,d._nearClipOffset=this._nearClipOffset,d._averageElevation=this._averageElevation,d._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,d._unmodified=this._unmodified,d._edgeInsets=this._edgeInsets.clone(),d._camera=this._camera.clone(),d._calcMatrices(),d.freezeTileCoverage=this.freezeTileCoverage,d.frustumCorners=this.frustumCorners,d._allowWorldUnderZoom=this._allowWorldUnderZoom,d}get isOrthographic(){return this.projection.name!=="globe"&&this._orthographicProjectionAtLowPitch&&this.pitch0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||d===Number.NEGATIVE_INFINITY&&(!g||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const w=this._elevation;g||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&w.exaggeration()&&this._centerAltitudeValidForExaggeration!==w.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*w.exaggeration(),this._centerAltitudeValidForExaggeration=w.exaggeration()):(this._centerAltitude=d||0,this._centerAltitudeValidForExaggeration=w.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const d=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(d)}sampleAverageElevation(){if(!this._elevation)return 0;const d=this._elevation,g=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],w=this.horizonLineFromTop();let j=0,I=0;for(let L=0;L{const ye=a.ck(re,ne,se,ce,oe);z.has(ye)||(I.push(new a.aR(ne,re,se,ce,oe)),z.add(ye))};for(let ne=0;nere.canonical.z)continue;const se=re.canonical,ce=re.overscaledZ,oe=re.wrap,ye=1<0,De=se.y+10,Ze=re.wrap-(Pe?0:1),$e=re.wrap+(ge?0:1),Ke=Pe?se.x-1:ye-1,Me=ge?se.x+1:0;if(L)w[0]<0?(H(ce,$e,se.z,Me,se.y),w[1]<0&&De&&(H(ce,oe,se.z,se.x,se.y+1),H(ce,$e,se.z,Me,se.y+1)),w[1]>0&&_e&&(H(ce,oe,se.z,se.x,se.y-1),H(ce,$e,se.z,Me,se.y-1))):w[0]>0?(H(ce,Ze,se.z,Ke,se.y),w[1]<0&&De&&(H(ce,oe,se.z,se.x,se.y+1),H(ce,Ze,se.z,Ke,se.y+1)),w[1]>0&&_e&&(H(ce,oe,se.z,se.x,se.y-1),H(ce,Ze,se.z,Ke,se.y-1))):w[1]<0&&De?H(ce,oe,se.z,se.x,se.y+1):_e&&H(ce,oe,se.z,se.x,se.y-1);else{const Be=re.visibleQuadrants;1&Be&&(H(ce,Ze,se.z,Ke,se.y),_e&&(H(ce,oe,se.z,se.x,se.y-1),H(ce,Ze,se.z,Ke,se.y-1))),2&Be&&(H(ce,$e,se.z,Me,se.y),_e&&(H(ce,oe,se.z,se.x,se.y-1),H(ce,$e,se.z,Me,se.y-1))),4&Be&&(H(ce,Ze,se.z,Ke,se.y),De&&(H(ce,oe,se.z,se.x,se.y+1),H(ce,Ze,se.z,Ke,se.y+1))),8&Be&&(H(ce,$e,se.z,Me,se.y),De&&(H(ce,oe,se.z,se.x,se.y+1),H(ce,$e,se.z,Me,se.y+1)))}}const Z=[];for(const ne of I)I.some(re=>ne.isChildOf(re))||Z.push(ne);if(I=Z.filter(ne=>!d.some(re=>!!(ne.overscaledZ{const ge=ye.canonical.x+.5-se[0],Pe=ye.canonical.y+.5-se[1];return ge*ge+Pe*Pe{const Ke=a.ck(De,Pe,_e,Ze,$e);I.has(Ke)||(j.push(new a.aR(Pe,De,_e,Ze,$e)),I.add(Ke))},F=d.reduce((Pe,De)=>Math.max(Pe,De.overscaledZ),w),z=1<{const _e=Math.floor(Pe[0]),Ze=Math.floor(Pe[1]),$e=(Pe[0]-_e)*a.an,Ke=(Pe[1]-Ze)*a.an,Me=Math.floor(De[0]),Be=Math.floor(De[1]),qe=(De[0]-Me)*a.an,st=(De[1]-Be)*a.an;for(let Qe=-1;Qe<=1;Qe++){const xt=_e+Qe;if(!(xt<0||xt>=z)){Z.x=$e-Qe*a.an,ne.x=qe-(xt-Me)*a.an;for(let ft=-1;ft<=1;ft++){const Lt=Ze+ft;Z.y=Ke-ft*a.an,ne.y=st-(Lt-Be)*a.an,a.cI(Z,ne,H)&&L(F,0,w,xt,Lt)}}}},se=g.points,ce=se[a.c9],oe=se[a.ca],ye=this._projectToGround(ce,se[a.cb]),ge=this._projectToGround(oe,se[a.cc]);return re(ce,ye),re(oe,ge),j}_projectToGround(d,g){return a.cd(a.ce(),d,g,d[2]/(d[2]-g[2]))}_projectToZ(d,g,w){const j=d[2]-g[2];return Math.abs(j)<1e-6?a.cf(d):a.cd(a.ce(),d,g,(d[2]-w)/j)}extendTileCoverForTunnels(d,g,w,j){if(w<18)return[];const I=g.points,L=I[a.cg],F=I[a.ch],z=I[a.ci],H=I[a.cj];if(z[2]>=0&&H[2]>=0||L[2]<=0||F[2]<=0)return[];const Z=z[2]<0?this._projectToZ(L,z,0):z,ne=H[2]<0?this._projectToZ(F,H,0):H,re=-j,se=z[2]3&&(oe.length=3),oe}_findExtensionTilesInQuad(d,g,w,j){const I=[],L=new Set;for(const Me of d)L.add(Me.key);const F=d.reduce((Me,Be)=>Math.max(Me,Be.overscaledZ),g),z=1<{const qe=Me.canonical.x+.5-$e,st=Me.canonical.y+.5-Ke,Qe=Be.canonical.x+.5-$e,xt=Be.canonical.y+.5-Ke;return qe*qe+st*st-(Qe*Qe+xt*xt)||Me.canonical.x-Be.canonical.x||Me.canonical.y-Be.canonical.y}),I}coveringTiles(d){let g=this.coveringZoomLevel(d);const w=g,j=this.elevation&&this.elevation.exaggeration(),I=j&&!d.isTerrainDEM,L=this.projection.name==="mercator";if(d.minzoom!==void 0&&gd.maxzoom&&(g=d.maxzoom);const F=this.locationCoordinate(this.center),z=this.center.lat,H=1<{const bt=new a.ag(et.x+25e-6,et.y,et.z),St=new a.ag(et.x,et.y+25e-6,et.z),nr=et.toLngLat(),Wt=bt.toLngLat(),Kt=St.toLngLat(),Mt=this.locationCoordinate(nr),kr=this.locationCoordinate(Wt),Lr=this.locationCoordinate(Kt),yr=Math.hypot(kr.x-Mt.x,kr.y-Mt.y),Er=Math.hypot(Lr.x-Mt.x,Lr.y-Mt.y);return Math.sqrt(yr*Er)*Ke/25e-6},Be=et=>{const gt=Ze,bt=$e;return{aabb:a.cp(this,H,0,0,0,et,bt,gt,this.projection),zoom:0,x:0,y:0,minZ:bt,maxZ:gt,wrap:et,fullyVisible:!1}},qe=[];let st=[];const Qe=g,xt=d.reparseOverscaled?w:g,ft=(ye-this._centerAltitude)*oe,Lt=et=>{if(!this._elevation||!et.tileID||!L)return;const gt=this._elevation.getMinMaxForTile(et.tileID),bt=et.aabb;gt?(bt.min[2]=gt.min,bt.max[2]=gt.max,bt.center[2]=(bt.min[2]+bt.max[2])/2):(et.shouldSplit=ot(et),et.shouldSplit||(bt.min[2]=bt.max[2]=bt.center[2]=this._centerAltitude))},Ft=(et,gt)=>{if(.707*gt{if(et.zoom<_e)return!0;if(et.zoom===Qe)return!1;if(et.shouldSplit!=null)return et.shouldSplit;const gt=et.aabb.distanceX(ge),bt=et.aabb.distanceY(ge);let St=ft,nr=1;if(ne){St=et.aabb.distanceZ(ge);const Er=Math.pow(2,et.zoom),Hr=a.bV((et.y+1)/Er),an=a.bV(et.y/Er),tn=Math.min(Math.max(z,Hr),an),bn=a.cM(tn)/a.cM(z);if(nr=tn===z?1/Math.max(1,this._mercatorScaleRatio-.3):Math.min(1,bn/this._mercatorScaleRatio),this.zoom<=a.cJ&&et.zoom===Qe-1&&bn>=.9)return!0}else if(I&&(St=et.aabb.distanceZ(ge)*oe),this.projection.isReprojectedInTileSpace&&w<=5){const Er=Math.pow(2,et.zoom),Hr=Me(new a.ag((et.x+.5)/Er,(et.y+.5)/Er));nr=Hr>.85?1:Hr}if(!L&&!ne){const Er=Math.sqrt(gt*gt+bt*bt+St*St);let Hr=(1<0;){const et=qe.pop(),gt=et.x,bt=et.y;let St=et.fullyVisible;const nr=()=>this.projection.name==="globe"&&(et.y===0||et.y===(1<Wt)continue;let Kt=0;if(!St){let yr=Pe?et.aabb.intersectsPrecise(se):et.aabb.intersectsPreciseFlat(se);if(yr===0&&nr()){const Er=new a.cn(et.zoom,gt,bt);yr=a.co(this,H,Er,!0).intersectsPrecise(se)}if(yr===0)continue;if(d.calculateQuadrantVisibility)if(se.containsPoint(et.aabb.center))Kt=15;else for(let Er=0;Er<4;Er++)et.aabb.quadrant(Er).intersects(se)!==0&&(Kt|=1<>1),kr={aabb:L?et.aabb.quadrant(Wt):a.cp(this,H,et.zoom+1,Kt,Mt,et.wrap,et.minZ,et.maxZ,this.projection),zoom:et.zoom+1,x:Kt,y:Mt,wrap:et.wrap,fullyVisible:St,tileID:void 0,shouldSplit:void 0,minZ:et.minZ,maxZ:et.maxZ};I&&!ne&&(kr.tileID=new a.aR(et.zoom+1===Qe?xt:et.zoom+1,et.wrap,et.zoom+1,Kt,Mt),Lt(kr)),qe.push(kr)}}if(this.fogCullDistSq){const et=this.fogCullDistSq,gt=this.horizonLineFromTop();st=st.filter(bt=>{const St=[0,0,0,1],nr=[a.an,a.an,0,1],Wt=this.calculateFogTileMatrix(bt.tileID.toUnwrapped());a.aE(St,St,Wt),a.aE(nr,nr,Wt);const Kt=a.cq([],St,nr),Mt=a.cr([],St,nr),kr=a.cK(Kt,Mt);if(kr===0)return!0;let Lr=!1;const yr=this._elevation;if(yr&&kr>et&>!==0){const Er=this.calculateProjMatrix(bt.tileID.toUnwrapped());let Hr;d.isTerrainDEM||(Hr=yr.getMinMaxForTile(bt.tileID)),Hr||(Hr={min:$e,max:Ze});const an=a.cs(this.rotation),tn=[an[0]*a.an,an[1]*a.an,Hr.max];a.ah(tn,tn,Er),Lr=(1-tn[1])*this.height*.5et.distanceSq-gt.distanceSq).map(et=>et.tileID)}resize(d,g){this.width=d,this.height=g,this.pixelsToGLUnits=[2/d,-2/g],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(d){return Math.pow(2,d)}scaleZoom(d){return Math.log2(d)}project(d){const g=a.aC(d.lat,-a.ct,a.ct),w=this.projection.project(d.lng,g);return new a.P(w.x*this.worldSize,w.y*this.worldSize)}unproject(d){return this.projection.unproject(d.x/this.worldSize,d.y/this.worldSize)}get point(){return this.project(this.center)}get pointMerc(){return this.point._div(this.worldSize)}get pixelsPerMeterRatio(){return this.pixelsPerMeter/a.bU(1,this.center.lat)/this.worldSize}setLocationAtPoint(d,g){let w,j;const I=this.centerPoint;if(this.projection.name==="globe"){const F=this.worldSize;w=(g.x-I.x)/F,j=(g.y-I.y)/F}else{const F=this.pointCoordinate(g),z=this.pointCoordinate(I);w=F.x-z.x,j=F.y-z.y}const L=this.locationCoordinate(d);this.setLocation(new a.ag(L.x-w,L.y-j))}setLocation(d){this.center=this.coordinateLocation(d),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(d,g){return this.projection.locationPoint(this,d,g)}locationPoint3D(d,g){return this.projection.locationPoint(this,d,g,!0)}pointLocation(d){return this.coordinateLocation(this.pointCoordinate(d))}pointLocation3D(d,g){return this.coordinateLocation(this.pointCoordinate3D(d,g))}locationCoordinate(d,g){const w=g?a.bU(g,d.lat):void 0,j=this.projection.project(d.lng,d.lat);return new a.ag(j.x,j.y,w)}coordinateLocation(d){return this.projection.unproject(d.x,d.y)}pointRayIntersection(d,g){const w=g??this._centerAltitude,j=[d.x,d.y,0,1],I=[d.x,d.y,1,1];a.aE(j,j,this.pixelMatrixInverse),a.aE(I,I,this.pixelMatrixInverse);const L=I[3];a.cu(j,j,1/j[3]),a.cu(I,I,1/L);const F=j[2],z=I[2];return{p0:j,p1:I,t:F===z?0:(w-F)/(z-F)}}screenPointToMercatorRay(d){const g=[d.x,d.y,0,1],w=[d.x,d.y,1,1];return a.aE(g,g,this.pixelMatrixInverse),a.aE(w,w,this.pixelMatrixInverse),a.cu(g,g,1/g[3]),a.cu(w,w,1/w[3]),g[2]=a.bU(g[2],this._center.lat)*this.worldSize,w[2]=a.bU(w[2],this._center.lat)*this.worldSize,a.cu(g,g,1/this.worldSize),a.cu(w,w,1/this.worldSize),new a.az([g[0],g[1],g[2]],a.ay([],a.ax([],w,g)))}rayIntersectionCoordinate(d){const{p0:g,p1:w,t:j}=d,I=a.bU(g[2],this._center.lat),L=a.bU(w[2],this._center.lat);return new a.ag(a.am(g[0],w[0],j)/this.worldSize,a.am(g[1],w[1],j)/this.worldSize,a.am(I,L,j))}pointCoordinate(d,g=this._centerAltitude){return this.projection.pointCoordinate(this,d.x,d.y,g)}pointCoordinate3D(d,g){if(!this.elevation)return this.pointCoordinate(d,g);let w=this.projection.pointCoordinate3D(this,d.x,d.y);if(w)return new a.ag(w[0],w[1],w[2]);let j=0,I=this.horizonLineFromTop();if(d.y>I)return this.pointCoordinate(d,g);const L=.02*I,F=d.clone();for(let z=0;z<10&&I-j>L;z++){F.y=a.am(j,I,.66);const H=this.projection.pointCoordinate3D(this,F.x,F.y);H?(I=F.y,w=H):j=F.y}return w?new a.ag(w[0],w[1],w[2]):this.pointCoordinate(d)}isPointAboveHorizon(d){return this.projection.isPointAboveHorizon(this,d)}isPointOnSurface(d){if(d.y<0||d.y>this.height||d.x<0||d.x>this.width)return!1;if(this.elevation||this.zoom>=a.cv)return!this.isPointAboveHorizon(d);const g=this.pointCoordinate(d);return g.y>=0&&g.y<=1}_coordinatePoint(d,g){const w=g&&this.elevation?this.elevation.getAtPointOrZero(d,this._centerAltitude):this._centerAltitude,j=[d.x*this.worldSize,d.y*this.worldSize,w+d.toAltitude(),1];return a.aE(j,j,this.pixelMatrix),j[3]>0?new a.P(j[0]/j[3],j[1]/j[3]):new a.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:d,left:g}=this._edgeInsets,w=this.height-this._edgeInsets.bottom,j=this.width-this._edgeInsets.right,I=this.pointLocation3D(new a.P(g,d)),L=this.pointLocation3D(new a.P(j,d)),F=this.pointLocation3D(new a.P(j,w)),z=this.pointLocation3D(new a.P(g,w));let H=Math.min(I.lng,L.lng,F.lng,z.lng),Z=Math.max(I.lng,L.lng,F.lng,z.lng),ne=Math.min(I.lat,L.lat,F.lat,z.lat),re=Math.max(I.lat,L.lat,F.lat,z.lat);const se=Math.pow(2,-this.zoom)/16*270,ce=this.projection.name==="globe"?1:4,oe=(ye,ge,Pe,De,_e)=>{const Ze=(ye+Pe)/2,$e=(ge+De)/2,Ke=new a.P(Ze,$e),{lng:Me,lat:Be}=this.pointLocation3D(Ke),qe=Math.max(0,H-Me,ne-Be,Me-Z,Be-re);H=Math.min(H,Me),Z=Math.max(Z,Me),ne=Math.min(ne,Be),re=Math.max(re,Be),(_ese)&&(oe(ye,ge,Ze,$e,_e+1),oe(Ze,$e,Pe,De,_e+1))};if(oe(g,d,j,d,1),oe(j,d,j,w,1),oe(j,w,g,w,1),oe(g,w,g,d,1),this.projection.name==="globe"){const[ye,ge]=a.cw(this);ye?(re=90,Z=180,H=-180):ge&&(ne=-90,Z=180,H=-180)}return new a.aK(new a.aU(H,ne),new a.aU(Z,re))}_getBoundsRectangular(d,g){const{top:w,left:j}=this._edgeInsets,I=this.height-this._edgeInsets.bottom,L=this.width-this._edgeInsets.right,F=new a.P(j,w),z=new a.P(L,w),H=new a.P(L,I),Z=new a.P(j,I);let ne=this.pointCoordinate(F,d),re=this.pointCoordinate(z,d);const se=this.pointCoordinate(H,g),ce=this.pointCoordinate(Z,g),oe=(ye,ge)=>(ge.y-ye.y)/(ge.x-ye.x);return ne.y>1&&re.y>=0?ne=new a.ag((1-ce.y)/oe(ce,ne)+ce.x,1):ne.y<0&&re.y<=1&&(ne=new a.ag(-ce.y/oe(ce,ne)+ce.x,0)),re.y>1&&ne.y>=0?re=new a.ag((1-se.y)/oe(se,re)+se.x,1):re.y<0&&ne.y<=1&&(re=new a.ag(-se.y/oe(se,re)+se.x,0)),new a.aK().extend(this.coordinateLocation(ne)).extend(this.coordinateLocation(re)).extend(this.coordinateLocation(ce)).extend(this.coordinateLocation(se))}_getBoundsRectangularTerrain(){const d=this.elevation;if(!d.visibleDemTiles.length||d.isUsingMockSource())return this._getBoundsRectangular(0,0);const g=d.visibleDemTiles.reduce((w,j)=>{if(j.dem){const I=j.dem.tree;w.min=Math.min(w.min,I.minimums[0]),w.max=Math.max(w.max,I.maximums[0])}return w},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(g.min*d.exaggeration(),g.max*d.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(d=!0){const g=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,w=this.height/2-g*(1-this._horizonShift);return d?Math.max(0,w):w}getMaxBounds(){return this.maxBounds}setMaxBounds(d){this.maxBounds=d,this.minLat=-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&&(F=ne-H),ne-Zse&&(L=se-z),se-re{for(let ot=0;ot<16;ot++)xt[ot]=a.am(ft[ot],Lt[ot],Ft)})(F,F,z,a.cL(this.pitch>=qm?1:this.pitch/qm))}else F=z;const H=a.cz([],z,L);let Z=a.cz([],F,L);if(this.projection.isReprojectedInTileSpace){const Be=this.locationCoordinate(this.center),qe=a.b9([]);a.bx(qe,qe,[Be.x*this.worldSize,Be.y*this.worldSize,0]),a.aD(qe,qe,a.cA(this)),a.bx(qe,qe,[-Be.x*this.worldSize,-Be.y*this.worldSize,0]),a.aD(Z,Z,qe),a.aD(H,H,qe),this.inverseAdjustmentMatrix=a.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=a.cC([],Z,[this.worldSize,this.worldSize,this.worldSize/I,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([],F);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 se=a.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=a.b8(se);const ce=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;se[8]=2*-d.x/this.width,se[9]=2*(d.y+ce)/this.height,this.skyboxMatrix=a.aD(re,se,re);const oe=this.point,ye=oe.x,ge=oe.y,Pe=this.width%2/2,De=this.height%2/2,_e=Math.cos(this.angle),Ze=Math.sin(this.angle),$e=ye-Math.round(ye)+_e*Pe+Ze*De,Ke=ge-Math.round(ge)+_e*De+Ze*Pe,Me=new Float64Array(Z);if(a.bx(Me,Me,[$e>.5?$e-1:$e,Ke>.5?Ke-1:Ke,0]),this.alignedProjMatrix=Me,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,H),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,w=this._camera.position,j=1/this.height/this._pixelsPerMercatorPixel,I=[d,d,g];a.bJ(I,I,j),a.bJ(w,w,-1),a.cG(w,w,I);const L=a.bb();a.bx(L,L,w),a.cC(L,L,I),this.mercatorFogMatrix=L,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(d,g,j)}_computeCameraPosition(d){const g=(d=d||this.pixelsPerMeter)/this.pixelsPerMeter,w=this._camera.forward(),j=this.point,I=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*g-d/this.worldSize*this._centerAltitude;return[j.x/this.worldSize-w[0]*I,j.y/this.worldSize-w[1]*I,d/this.worldSize*this._centerAltitude-w[2]*I]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(d){const g=this._maxCameraBoundsDistance()*Math.cos(this._pitch),w=this._camera.position[2],j=d[2];let I=1;this.projection.wrap&&(this.center=this.center.wrap()),j>0&&(I=Math.min((g-w)/j,1)),this._camera.position=a.bg([],this._camera.position,d,I),this._updateStateFromCamera()}_updateStateFromCamera(){const d=this._camera.position,g=this._camera.forward(),{pitch:w,bearing:j}=this._camera.getPitchBearing(),I=a.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,L=this._mercatorZfromZoom(this._maxZoom)*Math.cos(a.ap(this._maxPitch)),F=Math.max((d[2]-I)/Math.cos(w),L),z=this._zoomFromMercatorZ(F);a.bg(d,d,g,F),this._pitch=a.aC(w,a.ap(this.minPitch),a.ap(this.maxPitch)),this.angle=a.bs(j,-Math.PI,Math.PI),this._setZoom(a.aC(z,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,w=a.cv,j=0,I=1/0;for(;w-g>1e-6&&w>g;){const L=g+.5*(w-g),F=this.tileSize*Math.pow(2,L),z=this.getCameraToCenterDistance(this.projection,L,F),H=this.scaleZoom(z/(Math.max(0,d)*this.tileSize)),Z=Math.abs(L-H);ZH||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 w=a.ai(a.ax([],this._camera.position,d)),j=this._zoomFromMercatorZ(w)+g;return w-this._mercatorZfromZoom(j)}getCameraPoint(){if(this.projection.name==="globe"){const d=function([g,w,j],I){const L=[g,w,j,1];a.aE(L,L,I);const F=L[3]=Math.max(L[3],1e-6);return L[0]/=F,L[1]/=F,L[2]/=F,L}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new 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,w=this.worldSize){const j=a.cy(d,g,this.width,this.height,1024),I=d.pixelSpaceConversion(this.center.lat,w,j);let L=.5/Math.tan(.5*this._fov)*this.height*I;return this.isOrthographic&&(L=a.am(1,L,a.cL(this.pitch>=qm?1:this.pitch/qm))),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 Ma=(_,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,w=g.pitch,j=g.isLODDisabled(!1)?60:30;if(w0,uniformValues:{u_cutoff_params:[g._nearZ,g._farZ,(Z-g._nearZ)/I,(Z-re-g._nearZ)/I]}}},Tf=2048;class V_{constructor(d,g){this.aabb=d,this.lastCascade=g}}class yN{add(d,g){const w=this.receivers[d.key];w!==void 0?(w.aabb.min[0]=Math.min(w.aabb.min[0],g.min[0]),w.aabb.min[1]=Math.min(w.aabb.min[1],g.min[1]),w.aabb.min[2]=Math.min(w.aabb.min[2],g.min[2]),w.aabb.max[0]=Math.max(w.aabb.max[0],g.max[0]),w.aabb.max[1]=Math.max(w.aabb.max[1],g.max[1]),w.aabb.max[2]=Math.max(w.aabb.max[2],g.max[2])):this.receivers[d.key]=new V_(g,null)}clear(){this.receivers={}}get(d){return this.receivers[d.key]}computeRequiredCascades(d,g,w){const j=a.cU.fromPoints(d.points);let I=0;for(const L in this.receivers){const F=this.receivers[L];if(!F||!j.intersectsAabb(F.aabb))continue;F.aabb.min=j.closestPoint(F.aabb.min),F.aabb.max=j.closestPoint(F.aabb.max);const z=F.aabb.getCorners();for(let H=0;H1||re[1]<-1||re[1]>1){Z=!1;break}}if(F.lastCascade=H,I=Math.max(I,H),Z)break}}return I+1}}class o0{constructor(d){this.painter=d,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new yN,this._depthMode=new Ir(d.context.gl.LEQUAL,Ir.ReadWrite,[0,1]),this._uniformValues={u_light_matrix_0:new Float32Array(16),u_light_matrix_1:new Float32Array(16),u_shadow_intensity:0,u_fade_range:[0,0],u_shadow_normal_offset:[1,1,1],u_shadow_texel_size:1,u_shadow_map_resolution:1,u_shadow_direction:[0,0,1],u_shadow_bias:[36e-5,.0012,.012],u_shadowmap_0:0,u_shadowmap_1:0},this._forceDisable=!1,this.useNormalOffset=!1}destroy(){for(const d of this._cascades)d.texture.destroy(),d.framebuffer.destroy();this._cascades=[]}updateShadowParameters(d,g){const w=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!g||!g.properties)return;const j=g.properties.get("shadow-intensity"),I=g.properties.get("shadow-draw-before-layer");if(!g.shadowsEnabled()||j<=0)return;let L=-1,F=0;for(const ge of w.style.order){const Pe=w.style._mergedLayers[ge];Pe.hasShadowPass()&&!Pe.isHidden(d.zoom)&&(L=F),!I||I!==ge&&I!==Pe.slot||(this._drawShadowAfterLayer=F>0?F-1:0),F+=1}if(this._enabled=L>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=L);const z=w.context,H=Tf,Z=Tf;if(this._cascades.length===0||Tf!==this._cascades[0].texture.size[0]){this._cascades=[];for(let ge=0;ge<2;++ge){const Pe=z.gl,De=z.createFramebuffer(H,Z,0,"texture"),_e=new a.T(z,{width:H,height:Z,data:null},Pe.DEPTH_COMPONENT16);De.depthAttachment.set(_e.texture),this._cascades.push({framebuffer:De,texture:_e,matrix:[],far:0,boundingSphereRadius:0,frustum:new a.cl,scale:0})}}this.shadowDirection=xN(g);let ne=0;if(d.elevation){const ge=d.elevation,Pe=[1e4,-1e4];ge.visibleDemTiles.filter(De=>De.dem).forEach(De=>{const _e=De.dem.tree;Pe[0]=Math.min(Pe[0],_e.minimums[0]),Pe[1]=Math.max(Pe[1],_e.maximums[0])}),Pe[0]!==1e4&&(ne=(Pe[1]-Pe[0])*ge.exaggeration())}const re=1.5*d.cameraToCenterDistance,se=3*re,ce=new Float64Array(16);for(let ge=0;ge=0)return{};const I=function(z,H,Z){const ne=Z/(1<0&&(a.cT(I[1],I[1],[j[0]*L,0,0]),a.cT(I[2],I[2],[j[0]*L,0,0])),j[1]<0?(a.cT(I[0],I[0],[0,j[1]*L,0]),a.cT(I[1],I[1],[0,j[1]*L,0])):j[1]>0&&(a.cT(I[2],I[2],[0,j[1]*L,0]),a.cT(I[3],I[3],[0,j[1]*L,0]));const F={};return F.vertices=I,F.planes=[q_(I[1],I[0],I[4]),q_(I[2],I[1],I[5]),q_(I[3],I[2],I[6]),q_(I[0],I[3],I[7])],F}addShadowReceiver(d,g,w){this._receivers.add(d,a.cU.fromTileIdAndHeight(d,g,w))}getMaxCascadeForTile(d){const g=this._receivers.get(d);return g&&g.lastCascade?g.lastCascade:0}}function q_(_,d,g){const w=a.ax([],g,d),j=a.ax([],_,d),I=a.bh([],w,j),L=a.ai(I);return L===0?[0,0,1,0]:(a.bJ(I,I,1/L),[I[0],I[1],I[2],-a.bi(I,d)])}function xN(_){const d=_.properties.get("direction"),g=a.cP(d.x,d.y,d.z);g[2]=a.aC(g[2],0,75);const w=a.cR([g[0],g[1],g[2]]);return a.cQ(w.x,w.y,w.z)}function Gu(_,d,g){const w=d.properties.get("color-use-theme")==="none",j=d.properties.get("color"),I=d.properties.get("intensity"),L=d.properties.get("direction"),F=[L.x,L.y,L.z],z=g.properties.get("color-use-theme")==="none",H=g.properties.get("color"),Z=g.properties.get("intensity"),ne=Math.max(a.bi([0,0,1],F),0),re=[0,0,0];a.bJ(re,H.toPremultipliedRenderColor(z?null:_.getLut(d.scope)).toArray01Linear().slice(0,3),Z);const se=[0,0,0];return a.bJ(se,j.toPremultipliedRenderColor(w?null:_.getLut(g.scope)).toArray01Linear().slice(0,3),ne*I),a.cW([re[0]>0?re[0]/(re[0]+se[0]):0,re[1]>0?re[1]/(re[1]+se[1]):0,re[2]>0?re[2]/(re[2]+se[2]):0])}function l0(_,d,g,w,j,I){const L=_.zoom,F=_.scale,z=_.worldSize,H=1/z,Z=_.aspect,ne=Math.sqrt(1+Z*Z)*Math.tan(.5*_.fovX),re=ne*ne,se=w-g,ce=w+g;let oe,ye;re>se/ce?(oe=w,ye=w*ne):(oe=.5*ce*(1+re),ye=.5*Math.sqrt(se*se+2*(w*w+g*g)*re+ce*ce*re*re));const ge=_.projection.pixelsPerMeter(_.center.lat,z),Pe=_._camera.getCameraToWorldMercator(),De=[0,0,-oe*H];a.ah(De,De,Pe);let _e=ye*H;const Ze=function(St){return St[0]/=F,St[1]/=F,St[2]=a.bU(St[2],_._center.lat),St},$e=_._edgeInsets;if(!($e.left===0&&$e.top===0&&$e.right===0&&$e.bottom===0||$e.left===$e.right&&$e.top===$e.bottom)){const St=_._camera.getWorldToCamera(_.worldSize,_.projection.zAxisUnit==="meters"?ge:1),nr=_._camera.getCameraToClipPerspective(_._fov,_.width/_.height,g,w);nr[8]=2*-_.centerOffset.x/_.width,nr[9]=2*_.centerOffset.y/_.height;const Wt=new Float64Array(16);a.cz(Wt,nr,St);const Kt=new Float64Array(16);a.b7(Kt,Wt);const Mt=a.cl.fromInvProjectionMatrix(Kt,z,L,!0);for(const kr of Mt.points){const Lr=Ze(kr);_e=Math.max(_e,a.bK(a.cV([],De,Lr)))}}_e*=j/(j-1);const Ke=Math.acos(d[2]),Me=Math.atan2(-d[0],-d[1]),Be=new s0;Be.position=De,Be.setPitchBearing(Ke,Me);const qe=Be.getWorldToCamera(z,ge),st=_e*z,Qe=Math.min(_._mercatorZfromZoom(17)*z*-2,-2*st),xt=Be.getCameraToClipOrthographic(-st,st,-st,st,Qe,(st+I*ge)/d[2]),ft=new Float64Array(16);a.aD(ft,xt,qe);const Lt=a.cQ(Math.floor(1e6*De[0])/1e6*z,Math.floor(1e6*De[1])/1e6*z,0),Ft=.5*j,ot=[0,0,0];a.ah(ot,Lt,ft),a.bJ(ot,ot,Ft);const et=[Math.floor(ot[0]),Math.floor(ot[1]),Math.floor(ot[2])],gt=[0,0,0];a.ax(gt,ot,et),a.bJ(gt,gt,-1/Ft);const bt=new Float64Array(16);return a.b9(bt),a.bx(bt,bt,gt),a.aD(ft,bt,ft),[ft,st]}class j5 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(w=>{const j=a.cY(w),I=new a.cZ(d,g,void 0,void 0,j);return I.computeBoundsAndApplyParent(),I}).catch(w=>{if(w&&w.status===404)return null;this.fire(new a.B(new Error(`Could not load model ${d} from ${g}: ${w.message}`)))})}load(d,g,w={forceReload:!1}){this.models[g]||(this.models[g]={});const j=Object.keys(d),I=[],L=[];for(const F of j){const z=d[F];this.hasURLBeenRequested(z)&&!w.forceReload||(this.modelByURL[z]={modelId:F,scope:g},I.push(this.loadModel(F,z)),L.push(F)),this.models[g][F]||(this.models[g][F]={model:null,numReferences:1})}this.numModelsLoading[g]=(this.numModelsLoading[g]||0)+L.length,Promise.allSettled(I).then(F=>{for(let z=0;z{this.fire(new a.B(new Error(`Could not load models: ${F.message}`)))})}isLoaded(){for(const d in this.numModelsLoading)if(this.numModelsLoading[d]>0)return!1;return!0}hasModel(d,g,w={exactIdMatch:!1}){return!!(w.exactIdMatch?this.getModel(d,g):this.getModelByURL(this.modelUris[g][d]))}getModel(d,g){return this.models[g]||(this.models[g]={}),this.models[g][d]?this.models[g][d].model:void 0}getModelByURL(d){if(!d)return null;const g=this.modelByURL[d];return g?this.models[g.scope][g.modelId].model:null}hasModelBeenAdded(d,g){return this.models[g]&&this.models[g][d]!==void 0}getModelURIs(d){return this.modelUris[d]||{}}addModel(d,g,w){this.models[w]||(this.models[w]={}),this.modelUris[w]||(this.modelUris[w]={});const j=this.requestManager.normalizeModelURL(g);if((this.hasModel(d,w,{exactIdMatch:!0})||this.hasModelBeenAdded(d,w))&&this.modelUris[w][d]===j)this.models[w][d].numReferences++;else if(this.hasURLBeenRequested(j)){const{scope:I,modelId:L}=this.modelByURL[j];this.models[I][L].numReferences++}else this.modelUris[w][d]=j,this.load({[d]:this.modelUris[w][d]},w)}addModelURLs(d,g){this.models[g]||(this.models[g]={}),this.modelUris[g]||(this.modelUris[g]={});const w=this.modelUris[g];for(const j in d)w[j]=this.requestManager.normalizeModelURL(d[j])}reloadModels(d){this.load(this.modelUris[d],d,{forceReload:!0})}addModelsFromBucket(d,g){this.models[g]||(this.models[g]={}),this.modelUris[g]||(this.modelUris[g]={});const w={};for(const j of d)this.hasModel(j,g,{exactIdMatch:!0})||this.hasURLBeenRequested(j)?this.models[g][j].numReferences++:this.modelUris[g][j]&&!this.hasURLBeenRequested(j)?w[j]=this.modelUris[g][j]:!this.hasURLBeenRequested(j)&&a.c_(j,!1)&&(this.modelUris[g][j]=this.requestManager.normalizeModelURL(j),w[j]=this.modelUris[g][j]);this.load(w,g)}hasURLBeenRequested(d){return this.modelByURL[d]!==void 0}removeModel(d,g,w=!1,j=!1){if(this.models[g]&&this.models[g][d]&&(this.models[g][d].numReferences--,this.models[g][d].numReferences===0||j)){const I=this.modelUris[g][d];w||delete this.modelUris[g][d],delete this.modelByURL[I];const L=this.models[g][d].model;if(!L)return;delete this.models[g][d],L.destroy()}}destroy(){for(const d of Object.keys(this.models))for(const g of Object.keys(this.models[d])){const w=this.models[d][g].model;delete this.models[d][g],w&&w.destroy()}this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(d){return this.models[d]||(this.models[d]={}),Object.keys(this.models[d])}upload(d,g){this.models[g]||(this.models[g]={});for(const w in this.models[g])this.models[g][w].model&&this.models[g][w].model.upload(d.context)}}const KT=a.a8.colorTheme,Cg=new a.ab({data:new a.ac(KT.data)});function vN(_){if(!_.metadata||!_.metadata.content_area)return;const d=a.o.devicePixelRatio,{left:g,top:w,width:j,height:I}=_.metadata.content_area,L=g*d,F=w*d;return[L,F,L+j*d,F+I*d]}function c0(_){if(_)return _.map(([d,g])=>[d*a.o.devicePixelRatio,g*a.o.devicePixelRatio])}class YT{constructor(d,g,w){this.id=d,this.scope=g,this.sourceCache=w,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(d){this.missingRequests.has(d.name)||this.pendingRequests.has(d.name)||this.pendingRequests.add(d.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const d=new Map;if(!this.sourceCache.loaded())return d;const g=this.sourceCache.getVisibleCoordinates();if(g.length===0)return d;const w=this.sourceCache.getSource();if(!(w instanceof Fm))return d;const j=g.map(L=>this.sourceCache.getTile(L)),I=w.getImages(j,Array.from(this.pendingRequests));for(const[L,F]of I)d.set(a.I.from({name:L,iconsetId:this.id}),F),this.pendingRequests.delete(L);for(const L of this.pendingRequests)this.missingRequests.add(L);return this.pendingRequests.clear(),d}}class Ef{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(d,g,w,j,I){if(wz*this._hysteresisRatio&&(L=this._previousClosestBuildingId):H&&!L&&(L=this._previousClosestBuildingId),this._previousClosestBuildingId=L,L}_calculateDistance(d,g){if(!g.center)return Number.MAX_VALUE;const w=d.lat-g.center[1],j=d.lng-g.center[0];return w*w+j*j}_isBuildingVisible(d,g,w){if(!w)return!1;for(const j of d.floorIds){const I=d.floors[j];if(!I.geometry)continue;const L=I.geometry;if(L.type==="Polygon"){const F=this._convertRingToPoints(L.coordinates[0]);if(a.bw(F,w))return!0}else if(L.type==="MultiPolygon"){const F=this._convertMultiPolygonToPoints(L.coordinates);if(a.d0(w,F))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(w=>new a.P(w[0],w[1])))}}class A5 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 Ef,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[w,j]of Object.entries(d.buildings))if(this._buildings[w])for(const I of j.floorIds)this._buildings[w].floorIds.add(I),this._buildings[w].floors[I]?this._mergeFloors(this._buildings[w].floors[I],j.floors[I]):(this._buildings[w].floors[I]=j.floors[I],g=!0);else this._buildings[w]=j,g=!0;g&&this._recalculateActiveFloors()}getIndoorTileOptions(d,g){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(d,g),indoorState:this._indoorState}:null}getControlState(){const d=this._buildings,g=this._closestBuildingId,w=g&&d?d[g]:void 0;if(!w)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let j=null;for(const L of w.floorIds)if(this._activeFloors&&this._activeFloors.has(L)){j=L;break}const I=Array.from(w.floorIds).map(L=>({id:L,name:w.floors[L].name,zIndex:w.floors[L].zIndex})).sort((L,F)=>F.zIndex-L.zIndex).filter((L,F,z)=>F===0||L.zIndex!==z[F-1].zIndex);return{selectedFloorId:j,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:I}}_updateUI(){this._initialLoadDone=!0;const d=this._style.map.transform,g=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,d.center,d.zoom,d.getBounds(),this._makeViewportPolygon());if(g!==this._closestBuildingId){const w=this._closestBuildingId;this._closestBuildingId=g,this._onBuildingTransition(w,g),this._updateIndoorSelector()}}_onBuildingTransition(d,g){if(!this._indoorState)return;!g&&d?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!g&&!d&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new 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,w){if(g===w)return!0;if(!g||!w||g.size!==w.size)return!1;for(const j of g)if(!w.has(j))return!1;return!0})(d,this._activeFloors)||(this._activeFloors=d,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(d,g){g.geometry&&(d.geometry?(d.geometry.type==="Polygon"&&(d.geometry={type:"MultiPolygon",coordinates:[d.geometry.coordinates]}),g.geometry.type==="Polygon"?d.geometry.coordinates.push(g.geometry.coordinates):g.geometry.type==="MultiPolygon"&&d.geometry.coordinates.push(...g.geometry.coordinates)):d.geometry=g.geometry)}_makeViewportPolygon(){const d=this._style.map.transform,g=d.width,w=d.height;return[d.pointLocation(new a.P(0,0)),d.pointLocation(new a.P(g,0)),d.pointLocation(new a.P(g,w)),d.pointLocation(new a.P(0,w))].map(j=>new a.P(j.lng,j.lat))}}const Gm=(_,d)=>hr(_,d&&d.filter(g=>g.identifier!=="source.canvas")),k5=a.aJ(Jn,["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"]),_N=a.aJ(Jn,["setCenter","setZoom","setBearing","setPitch"]),ZT=new Set(["background","sky","slot","custom"]),G_={version:8,layers:[],sources:{}},XT={duration:300,delay:0};class yu 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({},XT),this._buildingIndex=new Zx(this),this.crossTileSymbolIndex=new kg,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 vn,this._hasDataDrivenEmissive=!1,this.indoorManager=new A5(this),this.dispatcher=g.dispatcher?g.dispatcher:new ar(En(),this),this.map.painter&&this.map.painter.context){const j=this.map.painter.context.maxUniformBufferBindings,I=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:j,maxUniformBlockSizeDwords:I,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}g.imageManager?this.imageManager=g.imageManager:(this.imageManager=new ni(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 j5(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 w=this;this._rtlTextPluginCallback=yu.registerForPluginStateChange(j=>{w.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:j.pluginStatus,pluginURL:j.pluginURL},(I,L)=>{if(a.d6(I),L&&L.every(F=>F))for(const F in w._sourceCaches){const z=w._sourceCaches[F],H=z.getSource().type;H!=="vector"&&H!=="geojson"||z.reload()}})}),this.on("data",j=>{if(j.dataType!=="source"||j.sourceDataType!=="metadata")return;const I=this.getOwnSource(j.sourceId);if(I&&I.vectorLayerIds)for(const L in this._layers){const F=this._layers[L];F.source===I.id&&this._validateLayer(F)}})}load(d){return d?(typeof d=="string"?this.loadURL(d):this.loadJSON(d),this):this}_getGlobalId(d){if(!d)return null;if(typeof d=="string"){if(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,w){this.globalId=this._getGlobalId(d);const j=(I,L)=>{try{L(null,this.setState(I,w))}catch(F){L(F,!1)}};if(typeof d=="string"){const I=this.map._requestManager.normalizeStyleURL(d),L=this.map._requestManager.transformRequest(I,a.R.Style);a.m(L,(F,z)=>{F?this.fire(new a.B(F)):z&&j(z,g)})}else typeof d=="object"&&j(d,g)}loadURL(d,g={}){this.fire(new a.C("dataloading",{dataType:"style"}));const w=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 j=this.importsCache.get(d);if(j)return this._load(j,w);const I=this.map._requestManager.transformRequest(d,a.R.Style);this._request=a.m(I,(L,F)=>{if(this._request=null,L)this.fire(new a.B(L));else if(F)return this.importsCache.set(d,F),this._load(F,w)})}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(G_,!1)}_loadImports(d,g,w){if(this.importDepth>=4)return a.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const j=[];for(const I of d){const L=this._createFragmentStyle(I),F=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(j.push(F),this.resolvedImports.has(I.url)){L.loadEmpty();continue}const z=I.data||this.importsCache.get(I.url);z?(I.data?(L.fire(new a.C("dataloading",{dataType:"style"})),L.globalId=L._getGlobalId(z),queueMicrotask(()=>L._load(z,g))):L.loadJSON(z,{validate:g}),this._isInternalStyle(z)&&(L.globalId=null)):I.url?L.loadURL(I.url,{validate:g}):L.loadEmpty();const H={style:L,id:I.id,config:I.config};if(w){const Z=this.fragments.findIndex(({id:ne})=>ne===w);this.fragments=this.fragments.slice(0,Z).concat(H).concat(this.fragments.slice(Z))}else this.fragments.push(H)}return Promise.allSettled(j)}getImportGlobalIds(d=this,g=new Set){for(const w of d.fragments)w.style.globalId&&g.add(w.style.globalId),this.getImportGlobalIds(w.style,g);return[...g.values()]}_createFragmentStyle(d){const g=this.scope?a.F(d.id,this.scope):d.id;let w;const j=this._initialConfig&&this._initialConfig[g];(d.config||j)&&(w=Object.assign({},d.config,j));const I=new yu(this.map,{scope:g,styleChanges:this._changes,importDepth:this.importDepth+1,importsCache:this.importsCache,resolvedImports:new Set(this.resolvedImports),dispatcher:this.dispatcher,imageManager:this.imageManager,glyphManager:this.glyphManager,modelManager:this.modelManager,config:w,configOptions:this.options,colorThemeOverride:d["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return I.setEventedParent(this.map,{style:I}),I}_reloadImports(){this.mergeAll(),this._updateMapProjection(),this.updateConfigDependencies(),this._updateLayers(this._indoorDependentLayers),this.map._triggerCameraUpdate(this.camera),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),this._shouldPrecompile=this.map._precompilePrograms&&this.isRootStyle()}_isInternalStyle(d){return this.isRootStyle()&&(d.fragment||!!d.schema&&d.fragment!==!1)}_load(d,g){if(this._isInternalStyle(d)){const I=Object.assign({},G_,{imports:[{id:"basemap",data:d,url:""}]},d.center?{center:d.center}:{},d.bearing?{bearing:d.bearing}:{},d.pitch?{pitch:d.pitch}:{},d.zoom?{zoom:d.zoom}:{},d.light?{light:d.light}:{});return this._importedAsBasemap=!0,void this._load(I,g)}if(this.updateConfig(this._config,d.schema),g&&Gm(this,du(d)))return;this._loaded=!0;for(const I in d.sources)this.addSource(I,d.sources[I],{validate:!1,isInitialLoad:!0});this.stylesheet=a.d9(d);const w=()=>{if(d.iconsets)for(const z in d.iconsets)this.addIconset(z,d.iconsets[z]);d.sprite?this._loadIconset(d.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0})),!this.glyphManager.url&&d.glyphs&&this.glyphManager.setURL(d.glyphs);const I=zT(this.stylesheet.layers);if(this._order=I.map(z=>z.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 z=this.stylesheet.lights[0];this.light=new $r(z.properties,z.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new $r(this.stylesheet.light)),this._layers={};for(const z of I){const H=a.de(z,this.scope,this._styleColorTheme.lut,this.options);H.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(H.fqid),H.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(H.fqid),this._hasAppearances=this._hasAppearances||H.getAppearances().length!==0,H.setEventedParent(this,{layer:{id:H.id}}),this._layers[H.id]=H;const Z=this.getOwnLayerSourceCache(H),ne=!!this.directionalLight&&this.directionalLight.shadowsEnabled();Z&&H.canCastShadows()&&ne&&(Z.castsShadows=!0)}if(this.glyphManager.url){const z=new Set;for(const H in this._layers){const Z=this._layers[H];if(Z.type==="symbol"&&Z.layout){const ne=Z.layout.get("text-font");ne&&ne.value&&ne.value.kind==="constant"&&z.add(ne.value.value.join(","))}}for(const H of z)this.glyphManager.prefetchRange(H,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const L=this.stylesheet.terrain;L&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(L,1)),this.stylesheet.fog&&this._createFog(this.stylesheet.fog),this.stylesheet.snow&&this._createSnow(this.stylesheet.snow),this.stylesheet.rain&&this._createRain(this.stylesheet.rain),this.stylesheet.transition&&this.setTransition(this.stylesheet.transition),this.fire(new a.C("data",{dataType:"style"}));const F=this.isRootStyle();d.imports?this._loadImports(d.imports,g).then(()=>{this._reloadImports(),this.fire(new a.C(F?"style.load":"style.import.load"))}).catch(z=>{this.fire(new a.B(new Error("Failed to load imports",z))),this.fire(new a.C(F?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new a.C(F?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const j=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(j){const I=this._evaluateColorThemeData(j);this._loadColorTheme(I).then(()=>{w()}).catch(L=>{a.w(`Couldn't load color theme from the stylesheet: ${L}`),w()})}else this._styleColorTheme.lut=null,w()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(d=>d.style.hasAppearances())}mergeAll(){let d,g,w,j,I,L,F,z,H,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 se of re.stylesheet.lights)se.type==="ambient"&&re.ambientLight!=null&&(g=re.ambientLight),se.type==="directional"&&re.directionalLight!=null&&(w=re.directionalLight);j=this._prioritizeTerrain(j,re.terrain,re.stylesheet.terrain),re.stylesheet.fog&&re.fog!=null&&(I=re.fog),re.stylesheet.snow&&re.snow!=null&&(L=re.snow),re.stylesheet.rain&&re.rain!=null&&(F=re.rain),re.stylesheet.camera!=null&&(Z=re.stylesheet.camera),re.stylesheet.projection!=null&&(z=re.stylesheet.projection),re.stylesheet.transition!=null&&(H=re.stylesheet.transition),ne[re.scope]=re._styleColorTheme}}),this.light=d,this.ambientLight=g,this.directionalLight=w,this.fog=I,this.snow=L,this.rain=F,this._styleColorThemeForScope=ne,j===null?delete this.terrain:this.terrain=j,this.camera=Z||{"camera-projection":"perspective"},this.projection=z||{name:"mercator"},this.transition=Object.assign({},XT,H),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(d){const g=w=>{for(const j of w.fragments)g(j.style);d(w)};g(this)}_prioritizeTerrain(d,g,w){const j=d&&d.drapeRenderMode===0;return w===null?g&&g.drapeRenderMode===0?g:j?d:null:g!=null&&(!d||j||g&&g.drapeRenderMode===1)?g:d}mergeTerrain(){let d;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(g=>{d=this._prioritizeTerrain(d,g.terrain,g.stylesheet.terrain)}),d===null?delete this.terrain:this.terrain=d}mergeProjection(){let d;this.forEachFragmentStyle(g=>{g.stylesheet.projection!=null&&(d=g.stylesheet.projection)}),this.projection=d||{name:"mercator"}}mergeSources(){const d={},g={},w={},j={};this.forEachFragmentStyle(I=>{for(const L in I._sourceCaches){const F=a.F(L,I.scope);d[F]=I._sourceCaches[L]}for(const L in I._otherSourceCaches){const F=a.F(L,I.scope);g[F]=I._otherSourceCaches[L]}for(const L in I._symbolSourceCaches){const F=a.F(L,I.scope);w[F]=I._symbolSourceCaches[L]}for(const L in I._fillExtrusionSourceCaches){const F=a.F(L,I.scope);j[F]=I._fillExtrusionSourceCaches[L]}}),this._mergedSourceCaches=d,this._mergedOtherSourceCaches=g,this._mergedSymbolSourceCaches=w,this._mergedFillExtrusionSourceCaches=j}mergeIndoor(){this.forEachFragmentStyle(d=>{if(d.stylesheet&&d.stylesheet.indoor)for(const g of Object.values(d.stylesheet.indoor)){const w=g,j=a.F(w.sourceId,d.scope);this._mergedIndoor[j]=new Set(w.sourceLayers||[])}})}mergeLayers(){const d={},g=[],w={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(L=>{for(const F of L._order){const z=L._layers[F];if(z.type==="slot"){const H=a.da(F);if(d[H])continue;d[H]=[]}z.slot&&d[z.slot]?d[z.slot].push(z):g.push(z)}}),this._mergedOrder=[];let j=-1;const I=(L=[])=>{for(const F of L)if(F.type==="slot"){const z=a.da(F.id);d[z]&&I(d[z]),this._mergedSlots.push(z)}else{const z=a.F(F.id,F.scope);this._mergedOrder.push(z),w[z]=F,F.is3D(!!this.terrain)&&(this._has3DLayers=!0,j=this._mergedOrder.length-1),F.type==="circle"&&(this._hasCircleLayers=!0),F.type==="symbol"&&(this._hasSymbolLayers=!0),F.type==="clip"&&(this._clipLayerPresent=!0)}};if(I(g),this._has3DLayers){const L={};for(let F=0;FL[F]-L[z])}this._mergedLayers=w,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(d){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,d),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(d){return d.data?function(g,w,j){const I=Object.assign({},w);for(const F of Object.keys(KT))I[F]===void 0&&(I[F]=KT[F].default);const L=new a.aa(Cg,g,new Map(j));return L.setTransitionOrValue(I,j),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((w,j)=>{const I="data:image/png;base64,";if(!d||d.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void w();let L=d;L.startsWith(I)||(L=I+L);const F=a.I.from("mapbox-reserved-lut"),z=new Image;z.src=L,z.onerror=()=>{this._styleColorTheme.lutLoading=!1,j(new Error("Failed to load image data"))},z.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==g)return void w();this._styleColorTheme.lutLoading=!1;const{width:H,height:Z,data:ne}=a.o.getImageData(z);if(Z>32)return void j(new Error("The height of the image must be less than or equal to 32 pixels."));if(H!==Z*Z)return void j(new Error("The width of the image must be equal to the height squared."));this.getImage(F)&&this.removeImage(F),this.addImage(F,{data:new a.q({width:H,height:Z},ne),pixelRatio:1,sdf:!1,usvg:!1,version:0});const re=this.imageManager.getImage(F,this.scope);re?(this._styleColorTheme.lut={image:re.data,data:d},w()):j(new Error("Missing LUT image."))}})}getLut(d){const g=this._styleColorThemeForScope[d];return g?g.lut:null}setProjection(d){d?this.stylesheet.projection=d:delete this.stylesheet.projection,this.mergeProjection(),this._updateMapProjection()}applyProjectionUpdate(){this._loaded&&(this.dispatcher.broadcast("setProjection",this.map.transform.projectionOptions),this.map.transform.projection.requiresDraping?(this.getTerrain()||this.stylesheet.terrain)&&!this.disableElevatedTerrain||this.setTerrainForDraping():this.terrainSetForDrapingOnly()&&this.setTerrain(null,0))}_updateMapProjection(){this.isRootStyle()&&(this.map._useExplicitProjection?this.applyProjectionUpdate():this.map._prioritizeAndUpdateProjection(null,this.projection))}_loadSprite(d){this._spriteRequest=function(g,w,j){let I,L,F;const z=a.o.devicePixelRatio>1?"@2x":"";let H=a.m(w.transformRequest(w.normalizeSpriteURL(g,z,".json"),a.R.SpriteJSON),(re,se)=>{H=null,F||(F=re,I=se,ne())}),Z=a.n(w.transformRequest(w.normalizeSpriteURL(g,z,".png"),a.R.SpriteImage),(re,se)=>{Z=null,F||(F=re,L=se,ne())});function ne(){if(F)j(F);else if(I&&L){const re=a.o.getImageData(L),se={};for(const ce in I){const{width:oe,height:ye,x:ge,y:Pe,sdf:De,pixelRatio:_e,stretchX:Ze,stretchY:$e,content:Ke}=I[ce],Me=new a.q({width:oe,height:ye});a.q.copy(re,Me,{x:ge,y:Pe},{x:0,y:0},{width:oe,height:ye},null),se[ce]={data:Me,pixelRatio:_e!==void 0?_e:1,sdf:De!==void 0&&De,stretchX:Ze,stretchY:$e,content:Ke,usvg:!1,version:0}}j(null,se)}}return{cancel(){H&&(H.cancel(),H=null),Z&&(Z.cancel(),Z=null)}}}(d,this.map._requestManager,(g,w)=>{if(this._spriteRequest=null,g)this.fire(new a.B(g));else if(w){const j=new Map;for(const I in w)j.set(a.I.from(I),w[I]);this.addImages(j)}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 w=this.getOwnSourceCache(g.source);if(!w)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 j=w.getSource();if(j.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`)));j.partial=!1;const I=new YT(d,this.scope,w);this.imageManager.addImageProvider(I,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 w,j;this._spriteRequest=(j=(I,L)=>{if(this._spriteRequest=null,I)g?this._loadSprite(d):this.fire(new a.B(I));else if(L){const F=new Map;for(const z in L)F.set(a.I.from(z),L[z]);this.addImages(F)}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((w=this.map._requestManager).transformRequest(w.normalizeIconsetURL(d),a.R.Iconset),(I,L)=>{if(I)return void j(I);const F={},z=a.c$(new a.a$(L));for(const H of z.icons){const Z={version:1,pixelRatio:a.o.devicePixelRatio,content:vN(H),stretchX:H.metadata?c0(H.metadata.stretch_x_areas):void 0,stretchY:H.metadata?c0(H.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:H};F[H.name]=Z}j(null,F)}))}_validateLayer(d){const g=this.getOwnSource(d.source);if(!g)return;const w=d.sourceLayer;w&&(g.type==="geojson"||g.vectorLayerIds&&g.vectorLayerIds.indexOf(w)===-1)&&this.fire(new a.B(new Error(`Source layer "${w}" does not exist on source "${g.id}" as specified by style layer "${d.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const d in this._sourceCaches)if(!this._sourceCaches[d].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading)return!1;for(const{style:d}of this.fragments)if(!d.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((d,g)=>{const w=this.fragments[g];return w&&w.style&&(d.data=w.style.serialize()),d})}_serializeSources(){const d={};for(const g in this._sourceCaches){const w=this._sourceCaches[g].getSource();d[w.id]||(d[w.id]=w.serialize())}return d}_serializeLayers(d){const g=[];for(const w of d){const j=this._layers[w];j&&j.type!=="custom"&&g.push(j.serialize())}return g}hasLightTransitions(){return!(!this.light||!this.light.hasTransition())||!(!this.ambientLight||!this.ambientLight.hasTransition())||!(!this.directionalLight||!this.directionalLight.hasTransition())}hasFogTransition(){return!!this.fog&&this.fog.hasTransition()}hasSnowTransition(){return!!this.snow&&this.snow.hasTransition()}hasRainTransition(){return!!this.rain&&this.rain.hasTransition()}hasTransitions(){if(this.hasLightTransitions()||this.hasFogTransition()||this.hasSnowTransition()||this.hasRainTransition())return!0;for(const d in this._sourceCaches)if(this._sourceCaches[d].hasTransition())return!0;for(const d in this._layers)if(this._layers[d].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const d in this._mergedLayers){const g=this._mergedLayers[d];if(g._transitionablePaint&&g._transitionablePaint._values){const w=g._transitionablePaint._values["line-emissive-strength"];if(w&&w.value&&w.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(d){return d?this.order:this._mergedOrder}isLayerDraped(d){return!!this.terrain&&d.isDraped(this.getLayerSourceCache(d))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(d){const g=this.getOwnLayer(d);if(g)return g;this.fire(new 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 w=this.map.painter;if(w)for(let j=d.minzoom||0;j<(d.maxzoom||25.5);j++){const I=d.getProgramIds();if(I)for(const L of I){const F=d.getDefaultProgramParams(L,g.zoom,this._styleColorTheme.lut);F&&(w.style=this,this.fog&&(w._fogVisible=!0,F.overrideFog=!0,w.getOrCreateProgram(L,F)),w._fogVisible=!1,F.overrideFog=!1,w.getOrCreateProgram(L,F),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(F.overrideRtt=!0,w.getOrCreateProgram(L,F)))}}}update(d){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(d),this.directionalLight&&this.directionalLight.recalculate(d);const g=this.calculateLightsBrightness();d.brightness=g||0,g!==this._brightness&&(this._brightness=g,this.dispatcher.broadcast("setBrightness",g)),d.worldview!==this._worldview&&(this._worldview=d.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const w=this._changes.isDirty();let j=!1;if(this._changes.isDirty()){const z=this._changes.getLayerUpdatesByScope();for(const H in z){const{updatedIds:Z,removedIds:ne}=z[H];(Z||ne)&&(this._updateWorkerLayers(H,Z,ne),j=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(d),this.light&&this.light.updateTransitions(d),this.ambientLight&&this.ambientLight.updateTransitions(d),this.directionalLight&&this.directionalLight.updateTransitions(d),this.fog&&this.fog.updateTransitions(d),this.snow&&this.snow.updateTransitions(d),this.rain&&this.rain.updateTransitions(d),this._changes.reset()}const I={};for(const z in this._mergedSourceCaches){const H=this._mergedSourceCaches[z];I[z]=H.used,H.used=!1,H.tileCoverLift=0}const L={};for(const z of this._mergedOrder){const H=this._mergedLayers[z];if((H.visibility!=="none"||H.hasTransition())&&H.recalculate(d,this._availableImages),!H.isHidden(d.zoom)){const Z=this.getLayerSourceCache(H);Z&&(Z.used=!0,Z.tileCoverLift=Math.max(Z.tileCoverLift,H.tileCoverLift()))}if(H.type==="fill-extrusion"){const Z=a.F(H.source,H.scope);if(Z in this._mergedFillExtrusionSourceCaches){const ne=H.layout&&H.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(H,d)}):this.precompilePrograms(H,d))}this._shouldPrecompile&&(this._precompileDone=!0);for(const z in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[z].setMaxzoomOverride(L[z]!=null?L[z]:null);this.terrain&&j&&this.mergeLayers();const F=this.imageManager.getPendingImageProviders();for(const z of F)z.sourceCache.used=!0;for(const z in I){const H=this._mergedSourceCaches[z];I[z]!==H.used&&H.getSource().fire(new a.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:H.getSource().id}))}this.light&&this.light.recalculate(d),this.terrain&&this.terrain.recalculate(d),this.fog&&this.fog.recalculate(d),this.snow&&this.snow.recalculate(d),this.rain&&this.rain.recalculate(d),this.z=d.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),w&&this.fire(new a.C("data",{dataType:"style"}))}updateImageProviders(){const d=this.imageManager.getPendingImageProviders();for(const g of d){const w=g.resolvePendingRequests(),j=this.getFragmentStyle(g.scope);j&&j.addImages(w)}}_updateTilesForChangedImages(){const d={};for(const g in this._mergedSourceCaches){const w=this._mergedSourceCaches[g].getSource().scope;d[w]=d[w]||this._changes.getUpdatedImages(w),d[w].length!==0&&this._mergedSourceCaches[g].reloadTilesForDependencies(["icons","patterns"],d[w])}for(const g in d)this._changes.resetUpdatedImages(g)}_updateWorkerLayers(d,g,w){const j=this.getFragmentStyle(d);j&&this.dispatcher.broadcast("updateLayers",{layers:g?j._serializeLayers(g):[],scope:d,removedIds:w||[],options:j.options})}setState(d,g){if(this._checkLoaded(),Gm(this,du(d)))return!1;(d=a.d9(d)).layers=zT(d.layers);const w=function(L,F){if(!L)return[{command:Jn.setStyle,args:[F]}];let z=[];try{if(!a.b6(L.version,F.version))return[{command:Jn.setStyle,args:[F]}];if(a.b6(L.center,F.center)||z.push({command:Jn.setCenter,args:[F.center]}),a.b6(L.zoom,F.zoom)||z.push({command:Jn.setZoom,args:[F.zoom]}),a.b6(L.bearing,F.bearing)||z.push({command:Jn.setBearing,args:[F.bearing]}),a.b6(L.pitch,F.pitch)||z.push({command:Jn.setPitch,args:[F.pitch]}),a.b6(L.sprite,F.sprite)||z.push({command:Jn.setSprite,args:[F.sprite]}),a.b6(L.glyphs,F.glyphs)||z.push({command:Jn.setGlyphs,args:[F.glyphs]}),a.b6(L.imports,F.imports)||function(se=[],ce=[],oe){ce=ce||[];const ye=(se=se||[]).map(Tg),ge=ce.map(Tg),Pe=se.reduce(Xx,{}),De=ce.reduce(Xx,{}),_e=ye.slice();let Ze,$e,Ke,Me;for(Ze=0,$e=0;Ze{se.source&&H[se.source]?z.push({command:Jn.removeLayer,args:[se.id]}):ne.push(se)});let re=L.terrain;re&&H[re.source]&&(z.push({command:Jn.setTerrain,args:[void 0]}),re=void 0),z=z.concat(Z),a.b6(re,F.terrain)||z.push({command:Jn.setTerrain,args:[F.terrain]}),function(se,ce,oe){ce=ce||[];const ye=(se=se||[]).map(Tg),ge=ce.map(Tg),Pe=se.reduce(Xx,{}),De=ce.reduce(Xx,{}),_e=ye.slice(),Ze=Object.create(null);let $e,Ke,Me,Be,qe,st,Qe;for($e=0,Ke=0;$e!(L.command in _N));if(w.length===0)return!1;const j=w.filter(L=>!(L.command in k5));if(j.length>0)throw new Error(`Unimplemented: ${j.map(L=>L.command).join(", ")}.`);const I=[];return w.forEach(L=>{I.push(this[L.command](...L.args))}),g&&Promise.all(I).then(g).catch(g),this.stylesheet=d,this.mergeAll(),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),!0}_updateWorkerImages(){this._availableImages=this.imageManager.listImages(this.scope),this.dispatcher.broadcast("setImages",{scope:this.scope,images:this._availableImages})}_updateWorkerModels(){this._availableModels=this.modelManager.getModelURIs(this.scope),this.dispatcher.broadcast("setModels",{scope:this.scope,models:this._availableModels})}addImages(d){if(d.size===0)return this;for(const[g,w]of d.entries()){if(this.getImage(g))return this.fire(new a.B(new Error(`An image with the name "${g.name}" already exists.`)));this.imageManager.addImage(g,this.scope,w),this._changes.updateImage(g,this.scope)}return this._updateWorkerImages(),this.fire(new 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,w=!1){this.imageManager.updateImage(d,this.scope,g),w&&(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,w={}){return this._checkLoaded(),this._validate(zt,`models.${d}`,g,null,w)||(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,w={}){if(this._checkLoaded(),this.getOwnSource(d)!==void 0)throw new Error(`There is already a source with ID "${d}".`);if(!g.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(g).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(g.type)>=0&&this._validate(Kx,`sources.${d}`,g,null,w))return;this.map&&this.map._collectResourceTiming&&(g.collectResourceTiming=!0);const j=P_(d,g,this.dispatcher,this);j.scope=this.scope,j.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(j.id),source:j.serialize(),sourceId:j.id}));const I=L=>{const F=(L===a.b4.Symbol?"symbol:":L===a.b4.FillExtrusion?"fill-extrusion:":"other:")+j.id,z=a.F(F,this.scope),H=this._sourceCaches[F]=new fu(z,j,L);L===a.b4.Symbol?this._symbolSourceCaches[j.id]=H:L===a.b4.FillExtrusion?this._fillExtrusionSourceCaches[j.id]=H:this._otherSourceCaches[j.id]=H,H.onAdd(this.map)};I(a.b4.Other),g.type!=="vector"&&g.type!=="geojson"||(I(a.b4.Symbol),g.type==="vector"&&I(a.b4.FillExtrusion)),j.onAdd&&j.onAdd(this.map),w.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(d){this._checkLoaded();const g=this.getOwnSource(d);if(!g)throw new Error("There is no source with this ID");for(const j in this._layers)if(this._layers[j].source===d)return this.fire(new a.B(new Error(`Source "${d}" cannot be removed while layer "${j}" 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 j=Object.entries(this.stylesheet.iconsets).find(([I,L])=>L.type==="source"&&L.source===d);if(j)return this.fire(new a.B(new Error(`Source "${d}" cannot be removed while iconset "${j[0]}" is using it.`)))}const w=this.getOwnSourceCaches(d);for(const j of w){const I=a.da(j.id);delete this._sourceCaches[I],this._changes.discardSourceCacheUpdate(j.id),j.fire(new a.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:j.getSource().id})),j.setEventedParent(null),j.clearTiles()}return delete this._otherSourceCaches[d],delete this._symbolSourceCaches[d],delete this._fillExtrusionSourceCaches[d],this.mergeSources(),g.setEventedParent(null),g.onRemove&&g.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(d,g){this._checkLoaded(),this.getOwnSource(d).setData(g),this._changes.setDirty()}getOwnSource(d){const g=this.getOwnSourceCache(d);return g&&g.getSource()}getOwnSources(){const d=[];for(const g in this._otherSourceCaches){const w=this.getOwnSourceCache(g);w&&d.push(w.getSource())}return d}areTilesLoaded(){const d=this._mergedSourceCaches;for(const g in d){const w=d[g]._tiles;for(const j in w){const I=w[j];if(I.state!=="loaded"&&I.state!=="errored")return!1}}return!0}setLights(d){if(this._checkLoaded(),!d)return delete this.ambientLight,void delete this.directionalLight;const g=this._getTransitionParameters();for(const I of d){if(this._validate(de,"lights",I))return;switch(I.type){case"ambient":if(this.ambientLight){const L=this.ambientLight;L.set(I),L.updateTransitions(g)}else this.ambientLight=new ja(I,So(),this.scope,this.options);break;case"directional":if(this.directionalLight){const L=this.directionalLight;L.set(I),L.updateTransitions(g)}else this.directionalLight=new ja(I,cc(),this.scope,this.options)}}const w=Object.assign(g,{worldview:this.map.getWorldview()}),j=new a.ae(this.z||0,w);this.ambientLight&&this.ambientLight.recalculate(j),this.directionalLight&&this.directionalLight.recalculate(j),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const d=this.directionalLight,g=this.ambientLight;if(!d||!g)return;const w=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)),j=d.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),I=d.properties.get("intensity"),L=d.properties.get("direction"),F=1-a.cP(L.x,L.y,L.z)[2]/90,z=w(j)*I*F,H=g.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Z=g.properties.get("intensity"),ne=w(H)*Z;return Number(((z+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),w=this.fragments.find(({id:I})=>I===g);if(!w)return;const j=a.da(d);return w.style.getFragmentStyle(j)}{const g=this.fragments.find(({id:w})=>w===d);return g?g.style:void 0}}setFeaturesetSelectors(d){if(!d)return;const g=(w,j="")=>`${w}::${j}`;this._featuresetSelectors={};for(const w in d){const j={},I=this._featuresetSelectors[w]=[];for(const L of d[w].selectors){if(L.featureNamespace){const z=this.getOwnLayer(L.layer);if(!z){a.w(`Layer is undefined for selector: ${L.layer}`);continue}const H=g(z.source,z.sourceLayer);if(H in j&&j[H]!==L.featureNamespace){a.w(`"featureNamespace ${L.featureNamespace} of featureset ${w}'s selector is not associated to the same source, skip this selector`);continue}j[H]=L.featureNamespace}let F;if(L.properties)for(const z in L.properties){const H=a.X(L.properties[z]);H.result==="success"&&(F=F||{},F[z]=H.value)}I.push({layerId:L.layer,namespace:L.featureNamespace,properties:F,uniqueFeatureID:L._uniqueFeatureID})}}}getFeaturesetDescriptors(d){const g=this.getFragmentStyle(d);if(!g||!g.stylesheet.featuresets)return[];const w=[];for(const j in g.stylesheet.featuresets)w.push({featuresetId:j,importId:g.scope?g.scope:void 0});return w}getFeaturesetLayers(d,g){const w=this.getFragmentStyle(g),j=w.stylesheet.featuresets;if(!j||!j[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 I=[];for(const L of j[d].selectors){const F=w.getOwnLayer(L.layer);F&&I.push(F)}return I}getConfigProperty(d,g){const w=this.getFragmentStyle(d);if(!w)return null;const j=a.F(g,w.scope),I=w.options.get(j),L=I?I.value||I.default:null;return L?L.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(d,g){const w=a.F(d,g);return this._mergedIndoor[w]}setIndoorData(d,g){this.indoorManager.setIndoorData(g)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(d,g,w){const j=this.getFragmentStyle(d);if(!j)return;const I=j.stylesheet.schema;if(!I||!I[g])return;const L=a.X(w);if(L.result!=="success")return void Gm(this,L.value);const F=L.value.expression,z=a.F(g,j.scope),H=j.options.get(z);if(!H)return;let Z;const{minValue:ne,maxValue:re,stepValue:se,type:ce,values:oe}=I[g],ye=a.X(I[g].default);ye.result==="success"&&(Z=ye.value.expression),Z?(this.options.set(z,Object.assign({},H,{value:F,default:Z,minValue:ne,maxValue:re,stepValue:se,type:ce,values:oe})),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 w=g.stylesheet.schema;if(!w)return null;const j={};for(const I in w){const L=a.F(I,g.scope),F=g.options.get(L),z=F?F.value||F.default:null;j[I]=z?z.serialize():null}return j}setConfig(d,g){const w=this.getFragmentStyle(d);w&&(w.updateConfig(g,w.stylesheet.schema),this.updateConfigDependencies())}getSchema(d){const g=this.getFragmentStyle(d);return g?g.stylesheet.schema:null}setSchema(d,g){const w=this.getFragmentStyle(d);w&&(w.stylesheet.schema=g,w.updateConfig(w._config,g),this.updateConfigDependencies())}updateConfig(d,g){if(this._config=d,d||g)if(g)for(const w in g){let j,I;const L=a.X(g[w].default);if(L.result==="success"&&(j=L.value.expression),d&&d[w]!==void 0){const re=a.X(d[w]);re.result==="success"&&(I=re.value.expression)}const{minValue:F,maxValue:z,stepValue:H,type:Z,values:ne}=g[w];if(j){const re=a.F(w,this.scope);this.options.set(re,{default:j,value:I,minValue:F,maxValue:z,stepValue:H,type:Z,values:ne})}else this.fire(new a.B(new Error(`No schema defined for config option "${w}".`)))}else this.fire(new a.B(new Error("Attempting to set config for a style without schema.")))}_updateLayers(d,g=()=>!0){for(const w of d){const j=this.getLayer(w);j&&g(j)&&(j.possiblyEvaluateVisibility(),this._updateLayer(j),this._changes.setDirty())}}updateConfigDependencies(d){this._updateLayers(this._configDependentLayers,g=>!d||g.expressionDependencies.configDependencies.has(d)),this.ambientLight&&this.ambientLight.updateConfig(this.options),this.directionalLight&&this.directionalLight.updateConfig(this.options),this.fog&&this.fog.updateConfig(this.options),this.snow&&this.snow.updateConfig(this.options),this.rain&&this.rain.updateConfig(this.options),this.forEachFragmentStyle(g=>{const w=g._styleColorTheme.colorThemeOverride?g._styleColorTheme.colorThemeOverride:g._styleColorTheme.colorTheme;if(w){const j=g._evaluateColorThemeData(w);(!g._styleColorTheme.lut&&j!==""||g._styleColorTheme.lut&&j!==g._styleColorTheme.lut.data)&&g.setColorTheme(w)}}),this._changes.setDirty()}addLayer(d,g,w={}){this._checkLoaded();const j=d.id;if(this._layers[j])return void this.fire(new a.B(new Error(`Layer with id "${j}" already exists on this map`)));let I;if(d.type==="custom"){if(Gm(this,a.dd(d)))return;I=a.de(d,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof d.source=="object"&&(this.addSource(j,d.source),d=a.d9(d),d=Object.assign(d,{source:j})),this._validate(rt,`layers.${j}`,d,{arrayIndex:-1},w))return;I=a.de(d,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(I),I.setEventedParent(this,{layer:{id:j}})}const L=a.F(I.source,I.scope);I.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(L),I.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(L);let F=this._order.length;if(g){const 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.`)));I.slot&&I.slot!==this._layers[g].slot?a.w(`Layer with id "${g}" has a different slot. Layers can only be rearranged within the same slot.`):F=ne}this._order.splice(F,0,j),this._handleLayerOrderChange(),this._layers[j]=I;const z=this.getOwnLayerSourceCache(I),H=!!this.directionalLight&&this.directionalLight.shadowsEnabled();z&&I.canCastShadows()&&H&&(z.castsShadows=!0);const Z=this._changes.getRemovedLayer(I);if(Z&&I.source&&z&&I.type!=="custom"){this._changes.discardLayerRemoval(I);const ne=a.F(I.source,I.scope);Z.type!==I.type?this._changes.updateSourceCache(ne,"clear"):(this._changes.updateSourceCache(ne,"reload"),z.pause())}this._updateLayer(I),I.onAdd&&I.onAdd(this.map),I.scope=this.scope,this.mergeLayers()}moveLayer(d,g){this._checkLoaded();const w=this._checkLayer(d);if(!w||d===g)return;const j=this._order.indexOf(d);this._order.splice(j,1);let I=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.`)));w.slot&&w.slot!==this._layers[g].slot?a.w(`Layer with id "${g}" has a different slot. Layers can only be rearranged within the same slot.`):I=L}this._order.splice(I,0,d),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(d){this._checkLoaded();const g=this._checkLayer(d);if(!g)return;g.setEventedParent(null);const w=this._order.indexOf(d);this._order.splice(w,1),delete this._layers[d],this._changes.setDirty(),this._handleLayerOrderChange(),this._configDependentLayers.delete(g.fqid),this._indoorDependentLayers.delete(g.fqid),this._changes.removeLayer(g);const j=this.getOwnLayerSourceCache(g);if(j&&j.castsShadows){let I=!1;for(const L in this._layers)if(this._layers[L].source===g.source&&this._layers[L].canCastShadows()){I=!0;break}j.castsShadows=I}g.onRemove&&g.onRemove(this.map),this.mergeLayers()}getOwnLayer(d){return this._layers[d]}hasLayer(d){return d in this._mergedLayers}hasLayerType(d){for(const g in this._layers)if(this._layers[g].type===d)return!0;return!1}setLayerZoomRange(d,g,w){this._checkLoaded();const j=this._checkLayer(d);j&&(j.minzoom===g&&j.maxzoom===w||(g!=null&&(j.minzoom=g),w!=null&&(j.maxzoom=w),this._updateLayer(j)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(d,g){this._checkLoaded();const w=this._checkLayer(d);w&&w.slot!==g&&(w.slot=g,this._updateLayer(w))}setFilter(d,g,w={}){this._checkLoaded();const j=this._checkLayer(d);if(j&&!a.b6(j.filter,g))return g==null?(j.filter=void 0,void this._updateLayer(j)):void(this._validate(dt,`layers.${j.id}.filter`,g,{layerType:j.type},w)||(j.filter=a.d9(g),this._updateLayer(j)))}getFilter(d){const g=this._checkLayer(d);if(g)return a.d9(g.filter)}setLayoutProperty(d,g,w,j={}){this._checkLoaded();const I=this._checkLayer(d);if(I&&!a.b6(I.getLayoutProperty(g),w)){if(w!=null&&(!j||j.validate!==!1)&&Gm(I,ht.call(du,{key:`layers.${d}.layout.${g}`,layerType:I.type,objectKey:g,value:w,styleSpec:a.a8,style:{glyphs:!0,sprite:!0}})))return;I.setLayoutProperty(g,w),I.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(I.fqid),I.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(I.fqid),this._updateLayer(I)}}setLayerProperty(d,g,w,j={}){this._checkLoaded();const I=this._checkLayer(d);I&&(g==="appearances"?(I.setAppearances(w),this._updateLayer(I)):I.isPaintProperty(g)?this.setPaintProperty(d,g,w,j):this.setLayoutProperty(d,g,w,j))}getLayoutProperty(d,g){const w=this._checkLayer(d);if(w)return w.getLayoutProperty(g)}setPaintProperty(d,g,w,j={}){this._checkLoaded();const I=this._checkLayer(d);if(!I||a.b6(I.getPaintProperty(g),w)||w!=null&&(!j||j.validate!==!1)&&Gm(I,it.call(du,{key:`layers.${d}.paint.${g}`,layerType:I.type,objectKey:g,value:w,styleSpec:a.a8})))return;const L=I.setPaintProperty(g,w);I.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(I.fqid),I.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(I.fqid),L&&this._updateLayer(I),this._changes.updatePaintProperties(I)}getPaintProperty(d,g){const w=this._checkLayer(d);if(w)return w.getPaintProperty(g)}setFeatureState(d,g){if(this._checkLoaded(),"target"in d){if("featuresetId"in d.target){const{featuresetId:z,importId:H}=d.target,Z=this.getFragmentStyle(H),ne=Z.getFeaturesetLayers(z);for(const{source:re,sourceLayer:se}of ne)Z.setFeatureState({id:d.id,source:re,sourceLayer:se},g)}else if("layerId"in d.target){const{layerId:z}=d.target,H=this.getLayer(z);this.setFeatureState({id:d.id,source:H.source,sourceLayer:H.sourceLayer},g)}return}const w=d.source,j=d.sourceLayer,I=this._checkSource(w);if(!I)return;const L=I.type;if(L==="geojson"&&j)return void this.fire(new a.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(L==="vector"&&!j)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 F=this.getOwnSourceCaches(w);for(const z of F)z.setFeatureState(j,d.id,g)}removeFeatureState(d,g){if(this._checkLoaded(),"target"in d){if("featuresetId"in d.target){const{featuresetId:z,importId:H}=d.target,Z=this.getFragmentStyle(H),ne=Z.getFeaturesetLayers(z);for(const{source:re,sourceLayer:se}of ne)Z.removeFeatureState({id:d.id,source:re,sourceLayer:se},g)}else if("layerId"in d.target){const{layerId:z}=d.target,H=this.getLayer(z);this.removeFeatureState({id:d.id,source:H.source,sourceLayer:H.sourceLayer},g)}return}const w=d.source,j=this._checkSource(w);if(!j)return;const I=j.type,L=I==="vector"?d.sourceLayer:void 0;if(I==="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 F=this.getOwnSourceCaches(w);for(const z of F)z.removeFeatureState(L,d.id,g)}getFeatureState(d){if(this._checkLoaded(),"target"in d){let I;if("featuresetId"in d.target){const{featuresetId:L,importId:F}=d.target,z=this.getFragmentStyle(F),H=z.getFeaturesetLayers(L);for(const{source:Z,sourceLayer:ne}of H){const re=z.getFeatureState({id:d.id,source:Z,sourceLayer:ne});if(re&&!I)I=re;else if(!a.b6(I,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,F=this.getLayer(L);I=this.getFeatureState({id:d.id,source:F.source,sourceLayer:F.sourceLayer})}return I}const g=d.source,w=d.sourceLayer,j=this._checkSource(g);if(j){if(j.type!=="vector"||w)return d.id===void 0&&this.fire(new a.B(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(g)[0].getFeatureState(w,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)},w=>w!==void 0)}_updateFilteredLayers(d){for(const g of Object.values(this._mergedLayers))d(g)&&this._updateLayer(g)}_updateLayer(d){this._changes.updateLayer(d);const g=this.getLayerSourceCache(d),w=a.F(d.source,d.scope),j=this._changes.getUpdatedSourceCaches();d.source&&!j[w]&&g&&g.getSource().type!=="raster"&&(this._changes.updateSourceCache(w,"reload"),g.pause()),d.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(d){const g=F=>this._mergedLayers[F].is3D(!!this.terrain),w=this.order,j={},I=[];for(let F=w.length-1;F>=0;F--){const z=w[F];if(g(z)){j[z]=F;for(const H of d){const Z=H[z];if(Z)for(const ne of Z)I.push(ne)}}}I.sort((F,z)=>z.intersectionZ-F.intersectionZ);const L=[];for(let F=w.length-1;F>=0;F--){const z=w[F];if(g(z))for(let H=I.length-1;H>=0;H--){const Z=I[H].feature;if(Z.layer&&j[Z.layer.id]{if(ZT.has(Z.type))return;const ne=this.getOwnLayerSourceCache(Z),re=I[ne.id]=I[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:j})};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 F=this._queryRenderedFeatures(d,I,w),z=this._flattenAndSortRenderedFeatures(F),H=[];for(const Z of z)a.dh(Z.layer.id)===this.scope&&H.push(Z);return H}queryRenderedFeatureset(d,g,w){let j;g&&!Array.isArray(g)&&g.filter&&(this._validate(dt,"queryRenderedFeatures.filter",g.filter,null,g),j=a.dg(g.filter));const I="mock",L=[];if(g&&g.target)L.push(Object.assign({},g,{targetId:I,filter:j}));else{const Z=this.getFeaturesetDescriptors();for(const ne of Z)L.push({targetId:I,filter:j,target:ne});for(const{style:ne}of this.fragments){const re=ne.getFeaturesetDescriptors();for(const se of re)L.push({targetId:I,filter:j,target:se})}}const F=this.queryRenderedTargets(d,L,w),z=[],H=new Set;for(const Z of F)for(const ne of Z.variants[I])Id(ne,Z,H)||z.push(new a.di(Z,ne));return z}queryRenderedTargets(d,g,w){const j={},I=(F,z,H,Z)=>{const ne=j[z.id]=j[z.id]||{sourceCache:z,layers:{},has3DLayers:!1};if(ne.layers[F.fqid]=ne.layers[F.fqid]||{styleLayer:F,targets:[]},F.is3D(!!this.terrain)&&(ne.has3DLayers=!0),!Z)return H.uniqueFeatureID=!1,void ne.layers[F.fqid].targets.push(H);ne.layers[F.fqid].targets.push(Object.assign({},H,{namespace:Z.namespace,properties:Z.properties,uniqueFeatureID:Z.uniqueFeatureID}))};for(const F of g)if("featuresetId"in F.target){const{featuresetId:z,importId:H}=F.target,Z=this.getFragmentStyle(H);if(!Z||!Z._featuresetSelectors)continue;const ne=Z._featuresetSelectors[z];if(!ne){this.fire(new a.B(new Error(`The featureset '${z}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const re of ne){const se=Z.getOwnLayer(re.layerId);se&&!ZT.has(se.type)&&I(se,Z.getOwnLayerSourceCache(se),F,re)}}else if("layerId"in F.target){const{layerId:z}=F.target,H=this.getLayer(z);if(!H||ZT.has(H.type))continue;I(H,this.getLayerSourceCache(H),F)}const L=this._queryRenderedFeatures(d,j,w);return this._flattenAndSortRenderedFeatures(L)}_queryRenderedFeatures(d,g,w){const j=[],I=!!this.map._showQueryGeometry,L=uc.createFromScreenPoints(d,w);for(const F in g){const z=fN(L,g[F],this._availableImages,w,I,this.getActualScope());Object.keys(z).length&&j.push(z)}if(this.placement)for(const F in g){if(g[F].sourceCache._renderSourceType!==a.b4.Symbol)continue;const z=R_(L.screenGeometry,g[F],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(z).length&&j.push(z)}return j}querySourceFeatures(d,g){const w=g&&g.filter;w&&this._validate(dt,"querySourceFeatures.filter",w,null,g);let j=[];const I=this.getOwnSourceCaches(d);for(const L of I)j=j.concat(OT(L,g));return j}addSourceType(d,g,w){return yu.getSourceType(d)?w(new Error(`A source type called "${d}" already exists.`)):(yu.setSourceType(d,g),g.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:d,url:g.workerSourceURL},w):w(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(d,g,w={}){this._checkLoaded();const j=this.light.getLight();let I=!1;for(const F in d)if(!a.b6(d[F],j[F])){I=!0;break}if(!I)return;const L=this._getTransitionParameters();this.light.setLight(d,g,w),this.light.updateTransitions(L)}getTerrain(){return this.terrain&&this.terrain.drapeRenderMode===1?this.terrain.get():null}setTerrainForDraping(){this.setTerrain({source:"",exaggeration:0},0)}checkCanvasFingerprintNoise(){this.disableElevatedTerrain===void 0&&(this.disableElevatedTerrain=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 w=d;const j=!("source"in d)||d.source==null;if(g===1){if(this.disableElevatedTerrain)return;if("source"in w&&typeof w.source=="object"){const F="terrain-dem-src";this.addSource(F,w.source),w=a.d9(w),w=Object.assign(w,{source:F})}const I=Object.assign({},w),L={};if(this.terrain&&j){I.source=this.terrain.get().source;const F=this.terrain?this.getFragmentStyle(this.terrain.scope):null;F&&(L.style=F.serialize())}if(this._validate(fe,"terrain",I,L))return}if(!this.terrain||this.terrain.scope!==this.scope&&!j||this.terrain&&g!==this.terrain.drapeRenderMode){if(!w)return;this._createTerrain(w,g),this.fire(new a.C("data",{dataType:"style"}))}else{const I=this.terrain,L=I.get();for(const F of Object.keys(a.a8.terrain))!w.hasOwnProperty(F)&&a.a8.terrain[F].default&&(w[F]=a.a8.terrain[F].default);for(const F in d)if(!a.b6(d[F],L[F])){I.set(d,this.options),this.stylesheet.terrain=d;const z=this._getTransitionParameters({duration:0});I.updateTransitions(z),this.fire(new a.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(d){const g=this.fog=new as(d,this.map.transform,this.scope,this.options);this.stylesheet.fog=g.get();const w=this._getTransitionParameters({duration:0});g.updateTransitions(w)}_createSnow(d){const g=this.snow=new ys(d,this.map.transform,this.scope,this.options);this.stylesheet.snow=g.get();const w=this._getTransitionParameters({duration:0});g.updateTransitions(w)}_createRain(d){const g=this.rain=new Mn(d,this.map.transform,this.scope,this.options);this.stylesheet.rain=g.get();const w=this._getTransitionParameters({duration:0});g.updateTransitions(w)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const d of this.map._markers)d._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(d){if(this._checkLoaded(),!d)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const g=this.fog;if(!a.b6(g.get(),d)){g.set(d,this.options),this.stylesheet.fog=g.get();const w=this._getTransitionParameters({duration:0});g.updateTransitions(w)}}else this._createFog(d);this._markersNeedUpdate=!0}getSnow(){return this.snow?this.snow.get():null}setSnow(d){if(this._checkLoaded(),!d)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const g=this.snow;if(!a.b6(g.get(),d)){g.set(d,this.options),this.stylesheet.snow=g.get();const w=this._getTransitionParameters({duration:0});g.updateTransitions(w)}}else this._createSnow(d);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(d){if(this._checkLoaded(),!d)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const g=this.rain;if(!a.b6(g.get(),d)){g.set(d,this.options),this.stylesheet.rain=g.get();const w=this._getTransitionParameters({duration:0});g.updateTransitions(w)}}else this._createRain(d);this._markersNeedUpdate=!0}_reloadColorTheme(){const d=()=>{for(const j in this._layers)this._layers[j].lut=this._styleColorTheme.lut;for(const j in this._sourceCaches)this._sourceCaches[j].clearTiles()},g=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!g)return this._styleColorTheme.lut=null,void d();const w=this._evaluateColorThemeData(g);this._loadColorTheme(w).then(()=>{this.fire(new a.C("colorthemeset")),d()}).catch(j=>{a.w(`Couldn't set color theme: ${j}`)})}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 w=this.getFragmentStyle(d);w&&(w._styleColorTheme.colorThemeOverride=g,w._reloadColorTheme())}_getTransitionParameters(d){return{now:a.o.now(),transition:Object.assign(this.transition,d)}}updateDrapeFirstLayers(){if(!this.terrain)return;const d=[],g=[];for(const w of this._mergedOrder)this.isLayerDraped(this._mergedLayers[w])?d.push(w):g.push(w);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...d),this._drapedFirstOrder.push(...g)}_createTerrain(d,g){const w=this.terrain=new Cn(d,g,this.scope,this.options,this.map.getWorldview());g===1&&(this.stylesheet.terrain=d),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const j=this._getTransitionParameters({duration:0});w.updateTransitions(j)}_force3DLayerUpdate(){for(const d in this._layers){const g=this._layers[d];g.type==="fill-extrusion"&&this._updateLayer(g)}}_forceSymbolLayerUpdate(){for(const d in this._layers){const g=this._layers[d];g.type==="symbol"&&this._updateLayer(g)}}_validate(d,g,w,j,I={}){if(I&&I.validate===!1)return!1;const L=Object.assign({},this.serialize());return Gm(this,d.call(du,Object.assign({key:g,style:L,value:w,styleSpec:a.a8},j)))}_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 w of g)w.clearTiles()}clearSources(){for(const d in this._mergedSourceCaches)this._mergedSourceCaches[d].clearTiles()}clearLayers(){for(const d in this._mergedLayers){const g=this._mergedLayers[d];g._clear&&g._clear()}}reloadSource(d){const g=this.getSourceCaches(d);for(const w of g)w.resume(),w.reload()}reloadSources(){for(const d of this.getSources())d.reload&&d.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(d=>{d.modelManager.reloadModels(d.scope)})}updateSources(d){let g;this.directionalLight&&(g=xN(this.directionalLight));const w=new Set,j=new Set,I=new Set;for(const L in this._mergedLayers){const F=this._mergedLayers[L];F.type==="building"?w.add(F.source):F.type==="raster"&&F.paint&&F.paint.get("raster-elevation-reference")==="ground"&&I.add(F.source),F.hasElevation()&&!j.has(F.source)&&j.add(F.source)}for(const L in this._mergedSourceCaches){const F=this._mergedSourceCaches[L],z=j.has(F._source.id);F._isRasterElevatedOverTerrain=I.has(F._source.id),w.has(F._source.id)&&(F._source.reparseOverscaled=!1),F.update(d,void 0,void 0,g,z)}}_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 r0),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(d,g,w,j,I){this.pauseablePlacement||(this.pauseablePlacement=new r0);let L=!1,F=!1;const z={},H={};for(const oe of this._mergedOrder){const ye=this._mergedLayers[oe];if(ye.type!=="symbol")continue;const ge=a.F(ye.source,ye.scope);let Pe=z[ge];if(!Pe){const _e=this.getLayerSourceCache(ye);if(!_e)continue;const Ze=_e.getRenderableIds(!0).map($e=>_e.getTileByID($e));H[ge]=Ze.slice(),Pe=z[ge]=Ze.sort(($e,Ke)=>Ke.tileID.overscaledZ-$e.tileID.overscaledZ||($e.tileID.isLessThan(Ke.tileID)?-1:1))}const De=this.crossTileSymbolIndex.addLayer(ye,Pe,d.center.lng,d.projection);L=L||De}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const Z=!!(this.placement&&!d.equals(this.placement.transform)),ne=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!I||this.placement.lastReplacementSourceUpdateTime!==I.updateTime)),re=Z||ne||L,se=(re||this.pauseablePlacement.isStale())&&w===0,ce=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(a.o.now(),d.zoom)&&w!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||se||ce)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(d,this._mergedOrder,g,w,j,this.placement,this.fog&&d.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const oe=this.map.painter.maxFrontCutoffRawStart;if(oe>0){const ye=180*d.pitch/Math.PI;if(ye>=15){const ge=Math.min(1,Math.max(0,(ye-15)/5)),Pe=ge*ge*(3-2*ge);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-Pe)+oe*Pe}}}if(this.pauseablePlacement.isDone()?re&&w!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,z,H,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(a.o.now()),F=!0),L&&this.pauseablePlacement.setStale()),F||L){this._buildingIndex.onNewFrame(d.zoom);for(let oe=0;oeI===d.id)!==-1)return void this.fire(new a.B(new Error(`Import with id '${d.id}' already exists in the map's style.`)));if(!g)return w.push(d),this._loadImports([d],!0);const j=w.findIndex(({id:I})=>I===g);return j===-1&&this.fire(new a.B(new Error(`Import with id "${g}" does not exist on this map.`))),this.stylesheet.imports=w.slice(0,j).concat(d).concat(w.slice(j)),this._loadImports([d],!0,g)}updateImport(d,g){this._checkLoaded();const w=this.stylesheet.imports||[],j=this.getImportIndex(d);return j===-1?this:typeof g=="string"?(this.setImportUrl(d,g),this):(g.url&&g.url!==w[j].url&&this.setImportUrl(d,g.url),a.b6(g.config,w[j].config)||this.setImportConfig(d,g.config,g.data.schema),a.b6(g.data,w[j].data)||this.setImportData(d,g.data),this)}moveImport(d,g){this._checkLoaded();let w=this.stylesheet.imports||[];const j=this.getImportIndex(d);if(j===-1)return this;const I=this.getImportIndex(g);if(I===-1)return this;const L=w[j],F=this.fragments[j];return w=w.filter(({id:z})=>z!==d),this.fragments=this.fragments.filter(({id:z})=>z!==d),this.stylesheet.imports=w.slice(0,I).concat(L).concat(w.slice(I)),this.fragments=this.fragments.slice(0,I).concat(F).concat(this.fragments.slice(I)),this.mergeLayers(),this}setImportUrl(d,g){this._checkLoaded();const w=this.stylesheet.imports||[],j=this.getImportIndex(d);if(j===-1)return this;w[j].url=g;const I=this.fragments[j];return I.style=this._createFragmentStyle(w[j]),I.style.on("style.import.load",()=>this.mergeAll()),I.style.loadURL(g),this}setImportData(d,g){this._checkLoaded();const w=this.getImportIndex(d),j=this.stylesheet.imports||[];return w===-1?this:g?(this.fragments[w].style.setState(g),this._reloadImports(),this):(delete j[w].data,this.setImportUrl(d,j[w].url))}setImportConfig(d,g,w){this._checkLoaded();const j=this.getImportIndex(d),I=this.stylesheet.imports||[];if(j===-1)return this;g?I[j].config=g:delete I[j].config;const L=this.fragments[j];w&&L.style.stylesheet&&(L.style.stylesheet.schema=w);const F=L.style.stylesheet&&L.style.stylesheet.schema;return L.config=g,L.style.updateConfig(g,F),this.updateConfigDependencies(),this}removeImport(d){this._checkLoaded();const g=this.stylesheet.imports||[],w=this.getImportIndex(d);w!==-1&&(g.splice(w,1),this.fragments[w].style._remove(),this.fragments.splice(w,1),this._reloadImports())}getImportIndex(d){const g=(this.stylesheet.imports||[]).findIndex(w=>w.id===d);return g===-1&&this.fire(new 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 w=this._mergedOtherSourceCaches[g];w&&d.push(w.getSource())}return d}getSource(d,g){const w=this.getSourceCache(d,g);return w&&w.getSource()}getLayerSource(d){const g=this.getLayerSourceCache(d);return g&&g.getSource()}getSourceCache(d,g){const w=a.F(d,g);return this._mergedOtherSourceCaches[w]}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 w=d[g];w==="reload"?this.reloadSource(g):w==="clear"&&this.clearSource(g)}}updateLayers(d){const g=this._changes.getUpdatedPaintProperties();for(const w of g){const j=this.getLayer(w);j&&j.updateTransitions(d)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(d){this.stylesheet.glyphs=d,this.glyphManager.setURL(d)}getImages(d,g,w){this.imageManager.getImages(g.images,g.scope,w),this._updateTilesForChangedImages();const j=L=>{if(L){const F=g.images.map(z=>a.I.toString(z));L.setDependencies(g.tileID.key,g.type,F)}},I=a.F(g.source,g.scope);j(this._mergedOtherSourceCaches[I]),j(this._mergedSymbolSourceCaches[I]),g.images.some(L=>L.iconsetId)&&this.fire(new a.C("data",{dataType:"style"}))}rasterizeImages(d,g,w){this.imageManager.rasterizeImages(g,w)}checkAtlasCache(d,g,w){const j=this.imageManager.imageAtlasCache.findCachedAtlas(g.descriptor);w(null,j&&j.contentDescriptor?{iconPositions:j.iconPositions,patternPositions:j.patternPositions,sourceHash:j.contentDescriptor.hash}:null)}getGlyphs(d,g,w){this.glyphManager.getGlyphs(g.stacks,w)}getOwnSourceCache(d){return this._otherSourceCaches[d]}getOwnLayerSourceCache(d){return d.type==="symbol"?this._symbolSourceCaches[d.source]:d.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[d.source]||this._otherSourceCaches[d.source]}getOwnSourceCaches(d){const g=[];return this._otherSourceCaches[d]&&g.push(this._otherSourceCaches[d]),this._symbolSourceCaches[d]&&g.push(this._symbolSourceCaches[d]),this._fillExtrusionSourceCaches[d]&&g.push(this._fillExtrusionSourceCaches[d]),g}_isSourceCacheLoaded(d){const g=this.getOwnSourceCaches(d);return g.length===0?(this.fire(new a.B(new Error(`There is no source with ID '${d}'`))),!1):g.every(w=>w.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(d,g){if(!this._clipLayerPresent&&d.type!=="fill-extrusion"&&d.type!=="building")return!1;const w=d.type==="fill-extrusion"&&(d.sourceLayer==="building"||d.sourceLayer==="procedural_buildings"),j=d.type==="building";if(d.is3D(!!this.terrain)){if(w||j||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)}}yu.getSourceType=function(_){return I_[_]},yu.setSourceType=function(_,d){I_[_]=d},yu.registerForPluginStateChange=a.dk;var QT=` #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`,JT=` #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;}`,jf=` #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`,u0="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;}",eE=` #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`,tE=`#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`,Ng=`#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`,Ig=`#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`,rE=`#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;}`,H_=`#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`,Nc=`#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 d0=/#include\s+"([^"]+)"/g,lr=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,bN=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,wN=new Set(["ifdef","ifndef","elif","if","defined"]),Hm=new Set;Sh(QT,Hm),Sh(jf,Hm),Sh(JT,Hm);const Hu={"_prelude_fog.vertex.glsl":tE,"_prelude_terrain.vertex.glsl":eE,"_prelude_shadow.vertex.glsl":H_,"_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":Ng,"_prelude_shadow.fragment.glsl":Nc,"_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":Ig,"_prelude_raster_particle.glsl":rE},Pg={};Bn("",eE),Bn(Ng,tE),Bn(Nc,H_),Bn(Ig,""),Bn(rE,"");const Af=Bn(JT,jf),h0=QT,Rg=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",h0,Af.fragmentSource].join(` `),C5=["precision highp float;",h0,Af.vertexSource].join(` `);var SN={background:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform vec4 u_color;uniform float u_opacity;uniform mediump float u_emissive_strength; #ifdef LIGHTING_3D_MODE in vec4 v_color; #endif void main() {vec4 out_color; #ifdef FEATURE_CUTOUT vec2 uv=gl_FragCoord.xy*u_inv_viewport_size.xy; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif float factorTex=min(texture(u_cutout_factor_image,uv).r,1.0);float cutoutFactor=(1.0-u_feature_cutout_params.x)*factorTex;out_color=u_color*(1.0-cutoutFactor); #else #ifdef LIGHTING_3D_MODE out_color=v_color; #else out_color=u_color; #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif #endif glFragColor=out_color*u_opacity; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_lighting.glsl" in ivec2 a_pos;uniform mat4 u_matrix;uniform mediump float u_emissive_strength; #ifdef LIGHTING_3D_MODE uniform mediump vec4 u_color;out vec4 v_color; #endif void main() {gl_Position=u_matrix*vec4(a_pos,0,1); #ifndef FEATURE_CUTOUT #ifdef LIGHTING_3D_MODE v_color=apply_lighting_with_emission_ground(u_color,u_emissive_strength); #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif #endif }`),backgroundPattern:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform vec2 u_pattern_tl;uniform vec2 u_pattern_br;uniform vec2 u_texsize;uniform float u_opacity;uniform float u_emissive_strength;uniform sampler2D u_image;in highp vec2 v_pos;void main() {highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(u_pattern_tl/u_texsize,u_pattern_br/u_texsize,imagecoord);vec4 out_color=textureLodCustom(u_image,pos,v_pos); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*u_opacity; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_pattern_size;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec2 u_pattern_units_to_pixels;in ivec2 a_pos;out highp vec2 v_pos;void main() {vec2 pos=vec2(a_pos);gl_Position=u_matrix*vec4(pos,0,1);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_pattern_size,u_pattern_units_to_pixels,pos); #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),building:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" const float window_depth=0.5;const float ao_radius=0.2;in vec4 v_color;in highp vec3 v_normal;in highp vec3 v_pos; #ifdef RENDER_FRONT_CUTOFF in float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT in vec4 v_ground_roof; #endif #endif #ifdef BUILDING_FAUX_FACADE in lowp float v_faux_facade;in highp float v_faux_facade_ed;in highp vec2 v_faux_facade_window;in highp vec2 v_faux_facade_floor;in highp vec2 v_faux_facade_range;in highp float v_aspect;in highp vec3 v_tbn_0;in highp vec3 v_tbn_1;in highp vec3 v_tbn_2;in highp vec4 v_faux_color_emissive;uniform float u_faux_facade_ao_intensity; #endif #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1; #endif #ifdef FLOOD_LIGHT in highp float v_flood_radius;in float v_has_flood_light; #endif uniform lowp float u_opacity;uniform vec3 u_camera_pos;uniform highp float u_tile_to_meter;uniform float u_facade_emissive_chance;uniform vec3 u_flood_light_color;uniform float u_flood_light_intensity;vec3 linearTosRGB(in vec3 color) {return pow(color,vec3(1./2.2));} #ifdef BUILDING_FAUX_FACADE highp float hash12(in highp vec2 p) {highp vec3 p3 =fract(vec3(p.xyx)*0.1031);p3+=dot(p3,p3.yzx+33.33);return fract((p3.x+p3.y)*p3.z);}float min3(in vec3 v) {return min(min(v.x,v.y),v.z);}highp vec2 get_uv_mask_id(in highp vec2 q,out highp float mask,out highp vec2 id) {highp vec2 p=q;mask=step(v_faux_facade_range.x,p.y)*step(p.y,v_faux_facade_range.y);p.y=p.y-v_faux_facade_range.x;highp vec2 uv=modf(p/v_faux_facade_floor,id);highp vec4 d=(v_faux_facade_floor.xyxy+vec4(-v_faux_facade_window,v_faux_facade_window))*0.5;highp vec4 edge=d/v_faux_facade_floor.xyxy;highp vec2 m=step(edge.xy,uv)*step(uv,edge.zw);mask*=m.x*m.y;uv-=vec2(0.5);uv*=vec2(0.5)/(vec2(0.5)-edge.xy);uv+=vec2(0.5);return uv;}highp float ray_unit_box(in highp vec3 ray_o,in highp vec3 ray_d,in highp vec3 bmin,in highp vec3 bmax) {highp vec3 planes=mix(bmin,bmax,step(0.0,ray_d));highp vec3 t=(planes-ray_o)/ray_d;return min3(t);}float get_emissive(in vec2 id) {if (u_facade_emissive_chance > 0.0) {return (step(hash12(id),u_facade_emissive_chance)+0.05)*v_faux_color_emissive.a;}return 0.0;}vec3 get_shade_info(in highp vec3 v,in highp vec3 v_normalized,in vec3 color,in vec2 id,in mat3 tbn,inout vec3 out_normal,inout float out_emissive) {vec3 out_color=color;highp vec3 abs_v=abs(v_normalized);bool x_major=abs_v.x >=abs_v.y && abs_v.x >=abs_v.z;bool y_major=abs_v.y >=abs_v.x && abs_v.y >=abs_v.z;bool z_major=abs_v.z >=abs_v.x && abs_v.z >=abs_v.y; #if 0 if (x_major) {out_color=v.x > 0.0 ? vec3(1.0,0.0,0.0) : vec3(0.0,1.0,1.0);} else if (y_major) {out_color=v.y > 0.0 ? vec3(0.0,1.0,0.0) : vec3(1.0,0.0,1.0);} else if (z_major) {out_color=v.z > 0.0 ? vec3(0.0,0.0,1.0) : vec3(1.0,1.0,0.0);}out_emissive=1.0; #else if (x_major) {out_normal=-sign(v.x)*tbn[0];} else if (y_major) {out_normal=vec3(0.0,0.0,-sign(v.y));} else if (z_major) {out_color=v_faux_color_emissive.rgb;out_emissive=v.z <=0.0 ? get_emissive(id) : out_emissive;}float ao=1.0;if (u_faux_facade_ao_intensity > 0.0) {vec4 ao_range=v_faux_facade_window.xxyy*0.5-vec4(0,ao_radius,0,ao_radius);vec2 ao_range_z=vec2(window_depth*0.5)-vec2(0.0,ao_radius);if (x_major || y_major) {ao*=smoothstep(-ao_range_z.x,-ao_range_z.y,v.z);} else if (z_major) {ao*=smoothstep(-ao_range.x,-ao_range.y,v.x)*(1.0-smoothstep(ao_range.y,ao_range.x,v.x));ao*=smoothstep(-ao_range.z,-ao_range.w,v.y)*(1.0-smoothstep(ao_range.w,ao_range.z,v.y));}ao=mix(1.0,min(1.0,ao+0.25),u_faux_facade_ao_intensity);}out_color*=ao; #endif return out_color;} #endif vec3 apply_lighting_linear(in vec3 color,in vec3 normal,in float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return color*(ambient_contrib+directional_contrib);}void main() {vec3 normal=normalize(v_normal);vec3 base_color=v_color.rgb;float emissive=v_color.a; #ifdef BUILDING_FAUX_FACADE if (v_faux_facade > 0.0) {highp mat3 tbn=mat3(v_tbn_0,v_tbn_1,v_tbn_2);highp vec3 v=vec3(v_pos.xy,v_pos.z/u_tile_to_meter)-u_camera_pos;highp vec3 view_tangent=transpose(tbn)*v;highp vec2 q=vec2(v_faux_facade_ed,v_pos.z);float mask=0.0;vec2 id=vec2(0.0);highp vec2 uv=get_uv_mask_id(q,mask,id);uv*=v_faux_facade_window;highp vec3 bmin=vec3(0.0,0.0,-window_depth);highp vec3 bmax=bmin+vec3(v_faux_facade_window,window_depth);highp vec3 ray_o=vec3(uv,0.0);highp vec3 ray_d=normalize(view_tangent);highp float t_min=ray_unit_box(ray_o,ray_d,bmin,bmax);highp vec3 hit=ray_o+t_min*ray_d;highp vec3 r=vec3(v_faux_facade_window,-window_depth);hit-=r*0.5;highp vec3 normalized=hit/r;vec3 out_normal=normal;float out_emissive=emissive;vec3 room_color=get_shade_info(hit,normalized,base_color,id,tbn,out_normal,out_emissive);base_color=mix(base_color,room_color,mask);normal=mix(normal,out_normal,mask);emissive=mix(emissive,out_emissive,mask);} #endif vec4 color=vec4(base_color,1.0);vec3 xy_flipped_normal=vec3(-normal.xy,normal.z);float shadowed_lighting_factor=0.0; #ifdef RENDER_SHADOWS #ifdef RENDER_CUTOFF shadowed_lighting_factor=shadowed_light_factor_normal_opacity(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;} #else shadowed_lighting_factor=shadowed_light_factor_normal(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w); #endif #else shadowed_lighting_factor=max(0.0,dot(xy_flipped_normal,u_lighting_directional_dir)); #endif color.rgb=apply_lighting_linear(color.rgb,xy_flipped_normal,shadowed_lighting_factor);color.rgb=linearTosRGB(color.rgb); #ifdef FLOOD_LIGHT float flood_radiance=(1.0-min(v_pos.z/v_flood_radius,1.0))*u_flood_light_intensity*v_has_flood_light;color.rgb=mix(color.rgb,u_flood_light_color,flood_radiance); #endif color.rgb=mix(color.rgb,linearTosRGB(base_color.rgb),emissive); #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos,v_pos.z)); #endif color*=u_opacity; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT {float ditherOpacity=cutoutGroundRoofOpacity(v_ground_roof);if (ditherOpacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (ditherOpacity < DITHER_THRESHOLDS[index]) {discard;}}} #else color=applyCutout(color,v_pos.z); #endif #endif #ifdef RENDER_FRONT_CUTOFF if (v_front_cutoff_opacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (v_front_cutoff_opacity < DITHER_THRESHOLDS[index]) {discard;}} #endif #ifdef FEATURE_CUTOUT color=apply_feature_cutout(color,gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #endif glFragColor=color; #ifdef DEBUG_SHOW_NORMALS color.rgb=xy_flipped_normal*0.5+vec3(0.5,0.5,0.5);color.a=1.0;glFragColor=color; #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in vec3 a_pos_3f;in ivec4 a_normal_3;in ivec4 a_centroid_3; #ifdef FLOOD_LIGHT in int a_flood_light_wall_radius_1i16; #endif #ifdef BUILDING_FAUX_FACADE in uvec4 a_faux_facade_data;in uvec2 a_faux_facade_vertical_range; #endif uniform mat4 u_matrix;uniform mat4 u_normal_matrix;uniform highp float u_tile_to_meter; #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params;out float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT out vec4 v_ground_roof; #endif #endif out vec4 v_color;out vec3 v_normal;out highp vec3 v_pos; #ifdef BUILDING_FAUX_FACADE out lowp float v_faux_facade;out highp float v_faux_facade_ed;out highp vec2 v_faux_facade_window;out highp vec2 v_faux_facade_floor;out highp vec2 v_faux_facade_range;out highp float v_aspect;out highp vec3 v_tbn_0;out highp vec3 v_tbn_1;out highp vec3 v_tbn_2;out highp vec4 v_faux_color_emissive; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1; #endif #ifdef FLOOD_LIGHT out highp float v_flood_radius;out float v_has_flood_light; #endif const float MAX_UINT_16=65535.0;const float MAX_INT_16=32767.0;const float MAX_UINT_8=255.0;const float TWO_POW_8=256.0;const float FLOOD_LIGHT_MAX_RADIUS_METER=2048.0;vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));} #ifdef BUILDING_FAUX_FACADE mat3 get_tbn(in vec3 normal) {const vec3 bitangent=vec3(0.0,0.0,1.0);vec3 tangent=normalize(vec3(normal.y,-normal.x,0.0));return mat3(tangent,bitangent,normal);} #endif #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 part_color_emissive #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 faux_facade_color_emissive void main() { #pragma mapbox: initialize-attribute-custom highp uvec2 part_color_emissive #pragma mapbox: initialize-attribute-custom highp uvec2 faux_facade_color_emissive #ifdef FLOOD_LIGHT v_flood_radius=(float(a_flood_light_wall_radius_1i16)/MAX_INT_16*FLOOD_LIGHT_MAX_RADIUS_METER);v_has_flood_light=step(0.0,v_flood_radius); #endif vec4 color_emissive=decode_color(vec2(part_color_emissive));v_color=vec4(sRGBToLinear(color_emissive.rgb),color_emissive.a);vec3 a_normal_3f=vec3(a_normal_3)/MAX_INT_16;v_normal=vec3(u_normal_matrix*vec4(a_normal_3f,0.0));float hidden=0.0;float depth_offset=0.0;vec2 centroid_xy=vec2(a_centroid_3.xy >> 2);vec2 spanBits=vec2(a_centroid_3.xy & 3); #ifdef BUILDING_FAUX_FACADE vec4 faux_facade_data=vec4(a_faux_facade_data);v_faux_facade=faux_facade_data.x;if (v_faux_facade > 0.0) {v_faux_facade_ed=faux_facade_data.x *u_tile_to_meter;float window_x_perc=floor(faux_facade_data.y/TWO_POW_8);float window_y_perc=faux_facade_data.y-TWO_POW_8*window_x_perc;vec2 window_perc=vec2(window_x_perc,window_y_perc)/MAX_UINT_8;v_faux_facade_floor=(faux_facade_data.zw/MAX_UINT_16*EXTENT)*u_tile_to_meter;v_faux_facade_window=window_perc*v_faux_facade_floor;v_faux_facade_range=(vec2(a_faux_facade_vertical_range)/MAX_UINT_16*EXTENT)*u_tile_to_meter;v_aspect=v_faux_facade_window.x/v_faux_facade_window.y;mat3 tbn=get_tbn(normalize(v_normal));v_tbn_0=tbn[0];v_tbn_1=tbn[1];v_tbn_2=tbn[2];v_faux_color_emissive=decode_color(vec2(faux_facade_color_emissive));v_faux_color_emissive.rgb=sRGBToLinear(v_faux_color_emissive.rgb);depth_offset=min(1000.0,float(a_centroid_3.z))*0.0000002;} #endif v_pos=a_pos_3f; #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) float halfSpanX=spanBits.x*10.0/u_tile_to_meter;float halfSpanY=spanBits.y*10.0/u_tile_to_meter;vec2 screenUpInTile=vec2(u_matrix[0][1],u_matrix[1][1]);vec2 spanOffset=vec2(halfSpanX,halfSpanY)*sign(screenUpInTile);vec2 cutoff_highestCorner=centroid_xy+spanOffset;vec2 cutoff_lowestCorner=centroid_xy-spanOffset; #endif #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec4 ground=u_matrix*vec4(centroid_xy,0.0,1.0); #endif #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,ground.z);hidden=float(v_cutoff_opacity==0.0);v_pos.z*=v_cutoff_opacity; #endif #ifdef RENDER_SHADOWS vec3 shadow_pos=v_pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset_model(v_normal);shadow_pos+=offset*shadow_normal_offset_multiplier0(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shadow_pos,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(shadow_pos,1.0); #endif #ifdef FOG v_fog_pos=fog_position(v_pos); #endif #ifdef RENDER_FRONT_CUTOFF v_front_cutoff_opacity=1.0;{hidden=max(hidden,float(ground.w <=0.0));float ndc_y=ground.y/max(ground.w,0.001);float threshold=u_front_cutoff_params.x*2.0-1.0;float range_ndc=u_front_cutoff_params.y*2.0;hidden=max(hidden,float(ndc_y < threshold-range_ndc));float t=clamp((ndc_y-(threshold-range_ndc))/max(range_ndc,0.001),0.0,1.0);v_front_cutoff_opacity=mix(u_front_cutoff_params.z,1.0,t);} #endif gl_Position=mix(u_matrix*vec4(v_pos,1),AWAY,hidden);gl_Position.z-=depth_offset*gl_Position.w; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT vec4 ic_ground=u_matrix*vec4(v_pos.xy,0.0,1.0);vec4 ic_roof=u_matrix*vec4(v_pos.xy,v_pos.z,1.0);v_ground_roof=vec4(ic_ground.xy/ic_ground.w,ic_roof.xy/ic_roof.w); #endif #endif }`),buildingBloom:Bn(`in vec4 v_color_emissive; #pragma mapbox: define-attribute highp vec4 bloom_attenuation #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation float saturate(float val) {return clamp(val,0.0,1.0);}void main() {float emission=v_color_emissive.a;float opacity=1.0; #ifdef HAS_ATTRIBUTE_a_bloom_attenuation float distance=length(vec2(1.3*max(0.0,abs(bloom_attenuation.x)-bloom_attenuation.z),bloom_attenuation.y));distance+= mix(0.5,0.0,clamp(emission-1.0,0.0,1.0));opacity*=saturate(1.0-distance*distance); #endif #ifdef RENDER_CUTOFF opacity*=v_cutoff_opacity; #endif glFragColor=vec4(v_color_emissive.rgb,1.0)*opacity;}`,`in vec3 a_pos_3f; #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 part_color_emissive #pragma mapbox: define-attribute highp vec4 bloom_attenuation out vec4 v_color_emissive;uniform mat4 u_matrix;vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}void main() { #pragma mapbox: initialize-attribute-custom highp uvec2 part_color_emissive #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation #ifdef HAS_ATTRIBUTE_a_part_color_emissive vec4 color_emissive=decode_color(vec2(part_color_emissive));float part_emissive=color_emissive.a*5.0;v_color_emissive=vec4(sRGBToLinear(color_emissive.rgb),part_emissive); #else v_color_emissive=vec4(1.0); #endif gl_Position=u_matrix*vec4(a_pos_3f,1.0); #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z); #endif }`),buildingDepth:Bn("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" in vec3 v_data;in float v_visibility; #pragma mapbox: define highp vec4 color #pragma mapbox: define mediump float radius #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define highp vec4 stroke_color #pragma mapbox: define mediump float stroke_width #pragma mapbox: define lowp float stroke_opacity uniform float u_emissive_strength;void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize mediump float radius #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp vec4 stroke_color #pragma mapbox: initialize mediump float stroke_width #pragma mapbox: initialize lowp float stroke_opacity vec2 extrude=v_data.xy;float blur_positive=blur < 0.0 ? 0.0 : 1.0;lowp float antialiasblur=v_data.z;float extrude_length=length(extrude)+antialiasblur*(1.0-blur_positive);float antialiased_blur=-max(abs(blur),antialiasblur);float antialiase_blur_opacity=smoothstep(0.0,antialiasblur,extrude_length-1.0);float opacity_t=blur_positive==1.0 ? smoothstep(0.0,-antialiased_blur,1.0-extrude_length) : smoothstep(antialiased_blur,0.0,extrude_length-1.0)-antialiase_blur_opacity;float color_t=stroke_width < 0.01 ? 0.0 : smoothstep( antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width) );vec4 out_color=mix(color*opacity,stroke_color*stroke_opacity,color_t); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #endif #ifdef FOG out_color=fog_apply_premultiplied(out_color,v_fog_pos); #endif glFragColor=out_color*(v_visibility*opacity_t); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif }`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #define NUM_VISIBILITY_RINGS 2 #define INV_SQRT2 0.70710678 #define ELEVATION_BIAS 0.0001 #define NUM_SAMPLES_PER_RING 16 uniform mat4 u_matrix;uniform mat2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;in ivec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir; #endif #ifdef ELEVATED_ROADS in float a_circle_z_offset; #endif out vec3 v_data;out float v_visibility; #pragma mapbox: define highp vec4 color #pragma mapbox: define mediump float radius #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define highp vec4 stroke_color #pragma mapbox: define mediump float stroke_width #pragma mapbox: define lowp float stroke_opacity vec2 calc_offset(vec2 extrusion,float radius,float stroke_width, float view_scale) {return extrusion*(radius+stroke_width)*u_extrude_scale*view_scale;}float cantilevered_elevation(vec2 pos,float radius,float stroke_width,float view_scale) {vec2 c1=pos+calc_offset(vec2(-1.0,-1.0),radius,stroke_width,view_scale);vec2 c2=pos+calc_offset(vec2(1.0,-1.0),radius,stroke_width,view_scale);vec2 c3=pos+calc_offset(vec2(1.0,1.0),radius,stroke_width,view_scale);vec2 c4=pos+calc_offset(vec2(-1.0,1.0),radius,stroke_width,view_scale);float h1=elevation(c1)+ELEVATION_BIAS;float h2=elevation(c2)+ELEVATION_BIAS;float h3=elevation(c3)+ELEVATION_BIAS;float h4=elevation(c4)+ELEVATION_BIAS;return max(h4,max(h3,max(h1,h2)));}float circle_elevation(vec2 pos) { #if defined(TERRAIN) return elevation(pos)+ELEVATION_BIAS; #else return 0.0; #endif }vec4 project_vertex(vec2 extrusion,vec4 world_center,vec4 projected_center,float radius,float stroke_width, float view_scale,mat3 surface_vectors) {vec2 sample_offset=calc_offset(extrusion,radius,stroke_width,view_scale); #ifdef PITCH_WITH_MAP #ifdef PROJECTION_GLOBE_VIEW return u_matrix*( world_center+vec4(sample_offset.x*surface_vectors[0]+sample_offset.y*surface_vectors[1],0) ); #else return u_matrix*( world_center+vec4(sample_offset,0,0) ); #endif #else return projected_center+vec4(sample_offset,0,0); #endif }float get_sample_step() { #ifdef PITCH_WITH_MAP return 2.0*PI/float(NUM_SAMPLES_PER_RING); #else return PI/float(NUM_SAMPLES_PER_RING); #endif }void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize mediump float radius #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp vec4 stroke_color #pragma mapbox: initialize mediump float stroke_width #pragma mapbox: initialize lowp float stroke_opacity vec2 pos2=vec2(a_pos);vec2 extrude=vec2(mod(pos2,2.0)*2.0-1.0);vec2 circle_center=floor(pos2*0.5);float height=circle_elevation(circle_center);vec4 world_center;mat3 surface_vectors; #ifdef PROJECTION_GLOBE_VIEW surface_vectors=globe_mercator_surface_vectors(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(circle_center)*height;vec3 globe_pos=vec3(a_pos_3)+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*height;vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,circle_center,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;vec3 pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);world_center=vec4(pos,1); #else surface_vectors=mat3(1.0);world_center=vec4(circle_center,height,1); #endif #ifdef ELEVATED_ROADS world_center.z+=a_circle_z_offset+ELEVATION_BIAS; #endif vec4 projected_center=u_matrix*world_center;float view_scale=0.0; #ifdef PITCH_WITH_MAP #ifdef SCALE_WITH_MAP view_scale=1.0; #else view_scale=projected_center.w/u_camera_to_center_distance; #endif #else #ifdef SCALE_WITH_MAP view_scale=u_camera_to_center_distance; #else view_scale=projected_center.w; #endif #endif gl_Position=project_vertex(extrude,world_center,projected_center,radius,stroke_width,view_scale,surface_vectors);float visibility=0.0; #ifdef TERRAIN float step=get_sample_step();vec4 occlusion_world_center;vec4 occlusion_projected_center; #ifdef PITCH_WITH_MAP float cantilevered_height=cantilevered_elevation(circle_center,radius,stroke_width,view_scale);occlusion_world_center=vec4(circle_center,cantilevered_height,1);occlusion_projected_center=u_matrix*occlusion_world_center; #else occlusion_world_center=world_center;occlusion_projected_center=projected_center; #endif for(int ring=0; ring < NUM_VISIBILITY_RINGS; ring++) {float scale=(float(ring)+1.0)/float(NUM_VISIBILITY_RINGS);for(int i=0; i < NUM_SAMPLES_PER_RING; i++) {vec2 extrusion=vec2(cos(step*float(i)),-sin(step*float(i)))*scale;vec4 frag_pos=project_vertex(extrusion,occlusion_world_center,occlusion_projected_center,radius,stroke_width,view_scale,surface_vectors);visibility+=float(!isOccluded(frag_pos));}}visibility/=float(NUM_VISIBILITY_RINGS)*float(NUM_SAMPLES_PER_RING); #else visibility=1.0; #endif #ifdef PROJECTION_GLOBE_VIEW visibility=1.0; #endif v_visibility=visibility;lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur); #ifdef FOG v_fog_pos=fog_position(world_center.xyz); #endif }`),clippingMask:Bn("void main() {glFragColor=vec4(1.0);}","in ivec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),heatmap:Bn(`#include "_prelude_fog.fragment.glsl" uniform highp float u_intensity;in vec2 v_extrude; #pragma mapbox: define highp float weight #define GAUSS_COEF 0.3989422804014327 void main() { #pragma mapbox: initialize highp float weight float d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);glFragColor=vec4(val,1.0,1.0,1.0); #ifdef FOG if (u_is_globe==0) {glFragColor.r*=pow(1.0-fog_opacity(v_fog_pos),2.0);} #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_terrain.vertex.glsl" #include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;in ivec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir; #endif out vec2 v_extrude; #pragma mapbox: define highp float weight #pragma mapbox: define mediump float radius const highp float ZERO=1.0/255.0/16.0; #define GAUSS_COEF 0.3989422804014327 void main() { #pragma mapbox: initialize highp float weight #pragma mapbox: initialize mediump float radius vec2 unscaled_extrude=vec2(mod(vec2(a_pos),2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 tilePos=floor(vec2(a_pos)*0.5);vec3 pos; #ifdef PROJECTION_GLOBE_VIEW vec3 pos_normal_3=vec3(a_pos_normal_3)/16384.0;mat3 surface_vectors=globe_mercator_surface_vectors(pos_normal_3,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(tilePos)*elevation(tilePos);vec3 globe_pos=vec3(a_pos_3)+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*elevation(tilePos);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,tilePos,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #else pos=vec3(tilePos+extrude,elevation(tilePos)); #endif gl_Position=u_matrix*vec4(pos,1); #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),heatmapTexture:Bn(`uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));glFragColor=color*u_opacity; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(0.0); #endif HANDLE_WIREFRAME_DEBUG;}`,"in ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=vec2(a_pos)*0.5+0.5;}"),collisionBox:Bn("in float v_placed;in float v_notUsed;void main() {vec4 red =vec4(1.0,0.0,0.0,1.0);vec4 blue=vec4(0.0,0.0,1.0,0.5);glFragColor =mix(red,blue,step(0.5,v_placed))*0.5;glFragColor*=mix(1.0,0.1,step(0.5,v_notUsed));}",`#include "_prelude_terrain.vertex.glsl" in ivec4 a_pos;in ivec2 a_anchor_pos;in ivec2 a_extrude;in uvec2 a_placed;in vec2 a_shift;in vec2 a_elevation_from_sea;in float a_size_scale;in vec2 a_padding;in float a_auto_z_offset;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance; #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform float u_zoom_transition; #endif out float v_placed;out float v_notUsed;void main() {vec2 anchor_pos=vec2(a_anchor_pos);float feature_elevation=a_elevation_from_sea.x+a_auto_z_offset;float terrain_elevation=(a_elevation_from_sea.y==1.0 ? 0.0 : elevation(anchor_pos));vec3 proj_pos=vec3(a_pos)+elevationVector(anchor_pos)*(feature_elevation+terrain_elevation); #ifdef PROJECTION_GLOBE_VIEW #ifndef PROJECTED_POS_ON_VIEWPORT vec3 globe_pos=proj_pos;vec3 mercator_pos=mercator_tile_position(u_inv_rot_matrix,anchor_pos,u_tile_id,u_merc_center);proj_pos=mix_globe_mercator(globe_pos,mercator_pos,u_zoom_transition); #endif #endif vec4 projectedPoint=u_matrix*vec4(proj_pos,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp( 0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,1.5);gl_Position=projectedPoint;gl_Position.xy+=(vec2(a_extrude)*a_size_scale+a_shift+a_padding)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=float(a_placed.x);v_notUsed=float(a_placed.y);}`),collisionCircle:Bn("in float v_radius;in vec2 v_extrude;in float v_perspective_ratio;in float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);glFragColor=color*alpha*opacity_t;}",`in vec2 a_pos_2f;in float a_radius;in ivec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;out float v_radius;out vec2 v_extrude;out float v_perspective_ratio;out float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos_2f;float radius=a_radius;int vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2( mix(-1.0,1.0,float(vertexIdx >=2)),mix(-1.0,1.0,float(vertexIdx >=1 && vertexIdx <=2)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp( 0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=float(a_flags.x);gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}`),debug:Bn("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);glFragColor=mix(u_color,overlay_color,overlay_color.a);}",`#include "_prelude_terrain.vertex.glsl" in ivec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3; #endif out vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {vec2 pos=vec2(a_pos);float h=elevation(pos);v_uv=pos/8192.0; #ifdef PROJECTION_GLOBE_VIEW gl_Position=u_matrix*vec4(vec3(a_pos_3)+elevationVector(pos)*h,1); #else gl_Position=u_matrix*vec4(pos*u_overlay_scale,h,1); #endif }`),elevatedStructuresDepth:Bn("void main() {}","in ivec2 a_pos;in float a_height;uniform mat4 u_matrix;uniform float u_depth_bias;void main() {gl_Position=u_matrix*vec4(a_pos,a_height,1);gl_Position.z=gl_Position.z+u_depth_bias;}"),elevatedStructuresDepthReconstruct:Bn(`#ifdef DEPTH_RECONSTRUCTION in float v_height; #endif void main() { #ifdef DEPTH_RECONSTRUCTION if (v_height >=0.0) discard; #else #ifdef FEATURE_CUTOUT apply_feature_cutout(vec4(0.0,0.0,0.0,1.0),gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #endif #endif glFragColor=vec4(1.0,0.0,0.0,1.0);}`,`in ivec2 a_pos;in float a_height;uniform mat4 u_matrix;uniform vec3 u_camera_pos;uniform highp float u_depth_bias;uniform lowp float u_height_scale;uniform lowp float u_reset_depth; #ifdef DEPTH_RECONSTRUCTION out float v_height; #endif void main() {vec3 vpos=vec3(a_pos,a_height*u_height_scale); #ifdef DEPTH_RECONSTRUCTION if (u_camera_pos.z > vpos.z) {vpos-=(u_camera_pos-vpos)*(vpos.z/(u_camera_pos.z-vpos.z));}v_height=a_height; #endif gl_Position=u_matrix*vec4(vpos,1);gl_Position.z=u_reset_depth==1.0 ? gl_Position.w : gl_Position.z+u_depth_bias;}`),elevatedStructures:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" in vec3 v_normal;in float v_height; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth; #endif vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}vec3 compute_view_dependent_emissive_color(float ndotl,float emissive_strength,vec3 color) {color=sRGBToLinear(color);color=color*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);color=linearTosRGB(color.rgb);return color;}uniform float u_emissive_strength; #pragma mapbox: define highp vec4 structure_color void main() { #pragma mapbox: initialize highp vec4 structure_color vec3 color=structure_color.xyz;vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE vec3 normal=normalize(v_normal);vec3 transformed_normal=vec3(-normal.xy,normal.z);float ndotl=calculate_NdotL(transformed_normal);float emissive_strength=u_emissive_strength;emissive_strength=0.0;vec3 emissive_color=compute_view_dependent_emissive_color(ndotl,emissive_strength,color.xyz); #ifdef RENDER_SHADOWS float light=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);color.rgb=apply_lighting(color.rgb,transformed_normal,light); #else color=apply_lighting(color,transformed_normal); #endif color=mix(color,emissive_color,emissive_strength);if (v_height < 0.0) {float penetration=max(v_height+7.5,0.0);float occlusion=1.0-1.0/PI*acos(1.0-penetration/4.0);color=color*(1.0-pow(occlusion,2.0)*0.3);} #endif #ifdef FOG color=fog_apply(color,v_fog_pos); #endif vec4 out_color=vec4(color,1.0); #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_height); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color;HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in ivec2 a_pos;in float a_height;in ivec4 a_pos_normal_3;uniform mat4 u_matrix;out vec3 v_normal;out float v_height; #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out float v_depth; #endif #pragma mapbox: define highp vec4 structure_color void main() { #pragma mapbox: initialize highp vec4 structure_color v_normal=vec3(a_pos_normal_3)/16384.0;v_height=a_height;vec3 pos=vec3(vec2(a_pos),a_height);gl_Position=u_matrix*vec4(pos,1); #ifdef RENDER_SHADOWS vec3 shd_pos0=pos;vec3 shd_pos1=pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(-v_normal.xy,v_normal.z));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),fill:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float opacity uniform float u_emissive_strength; #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #endif void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float opacity vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif vec4 out_color=color; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif out_color*=opacity; #ifdef INDICATOR_CUTOUT if (v_z_offset >=0.0) {out_color=applyCutout(out_color,v_z_offset);} #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset;out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #endif uniform mat4 u_matrix; #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float opacity #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp float z_offset #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset;v_road_z_offset=z_offset; #endif float hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden); #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif #ifdef INDICATOR_CUTOUT v_z_offset=z_offset; #endif }`),fillOutline:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" in highp vec2 v_pos;uniform float u_emissive_strength; #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #pragma mapbox: define highp vec4 outline_color #pragma mapbox: define lowp float opacity void main() { #pragma mapbox: initialize highp vec4 outline_color #pragma mapbox: initialize lowp float opacity float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=outline_color;vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color*(alpha*opacity); #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif uniform mat4 u_matrix;uniform vec2 u_world;out highp vec2 v_pos; #pragma mapbox: define highp vec4 outline_color #pragma mapbox: define lowp float opacity #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize highp vec4 outline_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp float z_offset #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset; #endif float hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden); #ifdef FLIP_Y v_pos=(vec2(gl_Position.x,-gl_Position.y)/gl_Position.w+1.0)/2.0*u_world; #else v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world; #endif #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),fillOutlinePattern:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_PATTERN_TRANSITION uniform float u_pattern_transition; #endif uniform float u_emissive_strength; #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif in highp vec2 v_pos;in highp vec2 v_pos_world; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);float dist=length(v_pos_world-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_PATTERN_TRANSITION vec2 pattern_b_tl=pattern_b.xy;vec2 pattern_b_br=pattern_b.zw;highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*(alpha*opacity); #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif out highp vec2 v_pos;out highp vec2 v_pos_world; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define lowp float pixel_ratio #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize lowp float pixel_ratio #pragma mapbox: initialize highp float z_offset vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw); #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset; #endif float hidden=float(opacity==0.0);vec2 pos=vec2(a_pos);gl_Position=mix(u_matrix*vec4(pos,z_offset,1),AWAY,hidden);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos); #ifdef FLIP_Y v_pos_world=(vec2(gl_Position.x,-gl_Position.y)/gl_Position.w+1.0)/2.0*u_world; #else v_pos_world=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world; #endif #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(pos,z_offset);vec3 shd_pos1=vec3(pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),fillPattern:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_PATTERN_TRANSITION uniform float u_pattern_transition; #endif in highp vec2 v_pos;uniform float u_emissive_strength; #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_PATTERN_TRANSITION vec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y); #ifdef ELEVATED_ROADS out_color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*opacity; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset;out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif out highp vec2 v_pos; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define lowp float pixel_ratio #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #pragma mapbox: initialize lowp float pixel_ratio #pragma mapbox: initialize highp float z_offset #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio; #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset;v_road_z_offset=z_offset; #endif float hidden=float(opacity==0.0);vec2 pos=vec2(a_pos);gl_Position=mix(u_matrix*vec4(pos,z_offset,1),AWAY,hidden);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos); #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(pos,z_offset);vec3 shd_pos1=vec3(pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),lineBlendComposite:Bn(`uniform sampler2D u_image;uniform float u_opacity;uniform int u_blend_mode;in vec2 v_pos; #define ADDITIVE 1 void main() {vec4 color=texture(u_image,v_pos);if (u_blend_mode==ADDITIVE) {if (color.a <=0.0) {discard;}float density=color.a;vec3 avgColor=color.rgb/max(density,0.001);float t=density/(1.0+density);glFragColor=vec4(avgColor*t*u_opacity,t*u_opacity);} else {vec3 multiplyFactor=color.rgb*u_opacity+(1.0-u_opacity);glFragColor=vec4(multiplyFactor,1.0);} #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(0.0); #endif HANDLE_WIREFRAME_DEBUG;}`,"in ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=vec2(a_pos)*0.5+0.5;}"),fillExtrusion:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" in vec4 v_color;in vec4 v_flat; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1; #endif uniform lowp float u_opacity; #ifdef RENDER_FRONT_CUTOFF in float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT in vec4 v_ground_roof; #endif #endif #ifdef FAUX_AO uniform lowp vec2 u_ao;in vec2 v_ao; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) in vec4 v_roof_color; #endif #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) in highp vec3 v_normal; #endif uniform vec3 u_flood_light_color;uniform highp float u_vertical_scale;uniform float u_flood_light_intensity;uniform vec3 u_ground_shadow_factor; #if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT) in float v_flood_radius;in float v_has_floodlight; #endif in float v_height; #pragma mapbox: define highp float emissive_strength void main() { #pragma mapbox: initialize highp float emissive_strength #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) vec3 normal=normalize(v_normal); #endif float z;vec4 color=v_color; #ifdef ZERO_ROOF_RADIUS z=float(normal.z > 0.00001); #ifdef LIGHTING_3D_MODE normal=mix(normal,vec3(0.0,0.0,1.0),z); #else color=mix(v_color,v_roof_color,z); #endif #endif float h=max(0.0,v_height);float ao_shade=1.0; #ifdef FAUX_AO float intensity=u_ao[0];float h_floors=h/(u_ao[1]*u_vertical_scale);float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);ao_shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x; #ifdef ZERO_ROOF_RADIUS concave*=(1.0-z); #endif float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);ao_shade*=mix(1.0,x_shade*x_shade*x_shade,concave); #ifdef LIGHTING_3D_MODE #ifdef FLOOD_LIGHT color.rgb*=mix(ao_shade,1.0,v_has_floodlight); #else color.rgb*=ao_shade; #endif #else color.rgb*=ao_shade; #endif #endif #ifdef LIGHTING_3D_MODE float flood_radiance=0.0; #ifdef FLOOD_LIGHT flood_radiance=(1.0-min(h/v_flood_radius,1.0))*u_flood_light_intensity*v_has_floodlight; #endif #ifdef RENDER_SHADOWS #ifdef FLOOD_LIGHT float ndotl_unclamped=dot(normal,u_shadow_direction);float ndotl=max(0.0,ndotl_unclamped);float occlusion=ndotl_unclamped < 0.0 ? 1.0 : shadow_occlusion(ndotl,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);vec3 litColor=apply_lighting(color.rgb,normal,(1.0-u_shadow_intensity*occlusion)*ndotl);vec3 floodLitColor=compute_flood_lighting(u_flood_light_color*u_opacity,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=mix(litColor,floodLitColor,flood_radiance); #else float shadowed_lighting_factor; #ifdef RENDER_CUTOFF shadowed_lighting_factor=shadowed_light_factor_normal_opacity(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;} #else shadowed_lighting_factor=shadowed_light_factor_normal(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w); #endif color.rgb=apply_lighting(color.rgb,normal,shadowed_lighting_factor); #endif #else color.rgb=apply_lighting(color.rgb,normal); #ifdef FLOOD_LIGHT color.rgb=mix(color.rgb,u_flood_light_color*u_opacity,flood_radiance); #endif #endif color.rgb=mix(color.rgb,v_flat.rgb,emissive_strength);color*=u_opacity; #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos,h)); #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT {float ditherOpacity=cutoutGroundRoofOpacity(v_ground_roof);if (ditherOpacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (ditherOpacity < DITHER_THRESHOLDS[index]) {discard;}}} #else color=applyCutout(color,h); #endif #endif #ifdef RENDER_FRONT_CUTOFF if (v_front_cutoff_opacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (v_front_cutoff_opacity < DITHER_THRESHOLDS[index]) {discard;}} #endif #ifdef FEATURE_CUTOUT color=apply_feature_cutout(color,gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #endif glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_lighting.glsl" #include "_prelude_material_table.vertex.glsl" uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_edge_radius;uniform float u_width_scale;in ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 a_join_normal_inside; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift; #endif #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif uniform highp float u_vertical_scale; #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params;out float v_front_cutoff_opacity; #endif out vec4 v_color;out vec4 v_flat; #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) out vec4 v_roof_color; #endif #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) out highp vec3 v_normal; #endif #ifdef FAUX_AO uniform lowp vec2 u_ao;out vec2 v_ao; #endif #if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT) out float v_flood_radius;out float v_has_floodlight; #endif out float v_height; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT out vec4 v_ground_roof; #endif #endif vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));} #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp vec4 color #pragma mapbox: define highp float flood_light_wall_radius #pragma mapbox: define highp float line_width #pragma mapbox: define highp float emissive_strength void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize highp float flood_light_wall_radius #pragma mapbox: initialize highp float line_width #pragma mapbox: initialize highp float emissive_strength base*=u_vertical_scale;height*=u_vertical_scale;vec4 top_up_ny_start=vec4(a_pos_normal_ed & 1);vec4 pos_nx=vec4(a_pos_normal_ed >> 1);float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny_start.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny_start.z-1.0)*(1.0-abs(x_normal)),0.0)); #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) v_normal=normal; #endif base=max(0.0,base);float attr_height=height;height=max(0.0,top_up_ny_start.y==0.0 && top_up_ny_start.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny_start.x;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=vec2(a_centroid_pos); #endif float ele=0.0;float h=0.0;float c_ele=0.0;vec3 pos; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && (int(centroid_pos.y) & 7)==7);c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base; #else h=t > 0.0 ? height : base; #endif pos=vec3(pos_nx.xy,h); #ifdef PROJECTION_GLOBE_VIEW float lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=vec3(a_pos_3)+globe_normal*(u_tile_up_scale*h);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,pos.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*pos.z;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #endif float cutoff=1.0;vec3 scaled_pos=pos; #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec2 centroid_decoded=pos.xy;bool isBorderCentroid=false;if (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {int iy=int(centroid_pos.y);int spanYbits=iy & 7;if (spanYbits==7) {isBorderCentroid=true;int borderID=(iy >> 3) & 3;float coordAlongBorder=float(iy >> 5)*4.0;if (borderID==0) centroid_decoded=vec2(0.0,coordAlongBorder);else if (borderID==1) centroid_decoded=vec2(EXTENT,coordAlongBorder);else if (borderID==2) centroid_decoded=vec2(coordAlongBorder,0.0);else centroid_decoded=vec2(coordAlongBorder,EXTENT);} else {centroid_decoded=floor(centroid_pos/8.0);}} #endif #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec4 ground=u_matrix*vec4(centroid_decoded,ele,1.0); #endif #ifdef RENDER_CUTOFF #ifdef CLIP_ZERO_TO_ONE cutoff=cutoff_opacity(u_cutoff_params,ground.z*2.0-ground.w); #else cutoff=cutoff_opacity(u_cutoff_params,ground.z); #endif if (centroid_pos.y !=0.0 && centroid_pos.x !=0.0) {vec3 centroid_random=vec3(centroid_pos.xy,centroid_pos.x+centroid_pos.y+1.0);vec3 ground_pos=centroid_random/8.0;vec3 g=floor(ground_pos);vec3 mod_=centroid_random-g*8.0;float seed=min(1.0,0.1*(min(3.5,max(mod_.x+mod_.y,0.2*attr_height))*0.35+mod_.z));if (cutoff < 0.8-seed) {cutoff=0.0;}}float cutoff_scale=cutoff;v_cutoff_opacity=cutoff;scaled_pos.z=mix(c_ele,h,cutoff_scale); #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (cutoff==0.0 && centroid_pos.x !=0.0) || (color.a==0.0)); #ifdef RENDER_FRONT_CUTOFF v_front_cutoff_opacity=1.0;if (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {hidden=max(hidden,float(ground.w <=0.0));float ndc_y=ground.y/max(ground.w,0.001);float threshold=u_front_cutoff_params.x*2.0-1.0;float range_ndc=u_front_cutoff_params.y*2.0;if (!isBorderCentroid) {hidden=max(hidden,float(ndc_y < threshold-range_ndc));}float t=clamp((ndc_y-(threshold-range_ndc))/max(range_ndc,0.001),0.0,1.0);v_front_cutoff_opacity=mix(u_front_cutoff_params.z,1.0,t);} #endif #ifdef RENDER_WALL_MODE vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);scaled_pos.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;scaled_pos.xy-=join_normal_inside.z*wall_offset*0.5; #endif gl_Position=mix(u_matrix*vec4(scaled_pos,1),AWAY,hidden);h=h-ele;v_height=h; #ifdef RENDER_SHADOWS vec3 shd_pos0=pos;vec3 shd_pos1=pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(normal);shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1); #endif float NdotL=0.0;float colorvalue=0.0; #ifndef LIGHTING_3D_MODE colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;NdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),NdotL);if (normal.y !=0.0) {float r=0.84;r=mix(0.7,0.98,1.0-u_lightintensity);NdotL*=( (1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));} #endif #ifdef FAUX_AO float concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height; #ifdef TERRAIN top_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height); #endif v_ao=vec2(mix(concave,-concave,start),y_ground);NdotL*=(1.0+0.05*(1.0-top_up_ny_start.y)*u_ao[0]); #ifdef PROJECTION_GLOBE_VIEW top_height+=u_height_lift; #endif gl_Position.z-=(0.0000006*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w; #endif #ifdef LIGHTING_3D_MODE #ifdef FLOOD_LIGHT float is_wall=1.0-float(t > 0.0 && top_up_ny_start.y > 0.0);v_has_floodlight=float(flood_light_wall_radius > 0.0 && is_wall > 0.0);v_flood_radius=flood_light_wall_radius*u_vertical_scale; #endif v_color=vec4(color.rgb,1.0);float ndotl=calculate_NdotL(normal);v_flat.rgb=sRGBToLinear(color.rgb);v_flat.rgb=v_flat.rgb*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);v_flat=vec4(linearTosRGB(v_flat.rgb),1.0); #else v_color=vec4(0.0,0.0,0.0,1.0);v_color.rgb+=clamp(color.rgb*NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_color*=u_opacity; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) float roofNdotL=clamp(u_lightpos.z,0.0,1.0);roofNdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),roofNdotL);v_roof_color=vec4(0.0,0.0,0.0,1.0);v_roof_color.rgb+=clamp(color.rgb*roofNdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_roof_color*=u_opacity; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT vec4 pos_ground=u_matrix*vec4(pos.xy,ele,1.0);vec4 pos_roof=u_matrix*vec4(pos.xy,ele+height,1.0);v_ground_roof=vec4(pos_ground.xy/pos_ground.w,pos_roof.xy/pos_roof.w); #endif #endif }`),fillExtrusionDepth:Bn("void main() {}",`#include "_prelude_terrain.vertex.glsl" #include "_prelude_material_table.vertex.glsl" uniform mat4 u_matrix;uniform float u_edge_radius;uniform float u_width_scale;uniform float u_vertical_scale; #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif in ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 a_join_normal_inside; #endif #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp float line_width #pragma mapbox: define highp vec4 color void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp float line_width #pragma mapbox: initialize highp vec4 color base*=u_vertical_scale;height*=u_vertical_scale;vec3 top_up_ny=vec3(a_pos_normal_ed.xyz & 1);vec3 pos_nx=vec3(a_pos_normal_ed.xyz >> 1);base=max(0.0,base);height=max(0.0,top_up_ny.y==0.0 && top_up_ny.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny.x;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=vec2(a_centroid_pos); #endif vec3 pos; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;float ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && int(centroid_pos.y)-(int(centroid_pos.y)/8)*8==7);float c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);float h=t > 0.0 ? max(h_base,h_height) : h_base;pos=vec3(pos_nx.xy,h); #else pos=vec3(pos_nx.xy,t > 0.0 ? height : base); #endif #ifdef RENDER_WALL_MODE vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);pos.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;pos.xy-=join_normal_inside.z*wall_offset*0.5; #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (color.a==0.0));gl_Position=mix(u_matrix*vec4(pos,1),AWAY,hidden);}`),fillExtrusionPattern:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_EXTRUSION_PATTERN_TRANSITION uniform float u_pattern_transition; #endif #ifdef FAUX_AO uniform lowp vec2 u_ao;in vec3 v_ao; #endif #ifdef LIGHTING_3D_MODE in vec3 v_normal; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif in highp vec2 v_pos;in vec4 v_lighting;uniform lowp float u_opacity; #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define highp float pixel_ratio void main() { #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize highp float pixel_ratio vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_EXTRUSION_PATTERN_TRANSITION vec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting(out_color,normalize(v_normal))*u_opacity; #else out_color=out_color*v_lighting; #endif #ifdef FAUX_AO float intensity=u_ao[0];float h=max(0.0,v_ao.z);float h_floors=h/u_ao[1];float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);float shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x;float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);shade*=mix(1.0,x_shade*x_shade*x_shade,concave);out_color.rgb=out_color.rgb*shade; #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,height); #endif glFragColor=out_color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #include "_prelude_lighting.glsl" #include "_prelude_material_table.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform float u_tile_units_to_pixels;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_width_scale;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;in ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 a_join_normal_inside; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift; #endif #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif out highp vec2 v_pos;out vec4 v_lighting; #ifdef FAUX_AO uniform lowp vec2 u_ao;out vec3 v_ao; #endif #ifdef LIGHTING_3D_MODE out vec3 v_normal; #endif #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp vec4 color #pragma mapbox: define mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define highp float pixel_ratio #pragma mapbox: define highp float line_width void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize highp float pixel_ratio #pragma mapbox: initialize highp float line_width vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec4 top_up_ny_start=vec4(a_pos_normal_ed & 1);vec4 pos_nx=vec4(a_pos_normal_ed >> 1);float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny_start.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny_start.z-1.0)*(1.0-abs(x_normal)),0.0));float edgedistance=float(a_pos_normal_ed.w);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;base=max(0.0,base);height=max(0.0,height);float t=top_up_ny_start.x;float z=t > 0.0 ? height : base;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=vec2(a_centroid_pos); #endif float ele=0.0;float h=z;vec3 p;float c_ele; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && int(centroid_pos.y)-(int(centroid_pos.y)/8)*8==7);c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base;p=vec3(pos_nx.xy,h); #else p=vec3(pos_nx.xy,z); #endif #ifdef PROJECTION_GLOBE_VIEW float lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=vec3(a_pos_3)+globe_normal*(u_tile_up_scale*(p.z+lift));vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,p.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*p.z;p=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #endif #ifdef RENDER_WALL_MODE vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);p.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;p.xy-=join_normal_inside.z*wall_offset*0.5; #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (color.a==0.0));gl_Position=mix(u_matrix*vec4(p,1),AWAY,hidden);vec2 pos=normal.z==1.0 ? pos_nx.xy : vec2(edgedistance,z*u_height_factor);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float NdotL=0.0; #ifdef LIGHTING_3D_MODE NdotL=calculate_NdotL(normal); #else NdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),NdotL); #endif if (normal.y !=0.0) {float r=0.84; #ifndef LIGHTING_3D_MODE r=mix(0.7,0.98,1.0-u_lightintensity); #endif NdotL*=( (1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));} #ifdef FAUX_AO float concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height; #ifdef TERRAIN top_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height); #endif v_ao=vec3(mix(concave,-concave,start),y_ground,h-ele);NdotL*=(1.0+0.05*(1.0-top_up_ny_start.y)*u_ao[0]); #ifdef PROJECTION_GLOBE_VIEW top_height+=u_height_lift; #endif gl_Position.z-=(0.0000006*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w; #endif #ifdef LIGHTING_3D_MODE v_normal=normal; #else v_lighting.rgb+=clamp(NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity; #endif #ifdef FOG v_fog_pos=fog_position(p); #endif }`),groundShadow:Bn(`#include "_prelude_shadow.fragment.glsl" precision highp float;uniform vec3 u_ground_shadow_factor;in vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1; #ifdef FOG in float v_fog_opacity; #endif void main() {float light=shadowed_light_factor_plane_bias(v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);vec3 shadow=mix(u_ground_shadow_factor,vec3(1.0),light); #ifdef RENDER_CUTOFF shadow=mix(vec3(1.0),shadow,cutoff_opacity(u_cutoff_params,1.0/gl_FragCoord.w)); #endif #ifdef FOG shadow=mix(shadow,vec3(1.0),v_fog_opacity); #endif #ifdef INDICATOR_CUTOUT shadow=mix(shadow,vec3(1.0),1.0-applyCutout(vec4(1.0),0.0).r); #endif #ifdef FEATURE_CUTOUT shadow=mix(shadow,vec3(1.0),get_cutout_factors(gl_FragCoord).y); #endif glFragColor=vec4(shadow,1.0);}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;in ivec2 a_pos;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1; #ifdef FOG out float v_fog_opacity; #endif void main() {gl_Position=u_matrix*vec4(a_pos,0.0,1.0);v_pos_light_view_0=u_light_matrix_0*vec4(a_pos,0.0,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(a_pos,0.0,1.0); #ifdef FOG v_fog_pos=fog_position(vec2(a_pos));v_fog_opacity=fog(v_fog_pos); #endif }`),fillExtrusionGroundEffect:Bn(`uniform highp float u_ao_pass;uniform highp float u_opacity;uniform highp float u_flood_light_intensity;uniform highp vec3 u_flood_light_color;uniform highp float u_attenuation;uniform sampler2D u_fb;uniform float u_fb_size; #ifdef SDF_SUBPASS in highp vec2 v_pos;in highp vec4 v_line_segment;in highp float v_flood_light_radius_tile;in highp vec2 v_ao;float line_df(highp vec2 a,highp vec2 b,highp vec2 p) {highp vec2 ba=b-a;highp vec2 pa=p-a;highp float r=clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);return length(pa-r*ba);} #ifdef FOG in highp float v_fog; #endif #endif void main() { #ifdef CLEAR_SUBPASS vec4 color=vec4(1.0); #ifdef CLEAR_FROM_TEXTURE color=texture(u_fb,gl_FragCoord.xy/vec2(u_fb_size)); #endif glFragColor=color; #else #ifdef SDF_SUBPASS highp float d=line_df(v_line_segment.xy,v_line_segment.zw,v_pos);highp float effect_radius=mix(v_flood_light_radius_tile,v_ao.y,u_ao_pass);d/=effect_radius;d=min(d,1.0);d=1.0-pow(1.0-d,u_attenuation);highp float effect_intensity=mix(u_flood_light_intensity,v_ao.x,u_ao_pass);highp float fog=1.0; #ifdef FOG fog=v_fog; #endif #ifdef RENDER_CUTOFF fog*=v_cutoff_opacity; #endif glFragColor=vec4(vec3(0.0),mix(1.0,d,effect_intensity*u_opacity*fog)); #else #ifdef USE_MRT1 out_Target1=vec4(1.0-texture(u_fb,gl_FragCoord.xy/vec2(u_fb_size)).a,0.0,0.0,0.0); #else vec4 color=mix(vec4(u_flood_light_color,1.0),vec4(vec3(0.0),1.0),u_ao_pass); #ifdef OVERDRAW_INSPECTOR color=vec4(1.0); #endif glFragColor=color; #endif #endif HANDLE_WIREFRAME_DEBUG; #endif }`,`#include "_prelude_fog.vertex.glsl" in highp ivec4 a_pos_end;in highp int a_angular_offset_factor;in highp uint a_hidden_by_landmark; #ifdef SDF_SUBPASS out highp vec2 v_pos;out highp vec4 v_line_segment;out highp float v_flood_light_radius_tile;out highp vec2 v_ao; #ifdef FOG out highp float v_fog; #endif #endif uniform highp float u_flood_light_intensity;uniform highp mat4 u_matrix;uniform highp float u_ao_pass;uniform highp float u_meter_to_tile;uniform highp float u_edge_radius;uniform highp float u_dynamic_offset;uniform highp vec2 u_ao; #pragma mapbox: define highp float flood_light_ground_radius const float TANGENT_CUTOFF=4.0;const float NORM=32767.0;void main() { #pragma mapbox: initialize highp float flood_light_ground_radius vec4 pos_end=vec4(a_pos_end);vec2 p=pos_end.xy;vec2 q=floor(pos_end.zw*0.5);vec2 start_bottom=pos_end.zw-q*2.0;float fl_ground_radius=abs(flood_light_ground_radius);float direction=flood_light_ground_radius < 0.0 ?-1.0 : 1.0;float flood_radius_tile=fl_ground_radius*u_meter_to_tile;vec2 v=normalize(q-p);float ao_radius=u_ao.y/3.5;float effect_radius=mix(flood_radius_tile,ao_radius,u_ao_pass)+u_edge_radius;float angular_offset_factor=float(a_angular_offset_factor)/NORM*TANGENT_CUTOFF;float angular_offset=direction*angular_offset_factor*effect_radius;float top=1.0-start_bottom.y;float side=(0.5-start_bottom.x)*2.0;vec2 extrusion_parallel=v*side*mix(u_dynamic_offset,angular_offset,top);vec2 perp=vec2(v.y,-v.x);vec2 extrusion_perp=direction*perp*effect_radius*top;vec3 pos=vec3(mix(q,p,start_bottom.x),0.0);pos.xy+=extrusion_parallel+extrusion_perp; #ifdef SDF_SUBPASS v_pos=pos.xy;v_line_segment=vec4(p,q)+perp.xyxy*u_edge_radius;v_flood_light_radius_tile=flood_radius_tile;v_ao=vec2(u_ao.x,ao_radius); #ifdef FOG v_fog_pos=fog_position(pos);v_fog=1.0-fog(v_fog_pos); #endif #endif float hidden_by_landmark=0.0; #ifdef HAS_CENTROID hidden_by_landmark=float(a_hidden_by_landmark); #endif float isFloodlit=float(fl_ground_radius > 0.0 && u_flood_light_intensity > 0.0);float hidden=mix(1.0-isFloodlit,isFloodlit,u_ao_pass);hidden+=hidden_by_landmark;gl_Position=mix(u_matrix*vec4(pos,1.0),AWAY,float(hidden > 0.0)); #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z); #endif }`),hillshadePrepare:Bn(`precision highp float;uniform highp sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;float getElevation(vec2 coord) {return texture(u_image,coord).r/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y));float b=getElevation(v_pos+vec2(0,-epsilon.y));float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y));float d=getElevation(v_pos+vec2(-epsilon.x,0));float e=getElevation(v_pos+vec2(epsilon.x,0));float f=getElevation(v_pos+vec2(-epsilon.x,epsilon.y));float g=getElevation(v_pos+vec2(0,epsilon.y));float h=getElevation(v_pos+vec2(epsilon.x,epsilon.y));float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2( (c+e+e+h)-(a+d+d+f),(f+g+g+h)-(a+b+b+c) )/pow(2.0,exaggeration+(19.2562-u_zoom));glFragColor=clamp(vec4( deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);}`,"uniform mat4 u_matrix;uniform vec2 u_dimension;in ivec2 a_pos;in uvec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(vec2(a_texture_pos)/8192.0)*scale+epsilon;}"),hillshade:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;uniform float u_emissive_strength;void main() {vec4 pixel=texture(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);glFragColor=accent_color*(1.0-shade_color.a)+shade_color; #ifdef LIGHTING_3D_MODE glFragColor=apply_lighting_with_emission_ground(glFragColor,u_emissive_strength); #endif #ifdef FOG glFragColor=fog_dither(fog_apply_premultiplied(glFragColor,v_fog_pos)); #endif #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;in ivec2 a_pos;in uvec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=vec2(a_texture_pos)/8192.0; #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),line:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform lowp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_floor_width_scale;uniform float u_alpha_discard_threshold;uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform highp vec2 u_trim_gradient_mix_range;uniform lowp vec4 u_trim_color;uniform bool u_emissive_in_shadows;in vec4 v_width2_dilute;in vec2 v_normal;in float v_gamma_scale;in highp vec3 v_uv; #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef VARIABLE_LINE_WIDTH in float stub_side; #endif #ifdef RENDER_LINE_DASH uniform sampler2D u_dash_image;in vec2 v_tex; #endif #ifdef RENDER_LINE_GRADIENT uniform sampler2D u_gradient_image; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif float luminance(vec3 c) {return (c.r+c.r+c.b+c.g+c.g+c.g)*0.1667;} #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float floorwidth #pragma mapbox: define mediump uvec4 dash #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define mediump float side_z_offset #pragma mapbox: define lowp float border_width #pragma mapbox: define lowp vec4 border_color #pragma mapbox: define lowp float emissive_strength float linearstep(float edge0,float edge1,float x) {return clamp((x-edge0)/(edge1-edge0),0.0,1.0);}void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float floorwidth #pragma mapbox: initialize mediump uvec4 dash #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump float side_z_offset #pragma mapbox: initialize lowp float border_width #pragma mapbox: initialize lowp vec4 border_color #pragma mapbox: initialize lowp float emissive_strength float dist=length(v_normal)*v_width2_dilute.x; #ifdef VARIABLE_LINE_WIDTH blur=mix(blur,0.0,stub_side); #endif float diluted_opacity=opacity*v_width2_dilute.z;float blur2=(u_width_scale*blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2_dilute.y-blur2),v_width2_dilute.x-dist)/blur2,0.0,1.0); #ifdef VARIABLE_LINE_WIDTH alpha=mix(alpha,1.0,stub_side); #endif alpha=side_z_offset > 0.0 ? 1.0-alpha : alpha; #ifdef RENDER_LINE_DASH float sdfdist=texture(u_dash_image,v_tex).r;float sdfgamma=1.0/(2.0*u_device_pixel_ratio)/(float(dash.z)+float(dash.w)/65535.0);float scaled_floorwidth=(floorwidth*u_floor_width_scale);alpha*=linearstep(0.5-sdfgamma/scaled_floorwidth,0.5+sdfgamma/scaled_floorwidth,sdfdist); #endif highp vec4 out_color; #ifdef RENDER_LINE_GRADIENT out_color=texture(u_gradient_image,v_uv.xy); #else out_color=color; #endif float trim_alpha=1.0; #ifdef RENDER_LINE_TRIM_OFFSET highp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);highp float gradient_trim_color_mix_factor=0.0; #ifdef RENDER_LINE_GRADIENT gradient_trim_color_mix_factor=smoothstep(u_trim_gradient_mix_range.x,u_trim_gradient_mix_range.y,line_progress); #endif highp vec4 trim_color=mix(u_trim_color,out_color,gradient_trim_color_mix_factor);out_color=mix(u_trim_gradient_mix_range.x < 1.0 ? color : out_color,trim_color,transition_factor);trim_alpha=1.0-transition_factor;} #endif if (u_alpha_discard_threshold !=0.0) {if (alpha < u_alpha_discard_threshold) {discard;}} #ifdef RENDER_LINE_BORDER #ifndef VARIABLE_LINE_WIDTH float edgeBlur=((border_width*u_width_scale)+1.0/u_device_pixel_ratio);float alpha2=clamp(min(dist-(v_width2_dilute.y-edgeBlur),v_width2_dilute.x-dist)/edgeBlur,0.0,1.0);if (alpha2 < 1.) {float smoothAlpha=smoothstep(0.6,1.0,alpha2);if (border_color.a==0.0) {float Y=(out_color.a > 0.01) ? luminance(out_color.rgb/out_color.a) : 1.;float adjustment=(Y > 0.) ? 0.5/Y : 0.45;if (out_color.a > 0.25 && Y < 0.25) {vec3 borderColor=(Y > 0.) ? out_color.rgb : vec3(1,1,1)*out_color.a;out_color.rgb=out_color.rgb+borderColor*(adjustment*(1.0-smoothAlpha));} else {out_color.rgb*=(0.6 +0.4*smoothAlpha);}} else {out_color=mix(border_color*trim_alpha,out_color,smoothAlpha);}out_color*=v_width2_dilute.w;} #endif #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);light=u_emissive_in_shadows ? mix(light,1.0,emissive_strength) : light; #ifdef ELEVATED_ROADS out_color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif out_color*=(alpha*diluted_opacity); #ifdef LINE_BLEND_MULTIPLY glFragColor=vec4(out_color.rgb+(1.0-out_color.a),1.0);HANDLE_WIREFRAME_DEBUG;return; #endif #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_z_offset); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color; #ifdef DUAL_SOURCE_BLENDING glFragColorSrc1=vec4(vec3(0.0),emissive_strength); #else #ifdef USE_MRT1 out_Target1=vec4(emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #define EXTRUDE_SCALE 0.015873016 in ivec2 a_pos_normal;in uvec4 a_data; #if defined(ELEVATED) || defined(ELEVATED_ROADS) || defined(VARIABLE_LINE_WIDTH) in vec3 a_z_offset_width; #endif #ifdef ELEVATION_GROUND_SCALE in float a_elevation_ground_scale; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) || defined(RENDER_LINE_CURVE) in highp vec3 a_packed; #endif #ifdef RENDER_LINE_DASH in float a_linesofar; #endif uniform mat4 u_matrix;uniform mat2 u_pixels_to_tile_units;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;uniform float u_width_scale;uniform highp float u_floor_width_scale; #ifdef RENDER_LINE_CURVE uniform mat3 u_curve_points_x;uniform mat3 u_curve_points_y;uniform mat3 u_curve_points_z;uniform float u_curve_point_count; #endif #ifdef ELEVATED uniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) { #ifdef ELEVATION_REFERENCE_SEA return 0.0; #else return elevation(apos); #endif } #endif out vec2 v_normal;out vec4 v_width2_dilute;out float v_gamma_scale;out highp vec3 v_uv; #ifdef ELEVATED_ROADS out highp float v_road_z_offset; #endif #ifdef VARIABLE_LINE_WIDTH out float stub_side; #endif #ifdef RENDER_LINE_DASH uniform vec2 u_texsize;uniform float u_tile_units_to_pixels;out vec2 v_tex; #endif #ifdef RENDER_LINE_GRADIENT uniform float u_image_height; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float floorwidth #pragma mapbox: define mediump uvec4 dash #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define mediump float gapwidth #pragma mapbox: define lowp float offset #pragma mapbox: define mediump float width #pragma mapbox: define mediump float side_z_offset #pragma mapbox: define lowp float border_width #pragma mapbox: define lowp vec4 border_color #pragma mapbox: define lowp float emissive_strength #ifdef RENDER_LINE_CURVE vec3 getCurvePoint(int index) {int row=index/3;int col=index-row*3;float x=u_curve_points_x[row][col];float y=u_curve_points_y[row][col];float z=u_curve_points_z[row][col];return vec3(x,y,z);}vec3 catmullRom(vec3 p0,vec3 p1,vec3 p2,vec3 p3,float t) {float t2=t*t;float t3=t2*t;return 0.5*( 2.0*p1+(-p0+p2)*t+(2.0*p0-5.0*p1+4.0*p2-p3)*t2+(-p0+3.0*p1-3.0*p2+p3)*t3 );}vec2 catmullRomTangent(vec2 p0,vec2 p1,vec2 p2,vec2 p3,float t) {float t2=t*t;return 0.5*( (-p0+p2)+(2.0*p0-5.0*p1+4.0*p2-p3)*2.0*t+(-p0+3.0*p1-3.0*p2+p3)*3.0*t2 );}struct CurveResult {vec3 point;vec2 tangent;};CurveResult calculateCurve(float line_progress) {float curve_progress=line_progress*(u_curve_point_count-1.0);float curve_progress_local=fract(curve_progress);float curve_segment=floor(curve_progress);int seg=int(curve_segment);vec3 p1=getCurvePoint(seg);vec3 p2=getCurvePoint(seg+1);float is_first_seg=step(curve_segment,0.5);vec3 p0_extrapolated=p1-(p2-p1);vec3 p0_fetched=getCurvePoint(max(seg-1,0));vec3 p0=mix(p0_fetched,p0_extrapolated,is_first_seg);int last_seg=int(u_curve_point_count)-2;float is_last_seg=step(float(last_seg)-0.5,curve_segment);vec3 p3_extrapolated=p2+(p2-p1);vec3 p3_fetched=getCurvePoint(min(seg+2,int(u_curve_point_count)-1));vec3 p3=mix(p3_fetched,p3_extrapolated,is_last_seg);vec3 point=catmullRom(p0,p1,p2,p3,curve_progress_local);vec2 tangent=catmullRomTangent(p0.xy,p1.xy,p2.xy,p3.xy,curve_progress_local)*(u_curve_point_count-1.0);CurveResult result;result.point=point;result.tangent=tangent;return result;} #endif void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float floorwidth #pragma mapbox: initialize mediump uvec4 dash #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump float gapwidth #pragma mapbox: initialize lowp float offset #pragma mapbox: initialize mediump float width #pragma mapbox: initialize mediump float side_z_offset #pragma mapbox: initialize lowp float border_width #pragma mapbox: initialize lowp vec4 border_color #pragma mapbox: initialize lowp float emissive_strength float a_z_offset; #if defined(ELEVATED) || defined(ELEVATED_ROADS) a_z_offset=a_z_offset_width.x; #endif highp float line_progress=0.0; #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) || defined(RENDER_LINE_CURVE) line_progress=a_packed[2]; #endif float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(a_data.xy)-128.0;float a_direction=float(a_data.z & 3u)-1.0;vec2 pos_normal=vec2(a_pos_normal);vec2 pos=floor(pos_normal*0.5);mediump vec2 normal=pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;offset=-1.0*offset*u_width_scale;bool left=normal.y==1.0; #ifdef RENDER_LINE_CURVE CurveResult curve=calculateCurve(line_progress);pos=curve.point.xy*8192.0;a_extrude=length(a_extrude)*normalize(curve.tangent);a_extrude=left ? vec2(-a_extrude.y,a_extrude.x) : vec2(a_extrude.y,-a_extrude.x);a_z_offset+=curve.point.z; #endif gapwidth=gapwidth/2.0;float halfwidth;float dilute_scale=1.0;float dilute_border_scale=1.0; #ifdef VARIABLE_LINE_WIDTH float left_width=a_z_offset_width.y;float right_width=a_z_offset_width.z;halfwidth=(u_width_scale*(left ? left_width : right_width))/2.0;if (side_z_offset !=0.0) {float left_f=step(1.0,normal.y);float is_negative=step(side_z_offset,0.0);float apply=mix(1.0-left_f,left_f,is_negative);a_extrude*=apply;a_z_offset+=abs(side_z_offset)*apply;v_normal*=left_f;}offset=border_width > 0.0 ? (left_width+right_width)*u_width_scale*0.5 : offset;halfwidth=border_width > 0.0 ? border_width*u_width_scale*0.5 : halfwidth;bool zero_right_width=border_width==0.0 && right_width==0.0;stub_side=zero_right_width ?-normal.y : 0.0;v_normal=!left && zero_right_width ? vec2(0.0) : v_normal;ANTIALIASING=!left && zero_right_width ? 0.0 : ANTIALIASING; #else halfwidth=(u_width_scale*width)/2.0; #endif float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*EXTRUDE_SCALE;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*EXTRUDE_SCALE*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy; #ifdef ELEVATED_ROADS v_road_z_offset=a_z_offset;gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,a_z_offset,1.0); #else #ifdef ELEVATED vec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;float scaled_z_offset=a_z_offset; #ifdef ELEVATION_GROUND_SCALE scaled_z_offset=a_z_offset*mix(1.0,u_exaggeration,a_elevation_ground_scale); #endif #ifdef CROSS_SLOPE_VERTICAL float top=pos_normal.y-2.0*floor(pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+scaled_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0); #else #ifdef CROSS_SLOPE_HORIZONTAL float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+scaled_z_offset; #else float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+scaled_z_offset; #endif #endif gl_Position=u_matrix*vec4(offset_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden); #else gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0); #endif #endif #ifndef ELEVATED #ifndef VARIABLE_LINE_WIDTH #ifndef RENDER_TO_TEXTURE float base_w=gl_Position.w;vec2 screen_width=abs(projected_extrude.xy/base_w*u_units_to_pixels);float max_extrude_component=max(screen_width.x,screen_width.y);if (width >=1.0 && base_w > 0.0 && max_extrude_component > 0.0001) {float min_pixel=1.05;if (max_extrude_component < min_pixel) {vec2 abs_pos=abs(gl_Position.xy);float is_out=max(abs_pos.x,abs_pos.y)/base_w;dilute_scale=mix(max_extrude_component/min_pixel,1.0,smoothstep(2.5,4.5,is_out));projected_extrude/=dilute_scale;}else { #ifdef RENDER_LINE_BORDER float border_ratio=(border_width*u_width_scale+ANTIALIASING)/outset;screen_width*=border_ratio;float max_border_component=max(screen_width.x,screen_width.y);dilute_border_scale=min(1.0,max_border_component/min_pixel); #endif }} #endif #endif #ifdef ELEVATED_ROADS gl_Position=gl_Position+projected_extrude; #else gl_Position=mix(gl_Position+projected_extrude,AWAY,hidden); #endif #endif #ifdef ELEVATED_ROADS #ifdef RENDER_SHADOWS vec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #endif #ifndef RENDER_TO_TEXTURE float epsilon=0.0001;float extrude_length_without_perspective=max(length(dist),epsilon);float extrude_length_with_perspective=max(length(projected_extrude_xy/gl_Position.w*u_units_to_pixels),epsilon);v_gamma_scale=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur)); #else v_gamma_scale=1.0; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) highp float a_uv_x=a_packed[0];float a_split_index=a_packed[1]; #ifdef RENDER_LINE_GRADIENT highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec3(a_uv_x,a_split_index*texel_height-half_texel_height,line_progress); #else v_uv=vec3(a_uv_x,0.0,line_progress); #endif #endif #ifdef RENDER_LINE_DASH vec4 dashf=vec4(dash);float totalLength=dashf.z+dashf.w/65535.0;float scale=totalLength==0.0 ? 0.0 : u_tile_units_to_pixels/totalLength;v_tex=vec2(a_linesofar*scale/(floorwidth*u_floor_width_scale),(-normal.y*dashf.y+dashf.x+0.5)/u_texsize.y); #endif v_width2_dilute=vec4(outset,inset,dilute_scale,dilute_border_scale); #ifdef FOG v_fog_pos=fog_position(pos); #endif #ifdef INDICATOR_CUTOUT v_z_offset=a_z_offset; #endif }`),linePattern:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform highp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_alpha_discard_threshold;uniform highp vec2 u_texsize;uniform highp float u_tile_units_to_pixels;uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform lowp vec4 u_trim_color;uniform sampler2D u_image; #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef LINE_PATTERN_TRANSITION uniform float u_pattern_transition; #endif in vec2 v_normal;in vec2 v_width2;in highp float v_linesofar;in float v_gamma_scale;in float v_width; #ifdef RENDER_LINE_TRIM_OFFSET in highp vec3 v_uv; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef LINE_JOIN_NONE in vec2 v_pattern_data; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #pragma mapbox: define mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define mediump float pixel_ratio #pragma mapbox: define mediump float blur #pragma mapbox: define mediump float opacity #pragma mapbox: define lowp float emissive_strength void main() { #pragma mapbox: initialize mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize mediump float pixel_ratio #pragma mapbox: initialize mediump float blur #pragma mapbox: initialize mediump float opacity #pragma mapbox: initialize lowp float emissive_strength vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;highp float pattern_size=display_size.x/u_tile_units_to_pixels;float aspect=display_size.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(u_width_scale*blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);highp float pattern_x=v_linesofar/pattern_size*aspect;highp float x=mod(pattern_x,1.0);highp float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;highp vec2 pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(x,y));highp vec2 lod_pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(pattern_x,y));vec4 color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU color=applyLUT(u_lutTexture,color); #endif #ifdef LINE_PATTERN_TRANSITION vec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl*texel_size-texel_size,pattern_b_br*texel_size+texel_size,vec2(x,y));vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);color=color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif #ifdef RENDER_LINE_TRIM_OFFSET highp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);color=mix(color,color.a*u_trim_color,transition_factor);} #endif #ifdef LINE_JOIN_NONE highp float pattern_len=pattern_size/aspect;highp float segment_phase=pattern_len-mod(v_linesofar-v_pattern_data.x+pattern_len,pattern_len);highp float visible_start=segment_phase-step(pattern_len*0.5,segment_phase)*pattern_len;highp float visible_end=floor((v_pattern_data.y-segment_phase)/pattern_len)*pattern_len+segment_phase;visible_end+=step(pattern_len*0.5,v_pattern_data.y-visible_end)*pattern_len;if (v_pattern_data.x < visible_start || v_pattern_data.x >=visible_end) {color=vec4(0.0);} #endif #ifdef LIGHTING_3D_MODE color=apply_lighting_with_emission_ground(color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth); #ifdef ELEVATED_ROADS color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #endif color*=(alpha*opacity);if (u_alpha_discard_threshold !=0.0) {if (color.a < u_alpha_discard_threshold) {discard;}} #ifdef INDICATOR_CUTOUT color=applyCutout(color,v_z_offset); #endif glFragColor=color; #ifdef DUAL_SOURCE_BLENDING glFragColorSrc1=vec4(vec3(0.0),emissive_strength); #else #ifdef USE_MRT1 out_Target1=vec4(emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #define scale 0.015873016 in ivec2 a_pos_normal;in uvec4 a_data; #if defined(ELEVATED) || defined(ELEVATED_ROADS) in vec3 a_z_offset_width; #endif #ifdef ELEVATION_GROUND_SCALE in float a_elevation_ground_scale; #endif #ifdef RENDER_LINE_TRIM_OFFSET in highp vec3 a_packed; #endif in highp float a_linesofar; #ifdef LINE_JOIN_NONE in highp vec3 a_pattern_data;out vec2 v_pattern_data; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #endif uniform mat4 u_matrix;uniform float u_tile_units_to_pixels;uniform vec2 u_units_to_pixels;uniform mat2 u_pixels_to_tile_units;uniform float u_device_pixel_ratio;uniform float u_width_scale;uniform float u_floor_width_scale; #ifdef ELEVATED uniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) { #ifdef ELEVATION_REFERENCE_SEA return 0.0; #else return elevation(apos); #endif } #endif out vec2 v_normal;out vec2 v_width2;out highp float v_linesofar;out float v_gamma_scale;out float v_width; #ifdef RENDER_LINE_TRIM_OFFSET out highp vec3 v_uv; #endif #ifdef ELEVATED_ROADS out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #pragma mapbox: define mediump float blur #pragma mapbox: define mediump float opacity #pragma mapbox: define mediump float offset #pragma mapbox: define mediump float gapwidth #pragma mapbox: define mediump float width #pragma mapbox: define mediump float floorwidth #pragma mapbox: define mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define mediump float pixel_ratio #pragma mapbox: define lowp float emissive_strength void main() { #pragma mapbox: initialize mediump float blur #pragma mapbox: initialize mediump float opacity #pragma mapbox: initialize mediump float offset #pragma mapbox: initialize mediump float gapwidth #pragma mapbox: initialize mediump float width #pragma mapbox: initialize mediump float floorwidth #pragma mapbox: initialize mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize mediump float pixel_ratio #pragma mapbox: initialize lowp float emissive_strength float a_z_offset; #if defined(ELEVATED) || defined(ELEVATED_ROADS) a_z_offset=a_z_offset_width.x; #endif float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(a_data.xy)-128.0;float a_direction=float(a_data.z & 3u)-1.0;vec2 pos_normal=vec2(a_pos_normal);vec2 pos=floor(pos_normal*0.5);vec2 normal=pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=(u_width_scale*width)/2.0;offset=-1.0*offset*u_width_scale;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);vec2 dist=outset*a_extrude*scale;float u=0.5*a_direction;float t=1.0-abs(u);vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy; #ifdef ELEVATED_ROADS v_road_z_offset=a_z_offset;gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,a_z_offset,1.0)+projected_extrude; #else #ifdef ELEVATED vec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;float scaled_z_offset=a_z_offset; #ifdef ELEVATION_GROUND_SCALE scaled_z_offset=a_z_offset*mix(1.0,u_exaggeration,a_elevation_ground_scale); #endif #ifdef CROSS_SLOPE_VERTICAL float top=pos_normal.y-2.0*floor(pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+scaled_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0); #else #ifdef CROSS_SLOPE_HORIZONTAL float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+scaled_z_offset; #else float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+scaled_z_offset; #endif #endif gl_Position=u_matrix*vec4(offset_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden); #else gl_Position=mix(u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0)+projected_extrude,AWAY,hidden); #endif #endif #ifdef ELEVATED_ROADS #ifdef RENDER_SHADOWS vec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #endif #ifndef RENDER_TO_TEXTURE float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude_xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur)); #else v_gamma_scale=1.0; #endif #ifdef RENDER_LINE_TRIM_OFFSET highp float a_uv_x=a_packed[0];highp float line_progress=a_packed[2];v_uv=vec3(a_uv_x,0.0,line_progress); #endif v_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=(floorwidth*u_floor_width_scale); #ifdef LINE_JOIN_NONE v_width=(floorwidth*u_floor_width_scale)+ANTIALIASING;mediump float pixels_to_tile_units=1.0/u_tile_units_to_pixels;mediump float pixel_ratio_inverse=1.0/pixel_ratio;mediump float aspect=v_width/(float(pattern.w-pattern.y)*pixel_ratio_inverse);highp float subt_multiple=float(pattern.z-pattern.x)*pixel_ratio_inverse*pixels_to_tile_units*aspect*32.0;highp float subt=floor(a_pattern_data.z/subt_multiple)*subt_multiple;float offset_sign=(fract(a_pattern_data.x)-0.5)*4.0;float line_progress_offset=offset_sign*v_width*0.5*pixels_to_tile_units;v_linesofar=(a_pattern_data.z-subt)+a_linesofar+line_progress_offset;v_pattern_data=vec2(a_pattern_data.x+line_progress_offset,a_pattern_data.y); #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif #ifdef INDICATOR_CUTOUT v_z_offset=a_z_offset; #endif }`),raster:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_raster_array.glsl" uniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;uniform highp float u_zoom_transition;in vec2 v_pos0;in vec2 v_pos1;in float v_depth; #ifdef PROJECTION_GLOBE_VIEW in float v_split_fade; #endif uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;uniform float u_emissive_strength; #ifndef RASTER_ARRAY uniform highp sampler2D u_image0;uniform sampler2D u_image1; #endif #ifdef RASTER_COLOR uniform sampler2D u_color_ramp;uniform highp vec4 u_colorization_mix;uniform highp float u_colorization_offset;uniform vec2 u_texture_res; #endif void main() {vec4 color0,color1,color;vec2 value; #ifdef RASTER_COLOR #ifdef RASTER_ARRAY #ifdef RASTER_ARRAY_LINEAR value=mix( raTexture2D_image0_linear(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_linear(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t ); #else value=mix( raTexture2D_image0_nearest(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_nearest(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t ); #endif if (value.y > 0.0) value.x/=value.y; #else color=mix(texture(u_image0,v_pos0),texture(u_image1,v_pos1),u_fade_t);value=vec2(u_colorization_offset+dot(color.rgb,u_colorization_mix.rgb),color.a); #endif color=texture(u_color_ramp,vec2(value.x,0.5));if (color.a > 0.0) color.rgb/=color.a;color.a*=value.y; #else color0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t); #endif color.a*=u_opacity; #ifdef GLOBE_POLES color.a*=1.0-smoothstep(0.0,0.05,u_zoom_transition); #endif vec3 rgb=color.rgb;rgb=vec3( dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);vec3 out_color=mix(u_high_vec,u_low_vec,rgb); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),u_emissive_strength).rgb; #endif #ifdef FOG highp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit)); #endif glFragColor=vec4(out_color*color.a,color.a); #ifdef PROJECTION_GLOBE_VIEW glFragColor*=mix(1.0,1.0-smoothstep(0.0,0.05,u_zoom_transition),smoothstep(0.8,0.9,v_split_fade)); #endif #ifdef RENDER_CUTOFF glFragColor=glFragColor*cutoff_opacity(u_cutoff_params,v_depth); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform vec2 u_perspective_transform;uniform vec2 u_texture_offset;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center; #ifdef ELEVATED uniform lowp float u_zbias_factor; #endif #define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8 #ifdef GLOBE_POLES in vec3 a_globe_pos;in vec2 a_uv; #else in ivec2 a_pos;in uvec2 a_texture_pos; #endif out vec2 v_pos0;out vec2 v_pos1;out float v_depth; #ifdef PROJECTION_GLOBE_VIEW out float v_split_fade; #endif void main() {vec2 uv; #ifdef GLOBE_POLES vec3 globe_pos=a_globe_pos;uv=a_uv;float ele=u_raster_elevation; #ifdef ELEVATION_REFERENCE_GROUND ele+=elevation(uv*EXTENT); #endif globe_pos+=normalize(globe_pos)*ele*GLOBE_UPSCALE;gl_Position=u_matrix*u_globe_matrix*vec4(globe_pos,1.0); #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(a_globe_pos,1.0)).xyz); #endif #else vec4 world_pos; #ifdef PROJECTION_GLOBE_VIEW vec2 texture_pos=vec2(a_texture_pos);uv=texture_pos/8192.0;vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]); float tiles=u_grid_matrix[0][2];if (tiles > 0.0) {float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvY=mercatorY*tiles-idy;float uvX=mercatorX*tiles-idx;uv=vec2(uvX,uvY);}float ele=u_raster_elevation; #ifdef ELEVATION_REFERENCE_GROUND ele+=elevation(uv*EXTENT)-decomposed_pos_and_skirt.z; #endif vec4 merc_world_pos=vec4(0.0); v_split_fade=0.0;if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,ele,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;float opposite_merc_center=mod(u_merc_center.x+0.5,1.0);float dist_from_poles=(abs(mercatorY-0.5)*2.0);float range=0.1;v_split_fade=abs(opposite_merc_center-mercatorX);v_split_fade=clamp(1.0-v_split_fade,0.0,1.0);v_split_fade=max(smoothstep(1.0-range,1.0,dist_from_poles),max(smoothstep(1.0-range,1.0,v_split_fade),smoothstep(1.0-range,1.0,1.0-v_split_fade)));}vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*ele*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);world_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0); #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif #else float ele=0.0;vec2 decodedPos=vec2(a_pos); #ifdef ELEVATION_REFERENCE_GROUND vec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;decodedPos=decomposedPosAndSkirt.xy;uv=decodedPos/8192.0;ele=elevation(decodedPos)-skirt; #else uv=vec2(a_texture_pos)/8192.0; #endif world_pos=vec4(decodedPos,(u_raster_elevation+ele),1.0); #ifdef FOG v_fog_pos=fog_position(decodedPos); #endif #endif float w=1.0+dot(uv*EXTENT,u_perspective_transform);gl_Position=u_matrix*world_pos*w; #endif v_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;v_pos0=u_texture_offset.x+u_texture_offset.y*v_pos0;v_pos1=u_texture_offset.x+u_texture_offset.y*v_pos1; #ifdef ELEVATED float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor);gl_Position.z-=(gl_Position.w*zbias); #endif #ifdef RENDER_CUTOFF v_depth=gl_Position.z; #endif }`),rasterParticle:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;in vec2 v_pos0;in vec2 v_pos1;uniform sampler2D u_image0;uniform sampler2D u_image1;void main() {vec4 color0,color1,color;color0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 out_color=color.rgb; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),1.0).rgb; #endif #ifdef FOG highp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit)); #endif glFragColor=vec4(out_color*color.a,color.a); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center; #define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8 in ivec2 a_pos;in uvec2 a_texture_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {float w=1.0;vec2 uv; #ifdef PROJECTION_GLOBE_VIEW vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]);float tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvX=mercatorX*tiles-idx;float uvY=mercatorY*tiles-idy;uv=vec2(uvX,uvY);vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,u_raster_elevation,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition)*w,w);gl_Position=u_matrix*interpolated_pos; #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif #else uv=vec2(a_texture_pos)/8192.0;gl_Position=u_matrix*vec4(vec2(a_pos)*w,u_raster_elevation*w,w); #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif #endif v_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}`),rasterParticleDraw:Bn("uniform sampler2D u_color_ramp;in float v_particle_speed;void main() {glFragColor=texture(u_color_ramp,vec2(v_particle_speed,0.5));}",`#include "_prelude_raster_particle.glsl" in int a_index;uniform sampler2D u_particle_texture;uniform float u_particle_texture_side_len;uniform vec2 u_tile_offset;out float v_particle_speed;void main() {ivec2 pixel_coord=ivec2( mod(float(a_index),u_particle_texture_side_len),float(a_index)/u_particle_texture_side_len);vec4 pixel=texelFetch(u_particle_texture,pixel_coord,0);vec2 pos=unpack_pos_from_rgba(pixel)+u_tile_offset;vec2 tex_coord=fract(pos);vec2 velocity=lookup_velocity(tex_coord);if (velocity==INVALID_VELOCITY) {gl_Position=AWAY;v_particle_speed=0.0;} else {gl_Position=vec4(2.0*pos-1.0,0,1);v_particle_speed=length(velocity);}gl_PointSize=1.0;}`),rasterParticleTexture:Bn("uniform sampler2D u_texture;uniform float u_opacity;in vec2 v_tex_pos;void main() {vec4 color=texture(u_texture,v_tex_pos);glFragColor=vec4(floor(255.0*color*u_opacity)/255.0);}","in ivec2 a_pos;out vec2 v_tex_pos;void main() {vec2 uv=0.5*vec2(a_pos)+vec2(0.5);v_tex_pos=uv;gl_Position=vec4(a_pos,0.0,1.0);}"),rasterParticleUpdate:Bn(`#include "_prelude_raster_particle.glsl" uniform sampler2D u_particle_texture;uniform mediump float u_particle_texture_side_len;uniform mediump float u_speed_factor;uniform highp float u_reset_rate;uniform highp float u_rand_seed;in highp vec2 v_tex_coord;vec2 linearstep(vec2 edge0,vec2 edge1,vec2 x) {return clamp((x-edge0)/(edge1-edge0),vec2(0),vec2(1));}const highp vec3 rand_constants=vec3(12.9898,78.233,4375.85453);highp float rand(const highp vec2 co) {highp float t=dot(rand_constants.xy,co);return fract(sin(t)*(rand_constants.z+t));}void main() {ivec2 pixel_coord=ivec2(v_tex_coord*u_particle_texture_side_len);highp vec4 pixel=texelFetch(u_particle_texture,pixel_coord,0);highp vec2 pos=unpack_pos_from_rgba(pixel);highp vec2 velocity=lookup_velocity(clamp(pos,0.0,1.0));highp vec2 dp=velocity==INVALID_VELOCITY ? vec2(0) : velocity*u_speed_factor;pos=pos+dp;highp vec2 seed=(pos+v_tex_coord)*u_rand_seed;highp vec2 random_pos=vec2(rand(seed+1.3),rand(seed+2.1));highp vec2 persist_rate=pow( linearstep(vec2(-u_particle_pos_offset),vec2(0),pos)*linearstep(vec2(1.0+u_particle_pos_offset),vec2(1),pos),vec2(4) );highp vec2 per_frame_persist=pow(persist_rate,abs(dp)/u_particle_pos_offset);highp float drop_rate=1.0-per_frame_persist.x*per_frame_persist.y;drop_rate=any(greaterThanEqual(abs(pos-0.5),vec2(0.5+u_particle_pos_offset))) ? 1.0 : drop_rate;highp float drop=step(1.0-drop_rate-u_reset_rate,rand(seed));highp vec2 next_pos=mix(pos,random_pos,drop);glFragColor=pack_pos_to_rgba(next_pos);}`,"in ivec2 a_pos;out vec2 v_tex_coord;void main() {v_tex_coord=0.5*vec2(a_pos+ivec2(1));gl_Position=vec4(a_pos,0.0,1.0);}"),symbol:Bn(`#include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #define SDF_PX 8.0 #define SDF 1.0 #define ICON 0.0 uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;uniform bool u_is_halo;uniform lowp float u_scale_factor; #ifdef ICON_TRANSITION uniform float u_icon_transition; #endif #ifdef COLOR_ADJUSTMENT uniform mat4 u_color_adj_mat; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #else #ifdef RENDER_SHADOWS in highp float v_z_offset; #endif #endif in vec2 v_tex_a; #ifdef ICON_TRANSITION in vec2 v_tex_b; #endif in float v_draw_halo;in vec3 v_gamma_scale_size_fade_opacity; #ifdef RENDER_TEXT_AND_SYMBOL in float is_sdf;in vec2 v_tex_a_icon; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef USE_PAINT_PROPERTIES_UBO in lowp float v_opacity; #ifdef RENDER_SDF in lowp vec4 v_fill_np_color;in lowp vec4 v_halo_np_color;in lowp float v_halo_width;in lowp float v_halo_blur; #endif #ifdef LIGHTING_3D_MODE in lowp float v_emissive_strength; #endif #else #pragma mapbox: define highp vec4 fill_color #pragma mapbox: define highp vec4 halo_color #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp float halo_width #pragma mapbox: define lowp float halo_blur #pragma mapbox: define lowp float emissive_strength #endif void main() { #ifdef USE_PAINT_PROPERTIES_UBO lowp float opacity=v_opacity;lowp vec4 fill_color=vec4(0.0);lowp vec4 halo_color=vec4(0.0);lowp float halo_width=0.0;lowp float halo_blur=0.0; #ifdef RENDER_SDF fill_color=vec4(v_fill_np_color.rgb*v_fill_np_color.a,v_fill_np_color.a);halo_color=vec4(v_halo_np_color.rgb*v_halo_np_color.a,v_halo_np_color.a);halo_width=v_halo_width;halo_blur=v_halo_blur; #endif lowp float emissive_strength=0.0; #ifdef LIGHTING_3D_MODE emissive_strength=v_emissive_strength; #endif #else #pragma mapbox: initialize highp vec4 fill_color #pragma mapbox: initialize highp vec4 halo_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize lowp float halo_width #pragma mapbox: initialize lowp float halo_blur #pragma mapbox: initialize lowp float emissive_strength #endif vec4 out_color;float fade_opacity=v_gamma_scale_size_fade_opacity[2]; #ifdef RENDER_TEXT_AND_SYMBOL if (is_sdf==ICON) {vec2 tex_icon=v_tex_a_icon;lowp float alpha=opacity*fade_opacity;glFragColor=texture(u_texture_icon,tex_icon)*alpha; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif return;} #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef RENDER_SDF float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_gamma_scale_size_fade_opacity.x;float size=v_gamma_scale_size_fade_opacity.y;float fontScale=u_is_text ? size/24.0 : size;out_color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;bool draw_halo=v_draw_halo > 0.0;if (draw_halo) {out_color=halo_color;gamma=(halo_blur*u_scale_factor*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width*u_scale_factor/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,v_tex_a).r;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);out_color*=alpha; #else #ifdef ICON_TRANSITION vec4 a=texture(u_texture,v_tex_a)*(1.0-u_icon_transition);vec4 b=texture(u_texture,v_tex_b)*u_icon_transition;out_color=(a+b); #else out_color=texture(u_texture,v_tex_a); #endif #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef COLOR_ADJUSTMENT out_color=u_color_adj_mat*out_color; #endif #endif out_color*=opacity*fade_opacity; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y); #ifdef TERRAIN out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #else out_color.rgb*=mix(v_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #endif #endif #endif #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_z_offset); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_terrain.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #define USING_APPEARANCE 1.0 in ivec4 a_pos_offset;in uvec4 a_tex_size;in ivec4 a_pixeloffset;in vec4 a_projected_pos;in uint a_fade_opacity; #ifdef Z_OFFSET in float a_auto_z_offset; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_globe_anchor;in vec3 a_globe_normal; #endif #ifdef ICON_TRANSITION in uvec2 a_texb; #endif #ifdef OCCLUSION_QUERIES in float a_occlusion_query_opacity; #endif #ifdef ELEVATED_ROADS in vec3 a_x_axis;in vec3 a_y_axis;uniform float u_normal_scale; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #else #ifdef RENDER_SHADOWS out highp float v_z_offset; #endif #endif uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_elevation_from_sea;uniform bool u_pitch_with_map;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec3 u_up_vector;uniform vec2 u_texsize_icon;uniform bool u_is_halo; #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_camera_forward;uniform float u_zoom_transition;uniform vec3 u_ecef_origin;uniform mat4 u_tile_matrix; #endif out vec2 v_tex_a; #ifdef ICON_TRANSITION out vec2 v_tex_b; #endif out float v_draw_halo;out vec3 v_gamma_scale_size_fade_opacity; #ifdef RENDER_TEXT_AND_SYMBOL out float is_sdf;out vec2 v_tex_a_icon; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #ifdef USE_PAINT_PROPERTIES_UBO #ifndef MAX_UBO_SIZE_VEC4 #define MAX_UBO_SIZE_VEC4 1024u #endif #define SPP_HEADER_SIZE_VEC4 3u #define DWORDS_PER_VEC4 4u struct SymbolPaintProperties {vec4 fill_np_color;vec4 halo_np_color;float opacity;float halo_width;float halo_blur;float emissive_strength;float occlusion_opacity;float z_offset;vec2 translate;};struct PropertyType {bool isDataDriven;bool isZoomDependent;uint offsetDwords;};struct SymbolPropertyHeader {uint dataDrivenBlockSizeVec4;PropertyType fill_np_color;PropertyType halo_np_color;PropertyType opacity;PropertyType halo_width;PropertyType halo_blur;PropertyType emissive_strength;PropertyType occlusion_opacity;PropertyType z_offset;PropertyType translate;};uniform float u_zoom;uniform lowp vec4 u_spp_fill_np_color;uniform lowp vec4 u_spp_halo_np_color;uniform lowp float u_spp_opacity;uniform lowp float u_spp_halo_width;uniform lowp float u_spp_halo_blur;uniform lowp float u_spp_emissive_strength;uniform lowp float u_spp_occlusion_opacity;uniform lowp float u_spp_z_offset;uniform lowp vec2 u_spp_translate_rotation;in float a_feature_index;layout(std140) uniform SymbolPaintPropertiesHeaderUniform {uvec4 header[SPP_HEADER_SIZE_VEC4];} u_spp_header;layout(std140) uniform SymbolPaintPropertiesUniform {vec4 properties[MAX_UBO_SIZE_VEC4];} u_spp_properties;layout(std140) uniform SymbolPaintPropertiesIndexUniform {uvec4 block_indices[MAX_UBO_SIZE_VEC4];} u_spp_index;out lowp float v_opacity; #ifdef RENDER_SDF out lowp vec4 v_fill_np_color;out lowp vec4 v_halo_np_color;out lowp float v_halo_width;out lowp float v_halo_blur; #endif #ifdef LIGHTING_3D_MODE out lowp float v_emissive_strength; #endif PropertyType getPropertyType(uint propertyIndex,uint dataDrivenMask,uint zoomDependentMask,uint offsetDwords) {PropertyType type;type.isDataDriven=(dataDrivenMask & (1u << propertyIndex)) !=0u;type.isZoomDependent=(zoomDependentMask & (1u << propertyIndex)) !=0u;type.offsetDwords=offsetDwords;return type;}SymbolPropertyHeader readSymbolPropertiesHeader() {SymbolPropertyHeader header;uint dataDrivenMask=u_spp_header.header[0][0];uint zoomDependentMask=u_spp_header.header[0][1];header.dataDrivenBlockSizeVec4=u_spp_header.header[0][2];header.fill_np_color =getPropertyType(0u,dataDrivenMask,zoomDependentMask,u_spp_header.header[0][3]);header.halo_np_color =getPropertyType(1u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][0]);header.opacity =getPropertyType(2u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][1]);header.halo_width =getPropertyType(3u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][2]);header.halo_blur =getPropertyType(4u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][3]);header.emissive_strength =getPropertyType(5u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][0]);header.occlusion_opacity =getPropertyType(6u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][1]);header.z_offset =getPropertyType(7u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][2]);header.translate =getPropertyType(8u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][3]);return header;}uint uvec4At(uvec4 v,uint index) {return (index==0u) ? v.x : (index==1u) ? v.y : (index==2u) ? v.z : v.w;}float vec4At(vec4 v,uint index) {return (index==0u) ? v.x : (index==1u) ? v.y : (index==2u) ? v.z : v.w;}vec4 readVec4(uint baseOffsetVec4,uint propertyOffsetDwords) {return u_spp_properties.properties[baseOffsetVec4+propertyOffsetDwords/DWORDS_PER_VEC4];}float readFloat(vec4 slot,uint propertyOffsetDwords) {return slot[propertyOffsetDwords % DWORDS_PER_VEC4];}uint readUint(uvec4 slot,uint offset) {return slot[offset % DWORDS_PER_VEC4];}vec2 readVec2(vec4 slot,uint propertyOffsetDwords) {float x=vec4At(slot,propertyOffsetDwords % DWORDS_PER_VEC4);float y=vec4At(slot,propertyOffsetDwords % DWORDS_PER_VEC4+1u);return vec2(x,y);}uint getDataDrivenBlockOffsetVec4(uint dataDrivenBlockSizeVec4) {uint featureIndex=uint(a_feature_index);uvec4 slot=u_spp_index.block_indices[featureIndex/DWORDS_PER_VEC4];uint blockIndex=uvec4At(slot,featureIndex % DWORDS_PER_VEC4);return blockIndex*dataDrivenBlockSizeVec4;}vec4 readColorProperty(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 color=readVec4(blockOffsetVec4,propertyType.offsetDwords);if (propertyType.isZoomDependent) {color=unpack_mix_color(color,u_zoom);} else {vec2 packedColor=readVec2(color,propertyType.offsetDwords);color=decode_color(packedColor);}return color;}vec2 readVec2Property(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 slot=readVec4(blockOffsetVec4,propertyType.offsetDwords);if (propertyType.isZoomDependent) {vec2 minVal=slot.xy;vec2 maxVal=slot.zw;return mix(minVal,maxVal,u_zoom);}return readVec2(slot,propertyType.offsetDwords);}float readFloatProperty(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 slot=readVec4(blockOffsetVec4,propertyType.offsetDwords);float value;if (propertyType.isZoomDependent) {vec2 packedValues=readVec2(slot,propertyType.offsetDwords);value=unpack_mix_vec2(packedValues,u_zoom);} else {value=readFloat(slot,propertyType.offsetDwords);}return value;}SymbolPaintProperties readSymbolPaintProperties() {SymbolPropertyHeader header=readSymbolPropertiesHeader();uint sizeVec4=header.dataDrivenBlockSizeVec4;SymbolPaintProperties props;props.fill_np_color =header.fill_np_color.isDataDriven ? readColorProperty(header.fill_np_color,sizeVec4) : u_spp_fill_np_color;props.halo_np_color =header.halo_np_color.isDataDriven ? readColorProperty(header.halo_np_color,sizeVec4) : u_spp_halo_np_color;props.opacity =header.opacity.isDataDriven ? readFloatProperty(header.opacity,sizeVec4) : u_spp_opacity;props.halo_width =header.halo_width.isDataDriven ? readFloatProperty(header.halo_width,sizeVec4) : u_spp_halo_width;props.halo_blur =header.halo_blur.isDataDriven ? readFloatProperty(header.halo_blur,sizeVec4) : u_spp_halo_blur;props.emissive_strength =header.emissive_strength.isDataDriven ? readFloatProperty(header.emissive_strength,sizeVec4) : u_spp_emissive_strength;props.occlusion_opacity =header.occlusion_opacity.isDataDriven ? readFloatProperty(header.occlusion_opacity,sizeVec4) : u_spp_occlusion_opacity;props.z_offset =header.z_offset.isDataDriven ? readFloatProperty(header.z_offset,sizeVec4) : u_spp_z_offset;props.translate =header.translate.isDataDriven ? readVec2Property(header.translate,sizeVec4) : vec2(0.0);return props;} #else #pragma mapbox: define highp vec4 fill_color #pragma mapbox: define highp vec4 halo_color #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp float halo_width #pragma mapbox: define lowp float halo_blur #pragma mapbox: define lowp float emissive_strength #pragma mapbox: define lowp float occlusion_opacity #pragma mapbox: define lowp float z_offset #endif vec2 unpack_opacity(uint packedOpacity) {return vec2(float(packedOpacity/2u)/127.0,float(packedOpacity & 1u));}void main() { #ifdef USE_PAINT_PROPERTIES_UBO SymbolPaintProperties paint_properties=readSymbolPaintProperties();lowp float opacity=paint_properties.opacity;v_opacity=opacity; #ifdef RENDER_SDF v_fill_np_color=paint_properties.fill_np_color;v_halo_np_color=paint_properties.halo_np_color;v_halo_width=paint_properties.halo_width;v_halo_blur=paint_properties.halo_blur; #endif #ifdef LIGHTING_3D_MODE v_emissive_strength=paint_properties.emissive_strength; #endif lowp float occlusion_opacity=paint_properties.occlusion_opacity;lowp float z_offset=paint_properties.z_offset; #else #pragma mapbox: initialize highp vec4 fill_color #pragma mapbox: initialize highp vec4 halo_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize lowp float halo_width #pragma mapbox: initialize lowp float halo_blur #pragma mapbox: initialize lowp float emissive_strength #pragma mapbox: initialize lowp float occlusion_opacity #pragma mapbox: initialize lowp float z_offset #endif vec2 a_pos=vec2(a_pos_offset.xy);vec2 a_offset=vec2(a_pos_offset.zw);vec2 a_tex=vec2(a_tex_size.xy);vec2 a_size=vec2(a_tex_size.zw);float a_size_min=floor(a_size[0]*0.5);float a_size_max= floor(a_size[1]*0.5);float a_apperance=a_size[1]-2.0*a_size_max;vec2 a_pxoffset=vec2(a_pixeloffset.xy);vec2 a_min_font_scale=vec2(a_pixeloffset.zw)/256.0;highp float segment_angle=-a_projected_pos[3];float size;if (a_apperance==USING_APPEARANCE) {size=a_size_max/128.0;} else if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size_max,u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 tile_anchor=a_pos;float e=u_elevation_from_sea ? z_offset : z_offset+elevation(tile_anchor); #ifdef Z_OFFSET e+=a_auto_z_offset; #endif vec3 h=elevationVector(tile_anchor)*e;float globe_occlusion_fade;vec3 world_pos;vec3 mercator_pos;vec3 world_pos_globe; #ifdef PROJECTION_GLOBE_VIEW mercator_pos=mercator_tile_position(u_inv_rot_matrix,tile_anchor,u_tile_id,u_merc_center);world_pos_globe=vec3(a_globe_anchor)+h;world_pos=mix_globe_mercator(world_pos_globe,mercator_pos,u_zoom_transition);vec4 ecef_point=u_tile_matrix*vec4(world_pos,1.0);vec3 origin_to_point=ecef_point.xyz-u_ecef_origin;globe_occlusion_fade=dot(origin_to_point,u_camera_forward) >=0.0 ? 0.0 : 1.0; #else world_pos=vec3(tile_anchor,0)+h;globe_occlusion_fade=1.0; #endif vec4 projected_point=u_matrix*vec4(world_pos,1);highp float camera_to_anchor_distance=projected_point.w;highp float distance_ratio=u_pitch_with_map ? camera_to_anchor_distance/u_camera_to_center_distance : u_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp( 0.5+0.5*distance_ratio,0.0,1.5);size*=perspective_ratio;float font_scale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetprojected_point;vec2 a; #ifdef PROJECTION_GLOBE_VIEW vec3 displacement=vec3(a_globe_normal.z,0,-a_globe_normal.x);offsetprojected_point=u_matrix*vec4(vec3(a_globe_anchor)+displacement,1);vec4 projected_point_globe=u_matrix*vec4(world_pos_globe,1);a=projected_point_globe.xy/projected_point_globe.w; #else offsetprojected_point=u_matrix*vec4(tile_anchor+vec2(1,0),0,1);a=projected_point.xy/projected_point.w; #endif vec2 b=offsetprojected_point.xy/offsetprojected_point.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}vec4 projected_pos; #ifdef PROJECTION_GLOBE_VIEW #ifdef PROJECTED_POS_ON_VIEWPORT projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xyz+h,1.0); #else vec3 proj_pos=mix_globe_mercator(a_projected_pos.xyz,mercator_pos,u_zoom_transition)+h;projected_pos=u_label_plane_matrix*vec4(proj_pos,1.0); #endif #else projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,h.z,1.0); #endif highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);float z=0.0;vec2 offset=rotation_matrix*(a_offset/32.0*max(a_min_font_scale,font_scale)+a_pxoffset/16.0); #ifdef TERRAIN #ifdef PITCH_WITH_MAP_TERRAIN vec4 tile_pos=u_label_plane_matrix_inv*vec4(a_projected_pos.xy+offset,0.0,1.0);z=elevation(tile_pos.xy); #endif #endif #ifdef Z_OFFSET z+=u_pitch_with_map ? a_auto_z_offset+z_offset : 0.0; #else z+=u_pitch_with_map ? z_offset : 0.0; #endif float occlusion_fade=globe_occlusion_fade;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float out_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change)); #ifdef DEPTH_OCCLUSION float depth_occlusion=occlusionFadeMultiSample(projected_point);float depth_occlusion_multplier=mix(occlusion_opacity,1.0,depth_occlusion);out_fade_opacity*=depth_occlusion_multplier; #endif #ifdef OCCLUSION_QUERIES float occludedFadeMultiplier=mix(occlusion_opacity,1.0,a_occlusion_query_opacity);out_fade_opacity*=occludedFadeMultiplier; #endif #ifdef Z_TEST_OCCLUSION out_fade_opacity*=occlusion_opacity; #endif float alpha=opacity*out_fade_opacity;float hidden=float(alpha==0.0 || projected_point.w <=0.0 || occlusion_fade==0.0);vec3 pos; #ifdef PROJECTION_GLOBE_VIEW vec3 xAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,u_up_vector)) : vec3(1,0,0);vec3 yAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,xAxis)) : vec3(0,1,0);pos=projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y; #else #ifdef ELEVATED_ROADS vec3 xAxis=vec3(a_x_axis.xy,a_x_axis.z*u_normal_scale);vec3 yAxis=vec3(a_y_axis.xy,a_y_axis.z*u_normal_scale);pos=projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y; #else pos=vec3(projected_pos.xy/projected_pos.w+offset,z); #endif #endif gl_Position=mix(u_coord_matrix*vec4(pos,1.0),AWAY,hidden); #ifdef USE_PAINT_PROPERTIES_UBO {vec2 tr=paint_properties.translate;vec2 rotated_tr=vec2( u_spp_translate_rotation.x*tr.x-u_spp_translate_rotation.y*tr.y,u_spp_translate_rotation.y*tr.x+u_spp_translate_rotation.x*tr.y );gl_Position.xy+=(u_coord_matrix*vec4(rotated_tr,0.0,0.0)).xy;} #endif float gamma_scale=gl_Position.w;v_draw_halo=(u_is_halo && float(gl_InstanceID)==0.0) ? 1.0 : 0.0;v_gamma_scale_size_fade_opacity=vec3(gamma_scale,size,out_fade_opacity);v_tex_a=a_tex/u_texsize; #ifdef RENDER_TEXT_AND_SYMBOL is_sdf=a_size[0]-2.0*a_size_min;v_tex_a_icon=a_tex/u_texsize_icon; #endif #ifdef ICON_TRANSITION v_tex_b=vec2(a_texb)/u_texsize; #endif #ifdef RENDER_SHADOWS vec4 shd_pos=u_inv_matrix*vec4(pos,1.0);vec3 shd_pos0=shd_pos.xyz;vec3 shd_pos1=shd_pos.xyz; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef INDICATOR_CUTOUT v_z_offset=e; #else #ifdef RENDER_SHADOWS v_z_offset=e; #endif #endif }`),terrainRaster:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image0; #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS uniform sampler2D u_image1;uniform float u_emissive_texture_available; #endif in vec2 v_pos0; #ifdef FOG in float v_fog_opacity; #endif #ifdef RENDER_SHADOWS in vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1; #endif uniform vec3 u_ground_shadow_factor;void main() {vec4 image_color=texture(u_image0,v_pos0);vec4 color; #ifdef LIGHTING_3D_MODE const vec3 normal=vec3(0.0,0.0,1.0); #ifdef RENDER_SHADOWS float cutoffOpacity=1.0; #ifdef RENDER_CUTOFF cutoffOpacity=cutoff_opacity(u_cutoff_params,1.0/gl_FragCoord.w); #endif #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : image_color.a;vec3 unlit_base=image_color.rgb*(1.0-emissive_strength);vec3 emissive_base=image_color.rgb*emissive_strength;float ndotl=u_shadow_direction.z;float occlusion=ndotl < 0.0 ? 1.0 : shadow_occlusion(v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,0.0);ndotl=max(0.0,ndotl);vec3 lit=apply_lighting(unlit_base,normal,mix(1.0,(1.0-(u_shadow_intensity*occlusion))*ndotl,cutoffOpacity));vec3 emissive=compute_emissive_draped(emissive_base,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=lit+emissive;color.a=1.0; #else float lighting_factor=shadowed_light_factor_normal_unbiased(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);color=apply_lighting(image_color,normal,mix(1.0,lighting_factor,cutoffOpacity)); #endif #else float lighting_factor=u_lighting_directional_dir.z;color=apply_lighting(image_color,normal,lighting_factor); #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : image_color.a;color.rgb=mix(color.rgb,image_color.rgb,emissive_strength);color.a=1.0; #endif #endif #else color=image_color; #endif #ifdef FOG #ifdef ZERO_EXAGGERATION color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #else color=fog_dither(fog_apply_from_vert(color,v_fog_opacity)); #endif #endif glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" uniform mat4 u_matrix;uniform float u_skirt_height;in ivec2 a_pos;out vec2 v_pos0; #ifdef FOG out float v_fog_opacity; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1; #endif void main() {vec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;vec2 decodedPos=decomposedPosAndSkirt.xy;float elevation=elevation(decodedPos)-skirt*u_skirt_height;v_pos0=decodedPos/8192.0;gl_Position=u_matrix*vec4(decodedPos,elevation,1.0); #ifdef FOG #ifdef ZERO_EXAGGERATION v_fog_pos=fog_position(decodedPos); #else v_fog_opacity=fog(fog_position(vec3(decodedPos,elevation))); #endif #endif #ifdef RENDER_SHADOWS vec3 pos=vec3(decodedPos,elevation);v_pos_light_view_0=u_light_matrix_0*vec4(pos,1.);v_pos_light_view_1=u_light_matrix_1*vec4(pos,1.); #endif }`),terrainDepth:Bn("precision highp float;in float v_depth;void main() {glFragColor=pack_depth(v_depth);}",`#include "_prelude_terrain.vertex.glsl" uniform mat4 u_matrix;in ivec2 a_pos;out float v_depth;void main() {float elevation=elevation(vec2(a_pos));gl_Position=u_matrix*vec4(a_pos,elevation,1.0);v_depth=gl_Position.z/gl_Position.w;}`),skybox:Bn(`#include "_prelude_fog.fragment.glsl" in lowp vec3 v_uv;uniform lowp samplerCube u_cubemap;uniform lowp float u_opacity;uniform highp float u_temporal_offset;uniform highp vec3 u_sun_direction;float sun_disk(highp vec3 ray_direction,highp vec3 sun_direction) {highp float cos_angle=dot(normalize(ray_direction),sun_direction);const highp float cos_sun_angular_diameter=0.99996192306;const highp float smoothstep_delta=1e-5;return smoothstep( cos_sun_angular_diameter-smoothstep_delta,cos_sun_angular_diameter+smoothstep_delta,cos_angle);}float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec3 uv=v_uv;const float y_bias=0.015;uv.y+=y_bias;uv.y=pow(abs(uv.y),1.0/5.0);uv.y=map(uv.y,0.0,1.0,-1.0,1.0);vec3 sky_color=texture(u_cubemap,uv).rgb; #ifdef FOG sky_color=fog_apply_sky_gradient(v_uv.xzy,sky_color); #endif sky_color+=0.1*sun_disk(v_uv,u_sun_direction);glFragColor=vec4(sky_color*u_opacity,u_opacity); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif }`,u0),skyboxGradient:Bn(`#include "_prelude_fog.fragment.glsl" in highp vec3 v_uv;uniform lowp sampler2D u_color_ramp;uniform highp vec3 u_center_direction;uniform lowp float u_radius;uniform lowp float u_opacity;uniform highp float u_temporal_offset;void main() {float progress=acos(dot(normalize(v_uv),u_center_direction))/u_radius;vec4 color=texture(u_color_ramp,vec2(progress,0.5)); #ifdef FOG color.rgb=fog_apply_sky_gradient(v_uv.xzy,color.rgb/color.a)*color.a; #endif color*=u_opacity;glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif }`,u0),skyboxCapture:Bn(` in highp vec3 v_position;uniform highp float u_sun_intensity;uniform highp float u_luminance;uniform lowp vec3 u_sun_direction;uniform highp vec4 u_color_tint_r;uniform highp vec4 u_color_tint_m;precision highp float; #define BETA_R vec3(5.5e-6,13.0e-6,22.4e-6) #define BETA_M vec3(21e-6,21e-6,21e-6) #define MIE_G 0.76 #define DENSITY_HEIGHT_SCALE_R 8000.0 #define DENSITY_HEIGHT_SCALE_M 1200.0 #define PLANET_RADIUS 6360e3 #define ATMOSPHERE_RADIUS 6420e3 #define SAMPLE_STEPS 10 #define DENSITY_STEPS 4 float ray_sphere_exit(vec3 orig,vec3 dir,float radius) {float a=dot(dir,dir);float b=2.0*dot(dir,orig);float c=dot(orig,orig)-radius*radius;float d=sqrt(b*b-4.0*a*c);return (-b+d)/(2.0*a);}vec3 extinction(vec2 density) {return exp(-vec3(BETA_R*u_color_tint_r.a*density.x+BETA_M*u_color_tint_m.a*density.y));}vec2 local_density(vec3 point) {float height=max(length(point)-PLANET_RADIUS,0.0);float exp_r=exp(-height/DENSITY_HEIGHT_SCALE_R);float exp_m=exp(-height/DENSITY_HEIGHT_SCALE_M);return vec2(exp_r,exp_m);}float phase_ray(float cos_angle) {return (3.0/(16.0*PI))*(1.0+cos_angle*cos_angle);}float phase_mie(float cos_angle) {return (3.0/(8.0*PI))*((1.0-MIE_G*MIE_G)*(1.0+cos_angle*cos_angle))/((2.0+MIE_G*MIE_G)*pow(1.0+MIE_G*MIE_G-2.0*MIE_G*cos_angle,1.5));}vec2 density_to_atmosphere(vec3 point,vec3 light_dir) {float ray_len=ray_sphere_exit(point,light_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(DENSITY_STEPS);vec2 density_point_to_atmosphere=vec2(0.0);for (int i=0; i < DENSITY_STEPS;++i) {vec3 point_on_ray=point+light_dir*((float(i)+0.5)*step_len);density_point_to_atmosphere+=local_density(point_on_ray)*step_len;;}return density_point_to_atmosphere;}vec3 atmosphere(vec3 ray_dir,vec3 sun_direction,float sun_intensity) {vec2 density_orig_to_point=vec2(0.0);vec3 scatter_r=vec3(0.0);vec3 scatter_m=vec3(0.0);vec3 origin=vec3(0.0,PLANET_RADIUS,0.0);float ray_len=ray_sphere_exit(origin,ray_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(SAMPLE_STEPS);for (int i=0; i < SAMPLE_STEPS;++i) {vec3 point_on_ray=origin+ray_dir*((float(i)+0.5)*step_len);vec2 density=local_density(point_on_ray)*step_len;density_orig_to_point+=density;vec2 density_point_to_atmosphere=density_to_atmosphere(point_on_ray,sun_direction);vec2 density_orig_to_atmosphere=density_orig_to_point+density_point_to_atmosphere;vec3 extinction=extinction(density_orig_to_atmosphere);scatter_r+=density.x*extinction;scatter_m+=density.y*extinction;}float cos_angle=dot(ray_dir,sun_direction);float phase_r=phase_ray(cos_angle);float phase_m=phase_mie(cos_angle);vec3 beta_r=BETA_R*u_color_tint_r.rgb*u_color_tint_r.a;vec3 beta_m=BETA_M*u_color_tint_m.rgb*u_color_tint_m.a;return (scatter_r*phase_r*beta_r+scatter_m*phase_m*beta_m)*sun_intensity;}const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;vec3 uncharted2_tonemap(vec3 x) {return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;}void main() {vec3 ray_direction=v_position;ray_direction.y=pow(ray_direction.y,5.0);const float y_bias=0.015;ray_direction.y+=y_bias;vec3 color=atmosphere(normalize(ray_direction),u_sun_direction,u_sun_intensity);float white_scale=1.0748724675633854;color=uncharted2_tonemap((log2(2.0/pow(u_luminance,4.0)))*color)*white_scale;glFragColor=vec4(color,1.0);}`,"in highp vec3 a_pos_3f;uniform mat3 u_matrix_3f;out highp vec3 v_position;float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec4 pos=vec4(u_matrix_3f*a_pos_3f,1.0);v_position=pos.xyz;v_position.y*=-1.0;v_position.y=map(v_position.y,-1.0,1.0,0.0,1.0);gl_Position=vec4(a_pos_3f.xy,0.0,1.0);}"),globeRaster:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image0; #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS uniform sampler2D u_image1;uniform float u_emissive_texture_available; #endif uniform float u_far_z_cutoff;in vec2 v_pos0; #ifndef FOG uniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform vec2 u_viewport; #endif void main() {vec4 color; #ifdef CUSTOM_ANTIALIASING highp vec2 uv=gl_FragCoord.xy/u_viewport; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif highp vec3 ray_dir=mix( mix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);highp vec3 dir=normalize(ray_dir);highp vec3 closest_point=dot(u_globe_pos,dir)*dir;highp float norm_dist_from_center=1.0-length(closest_point-u_globe_pos)/u_globe_radius;const float antialias_pixel=2.0;highp float antialias_factor=antialias_pixel*fwidth(norm_dist_from_center);highp float antialias=smoothstep(0.0,antialias_factor,norm_dist_from_center);vec4 raster=texture(u_image0,v_pos0); #ifdef LIGHTING_3D_MODE #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : raster.a;raster=apply_lighting_with_emission_ground(raster,emissive_strength);color=vec4(clamp(raster.rgb,vec3(0),vec3(1))*antialias,antialias); #else raster=apply_lighting_ground(raster);color=vec4(raster.rgb*antialias,raster.a*antialias); #endif #else color=vec4(raster.rgb*antialias,raster.a*antialias); #endif #else color=texture(u_image0,v_pos0); #ifdef LIGHTING_3D_MODE #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : color.a;color=apply_lighting_with_emission_ground(color,emissive_strength);color.a=1.0; #else color=apply_lighting_ground(color); #endif #endif #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #endif color*=1.0-step(u_far_z_cutoff,1.0/gl_FragCoord.w);glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" uniform mat4 u_proj_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform float u_zoom_transition;uniform vec2 u_merc_center;uniform mat3 u_grid_matrix;uniform float u_skirt_height; #ifdef GLOBE_POLES in vec3 a_globe_pos;in vec2 a_uv; #else in ivec2 a_pos; #endif out vec2 v_pos0;void main() { #ifdef GLOBE_POLES vec3 globe_pos=a_globe_pos;vec2 uv=a_uv; #else float tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float uvY=mercatorY*tiles-idy;float mercatorX=mercatorXfromLng(latLng[1]);float uvX=mercatorX*tiles-idx;vec3 globe_pos=latLngToECEF(latLng.xy);vec2 merc_pos=vec2(mercatorX,mercatorY);vec2 uv=vec2(uvX,uvY); #endif v_pos0=uv;vec2 tile_pos=uv*EXTENT;vec3 globe_derived_up_vector=normalize(globe_pos)*u_tile_up_scale; #ifdef GLOBE_POLES vec3 up_vector=globe_derived_up_vector; #else vec3 up_vector=elevationVector(tile_pos); #endif float height=elevation(tile_pos);globe_pos+=up_vector*height; #ifndef GLOBE_POLES globe_pos-=globe_derived_up_vector*u_skirt_height*decomposed_pos_and_skirt.z; #endif #ifdef GLOBE_POLES vec4 interpolated_pos=u_globe_matrix*vec4(globe_pos,1.0); #else vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {merc_world_pos=vec4(merc_pos,height-u_skirt_height*decomposed_pos_and_skirt.z,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0); #endif gl_Position=u_proj_matrix*interpolated_pos; #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif }`),globeAtmosphere:Bn(`#include "_prelude_fog.fragment.glsl" uniform float u_transition;uniform highp float u_fadeout_range;uniform highp float u_temporal_offset;uniform vec4 u_atmosphere_fog_color;uniform vec4 u_high_color;uniform vec4 u_space_color;uniform float u_horizon_angle;in highp vec3 v_ray_dir;in highp vec3 v_horizon_dir;void main() {highp vec3 dir=normalize(v_ray_dir);float globe_pos_dot_dir; #ifdef PROJECTION_GLOBE_VIEW globe_pos_dot_dir=dot(u_globe_pos,dir);highp vec3 closest_point_forward=abs(globe_pos_dot_dir)*dir;float norm_dist_from_center=length(closest_point_forward-u_globe_pos)/u_globe_radius;if (norm_dist_from_center < 0.98) { #ifdef ALPHA_PASS glFragColor=vec4(0,0,0,0);return; #else #ifdef NATIVE glFragColor=vec4(1,1,1,1); #else glFragColor=vec4(0,0,0,1); #endif return; #endif } #endif highp vec3 horizon_dir=normalize(v_horizon_dir);float horizon_angle_mercator=dir.y < horizon_dir.y ? 0.0 : max(acos(clamp(dot(dir,horizon_dir),-1.0,1.0)),0.0);float horizon_angle; #ifdef PROJECTION_GLOBE_VIEW highp vec3 closest_point=globe_pos_dot_dir*dir;highp float closest_point_to_center=length(closest_point-u_globe_pos);highp float theta=asin(clamp(closest_point_to_center/length(u_globe_pos),-1.0,1.0));horizon_angle=globe_pos_dot_dir < 0.0 ? PI-theta-u_horizon_angle : theta-u_horizon_angle;float angle_t=pow(u_transition,10.0);horizon_angle=mix(horizon_angle,horizon_angle_mercator,angle_t); #else horizon_angle=horizon_angle_mercator; #endif horizon_angle/=PI;float t=exp(-horizon_angle/u_fadeout_range);float alpha_0=u_atmosphere_fog_color.a;float alpha_1=u_high_color.a;float alpha_2=u_space_color.a;vec3 color_stop_0=u_atmosphere_fog_color.rgb;vec3 color_stop_1=u_high_color.rgb;vec3 color_stop_2=u_space_color.rgb; #ifdef ALPHA_PASS float a0=mix(alpha_2,1.0,alpha_1);float a1=mix(a0,1.0,alpha_0);float a2=mix(a0,a1,t);float a =mix(alpha_2,a2,t);glFragColor=vec4(1.0,1.0,1.0,a); #else vec3 c0=mix(color_stop_2,color_stop_1,alpha_1);vec3 c1=mix(c0,color_stop_0,alpha_0);vec3 c2=mix(c0,c1,t);vec3 c=c2;glFragColor=vec4(c*t,t); #endif }`,`in vec3 a_pos;in vec2 a_uv;uniform vec3 u_frustum_tl;uniform vec3 u_frustum_tr;uniform vec3 u_frustum_br;uniform vec3 u_frustum_bl;uniform float u_horizon;out highp vec3 v_ray_dir;out highp vec3 v_horizon_dir;void main() {v_ray_dir=mix( mix(u_frustum_tl,u_frustum_tr,a_uv.x),mix(u_frustum_bl,u_frustum_br,a_uv.x),a_uv.y);v_horizon_dir=mix( mix(u_frustum_tl,u_frustum_bl,u_horizon),mix(u_frustum_tr,u_frustum_br,u_horizon),a_uv.x);gl_Position=vec4(a_pos,1.0);}`),model:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" uniform float u_opacity; #ifdef DITHERED_DISCARD uniform float u_dithered_discard_threshold; #endif uniform vec3 u_lightcolor;uniform vec3 u_lightpos;uniform float u_lightintensity;uniform vec4 u_baseColorFactor;uniform vec4 u_emissiveFactor;uniform float u_metallicFactor;uniform float u_roughnessFactor;uniform float u_emissive_strength;in highp vec4 v_position_height;in lowp vec4 v_color_mix; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth_shadows; #endif #ifdef OCCLUSION_TEXTURE_TRANSFORM uniform vec4 u_occlusionTextureTransform; #endif #pragma mapbox: define-attribute highp vec3 normal_3f #pragma mapbox: define-attribute highp vec3 color_3f #pragma mapbox: define-attribute highp vec4 color_4f #pragma mapbox: define-attribute highp vec2 uv_2f #pragma mapbox: initialize-attribute highp vec3 normal_3f #pragma mapbox: initialize-attribute highp vec3 color_3f #pragma mapbox: initialize-attribute highp vec4 color_4f #pragma mapbox: initialize-attribute highp vec2 uv_2f #ifdef HAS_ATTRIBUTE_a_pbr in lowp vec4 v_roughness_metallic_emissive_alpha;in mediump vec4 v_height_based_emission_params; #endif #ifdef HAS_TEXTURE_u_baseColorTexture uniform sampler2D u_baseColorTexture;uniform bool u_baseTextureIsAlpha;uniform bool u_alphaMask;uniform float u_alphaCutoff; #endif #ifdef HAS_TEXTURE_u_metallicRoughnessTexture uniform sampler2D u_metallicRoughnessTexture; #endif #ifdef HAS_TEXTURE_u_occlusionTexture uniform sampler2D u_occlusionTexture;uniform float u_aoIntensity; #endif #ifdef HAS_TEXTURE_u_normalTexture uniform sampler2D u_normalTexture; #endif #ifdef HAS_TEXTURE_u_emissionTexture uniform sampler2D u_emissionTexture; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef TERRAIN_FRAGMENT_OCCLUSION in highp float v_depth;uniform highp sampler2D u_depthTexture;uniform highp vec2 u_inv_depth_size;uniform highp vec2 u_depth_range_unpack; #ifdef DEPTH_D24 highp float unpack_depth(highp float depth) {return depth*u_depth_range_unpack.x+u_depth_range_unpack.y;} #else highp float unpack_depth_rgba(highp vec4 rgba_depth) {const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(rgba_depth,bit_shift)*2.0-1.0;} #endif bool isOccluded() {highp vec2 coord=gl_FragCoord.xy*u_inv_depth_size; #ifdef FLIP_Y coord.y=1.0-coord.y; #endif #ifdef DEPTH_D24 highp float depth=unpack_depth(texture(u_depthTexture,coord).r); #else highp float depth=unpack_depth_rgba(texture(u_depthTexture,coord)); #endif return v_depth > depth+0.0005;} #endif #define saturate(_x) clamp(_x,0.,1.) vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}float calculate_NdotL(vec3 normal,vec3 lightDir) {const float ext=0.70710678118;return (clamp(dot(normal,lightDir),-ext,1.0)+ext)/(1.0+ext);}vec3 getDiffuseShadedColor(vec3 albedo,vec3 normal,vec3 lightDir,vec3 lightColor) { #ifdef LIGHTING_3D_MODE vec3 transformed_normal=vec3(-normal.xy,normal.z);float lighting_factor; #ifdef RENDER_SHADOWS lighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows); #else lighting_factor=saturate(dot(transformed_normal,u_lighting_directional_dir)); #endif return apply_lighting(albedo,transformed_normal,lighting_factor); #else vec3 n=normal;float colorvalue=((albedo.x*0.2126)+(albedo.y*0.7152))+(albedo.z*0.0722);vec3 c=vec3(0.03,0.03,0.03);float directional=clamp(dot(n,vec3(lightDir)),0.0,1.0);directional=mix(1.0-u_lightintensity,max((1.0-colorvalue)+u_lightintensity,1.0),directional);vec3 c3=c+clamp((albedo*directional)*lightColor,mix(vec3(0.0),vec3(0.3),vec3(1.0)-lightColor),vec3(1.0));return c3; #endif }vec4 getBaseColor() {vec4 albedo=u_baseColorFactor; #ifdef HAS_ATTRIBUTE_a_color_3f albedo*=vec4(color_3f,1.0); #endif #ifdef HAS_ATTRIBUTE_a_pbr #else #ifdef HAS_ATTRIBUTE_a_color_4f albedo*=color_4f; #endif #endif #if defined (HAS_TEXTURE_u_baseColorTexture) && defined (HAS_ATTRIBUTE_a_uv_2f) vec4 texColor=texture(u_baseColorTexture,uv_2f);if(u_alphaMask) {if (texColor.w < u_alphaCutoff) {discard;}} #ifdef UNPREMULT_TEXTURE_IN_SHADER if(texColor.w > 0.0) {texColor.rgb/=texColor.w;}texColor.w=1.0; #endif if(u_baseTextureIsAlpha) {if (texColor.r < 0.5) {discard;}} else {texColor.rgb=sRGBToLinear(texColor.rgb);albedo*=texColor;} #endif vec4 color=vec4(mix(albedo.rgb,v_color_mix.rgb,v_color_mix.a),albedo.a); #ifdef APPLY_LUT_ON_GPU color=applyLUT(u_lutTexture,color); #endif return color;}highp mat3 cotangentFrame(highp vec3 N,highp vec3 p,highp vec2 uv ) { #ifdef HAS_TEXTURE_u_normalTexture highp vec3 dp1=vec3(dFdx(p.x),dFdx(p.y),dFdx(p.z));highp vec3 dp2=vec3(dFdy(p.x),dFdy(p.y),dFdy(p.z));highp vec2 duv1=vec2(dFdx(uv.x),dFdx(uv.y));highp vec2 duv2=vec2(dFdy(uv.x),dFdy(uv.y));highp vec3 dp2perp=cross( dp2,N );highp vec3 dp1perp=cross( N,dp1 );highp vec3 T=dp2perp*duv1.x+dp1perp*duv2.x;highp vec3 B=dp2perp*duv1.y+dp1perp*duv2.y; #ifdef FLIP_Y T=-T;B=-B; #endif highp float lengthT=dot(T,T);highp float lengthB=dot(B,B);highp float maxLength=max(lengthT,lengthB);highp float invmax=inversesqrt( maxLength );highp mat3 res=mat3( T*invmax,B*invmax,N );return res; #else return mat3(1.0); #endif }highp vec3 getNormal(){highp vec3 n; #ifdef HAS_ATTRIBUTE_a_normal_3f n=normalize(normal_3f); #else highp vec3 fdx=vec3(dFdx(v_position_height.x),dFdx(v_position_height.y),dFdx(v_position_height.z));highp vec3 fdy=vec3(dFdy(v_position_height.x),dFdy(v_position_height.y),dFdy(v_position_height.z)); #ifdef FLIP_Y n=normalize(cross(fdx,fdy)); #else n=normalize(cross(fdx,fdy))*-1.0; #endif #endif #if defined(HAS_TEXTURE_u_normalTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) vec3 nMap=texture( u_normalTexture,uv_2f).xyz;nMap=normalize(2.0*nMap-vec3(1.0));highp vec3 v=normalize(-v_position_height.xyz);highp mat3 TBN=cotangentFrame(n,v,uv_2f);n=normalize(TBN*nMap); #endif return n;}struct Material {float perceptualRoughness;float alphaRoughness;float metallic;vec3 f90;vec4 baseColor;vec3 diffuseColor;vec3 specularColor;highp vec3 normal;};Material getPBRMaterial() {Material mat;mat.baseColor=getBaseColor();mat.perceptualRoughness=u_roughnessFactor;mat.metallic=u_metallicFactor; #ifdef HAS_ATTRIBUTE_a_pbr mat.perceptualRoughness=v_roughness_metallic_emissive_alpha.x;mat.metallic=v_roughness_metallic_emissive_alpha.y;mat.baseColor.w*=v_roughness_metallic_emissive_alpha.w; #endif #if defined(HAS_TEXTURE_u_metallicRoughnessTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) vec4 mrSample=texture(u_metallicRoughnessTexture,uv_2f);mat.perceptualRoughness*=mrSample.g;mat.metallic*=mrSample.b; #endif const float c_minRoughness=0.04;mat.perceptualRoughness=clamp(mat.perceptualRoughness,c_minRoughness,1.0);mat.metallic=saturate(mat.metallic);mat.alphaRoughness=mat.perceptualRoughness*mat.perceptualRoughness;const vec3 f0=vec3(0.04);mat.diffuseColor=mat.baseColor.rgb*(vec3(1.0)-f0);mat.diffuseColor*=1.0-mat.metallic;mat.specularColor=mix(f0,mat.baseColor.rgb,mat.metallic);highp float reflectance=max(max(mat.specularColor.r,mat.specularColor.g),mat.specularColor.b);highp float reflectance90=saturate(reflectance*25.0);mat.f90=vec3(reflectance90);mat.normal=getNormal();return mat;}float V_GGX(float NdotL,float NdotV,float roughness) {float a2=roughness*roughness;float GGXV=NdotL*sqrt(NdotV*NdotV*(1.0-a2)+a2);float GGXL=NdotV*sqrt(NdotL*NdotL*(1.0-a2)+a2);return 0.5/(GGXV+GGXL);}float V_GGXFast(float NdotL,float NdotV,float roughness) {float a=roughness;float GGXV=NdotL*(NdotV*(1.0-a)+a);float GGXL=NdotV*(NdotL*(1.0-a)+a);return 0.5/(GGXV+GGXL);}vec3 F_Schlick(vec3 specularColor,vec3 f90,float VdotH) {return specularColor+(f90-specularColor)*pow(clamp(1.0-VdotH,0.0,1.0),5.0);}vec3 F_SchlickFast(vec3 specularColor,float VdotH) {float x=1.0-VdotH;float x4=x*x*x*x;return specularColor+(1.0-specularColor)*x4*x;}float D_GGX(highp float NdotH,float alphaRoughness) {highp float a4=alphaRoughness*alphaRoughness;highp float f=(NdotH*a4-NdotH)*NdotH+1.0;return a4/(PI*f*f);}vec3 diffuseBurley(Material mat,float LdotH,float NdotL,float NdotV) {float f90=2.0*LdotH*LdotH*mat.alphaRoughness-0.5;return (mat.diffuseColor/PI)*(1.0+f90*pow((1.0-NdotL),5.0))*(1.0+f90*pow((1.0-NdotV),5.0));}vec3 diffuseLambertian(Material mat) { #ifdef LIGHTING_3D_MODE return mat.diffuseColor; #else return mat.diffuseColor/PI; #endif }vec3 EnvBRDFApprox(vec3 specularColor,float roughness,highp float NdotV) {vec4 c0=vec4(-1,-0.0275,-0.572,0.022);vec4 c1=vec4(1,0.0425,1.04,-0.04);highp vec4 r=roughness*c0+c1;highp float a004=min(r.x*r.x,exp2(-9.28*NdotV))*r.x+r.y;vec2 AB=vec2(-1.04,1.04)*a004+r.zw;return specularColor*AB.x+AB.y;}vec3 computeIndirectLightContribution(Material mat,float NdotV,vec3 normal) {vec3 env_light=vec3(0.65,0.65,0.65); #ifdef LIGHTING_3D_MODE float ambient_factor=calculate_ambient_directional_factor(normal);env_light=u_lighting_ambient_color*ambient_factor; #endif vec3 envBRDF=EnvBRDFApprox(mat.specularColor,mat.perceptualRoughness,NdotV);vec3 indirectSpecular= envBRDF*env_light;vec3 indirectDiffuse=mat.diffuseColor*env_light;return indirectSpecular+indirectDiffuse;}vec3 computeLightContribution(Material mat,vec3 lightPosition,vec3 lightColor) {highp vec3 n=mat.normal;highp vec3 v=normalize(-v_position_height.xyz);highp vec3 l=normalize(lightPosition);highp vec3 h=normalize(v+l);float NdotV=clamp(abs(dot(n,v)),0.001,1.0);float NdotL=saturate(dot(n,l));highp float NdotH=saturate(dot(n,h));float VdotH=saturate(dot(v,h));vec3 f=F_SchlickFast(mat.specularColor,VdotH);float g=V_GGXFast(NdotL,NdotV,mat.alphaRoughness);float d=D_GGX(NdotH,mat.alphaRoughness);vec3 diffuseTerm=(1.0-f)*diffuseLambertian(mat);vec3 specularTerm=f*g*d;vec3 transformed_normal=vec3(-n.xy,n.z);float lighting_factor; #ifdef RENDER_SHADOWS lighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows); #else lighting_factor=NdotL; #endif vec3 directLightColor=(specularTerm+diffuseTerm)*lighting_factor*lightColor;vec3 indirectLightColor=computeIndirectLightContribution(mat,NdotV,transformed_normal);vec3 color=(saturate(directLightColor)+indirectLightColor);float intensityFactor=1.0; #if !defined(LIGHTING_3D_MODE) const vec3 luminosityFactor=vec3(0.2126,0.7152,0.0722);float luminance=dot(diffuseTerm,luminosityFactor);intensityFactor=mix((1.0-u_lightintensity),max((1.0-luminance+u_lightintensity),1.0),NdotL); #endif color*=intensityFactor;return color;}void main() { #ifdef TERRAIN_FRAGMENT_OCCLUSION if (isOccluded()) {discard;} #endif vec3 lightDir=u_lightpos;vec3 lightColor=u_lightcolor; #ifdef LIGHTING_3D_MODE lightDir=u_lighting_directional_dir;lightDir.xy=-lightDir.xy;lightColor=u_lighting_directional_color; #endif vec4 finalColor; #ifdef DIFFUSE_SHADED vec3 N=getNormal();vec3 baseColor=getBaseColor().rgb;vec3 diffuse=getDiffuseShadedColor(baseColor,N,lightDir,lightColor); #ifdef HAS_TEXTURE_u_occlusionTexture float ao=(texture(u_occlusionTexture,uv_2f).r-1.0)*u_aoIntensity+1.0;diffuse*=ao; #endif finalColor=vec4(mix(diffuse,baseColor,u_emissive_strength),1.0)*u_opacity; #else Material mat=getPBRMaterial();vec3 color=computeLightContribution(mat,lightDir,lightColor);float ao=1.0; #if defined (HAS_TEXTURE_u_occlusionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) #ifdef OCCLUSION_TEXTURE_TRANSFORM vec2 uv=uv_2f.xy*u_occlusionTextureTransform.zw+u_occlusionTextureTransform.xy; #else vec2 uv=uv_2f; #endif ao=(texture(u_occlusionTexture,uv).x-1.0)*u_aoIntensity+1.0;color*=ao; #endif vec4 emissive=u_emissiveFactor; #if defined(HAS_TEXTURE_u_emissionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) emissive.rgb*=sRGBToLinear(texture(u_emissionTexture,uv_2f).rgb); #endif #ifdef APPLY_LUT_ON_GPU float emissiveFactorLength=max(length(u_emissiveFactor.rgb),0.001);emissive.rgb=sRGBToLinear(applyLUT(u_lutTexture,linearTosRGB(emissive.rgb/emissiveFactorLength).rbg))*emissiveFactorLength; #endif color+=emissive.rgb;float opacity=mat.baseColor.w*u_opacity; #ifdef HAS_ATTRIBUTE_a_pbr float resEmission=v_roughness_metallic_emissive_alpha.z;resEmission*=v_height_based_emission_params.z+v_height_based_emission_params.w*pow(clamp(v_height_based_emission_params.x,0.0,1.0),v_height_based_emission_params.y);vec3 color_mix=v_color_mix.rgb; #ifdef APPLY_LUT_ON_GPU color_mix=applyLUT(u_lutTexture,color_mix); #endif color=mix(color,color_mix,min(1.0,resEmission)); #ifdef HAS_ATTRIBUTE_a_color_4f float distance=length(vec2(1.3*max(0.0,abs(color_4f.x)-color_4f.z),color_4f.y));distance+= mix(0.5,0.0,clamp(resEmission-1.0,0.0,1.0));opacity*=v_roughness_metallic_emissive_alpha.w*saturate(1.0-distance*distance); #endif #endif vec3 unlitColor=mat.baseColor.rgb*ao+emissive.rgb;color=mix(color,unlitColor,u_emissive_strength);color=linearTosRGB(color);color*=opacity;finalColor=vec4(color,opacity); #endif #ifdef DITHERED_DISCARD if (abs(u_dithered_discard_threshold) < 1.0) {float ditherValue=fract(52.9829189*fract(0.06711056*gl_FragCoord.x+0.00583715*gl_FragCoord.y));float compareValue=mix(1.0-ditherValue,ditherValue,step(0.0,u_dithered_discard_threshold));if (abs(u_dithered_discard_threshold) < compareValue) {discard;}} #endif #ifdef FOG finalColor=fog_dither(fog_apply_premultiplied(finalColor,v_fog_pos,v_position_height.w)); #endif #ifdef RENDER_CUTOFF finalColor*=v_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT finalColor=applyCutout(finalColor,v_position_height.w); #endif #ifdef FEATURE_CUTOUT finalColor=apply_feature_cutout(finalColor,gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #endif glFragColor=finalColor; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in vec3 a_pos_3f; #pragma mapbox: define-attribute highp vec3 normal_3f #pragma mapbox: define-attribute highp vec2 uv_2f #pragma mapbox: define-attribute highp vec3 color_3f #pragma mapbox: define-attribute highp vec4 color_4f #pragma mapbox: define-attribute-vertex-shader-only highp uvec4 pbr #pragma mapbox: define-attribute-vertex-shader-only highp vec3 heightBasedEmissiveStrength uniform mat4 u_matrix;uniform mat4 u_node_matrix;uniform mat4 u_lighting_matrix;uniform vec3 u_camera_pos;uniform vec4 u_color_mix; #ifdef INSTANCED_ARRAYS in vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3; #else uniform highp mat4 u_normal_matrix; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out float v_depth_shadows; #endif out vec4 v_position_height;out lowp vec4 v_color_mix; #ifdef TERRAIN_FRAGMENT_OCCLUSION out highp float v_depth; #endif #ifdef HAS_ATTRIBUTE_a_pbr out lowp vec4 v_roughness_metallic_emissive_alpha;out mediump vec4 v_height_based_emission_params; #endif vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}void main() { #pragma mapbox: initialize-attribute highp vec3 normal_3f #pragma mapbox: initialize-attribute highp vec2 uv_2f #pragma mapbox: initialize-attribute highp vec3 color_3f #pragma mapbox: initialize-attribute highp vec4 color_4f #pragma mapbox: initialize-attribute-custom highp uvec4 pbr #pragma mapbox: initialize-attribute-custom highp vec3 heightBasedEmissiveStrength highp mat4 normal_matrix; #ifdef INSTANCED_ARRAYS normal_matrix=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3); #else normal_matrix=u_normal_matrix; #endif vec3 local_pos;mat3 rs; #ifdef MODEL_POSITION_ON_GPU vec3 pos_color=normal_matrix[0].xyz;vec4 translate=normal_matrix[1];vec3 pos_a=floor(pos_color);vec3 rgb=1.05*(pos_color-pos_a);float hidden=float(pos_a.x > EXTENT);float color_mix=pos_a.z/100.0;v_color_mix=vec4(sRGBToLinear(rgb),color_mix);float meter_to_tile=normal_matrix[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);rs[0].x=normal_matrix[1].w;rs[0].yz=normal_matrix[2].xy;rs[1].xy=normal_matrix[2].zw;rs[1].z=normal_matrix[3].x;rs[2].xyz=normal_matrix[3].yzw;vec4 pos_node=u_lighting_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;local_pos=pos.xyz;gl_Position=mix(u_matrix*pos,AWAY,hidden);pos.z*=meter_to_tile;v_position_height.xyz=pos.xyz-u_camera_pos; #else local_pos=a_pos_3f;gl_Position=u_matrix*vec4(a_pos_3f,1);v_position_height.xyz=vec3(u_lighting_matrix*vec4(a_pos_3f,1));v_color_mix=vec4(sRGBToLinear(u_color_mix.rgb),u_color_mix.a); #endif v_position_height.w=a_pos_3f.z; #ifdef HAS_ATTRIBUTE_a_pbr vec4 albedo_c=decode_color(vec2(pbr.xy));vec2 e_r_m=unpack_float(float(pbr.z));vec2 r_m= unpack_float(e_r_m.y*16.0);r_m.r=r_m.r*16.0;v_color_mix=vec4(albedo_c.rgb,1.0);v_roughness_metallic_emissive_alpha=vec4(vec3(r_m,e_r_m.x)/255.0,albedo_c.a);v_roughness_metallic_emissive_alpha.z*=2.0;float heightBasedRelativeIntepolation=a_pos_3f.z*heightBasedEmissiveStrength.x+heightBasedEmissiveStrength.y;v_height_based_emission_params.x=heightBasedRelativeIntepolation;v_height_based_emission_params.y=heightBasedEmissiveStrength.z;vec2 emissionMultiplierValues=unpack_float(float(pbr.w))/256.0;v_height_based_emission_params.z=emissionMultiplierValues.x;v_height_based_emission_params.w=emissionMultiplierValues.y-emissionMultiplierValues.x; #endif #ifdef FOG v_fog_pos=fog_position(local_pos); #endif #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z); #endif #ifdef TERRAIN_FRAGMENT_OCCLUSION v_depth=gl_Position.z/gl_Position.w; #ifdef CLIP_ZERO_TO_ONE v_depth=-1.0+2.0*v_depth; #endif #endif #ifdef HAS_ATTRIBUTE_a_normal_3f #ifdef MODEL_POSITION_ON_GPU float x_squared_scale=dot(rs[0],rs[0]);float y_squared_scale=dot(rs[1],rs[1]);float z_squared_scale=dot(rs[2],rs[2]);vec3 squared_scale=vec3(x_squared_scale,y_squared_scale,z_squared_scale);normal_3f=rs*((u_lighting_matrix*vec4(normal_3f,0.0)).xyz/squared_scale);normal_3f=normalize(normal_3f); #else normal_3f=vec3(normal_matrix*vec4(normal_3f,0)); #endif #endif #ifdef HAS_ATTRIBUTE_a_pbr #ifdef HAS_ATTRIBUTE_a_color_4f v_roughness_metallic_emissive_alpha.w=clamp(color_4f.a*v_roughness_metallic_emissive_alpha.w*(v_roughness_metallic_emissive_alpha.z-1.0),0.0,1.0); #endif #endif #ifdef RENDER_SHADOWS vec4 shadow_pos=u_node_matrix*vec4(local_pos,1.0); #ifdef NORMAL_OFFSET #ifdef HAS_ATTRIBUTE_a_normal_3f #ifdef MODEL_POSITION_ON_GPU vec3 offset=shadow_normal_offset(vec3(-normal_3f.xy,normal_3f.z));shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0(); #else vec3 offset=shadow_normal_offset_model(normal_3f);shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0(); #endif #endif #endif v_pos_light_view_0=u_light_matrix_0*shadow_pos;v_pos_light_view_1=u_light_matrix_1*shadow_pos;v_depth_shadows=gl_Position.w; #endif }`),modelDepth:Bn("void main() {}",`in vec3 a_pos_3f;uniform mat4 u_matrix; #ifdef MODEL_POSITION_ON_GPU #ifdef INSTANCED_ARRAYS in vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3; #else uniform highp mat4 u_instance; #endif uniform highp mat4 u_node_matrix; #endif void main() { #ifdef MODEL_POSITION_ON_GPU highp mat4 instance; #ifdef INSTANCED_ARRAYS instance=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3); #else instance=u_instance; #endif vec3 pos_color=instance[0].xyz;vec4 translate=instance[1];vec3 pos_a=floor(pos_color);float hidden=float(pos_a.x > EXTENT);float meter_to_tile=instance[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);mat3 rs;rs[0].x=instance[1].w;rs[0].yz=instance[2].xy;rs[1].xy=instance[2].zw;rs[1].z=instance[3].x;rs[2].xyz=instance[3].yzw;vec4 pos_node=u_node_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;gl_Position=mix(u_matrix*pos,AWAY,hidden); #else gl_Position=u_matrix*vec4(a_pos_3f,1); #endif }`),stars:Bn(`in highp vec2 v_uv;in mediump float v_intensity;float shapeCircle(in vec2 uv) {float beginFade=0.6;float lengthFromCenter=length(v_uv);return 1.0-clamp((lengthFromCenter-beginFade)/(1.0-beginFade),0.0,1.0);}void main() {float alpha=shapeCircle(v_uv);vec3 color=vec3(1.0,1.0,1.0);alpha*=v_intensity;glFragColor=vec4(color*alpha,alpha);HANDLE_WIREFRAME_DEBUG;}`,` in vec3 a_pos_3f;in vec2 a_uv;in float a_size_scale;in float a_opacity;uniform mat4 u_matrix;uniform vec3 u_up;uniform vec3 u_right;uniform float u_intensity_multiplier;out highp vec2 v_uv;out mediump float v_intensity;void main() {v_uv=a_uv;v_intensity=a_opacity*u_intensity_multiplier;vec3 pos=a_pos_3f;pos+=a_uv.x*u_right*a_size_scale;pos+=a_uv.y*u_up*a_size_scale;gl_Position=u_matrix*vec4(pos,1.0);}`),snowParticle:Bn("in highp vec2 uv;in highp float alphaMultiplier;uniform vec4 u_particleColor;uniform vec2 u_simpleShapeParameters;void main() {float t=clamp((length(uv)-u_simpleShapeParameters.x)/(1.0-u_simpleShapeParameters.x),0.0,1.0);float alpha=1.0-pow(t,pow(10.0,u_simpleShapeParameters.y));alpha*=alphaMultiplier;alpha*=u_particleColor.a;vec3 color=u_particleColor.rgb*alpha;glFragColor=vec4(color,alpha) ;HANDLE_WIREFRAME_DEBUG;}",` in highp vec3 a_pos_3f;in highp vec2 a_uv;in highp vec4 a_snowParticleData;in highp vec4 a_snowParticleDataHorizontalOscillation;uniform mat4 u_modelview;uniform mat4 u_projection;uniform vec3 u_cam_pos;uniform vec2 u_screenSize;uniform float u_time;uniform float u_boxSize;uniform float u_velocityConeAperture; uniform float u_velocity;uniform vec3 u_direction;uniform float u_horizontalOscillationRadius; uniform float u_horizontalOscillationRate; uniform float u_billboardSize;uniform vec2 u_thinningCenterPos;uniform vec3 u_thinningShape;uniform float u_thinningAffectedRatio;uniform float u_thinningParticleOffset;out highp vec2 uv;out highp float alphaMultiplier;void main() {vec3 pos=a_pos_3f;float halfBoxSize=0.5*u_boxSize;pos.xyz*=halfBoxSize;pos+=u_cam_pos;float velocityConeApertureRad=radians(u_velocityConeAperture*0.5);float coneAnglePichRad=velocityConeApertureRad*a_snowParticleData.z;float coneAngleHeadingRad=a_snowParticleData.w*radians(360.0);vec3 localZ=normalize(u_direction);vec3 localX=normalize(cross(localZ,vec3(1,0,0)));vec3 localY=normalize(cross(localZ,localX));vec3 direction;direction.x=cos(coneAngleHeadingRad)*sin(coneAnglePichRad);direction.y=sin(coneAngleHeadingRad)*sin(coneAnglePichRad);direction.z=cos(coneAnglePichRad);direction=normalize(direction);vec3 simPosLocal=vec3(0,0,0);float velocityScale=(1.0+3.0*a_snowParticleData.y)*u_velocity;simPosLocal+=direction*velocityScale*u_time;float horizontalOscillationRadius=u_horizontalOscillationRadius*a_snowParticleDataHorizontalOscillation.x;float horizontalOscillationAngle=u_horizontalOscillationRate*u_time*(-1.0+2.0*a_snowParticleDataHorizontalOscillation.y);simPosLocal.xy+=horizontalOscillationRadius*vec2(cos(horizontalOscillationAngle),sin(horizontalOscillationAngle));vec3 simPos=localX*simPosLocal.x+ localY*simPosLocal.y+localZ*simPosLocal.z;pos+=simPos;pos=fract((pos+vec3(halfBoxSize))/vec3(u_boxSize))*u_boxSize-vec3(halfBoxSize);float clipZ=-u_cam_pos.z+pos.z;vec4 posView=u_modelview*vec4(pos,1.0);float size=u_billboardSize;alphaMultiplier=1.0;vec4 posScreen=u_projection*posView;posScreen/=posScreen.w;posScreen.xy=vec2(0.5)+posScreen.xy*0.5;posScreen.xy*=u_screenSize;vec2 thinningCenterPos=u_thinningCenterPos.xy;thinningCenterPos.y=u_screenSize.y-thinningCenterPos.y;float screenDist=length((thinningCenterPos-posScreen.xy)/(0.5*u_screenSize));screenDist+=a_snowParticleData.x*u_thinningParticleOffset;float scaleFactorMode=0.0;float thinningShapeDist=u_thinningShape.x+u_thinningShape.y;if (screenDist < thinningShapeDist) {float thinningFadeRatio=clamp((screenDist-u_thinningShape.x)/u_thinningShape.y,0.0,1.0);thinningFadeRatio=pow(thinningFadeRatio,u_thinningShape.z);if (a_snowParticleData.x < u_thinningAffectedRatio) {scaleFactorMode=1.0-thinningFadeRatio;alphaMultiplier=thinningFadeRatio;}}vec4 posScreen1=u_projection*vec4(posView.x-size,posView.yzw);posScreen1/=posScreen1.w;vec4 posScreen2=u_projection*vec4(posView.x+size,posView.yzw);posScreen2/=posScreen2.w;posScreen1.xy=vec2(0.5)+posScreen1.xy*0.5;posScreen1.xy*=u_screenSize;posScreen2.xy=vec2(0.5)+posScreen2.xy*0.5;posScreen2.xy*=u_screenSize;float screenLength=length(posScreen1.xy-posScreen2.xy);float screenEpsilon=3.0;float scaleFactor=1.0;if (screenLength < screenEpsilon) {scaleFactor=screenEpsilon/max(screenLength,0.01);scaleFactor=mix(scaleFactor,1.0,scaleFactorMode);}float screenEpsilon2=15.0;if (screenLength > screenEpsilon2) {scaleFactor=screenEpsilon2/max(screenLength,0.01);}size*=scaleFactor;vec2 right=size*vec2(1,0);vec2 up=size*vec2(0,1);posView.xy+=right*a_uv.x;posView.xy+=up*a_uv.y;uv=a_uv;gl_Position=u_projection*posView;}`),rainParticle:Bn("in highp vec2 uv;in highp float particleRandomValue;uniform sampler2D u_texScreen;uniform float u_distortionStrength;uniform vec4 u_color;uniform vec2 u_thinningCenterPos;uniform vec3 u_thinningShape;uniform float u_thinningAffectedRatio;uniform float u_thinningParticleOffset;uniform float u_shapeDirectionalPower;uniform float u_mode;void main() {vec2 st=uv*0.5+vec2(0.5);vec2 uvm=uv;uvm.y=-1.0+2.0*pow(st.y,u_shapeDirectionalPower);float shape=clamp(1.0-length(uvm),0.0,1.0);float alpha=abs(shape)*u_color.a;vec2 screenSize=vec2(textureSize(u_texScreen,0));vec2 thinningCenterPos=u_thinningCenterPos.xy;thinningCenterPos.y=screenSize.y-thinningCenterPos.y;float screenDist=length((thinningCenterPos-gl_FragCoord.xy)/(0.5*screenSize));screenDist+=(0.5+0.5*particleRandomValue)*u_thinningParticleOffset;float thinningShapeDist=u_thinningShape.x+u_thinningShape.y;float thinningAlpha=1.0;if (screenDist < thinningShapeDist) {float thinningFadeRatio=clamp((screenDist-u_thinningShape.x)/u_thinningShape.y,0.0,1.0);thinningFadeRatio=pow(thinningFadeRatio,u_thinningShape.z);thinningAlpha*=thinningFadeRatio;}vec2 offsetXY=normalize(uvm)*abs(shape);vec2 stScreen=(gl_FragCoord.xy+offsetXY*u_distortionStrength*thinningAlpha)/screenSize;vec3 colorScreen=texture(u_texScreen,stScreen).rgb;alpha*=thinningAlpha;glFragColor=mix(vec4(colorScreen,1.0),vec4(u_color.rgb*alpha,alpha),u_mode);HANDLE_WIREFRAME_DEBUG;}",` in highp vec3 a_pos_3f;in highp vec2 a_uv;in highp vec4 a_rainParticleData;uniform mat4 u_modelview;uniform mat4 u_projection;uniform vec3 u_cam_pos;uniform float u_time;uniform float u_boxSize;uniform float u_velocityConeAperture; uniform float u_velocity; uniform vec2 u_rainDropletSize;uniform vec3 u_rainDirection;out highp vec2 uv;out highp float particleRandomValue;void main() {vec3 pos=a_pos_3f;float halfBoxSize=0.5*u_boxSize;pos*=halfBoxSize; pos+=u_cam_pos;float velocityConeApertureRad=radians(u_velocityConeAperture*0.5);float coneAnglePichRad=velocityConeApertureRad*a_rainParticleData.z;float coneAngleHeadingRad=a_rainParticleData.w*radians(360.0);vec3 localZ=normalize(u_rainDirection);vec3 localX=normalize(cross(localZ,vec3(1,0,0)));vec3 localY=normalize(cross(localZ,localX));vec3 directionLocal;directionLocal.x=cos(coneAngleHeadingRad)*sin(coneAnglePichRad);directionLocal.y=sin(coneAngleHeadingRad)*sin(coneAnglePichRad);directionLocal.z=cos(coneAnglePichRad);directionLocal=normalize(directionLocal);vec3 directionWorld=localX*directionLocal.x+localY*directionLocal.y+localZ*directionLocal.z;float velocityScale=(1.0+3.0*a_rainParticleData.y)*u_velocity;vec3 simPosLocal=vec3(0,0,0);simPosLocal+=directionLocal*velocityScale*u_time;vec3 simPos=localX*simPosLocal.x+ localY*simPosLocal.y+localZ*simPosLocal.z;pos+=simPos;pos=fract((pos+vec3(halfBoxSize))/vec3(u_boxSize))*u_boxSize-vec3(halfBoxSize);vec4 posView=u_modelview*vec4(pos,1.0);vec3 directionView=normalize((u_modelview*vec4(directionWorld,0.0)).xyz);vec3 side=cross(directionView,normalize(posView.xyz));posView.xyz+=side*a_uv.x*u_rainDropletSize.x;posView.xyz+=directionView*a_uv.y*u_rainDropletSize.y;uv=a_uv;particleRandomValue=a_rainParticleData.x;gl_Position=u_projection*posView;}`),vignette:Bn("uniform vec3 u_vignetteShape;uniform vec4 u_vignetteColor;in vec2 st;void main() {float screenDist=length(st);float alpha=clamp((screenDist-u_vignetteShape.x)/u_vignetteShape.y,0.0,1.0);alpha=pow(alpha,u_vignetteShape.z)*u_vignetteColor.a;vec3 color=u_vignetteColor.rgb;glFragColor=vec4(color*alpha,alpha) ;}","in vec2 a_pos_2f;out vec2 st;void main() {st=a_pos_2f;gl_Position=vec4(a_pos_2f,0,1);}"),occlusion:Bn("uniform vec4 u_color;void main() {glFragColor=u_color;}",`#include "_prelude_terrain.vertex.glsl" in highp vec2 a_offset_xy;uniform highp vec3 u_anchorPos;uniform mat4 u_matrix;uniform vec2 u_screenSizePx;uniform vec2 u_occluderSizePx;void main() {vec3 world_pos=u_anchorPos; #ifdef TERRAIN float e=elevation(world_pos.xy);world_pos.z+=e; #endif vec4 projected_point=u_matrix*vec4(world_pos,1.0);projected_point.xy+=projected_point.w*a_offset_xy*0.5*u_occluderSizePx/u_screenSizePx;gl_Position=projected_point;}`)};function Sh(_,d){const g=_.split(` `);for(let w of g){if(w=w.trimStart(),w[0]!=="#"||!w.includes("if")||w.startsWith("#endif"))continue;const j=w.match(bN);if(j)for(const I of j)wN.has(I)||d.add(I)}}function TN(_){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(_)}function Bn(_,d){const g=new Set,w=[],j=[];_=_.replace(d0,(L,F)=>(j.push(F),"")),d=d.replace(d0,(L,F)=>(w.push(F),""));let I=new Set(Hm);Sh(_,I),Sh(d,I);for(const L of[...w,...j])Pg[L]||(Pg[L]=new Set,Sh(Hu[L],Pg[L])),I=new Set([...I,...Pg[L]]);return{fragmentSource:_=_.replace(lr,(L,F,z,H,Z)=>(g.add(Z),F==="define"?` #ifndef HAS_UNIFORM_u_${Z} ${TN(H)?"flat ":""}in ${z} ${H} ${Z}; #else uniform ${z} ${H} u_${Z}; #endif `:F==="initialize"?` #ifdef HAS_UNIFORM_u_${Z} ${z} ${H} ${Z} = u_${Z}; #endif `:F==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Z} in ${z} ${H} ${Z}; #endif `:F==="initialize-attribute"?"":void 0)),vertexSource:d=d.replace(lr,(L,F,z,H,Z)=>{const ne=`MATERIAL_ATTRIBUTE_OFFSET_${Z}`,re=H==="float"?"vec2":H,se=`GET_ATTRIBUTE_${re}(a_${Z}, materialInfo, ${ne})`,ce=Z.match(/color/)?"color":re;return F==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${Z} in ${z} ${H} a_${Z}; #endif `:g.has(Z)?F==="define"?` #ifndef HAS_UNIFORM_u_${Z} uniform lowp float u_${Z}_t; #if !defined(${ne}) in ${z} ${re} a_${Z}; #endif ${TN(H)?"flat ":""}out ${z} ${H} ${Z}; #else uniform ${z} ${H} u_${Z}; #endif `:F==="initialize"?ce==="vec4"||ce==="uvec4"?` #ifndef HAS_UNIFORM_u_${Z} ${Z} = a_${Z}; #else ${z} ${H} ${Z} = u_${Z}; #endif `:` #if !defined(HAS_UNIFORM_u_${Z}) #ifdef ${ne} ${Z} = unpack_mix_${ce}(${se}, u_${Z}_t); #else ${Z} = unpack_mix_${ce}(a_${Z}, u_${Z}_t); #endif #else ${z} ${H} ${Z} = u_${Z}; #endif `:F==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Z} in ${z} ${H} a_${Z}; out ${z} ${H} ${Z}; #endif `:F==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Z} ${Z} = a_${Z}; #endif `:void 0:F==="define"?` #ifndef HAS_UNIFORM_u_${Z} uniform lowp float u_${Z}_t; #if !defined(${ne}) in ${z} ${re} a_${Z}; #endif #else uniform ${z} ${H} u_${Z}; #endif `:F==="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 ${z} ${H} u_${Z}; #endif `:` #ifdef INSTANCED_ARRAYS in ${z} ${re} a_${Z}; #else uniform ${z} ${H} u_${Z}; #endif `:F==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${Z} ${z} ${H} ${Z} = a_${Z}; #endif `:ce==="vec4"||ce==="uvec4"?` #ifndef HAS_UNIFORM_u_${Z} #ifdef ${ne} ${z} ${H} ${Z} = ${se}; #else ${z} ${H} ${Z} = a_${Z}; #endif #else ${z} ${H} ${Z} = u_${Z}; #endif `:` #ifndef HAS_UNIFORM_u_${Z} #ifdef ${ne} ${z} ${H} ${Z} = unpack_mix_${ce}(${se}, u_${Z}_t); #else ${z} ${H} ${Z} = unpack_mix_${ce}(a_${Z}, u_${Z}_t); #endif #else ${z} ${H} ${Z} = u_${Z}; #endif `}),usedDefines:I,vertexIncludes:w,fragmentIncludes:j}}class EN{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(d,g,w,j,I,L,F,z){this.context=d;let H=this.boundPaintVertexBuffers.length!==j.length;for(let ne=0;!H&&ne{const Ze=De.paint.get("hillshade-shadow-color"),$e=De.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",Ke=De.paint.get("hillshade-highlight-color"),Me=De.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",Be=De.paint.get("hillshade-accent-color"),qe=De.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",st=De.paint.get("hillshade-emissive-strength");let Qe=a.ap(De.paint.get("hillshade-illumination-direction"));if(De.paint.get("hillshade-illumination-anchor")==="viewport")Qe-=ge.transform.angle;else if(ge.style&&ge.style.enable3dLights()&&ge.style.directionalLight){const ft=ge.style.directionalLight.properties.get("direction"),Lt=a.cP(ft.x,ft.y,ft.z);Qe=a.ap(Lt[1])}const xt=!ge.options.moving;return{u_matrix:_e||ge.transform.calculateProjMatrix(Pe.tileID.toUnwrapped(),xt),u_image:0,u_latrange:nE(0,Pe.tileID),u_light:[De.paint.get("hillshade-exaggeration"),Qe],u_shadow:Ze.toPremultipliedRenderColor($e?null:De.lut),u_highlight:Ke.toPremultipliedRenderColor(Me?null:De.lut),u_emissive_strength:st,u_accent:Be.toPremultipliedRenderColor(qe?null:De.lut)}})(_,g,w,_.terrain?d.projMatrix:null);_.uploadCommonUniforms(F,re,d.toUnwrapped());const{tileBoundsBuffer:ce,tileBoundsIndexBuffer:oe,tileBoundsSegments:ye}=_.getTileBoundsBuffers(g);re.draw(_,z.TRIANGLES,j,I,L,Gr.disabled,se,w.id,ce,oe,ye)}function jN(_,d,g){if(!d.needsDEMTextureUpload)return;const w=_.context,j=w.gl;w.pixelStoreUnpackPremultiplyAlpha.set(!1),d.demTexture=d.demTexture||_.getTileTexture(g.stride);const I=g.getPixels();d.demTexture?d.demTexture.update(I,{premultiply:!1}):d.demTexture=new a.T(w,I,j.R32F,{premultiply:!1}),d.needsDEMTextureUpload=!1}function I5(_,d,g){const w=_.context,j=w.gl;if(!d.dem)return;const I=d.dem;if(w.activeTexture.set(j.TEXTURE1),jN(_,d,I),!d.demTexture)return;d.demTexture.bind(j.NEAREST,j.CLAMP_TO_EDGE);const L=I.dim;w.activeTexture.set(j.TEXTURE0);let F=d.hillshadeFBO;if(!F){const re=new a.T(w,{width:L,height:L,data:null},j.RGBA8);re.bind(j.LINEAR,j.CLAMP_TO_EDGE),F=d.hillshadeFBO=w.createFramebuffer(L,L,1,"renderbuffer"),F.colorAttachment0.set(re.texture)}w.bindFramebuffer.set(F.framebuffer),w.viewport.set([0,0,L,L]);const{tileBoundsBuffer:z,tileBoundsIndexBuffer:H,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(_,j.TRIANGLES,Ir.disabled,Jr.disabled,Yr.unblended,Gr.disabled,((re,se)=>{const ce=se.stride,oe=a.bb();return a.bT(oe,0,a.an,-a.an,0,0,1),a.bx(oe,oe,[0,-a.an,0]),{u_matrix:oe,u_image:1,u_dimension:[ce,ce],u_zoom:re.overscaledZ}})(d.tileID,I),g.id,z,H,Z),d.needsHillshadePrepare=!1}class ls{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 AN extends ls{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 P5 extends ls{getDefault(){return 1}set(d){(d!==this.current||this.dirty)&&(this.gl.clearDepth(d),this.current=d,this.dirty=!1)}}class W_ extends ls{getDefault(){return 0}set(d){(d!==this.current||this.dirty)&&(this.gl.clearStencil(d),this.current=d,this.dirty=!1)}}class R5 extends ls{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 kN extends ls{getDefault(){return!0}set(d){(d!==this.current||this.dirty)&&(this.gl.depthMask(d),this.current=d,this.dirty=!1)}}class iE extends ls{getDefault(){return 255}set(d){(d!==this.current||this.dirty)&&(this.gl.stencilMask(d),this.current=d,this.dirty=!1)}}class K_ extends ls{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 sE extends ls{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 Wm extends ls{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 Km extends ls{getDefault(){return[0,1]}set(d){const g=this.current;(d[0]!==g[0]||d[1]!==g[1]||this.dirty)&&(this.gl.depthRange(d[0],d[1]),this.current=d,this.dirty=!1)}}class Lg extends ls{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 Pd extends ls{getDefault(){return this.gl.LESS}set(d){(d!==this.current||this.dirty)&&(this.gl.depthFunc(d),this.current=d,this.dirty=!1)}}class CN extends ls{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 aE extends ls{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 NN extends ls{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 Dg extends ls{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 Y_ extends ls{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 Z_ extends ls{getDefault(){return this.gl.BACK}set(d){(d!==this.current||this.dirty)&&(this.gl.cullFace(d),this.current=d,this.dirty=!1)}}class oE extends ls{getDefault(){return this.gl.CCW}set(d){(d!==this.current||this.dirty)&&(this.gl.frontFace(d),this.current=d,this.dirty=!1)}}let X_=class extends ls{getDefault(){return null}set(_){(_!==this.current||this.dirty)&&(this.gl.useProgram(_),this.current=_,this.dirty=!1)}};class f0 extends ls{getDefault(){return this.gl.TEXTURE0}set(d){(d!==this.current||this.dirty)&&(this.gl.activeTexture(d),this.current=d,this.dirty=!1)}}class IN extends ls{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 PN extends ls{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 RN extends ls{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 Mg extends ls{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 LN extends ls{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 L5 extends ls{getDefault(){return null}set(d){const g=this.gl;g.bindBuffer(g.ELEMENT_ARRAY_BUFFER,d),this.current=d,this.dirty=!1}}class D5 extends ls{getDefault(){return null}set(d){this.gl&&(d!==this.current||this.dirty)&&(this.gl.bindVertexArray(d),this.current=d,this.dirty=!1)}}class M5 extends ls{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 lE extends ls{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 cE extends ls{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 m0 extends ls{constructor(d,g){super(d),this.context=d,this.parent=g}getDefault(){return null}}class Og extends m0{constructor(d,g,w=0){super(d,g),this.attachmentPoint=d.gl.COLOR_ATTACHMENT0+w}setDirty(){this.dirty=!0}set(d){if(d===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const g=this.gl;g.framebufferTexture2D(g.FRAMEBUFFER,this.attachmentPoint,g.TEXTURE_2D,d,0),this.current=d,this.dirty=!1}}class uE extends m0{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 DN extends m0{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 O5 extends uE{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const p0=(_,d,g,w)=>({u_matrix:_,u_image0:0,u_image1:1,u_skirt_height:d,u_ground_shadow_factor:g,u_emissive_texture_available:w}),Fg=(_,d,g,w,j,I,L,F,z,H,Z,ne,re,se,ce,oe,ye)=>({u_proj_matrix:Float32Array.from(_),u_globe_matrix:d,u_normalize_matrix:Float32Array.from(w),u_merc_matrix:g,u_zoom_transition:j,u_merc_center:I,u_image0:0,u_image1:1,u_frustum_tl:L,u_frustum_tr:F,u_frustum_br:z,u_frustum_bl:H,u_globe_pos:Z,u_globe_radius:ne,u_viewport:re,u_grid_matrix:ye?Float32Array.from(ye):new Float32Array(9),u_skirt_height:se,u_far_z_cutoff:ce,u_emissive_texture_available:oe});function dE(_,d){return _!=null&&d!=null&&!(!_.hasData()||!d.hasData())&&_.demTexture!=null&&d.demTexture!=null&&_.tileID.key!==d.tileID.key}const Fo=new class{constructor(){this.operations={}}newMorphing(_,d,g,w,j){if(_ in this.operations){const I=this.operations[_];I.to.tileID.key!==g.tileID.key&&(I.queued=g)}else this.operations[_]={startTime:w,phase:0,duration:j,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()}},Q_={0:null,1:"TERRAIN_VERTEX_MORPHING"};function g0(_,d,g){if(d===0)return 0;const w=d<1&&g===514?.25/d:1;return 6*Math.pow(1.5,22-_)*Math.max(d,1)*w}function J_(_,d){const g=1<<_.z;return!d&&(_.x===0||_.x===g-1)||_.y===0||_.y===g-1}function y0(_,d){if(!_.style||!_.style.enable3dLights())return;const g=_.context,w=g.gl;g.activeTexture.set(w.TEXTURE1),d?d.bind(w.LINEAR,w.CLAMP_TO_EDGE):_.emptyTexture.bind(w.LINEAR,w.CLAMP_TO_EDGE)}const x0=_=>({u_matrix:_});function v0(_,d,g,w,j){if(j>0){const I=a.o.now(),L=(I-_.timeAdded)/j,F=d?(I-d.timeAdded)/j:-1,z=g.getSource(),H=w.coveringZoomLevel({tileSize:z.tileSize,roundZoom:z.roundZoom}),Z=!d||Math.abs(d.tileID.overscaledZ-H)>Math.abs(_.tileID.overscaledZ-H),ne=Z&&_.refreshedUponExpiration?1:a.aC(Z?L:1-F,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 eb extends fu{constructor(d){const g={type:"raster-dem",maxzoom:Math.ceil(d.transform.maxZoom)},w=P_("mock-dem",g,d.style.dispatcher,d.style);super("mock-dem",w,null),w.setEventedParent(this),this._sourceLoaded=!0}_loadTile(d,g){d.state="loaded",g(null)}}class hE extends fu{constructor(d){const g=P_("proxy",{type:"geojson",maxzoom:Math.ceil(d.transform.maxZoom)},d.style.dispatcher,d.style);super("proxy",g,null),g.setEventedParent(this),this.map=this.getSource().map=d,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(d,g,w){if(d.freezeTileCoverage)return;this.transform=d;const j=d.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((I,L)=>{if(I[L.key]="",!this._tiles[L.key]){const F=new a.b0(L,this._source.tileSize*L.overscaleFactor(),d.tileZoom,void 0,void 0,this._source.worldview);F.state="loaded",this._tiles[L.key]=F}return I},{});for(const I in this._tiles)I in j||(this.freeFBO(I),this._tiles[I].unloadVectorData(),delete this._tiles[I])}freeFBO(d){const g=this.proxyCachedFBO[d];if(g!==void 0){const w=Object.values(g);this.renderCachePool.push(...w),delete this.proxyCachedFBO[d]}}deallocRenderCache(){this.renderCache.forEach(d=>d.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class tb extends a.aR{constructor(d,g,w){super(d.overscaledZ,d.wrap,d.canonical.z,d.canonical.x,d.canonical.y),this.proxyTileKey=g,this.projMatrix=w}}class _0 extends a.bu{constructor(d,g){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=d,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[w,j,I]=function(){const z=new a.dB,H=new a.dC,Z=131;z.reserve(17161),H.reserve(33800);const ne=a.an/128,re=a.an+ne/2,se=re+ne;for(let oe=-ne;oere||oe<0||oe>re?24575:0,Pe=a.aC(Math.round(ye),0,a.an),De=a.aC(Math.round(oe),0,a.an);z.emplaceBack(Pe+ge,De)}const ce=(oe,ye)=>{const ge=ye*Z+oe;H.emplaceBack(ge+1,ge,ge+Z),H.emplaceBack(ge+Z,ge+Z+1,ge+1)};for(let oe=1;oe<129;oe++)for(let ye=1;ye<129;ye++)ce(ye,oe);return[0,129].forEach(oe=>{for(let ye=0;ye<130;ye++)ce(ye,oe),ce(oe,ye)}),[z,H,32768]}(),L=d.context;this.gridBuffer=L.createVertexBuffer(w,a.dx.members),this.gridIndexBuffer=L.createIndexBuffer(j),this.gridSegments=a.dy.simpleSegment(0,0,w.length,j.length),this.gridNoSkirtSegments=a.dy.simpleSegment(0,0,w.length,I),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new hE(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 F=L.gl;this._overlapStencilMode=new Jr({func:F.GEQUAL,mask:255},0,255,F.KEEP,F.KEEP,F.REPLACE),this._previousZoom=d.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=g,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new eb(g.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1}set style(d){d.on("data",this._onStyleDataEvent.bind(this)),this._style=d,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(d,g,w){if(d&&d.terrain){this._style!==d&&(this.style=d,this._evaluationZoom=void 0);const j=d.terrain.properties,I=d.terrain.drapeRenderMode===0,L=d.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=a.o.now();const F=d.terrain&&d.terrain.scope,z=j.get("source"),H=I?this._mockSourceCache:d.getSourceCache(z,F);if(!H)return void a.w(`Couldn't find terrain source "${z}".`);if(this.sourceCache=H,this._attenuationRange=d.terrain.getAttenuationRange(),this._exaggeration=L?this.calculateExaggeration(g):j.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,w),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(g),this._emptyDEMTextureDirty=!0,this._previousZoom=g.zoom}else this._disable()}calculateExaggeration(d){if(this._attenuationRange&&d.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(d.zoom);const g=this._previousCameraAltitude,w=d.getFreeCameraOptions().position.z/d.pixelsPerMeter*d.worldSize;this._previousCameraAltitude=w;const j=g!=null?w-g:Number.MAX_VALUE;if(Math.abs(j)<2)return this._exaggeration;const I=d.zoom,L=this._style.terrain;if(!this._previousUpdateTimestamp)return L.getExaggeration(I);let F=I-this._previousZoom;const z=this._previousUpdateTimestamp;let H=I;this._evaluationZoom!=null&&(H=this._evaluationZoom,Math.abs(I-H)>.5&&(F=.5*(I-H+F)),F*j<0&&(H+=F)),this._evaluationZoom=H;const Z=L.getExaggeration(H),ne=Z===L.getExaggeration(Math.max(0,H-.1));if(ne&&Math.abs(Z-this._exaggeration)<.01)return Z;let re=Math.min(.1,.00375*(this._updateTimestamp-z));return(ne||Z<.1||Math.abs(F)<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,w=this.painter.transform;this._initializing&&(this._initializing=w._centerAltitude===0&&this.getAtPointOrZero(a.ag.fromLngLat(w.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const j=this.proxyCoords=g.getIds().map(z=>{const H=g.getTileByID(z).tileID;return H.projMatrix=w.calculateProjMatrix(H.toUnwrapped()),H});(function(z,H){const Z=H.transform.pointCoordinate(H.transform.getCameraPoint()),ne=new a.P(Z.x,Z.y);z.sort((re,se)=>{if(se.overscaledZ-re.overscaledZ)return se.overscaledZ-re.overscaledZ;const ce=new a.P(re.canonical.x+(1<{this.proxyToSource[z.key]={}}),this.terrainTileForTile={};const L=this._style._mergedSourceCaches;for(const z in L){const H=L[z];if(!H.used||(H!==this.sourceCache&&this.resetTileLookupCache(H.id),this._setupProxiedCoordsForOrtho(H,d[z],I),H.usedForTerrain))continue;const Z=d[z];(H.getSource().reparseOverscaled||H._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(Z)}this.proxiedCoords[g.id]=j.map(z=>new tb(z,z.key,this.orthoMatrix)),this._assignTerrainTiles(j),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(I),this.renderingToTexture=!1;const F={};this._visibleDemTiles=[];for(const z of this.proxyCoords){const H=this.terrainTileForTile[z.key];if(!H)continue;const Z=H.tileID.key;Z in F||(this._visibleDemTiles.push(H),F[Z]=Z)}}_assignTerrainTiles(d){this._initializing||d.forEach(g=>{if(this.terrainTileForTile[g.key])return;const w=this._findTileCoveringTileID(g,this.sourceCache);w&&(this.terrainTileForTile[g.key]=w)})}_prepareDEMTextures(){const d=this.painter.context,g=d.gl;for(const w in this.terrainTileForTile){const j=this.terrainTileForTile[w],I=j.dem;!I||j.demTexture&&!j.needsDEMTextureUpload||(d.activeTexture.set(g.TEXTURE1),jN(this.painter,j,I))}}_prepareDemTileUniforms(d,g,w,j){if(!g||g.demTexture==null)return!1;const I=d.tileID.canonical,L=Math.pow(2,g.tileID.canonical.z-I.z),F=j||"";return w[`u_dem_tl${F}`]=[I.x*L%1,I.y*L%1],w[`u_dem_scale${F}`]=L,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let d=0;const g=this._visibleDemTiles.reduce((w,j)=>{if(!j.dem)return w;const I=j.dem.tree.minimums[0];return I>0&&d++,w+I},0);return d?g/d:0}_updateEmptyDEMTexture(){const d=this.painter.context,g=d.gl;d.activeTexture.set(g.TEXTURE2);const w=this._getLoadedAreaMinimum(),j=new a.dz({width:1,height:1},new Float32Array([w]));this._emptyDEMTextureDirty=!1;let I=this._emptyDEMTexture;return I?I.update(j,{premultiply:!1}):I=this._emptyDEMTexture=new a.T(d,j,g.R32F,{premultiply:!1}),I}setupElevationDraw(d,g,w){const j=this.painter.context,I=j.gl,L={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0};L.u_exaggeration=this.exaggeration();let F=null,z=null,H=1;if(w&&w.morphing&&this._useVertexMorphing){const se=w.morphing.srcDemTile,ce=w.morphing.dstDemTile;H=w.morphing.phase,se&&ce&&(this._prepareDemTileUniforms(d,se,L,"_prev")&&(z=se),this._prepareDemTileUniforms(d,ce,L)&&(F=ce))}const Z=se=>se&&se.demTexture&&this.painter.linearFloatFilteringSupported()?I.LINEAR:I.NEAREST;let ne=null;var re;if(this.enabled?z&&F?(ne=F.demTexture,j.activeTexture.set(I.TEXTURE4),z.demTexture.bind(Z(z),I.CLAMP_TO_EDGE),L.u_dem_lerp=H):(F=this.terrainTileForTile[d.tileID.key],ne=this._prepareDemTileUniforms(d,F,L)?F.demTexture:this.emptyDEMTexture):ne=this.emptyDEMTexture,j.activeTexture.set(I.TEXTURE2),ne&&(L.u_dem_size=(re=ne).size[0]===1?1:re.size[0]-2,ne.bind(Z(F),I.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(w&&w.useDepthForOcclusion,g,L),w&&w.useMeterToDem&&F){const se=(1<{if(ge===ft)return;const Lt=[Q_[ft],"PROJECTION_GLOBE_VIEW"];De&&Lt.push("CUSTOM_ANTIALIASING");const Ft=H.isTileAffectedByFog(xt);ye=H.getOrCreateProgram("globeRaster",{defines:Lt,overrideFog:Ft}),ge=ft},Ze=H.colorModeForRenderPass(),$e=new Ir(oe.LEQUAL,Ir.ReadWrite,H.depthRangeFor3D);Fo.update(se);const Ke=a.dq(Pe),Me=[a.aH(Pe.center.lng),a.aL(Pe.center.lat)],Be=H.globeSharedBuffers,qe=[Pe.width*a.o.devicePixelRatio,Pe.height*a.o.devicePixelRatio],st=Float32Array.from(Pe.globeMatrix),Qe={useDenormalizedUpVectorScale:!0};{const xt=H.transform,ft=g0(xt.zoom,Z.exaggeration(),Z.sourceCache._source.tileSize);ge=-1;const Lt=oe.TRIANGLES;for(const Ft of re){const ot=ne.getTile(Ft),et=Jr.disabled,gt=Z.prevTerrainTileForTile[Ft.key],bt=Z.terrainTileForTile[Ft.key];dE(gt,bt)&&Fo.newMorphing(Ft.key,gt,bt,se,250),y0(H,ot.emissiveTexture),ce.activeTexture.set(oe.TEXTURE0),ot.texture&&ot.texture.bind(oe.LINEAR,oe.CLAMP_TO_EDGE);const St=Fo.getMorphValuesForProxy(Ft.key),nr=St?1:0;St&&Object.assign(Qe,{morphing:{srcDemTile:St.from,dstDemTile:St.to,phase:a.dn(St.phase)}});const Wt=a.dr(Ft.canonical),Kt=a.ds(Wt.getCenter().lat),Mt=a.dt(Ft.canonical,Wt,Kt,xt.worldSize/xt._pixelsPerMercatorPixel),kr=a.du(a.dv(Ft.canonical)),Lr=H.emissiveMode==="mrt-fallback"?1:0,yr=Fg(xt.expandedFarZProjMatrix,st,Ke,kr,a.al(xt.zoom),Me,xt.frustumCorners.TL,xt.frustumCorners.TR,xt.frustumCorners.BR,xt.frustumCorners.BL,xt.globeCenterInViewSpace,xt.globeRadius,qe,ft,xt._farZ,Lr,Mt);if(_e(Ft,nr),ye&&(Z.setupElevationDraw(ot,ye,Qe),H.uploadCommonUniforms(ce,ye,Ft.toUnwrapped()),Be)){const[Er,Hr,an]=Be.getGridBuffers(Kt,ft!==0);ye.draw(H,Lt,$e,et,Ze,Gr.backCCW,yr,"globe_raster",Er,Hr,an)}}}if(Be&&(H.renderDefaultNorthPole||H.renderDefaultSouthPole)){const xt=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];De&&xt.push("CUSTOM_ANTIALIASING"),ye=H.getOrCreateProgram("globeRaster",{defines:xt});for(const ft of re){const{x:Lt,y:Ft,z:ot}=ft.canonical,et=Ft===0,gt=Ft===(1<Er.draw(H,oe.TRIANGLES,$e,Jr.disabled,Ze,Gr.disabled,Fg(Pe.expandedFarZProjMatrix,Mt,Mt,kr,0,Me,Pe.frustumCorners.TL,Pe.frustumCorners.TR,Pe.frustumCorners.BR,Pe.frustumCorners.BL,Pe.globeCenterInViewSpace,Pe.globeRadius,qe,0,Pe._farZ,Lr),"globe_pole_raster",Hr,nr,Wt);Z.setupElevationDraw(Kt,ye,Qe),H.uploadCommonUniforms(ce,ye,ft.toUnwrapped()),et&&H.renderDefaultNorthPole&&yr(ye,bt),gt&&H.renderDefaultSouthPole&&(Mt=a.cC(a.bb(),Mt,[1,-1,1]),yr(ye,St))}}}})(j,I,L,F,z);else{const H=j.context,Z=H.gl;let ne,re;const se=j.shadowRenderer,ce=Ma(j,j.longestCutoffRange),oe=Ze=>{if(re===Ze)return;const $e=[];$e.push(Q_[Ze]),ce.shouldRenderCutoff&&$e.push("RENDER_CUTOFF"),se&&($e.push("RENDER_SHADOWS"),se.useNormalOffset&&$e.push("NORMAL_OFFSET")),ne=j.getOrCreateProgram("terrainRaster",{defines:$e}),re=Ze},ye=j.colorModeForRenderPass(),ge=new Ir(Z.LEQUAL,Ir.ReadWrite,j.depthRangeFor3D);Fo.update(z);const Pe=j.transform,De=g0(Pe.zoom,I.exaggeration(),I.sourceCache._source.tileSize);let _e=[0,0,0];if(se){const Ze=j.style.directionalLight,$e=j.style.ambientLight;Ze&&$e&&(_e=Gu(j.style,Ze,$e))}{re=-1;const Ze=Z.TRIANGLES,[$e,Ke]=[I.gridIndexBuffer,I.gridSegments];for(const Me of F){const Be=L.getTile(Me),qe=Jr.disabled,st=I.prevTerrainTileForTile[Me.key],Qe=I.terrainTileForTile[Me.key];dE(st,Qe)&&Fo.newMorphing(Me.key,st,Qe,z,250),y0(j,Be.emissiveTexture),H.activeTexture.set(Z.TEXTURE0),Be.texture&&Be.texture.bind(Z.LINEAR,Z.CLAMP_TO_EDGE);const xt=Fo.getMorphValuesForProxy(Me.key),ft=xt?1:0;let Lt;xt&&(Lt={morphing:{srcDemTile:xt.from,dstDemTile:xt.to,phase:a.dn(xt.phase)}});const Ft=j.emissiveMode==="mrt-fallback"?1:0,ot=p0(Me.projMatrix,J_(Me.canonical,Pe.renderWorldCopies)?De/10:De,_e,Ft);if(oe(ft),!ne)continue;I.setupElevationDraw(Be,ne,Lt);const et=Me.toUnwrapped();se&&se.setupShadows(et,ne),j.uploadCommonUniforms(H,ne,et,null,ce),ne.draw(j,Ze,ge,qe,ye,Gr.backCCW,ot,"terrain_raster",I.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,w=this.painter.context,j=this.proxySourceCache,I=this.proxiedCoords[j.id],L=this._drapedRenderBatches.shift(),F=g.style.order,z=[];this._updateFBOs(g.emissiveMode==="mrt-fallback");let H=0;for(const Z of I){const ne=j.getTileByID(Z.proxyTileKey),re=j.proxyCachedFBO[Z.key]?j.proxyCachedFBO[Z.key][d]:void 0,se=re!==void 0?j.renderCache[re]:this.pool[H++],ce=re!==void 0;if(ne.texture=se.tex,ne.emissiveTexture=se.emissiveTex,ce&&!se.dirty){z.push(ne.tileID);continue}w.bindFramebuffer.set(se.fb.framebuffer);const oe=w.gl;let ye;oe.drawBuffers(g.emissiveMode==="mrt-fallback"?[oe.COLOR_ATTACHMENT0,oe.COLOR_ATTACHMENT1]:[oe.COLOR_ATTACHMENT0]),this.renderedToTile=!1,se.dirty&&(w.clear({color:a.aq.transparent,stencil:0}),se.dirty=!1);for(let ge=L.start;ge<=L.end;++ge){const Pe=g.style._mergedLayers[F[ge]];if(Pe.isHidden(g.transform.zoom))continue;const De=g.style.getLayerSourceCache(Pe),_e=De?this.proxyToSource[Z.key][De.id]:[Z];if(!_e)continue;const Ze=_e;w.viewport.set([0,0,se.fb.width,se.fb.height]),ye!==(De?De.id:null)&&(this._setupStencil(se,_e,Pe,De),ye=De?De.id:null),g.renderLayer(g,De,Pe,Ze)}if(oe.drawBuffers([oe.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const ge of this._pendingGroundEffectLayers){const Pe=g.style._mergedLayers[F[ge]];if(Pe.isHidden(g.transform.zoom))continue;const De=g.style.getLayerSourceCache(Pe),_e=De?this.proxyToSource[Z.key][De.id]:[Z];if(!_e)continue;const Ze=_e;w.viewport.set([0,0,se.fb.width,se.fb.height]),ye!==(De?De.id:null)&&(this._setupStencil(se,_e,Pe,De),ye=De?De.id:null),g.renderLayer(g,De,Pe,Ze)}this.renderedToTile?(se.dirty=!0,z.push(ne.tileID)):ce||--H,H===5&&(H=0,this.renderToBackBuffer(z))}return this.renderToBackBuffer(z),this.renderingToTexture=!1,w.bindFramebuffer.set(null),w.viewport.set([0,0,g.width,g.height]),L.end+1}postRender(){}isLayerOrderingCorrect(d){const g=d.order.length;let w=-1,j=g;for(let I=0;Iw}getMinElevationBelowMSL(){let d=0;return this._visibleDemTiles.filter(g=>g.dem).forEach(g=>{d=Math.min(d,g.dem.tree.minimums[0])}),d===0?d:(d-30)*this._exaggeration}raycast(d,g,w){if(!this._visibleDemTiles)return null;const j=this._visibleDemTiles.filter(I=>I.dem).map(I=>{const L=I.tileID,F=1<(I.t!==null?I.t:Number.MAX_VALUE)-(L.t!==null?L.t:Number.MAX_VALUE));for(const I of j){if(I.t==null)return null;const L=I.tile.dem.tree.raycast(I.minx,I.miny,I.maxx,I.maxy,d,g,w);if(L!=null)return L}return null}_createFBO(){const d=this.painter.context,g=d.gl,w=this.drapeBufferSize;d.activeTexture.set(g.TEXTURE0);const j=new a.T(d,{width:w[0],height:w[1],data:null},g.RGBA8);j.bind(g.LINEAR,g.CLAMP_TO_EDGE);const I=d.createFramebuffer(w[0],w[1],1,null);let L;return I.colorAttachment0.set(j.texture),this._emissiveTexture&&(L=new a.T(d,{width:w[0],height:w[1],data:null},g.R8),L.bind(g.LINEAR,g.CLAMP_TO_EDGE),I.createColorAttachment(d,1),I.colorAttachment1.set(L.texture)),I.depthAttachment=new O5(d,I.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=d.createRenderbuffer(d.gl.DEPTH_STENCIL,w[0],w[1]),this._stencilRef=0,I.depthAttachment.set(this._sharedDepthStencil),d.clear({stencil:0})):I.depthAttachment.set(this._sharedDepthStencil),d.extTextureFilterAnisotropic&&g.texParameterf(g.TEXTURE_2D,d.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,d.extTextureFilterAnisotropicMax),{fb:I,tex:j,emissiveTex:L,dirty:!1}}_updateFBOs(d){if(this._emissiveTexture!==d){for(const g of this.pool)this._updateFBO(g,d);for(const g of this.proxySourceCache.renderCache)this._updateFBO(g,d);this._emissiveTexture=d}}_updateFBO(d,g){const w=d.fb,j=this.painter.context,I=j.gl,L=this.drapeBufferSize;if(g){const F=new a.T(j,{width:L[0],height:L[1],data:null},I.R8);F.bind(I.LINEAR,I.CLAMP_TO_EDGE),d.emissiveTex=F,w.createColorAttachment(j,1),w.colorAttachment1.set(F.texture)}else d.emissiveTex=void 0,w.removeColorAttachment(j,1);d.dirty=!0}_initFBOPool(){for(;this.pool.length{const g=this._style._mergedLayers[d],w=g.isHidden(this.painter.transform.zoom);return g.type==="hillshade"||g.type==="custom"?!w&&g.shouldRedrape():!w&&g.hasTransition()})}_clearLineLayersFromRenderCache(){let d=!1;for(const w of this._style.getSources())if(w instanceof $l){d=!0;break}if(!d)return;const g={};for(let w=0;wz>F.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=w}_setupRenderCache(d){const g=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,g.renderCache.length>g.renderCachePool.length){const L=Object.values(g.proxyCachedFBO);g.proxyCachedFBO={};for(let F=0;F=0;L--){const F=w[L];if(g.getTileByID(F.key),g.proxyCachedFBO[F.key]!==void 0){const z=d[F.key],H=this.proxyToSource[F.key];let Z=0;for(const ne in H){const re=H[ne],se=z[ne];if(!se||se.length!==re.length||re.some((ce,oe)=>ce!==se[oe]||j[ne]&&j[ne].hasOwnProperty(ce.key))){Z=-1;break}++Z}for(const ne in g.proxyCachedFBO[F.key])g.renderCache[g.proxyCachedFBO[F.key][ne]].dirty=Z<0||Z!==Object.values(z).length}}const I=[...this._drapedRenderBatches];I.sort((L,F)=>F.end-F.start-(L.end-L.start));for(const L of I)for(const F of w){if(g.proxyCachedFBO[F.key])continue;let z=g.renderCachePool.pop();z===void 0&&g.renderCache.length<50&&(z=g.renderCache.length,g.renderCache.push(this._createFBO())),z!==void 0&&(g.proxyCachedFBO[F.key]={},g.proxyCachedFBO[F.key][L.start]=z,g.renderCache[z].dirty=!0)}this._tilesDirty={}}_setupStencil(d,g,w,j){if(!j||!this._sourceTilesOverlap[j.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const I=this.painter.context,L=I.gl;if(g.length<=1)return void(this._overlapStencilType=!1);let F;if(w.isTileClipped())F=g.length,this._overlapStencilMode.test={func:L.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(g[0].overscaledZ>g[g.length-1].overscaledZ))return void(this._overlapStencilType=!1);F=1,this._overlapStencilMode.test={func:L.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+F>255&&(I.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=F,this._overlapStencilMode.ref=this._stencilRef,w.isTileClipped()&&this._renderTileClippingMasks(g,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(d){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[d.key]),this._overlapStencilMode):Jr.disabled}_renderTileClippingMasks(d,g){const w=this.painter,j=this.painter.context,I=j.gl;w._tileClippingMaskIDs={},j.setColorMode(Yr.disabled),j.setDepthMode(Ir.disabled);const L=w.getOrCreateProgram("clippingMask");for(const F of d){const z=w._tileClippingMaskIDs[F.key]=--g;L.draw(w,I.TRIANGLES,Ir.disabled,new Jr({func:I.ALWAYS,mask:0},z,255,I.KEEP,I.KEEP,I.REPLACE),Yr.disabled,Gr.disabled,x0(F.projMatrix),"$clipping",w.tileExtentBuffer,w.quadTriangleIndexBuffer,w.tileExtentSegments)}}pointCoordinate(d){const g=this.painter.transform;if(d.x<0||d.x>g.width||d.y<0||d.y>g.height)return null;const w=[d.x,d.y,1,1];a.aE(w,w,g.pixelMatrixInverse),a.cu(w,w,1/w[3]),w[0]/=g.worldSize,w[1]/=g.worldSize;const j=g._camera.position,I=a.bU(1,g.center.lat),L=[j[0],j[1],j[2]/I,0],F=a.cV([],w.slice(0,3),L);a.ay(F,F);const z=this.raycast(L,F,this._exaggeration);return z!==null&&z?(a.bg(L,L,F,z),L[3]=L[2],L[2]*=I,L):null}_setupProxiedCoordsForOrtho(d,g,w){if(d.getSource()instanceof a.aV)return this._setupProxiedCoordsForImageSource(d,g,w);this._findCoveringTileCache[d.id]=this._findCoveringTileCache[d.id]||{};const j=this.proxiedCoords[d.id]=[],I=this.proxyCoords;for(let z=0;zZ.overscaledZ-H.overscaledZ)}_setupProxiedCoordsForImageSource(d,g,w){if(!d.getSource().loaded())return;const j=this.proxiedCoords[d.id]=[],I=this.proxyCoords,L=d.getSource(),F=L.tileID;if(!F)return;const z=new a.P(F.x,F.y)._div(1<(ne.min.x=Math.min(ne.min.x,re.x-z.x),ne.min.y=Math.min(ne.min.y,re.y-z.y),ne.max.x=Math.max(ne.max.x,re.x-z.x),ne.max.y=Math.max(ne.max.y,re.y-z.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 se=ne.wrap+ne.canonical.x/(1<ye+H.max.x||ce+oege+H.max.y};for(let ne=0;neL.key===g.tileID.key);if(I)return I}if(g.tileID.key!==d.key){const I=d.canonical.z-g.tileID.canonical.z;let L,F,z;j=a.bb();const H=g.tileID.wrap-d.wrap<0?(L=a.an>>I,F=L*((g.tileID.canonical.x<=ne){const re=d.canonical.z-ne;g.getSource().reparseOverscaled?(F=Math.max(d.canonical.z+2,g.transform.tileZoom),L=new a.aR(F,d.wrap,ne,d.canonical.x>>re,d.canonical.y>>re)):re!==0&&(F=ne,L=new a.aR(F,d.wrap,ne,d.canonical.x>>re,d.canonical.y>>re))}L.key!==d.key&&(H.push(L.key),w=g.getTile(L))}const Z=ne=>{H.forEach(re=>{j[re]=ne}),H.length=0};for(F-=1;F>=z&&(!w||!w.hasData());F--){w&&Z(w.tileID.key);const ne=L.calculateScaledKey(F);if(w=g.getTileByID(ne),w&&w.hasData())break;const re=j[ne];if(re===null)break;re===void 0?H.push(ne):w=g.getTileByID(re)}return Z(w?w.tileID.key:null),w&&w.hasData()?w:null}findDEMTileFor(d){return this.enabled?this._findTileCoveringTileID(d,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(d,g){let w=this._tilesDirty[d];w||(w=this._tilesDirty[d]={}),w[g.key]=!0}}function fE(_,d,g){const w=function(F,z,H){const Z=a.bi(z,F),ne=a.bi(H,[.2126,.7152,.0722]),re=(ce,oe,ye)=>(1-ye)*ce+ye*oe,se=re(1-.3*Math.min(ne,1),1,Math.min(Z+1,1));return re(.92,1,Math.asin(a.aC(z[2],-1,1))/Math.PI+.5)*se}(_,[0,0,1],d),j=[0,0,0];a.bJ(j,g.slice(0,3),w);const I=[0,0,0];a.bJ(I,d.slice(0,3),_[2]);const L=[0,0,0];return a.cT(L,j,I),a.cW(L)}const MN=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],ON=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class Ym{static cacheKey(d,g,w,j){const I=[g];j&&I.push(j.cacheKey);for(const L of w)(typeof L=="string"&&L.includes(" ")||d.usedDefines.has(L))&&I.push(L);return I.join("/")}constructor(d,g,w,j,I,L){const F=d.gl;this.program=F.createProgram(),this.configuration=j,this.name=g,this.fixedDefines=[...L];const z=`#version 300 es ${(j?j.defines():[]).concat(L.map(oe=>`#define ${oe}`)).join(` `)}`,H=[z,Rg];for(const oe of w.fragmentIncludes)H.push(Hu[oe]);H.push(w.fragmentSource);const Z=H.join(` `),ne=[z,C5];for(const oe of w.vertexIncludes)ne.push(Hu[oe]);this.forceManualRenderingForInstanceIDShaders=d.forceManualRenderingForInstanceIDShaders&&w.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&ne.push("uniform int u_instanceID;"),ne.push(w.vertexSource);let re=ne.join(` `);this.forceManualRenderingForInstanceIDShaders&&(re=re.replaceAll("gl_InstanceID","u_instanceID"));const se=F.createShader(F.FRAGMENT_SHADER);if(F.isContextLost())return void(this.failedToCreate=!0);F.shaderSource(se,Z),F.compileShader(se),F.attachShader(this.program,se);const ce=F.createShader(F.VERTEX_SHADER);F.isContextLost()?this.failedToCreate=!0:(F.shaderSource(ce,re),F.compileShader(ce),F.attachShader(this.program,ce),this.attributes={},F.linkProgram(this.program),F.deleteShader(ce),F.deleteShader(se),this.fixedUniforms=I(d),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=j?j.getUniforms(d):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(oe=>({u_instanceID:new a.bX(oe)}))(d)),(L.includes("TERRAIN")||L.includes("ELEVATED")||g.includes("symbol")||g.includes("circle"))&&(this.terrainUniforms=(oe=>({u_dem:new a.bX(oe),u_dem_prev:new a.bX(oe),u_dem_tl:new a.b_(oe),u_dem_scale:new a.bZ(oe),u_dem_tl_prev:new a.b_(oe),u_dem_scale_prev:new a.bZ(oe),u_dem_size:new a.bZ(oe),u_dem_lerp:new a.bZ(oe),u_exaggeration:new a.bZ(oe),u_depth:new a.bX(oe),u_depth_size_inv:new a.b_(oe),u_depth_range_unpack:new a.b_(oe),u_occluder_half_size:new a.bZ(oe),u_occlusion_depth_offset:new a.bZ(oe),u_meter_to_dem:new a.bZ(oe),u_label_plane_matrix_inv:new a.b$(oe)}))(d)),L.includes("GLOBE")&&(this.globeUniforms=(oe=>({u_tile_tl_up:new a.bY(oe),u_tile_tr_up:new a.bY(oe),u_tile_br_up:new a.bY(oe),u_tile_bl_up:new a.bY(oe),u_tile_up_scale:new a.bZ(oe)}))(d)),L.includes("FOG")&&(this.fogUniforms=(oe=>({u_fog_matrix:new a.b$(oe),u_fog_range:new a.b_(oe),u_fog_color:new a.cO(oe),u_fog_horizon_blend:new a.bZ(oe),u_fog_vertical_limit:new a.b_(oe),u_fog_temporal_offset:new a.bZ(oe),u_frustum_tl:new a.bY(oe),u_frustum_tr:new a.bY(oe),u_frustum_br:new a.bY(oe),u_frustum_bl:new a.bY(oe),u_globe_pos:new a.bY(oe),u_globe_radius:new a.bZ(oe),u_globe_transition:new a.bZ(oe),u_is_globe:new a.bX(oe),u_viewport:new a.b_(oe)}))(d)),L.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(oe=>({u_cutoff_params:new a.cO(oe)}))(d)),L.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(oe=>({u_lighting_ambient_color:new a.bY(oe),u_lighting_directional_dir:new a.bY(oe),u_lighting_directional_color:new a.bY(oe),u_ground_radiance:new a.bY(oe)}))(d)),L.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(oe=>({u_light_matrix_0:new a.b$(oe),u_light_matrix_1:new a.b$(oe),u_fade_range:new a.b_(oe),u_shadow_normal_offset:new a.bY(oe),u_shadow_intensity:new a.bZ(oe),u_shadow_texel_size:new a.bZ(oe),u_shadow_map_resolution:new a.bZ(oe),u_shadow_direction:new a.bY(oe),u_shadow_bias:new a.bY(oe),u_shadowmap_0:new a.bX(oe),u_shadowmap_1:new a.bX(oe)}))(d)))}getAttributeLocation(d,g){let w=this.attributes[g];return w===void 0&&(w=this.attributes[g]=d.getAttribLocation(this.program,g)),w}setTerrainUniformValues(d,g){if(!this.terrainUniforms)return;const w=this.terrainUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const j in g)w[j]&&w[j].set(this.program,j,g[j])}}setGlobeUniformValues(d,g){if(!this.globeUniforms)return;const w=this.globeUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const j in g)w[j]&&w[j].set(this.program,j,g[j])}}setFogUniformValues(d,g){if(!this.fogUniforms)return;const w=this.fogUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const j in g)w[j].set(this.program,j,g[j])}}setCutoffUniformValues(d,g){if(!this.cutoffUniforms)return;const w=this.cutoffUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const j in g)w[j].set(this.program,j,g[j])}}setLightsUniformValues(d,g){if(!this.lightsUniforms)return;const w=this.lightsUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const j in g)w[j].set(this.program,j,g[j])}}setShadowUniformValues(d,g){if(this.failedToCreate||!this.shadowUniforms)return;const w=this.shadowUniforms;d.program.set(this.program);for(const j in g)w[j].set(this.program,j,g[j])}_drawDebugWireframe(d,g,w,j,I,L,F,z,H,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||!MN.includes(this.name))||!(!ne.layers3D||!ON.includes(this.name))))return;const se=re.gl,ce=d.wireframeDebugCache.getLinesFromTrianglesBuffer(d.frameCounter,I,re);if(!ce)return;const oe=[...this.fixedDefines,"DEBUG_WIREFRAME"],ye=d.getOrCreateProgram(this.name,{config:this.configuration,defines:oe});re.program.set(ye.program);const ge=(_e,Ze,$e)=>{if(Ze[_e]&&$e[_e])for(const Ke in Ze[_e])$e[_e][Ke]&&$e[_e][Ke].set($e.program,Ke,Ze[_e][Ke].current)};H&&H.setUniforms(ye.program,re,ye.binderUniforms,F,{zoom:z}),ge("fixedUniforms",this,ye),ge("terrainUniforms",this,ye),ge("globeUniforms",this,ye),ge("fogUniforms",this,ye),ge("lightsUniforms",this,ye),ge("shadowUniforms",this,ye),ce.bind(),re.setColorMode(new Yr([se.ONE,se.ONE_MINUS_SRC_ALPHA,se.ZERO,se.ONE],a.aq.transparent,[!0,!0,!0,!1])),re.setDepthMode(new Ir(g.func===se.LESS?se.LEQUAL:g.func,Ir.ReadOnly,g.range)),re.setStencilMode(Jr.disabled);const Pe=3*L.primitiveLength*2,De=3*L.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const _e=Z||1;for(let Ze=0;Ze<_e;++Ze)ye.instancingUniforms.u_instanceID.set(this.program,"u_instanceID",Ze),se.drawElements(se.LINES,Pe,se.UNSIGNED_SHORT,De)}else Z&&Z>1?se.drawElementsInstanced(se.LINES,Pe,se.UNSIGNED_SHORT,De,Z):se.drawElements(se.LINES,Pe,se.UNSIGNED_SHORT,De);I.bind(),re.program.set(this.program),re.setDepthMode(g),re.setStencilMode(w),re.setColorMode(j)}checkUniforms(d,g,w){if(this.fixedDefines.includes(g)){for(const j of Object.keys(w))if(!w[j].initialized)throw new Error(`Program '${this.name}', from draw '${d}': uniform ${j} not set but required by ${g} being defined`)}}draw(d,g,w,j,I,L,F,z,H,Z,ne,re,se,ce,oe,ye){const ge=d.context,Pe=ge.gl;if(this.failedToCreate)return;ge.program.set(this.program),ge.setDepthMode(w),ge.setStencilMode(j),ge.setColorMode(I),ge.setCullFace(L);for(const[Me,Be]of this.fixedUniformsEntries)Be.set(this.program,Me,F[Me]);ce&&ce.setUniforms(this.program,ge,this.binderUniforms,re,{zoom:se});const De={[Pe.POINTS]:1,[Pe.LINES]:2,[Pe.TRIANGLES]:3,[Pe.LINE_STRIP]:1}[g];this.checkUniforms(z,"RENDER_SHADOWS",this.shadowUniforms);const _e=oe||[],Ze=ce?ce.getPaintVertexBuffers():[],$e=g===Pe.TRIANGLES&&Z,Ke=ye&&ye>0?1:void 0;for(const Me of ne.get()){const Be=Me.vaos||(Me.vaos={});if((Be[z]||(Be[z]=new EN)).bind(ge,this,H,Ze,Z,Me.vertexOffset,_e,Ke),this.forceManualRenderingForInstanceIDShaders){const qe=ye||1;for(let st=0;st1?Pe.drawElementsInstanced(g,Me.primitiveLength*De,Pe.UNSIGNED_SHORT,Me.primitiveOffset*De*2,ye):Z?Pe.drawElements(g,Me.primitiveLength*De,Pe.UNSIGNED_SHORT,Me.primitiveOffset*De*2):Pe.drawArrays(g,Me.vertexOffset,Me.vertexLength);$e&&this._drawDebugWireframe(d,w,j,I,Z,Me,re,se,ce,ye)}}}function FN(_,d,g=0){const w=Math.pow(2,d.tileID.overscaledZ),j=d.tileSize*Math.pow(2,_.transform.tileZoom)/w,I=j*(d.tileID.canonical.x+d.tileID.wrap*w),L=j*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:[I>>16,L>>16],u_pixel_coord_lower:[65535&I,65535&L],u_pattern_transition:g}}const rb={terrain:0,flat:1},F5=a.bb(),BN=(_,d,g,w,j,I,L,F,z,H,Z,ne,re,se,ce,oe,ye,ge,Pe=[0,0,1])=>{const De=d.style.light,_e=De.properties.get("position"),Ze=[_e.x,_e.y,_e.z],$e=a.dE();De.properties.get("anchor")==="viewport"&&(a.dF($e,-d.transform.angle),a.dG(Ze,Ze,$e));const Ke=De.properties.get("color").toPremultipliedRenderColor(null),Me=d.transform,Be={u_matrix:_,u_lightpos:Ze,u_lightintensity:De.properties.get("intensity"),u_lightcolor:[Ke.r,Ke.g,Ke.b],u_vertical_gradient:+g,u_opacity:w,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:F5,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:rb[H],u_base_type:rb[Z],u_ao:j,u_edge_radius:I,u_width_scale:L,u_flood_light_color:ce,u_vertical_scale:oe,u_flood_light_intensity:ye,u_ground_shadow_factor:ge,u_front_cutoff_params:Pe};return Me.projection.name==="globe"&&(Be.u_tile_id=[F.canonical.x,F.canonical.y,1<({u_matrix:_,u_edge_radius:d,u_width_scale:g,u_vertical_scale:w,u_height_type:rb[j],u_base_type:rb[I]}),$5=(_,d,g,w,j,I,L,F,z,H,Z,ne,re,se,ce,oe,ye,ge)=>{const Pe=BN(_,d,g,w,j,I,L,F,H,Z,ne,re,se,ce,oe,ye,1,[0,0,0]),De={u_height_factor:-Math.pow(2,F.overscaledZ)/z.tileSize/8};return Object.assign(Pe,FN(d,z,ge),De)},nb=(_,d,g)=>({u_matrix:_,u_emissive_strength:d,u_ground_shadow_factor:g}),ib=(_,d,g,w,j,I=0)=>Object.assign(nb(_,d,j),FN(g,w,I)),$N=(_,d,g,w)=>({u_matrix:_,u_world:g,u_emissive_strength:d,u_ground_shadow_factor:w}),Bg=(_,d,g,w,j,I,L=0)=>Object.assign(ib(_,d,g,w,I,L),{u_world:j}),zN=(_,d)=>({u_matrix:_,u_depth_bias:d}),UN=(_,d)=>({u_matrix:_,u_ground_shadow_factor:d}),b0=(_,d,g,w,j)=>({u_matrix:_,u_camera_pos:[d[0],d[1],d[2]],u_depth_bias:g,u_height_scale:w,u_reset_depth:j}),sb=(_,d,g)=>({u_image:_,u_opacity:d,u_blend_mode:g}),kf=(_,d,g,w,j,I,L,F,z,H=[0,0,1])=>({u_matrix:_,u_normal_matrix:d,u_opacity:g,u_faux_facade_ao_intensity:w,u_camera_pos:j,u_tile_to_meter:I,u_facade_emissive_chance:L,u_flood_light_color:F,u_flood_light_intensity:z,u_front_cutoff_params:H}),ab=_=>({u_matrix:_}),ob=_=>({u_matrix:_}),VN=(_,d,g,w,j,I,L,F)=>{const z=a.an/I.tileSize;return{u_matrix:_,u_inv_rot_matrix:d,u_camera_to_center_distance:g.getCameraToCenterDistance(F),u_extrude_scale:[g.pixelsToGLUnits[0]/z,g.pixelsToGLUnits[1]/z],u_zoom_transition:w,u_tile_id:L,u_merc_center:j}},Cf=(_,d,g,w)=>({u_matrix:_,u_inv_matrix:d,u_camera_to_center_distance:g.getCameraToCenterDistance(w),u_viewport_size:[g.width,g.height]}),w0=(_,d,g=1)=>({u_matrix:_,u_color:d,u_overlay:0,u_overlay_scale:g}),lb=a.bb(),qN=(_,d,g,w,j,I,L)=>{const F=_.transform,z=F.projection.name==="globe",H=z?a.dH(F.zoom,d.canonical)*F._pixelsPerMercatorPixel:a.aA(g,1,I),Z={u_matrix:d.projMatrix,u_extrude_scale:H,u_intensity:L,u_inv_rot_matrix:lb,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(z){Z.u_inv_rot_matrix=w,Z.u_merc_center=j,Z.u_tile_id=[d.canonical.x,d.canonical.y,1<({u_matrix:d,u_normalize_matrix:g,u_globe_matrix:w,u_merc_matrix:j,u_grid_matrix:I,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:HN(re.paint.get("raster-hue-rotate")),u_perspective_transform:se,u_raster_elevation:ce,u_zoom_transition:F,u_merc_center:z,u_cutoff_params:H,u_colorization_mix:mE(a.dK,ye,Pe),u_colorization_offset:cb(a.dK,ge,Pe),u_color_ramp:oe,u_texture_offset:[_e/(De+2*_e),De/(De+2*_e)],u_texture_res:[De+2*_e,De+2*_e],u_emissive_strength:Ze,u_zbias_factor:pE(_)});function HN(_){_*=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 Rd=.05,z5=(_,d,g,w,j,I,L,F,z,H,Z,ne)=>({u_matrix:_,u_normalize_matrix:d,u_globe_matrix:g,u_merc_matrix:w,u_grid_matrix:j,u_tl_parent:I,u_scale_parent:H,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:F,u_cutoff_params:z}),U5=(_,d,g,w,j,I,L,F,z,H)=>({u_particle_texture:_,u_particle_texture_side_len:d,u_tile_offset:g,u_velocity:w,u_color_ramp:I,u_velocity_res:j,u_max_speed:L,u_uv_offset:F,u_data_scale:[255*z[0],255*z[1]],u_data_offset:H,u_particle_pos_scale:1.1,u_particle_pos_offset:[Rd,Rd]}),WN=(_,d,g,w,j,I,L,F,z,H)=>({u_particle_texture:_,u_particle_texture_side_len:d,u_velocity:g,u_velocity_res:w,u_max_speed:j,u_speed_factor:I,u_reset_rate:L,u_rand_seed:Math.random(),u_uv_offset:F,u_data_scale:[255*z[0],255*z[1]],u_data_offset:H,u_particle_pos_scale:1.1,u_particle_pos_offset:[Rd,Rd]}),KN=a.bb(),ub=(_,d,g,w,j,I,L,F,z,H,Z,ne,re,se,ce,oe,ye,ge,Pe,De,_e,Ze,$e,Ke)=>{const Me=j.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:Me.getCameraToCenterDistance(Pe),u_rotate_symbol:+g,u_aspect_ratio:Me.width/Me.height,u_fade_change:j.options.fadeDuration?j.symbolFadeChange:1,u_matrix:I,u_label_plane_matrix:L,u_coord_matrix:F,u_is_text:+H,u_elevation_from_sea:z?1:0,u_pitch_with_map:+w,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:KN,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:KN,u_up_vector:[0,-1,0],u_color_adj_mat:Ze,u_icon_transition:$e||0,u_gamma_scale:w?j.transform.getCameraToCenterDistance(Pe)*Math.cos(j.terrain?0:j.transform._pitch):1,u_device_pixel_ratio:a.o.devicePixelRatio,u_is_halo:1,u_scale_factor:Ke||1,u_ground_shadow_factor:De,u_inv_matrix:a.b7(a.bb(),L),u_normal_scale:_e,u_lutTexture:10,u_zoom:Me.zoom-Math.floor(Me.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 Pe.name==="globe"&&(Be.u_tile_id=[se.canonical.x,se.canonical.y,1<({u_matrix:_,u_emissive_strength:d,u_opacity:g,u_color:w}),Nf=(_,d,g,w,j,I,L,F,z)=>Object.assign(function(H,Z,ne,re,se,ce){const{width:oe,height:ye}=re.imageManager.getPixelSize(Z),ge=Math.pow(2,ce.tileID.overscaledZ),Pe=ce.tileSize*Math.pow(2,re.transform.tileZoom)/ge,De=Pe*(ce.tileID.canonical.x+ce.tileID.wrap*ge),_e=Pe*ce.tileID.canonical.y;return{u_image:0,u_pattern_tl:ne.tl,u_pattern_br:ne.br,u_texsize:[oe,ye],u_pattern_size:ne.displaySize,u_pattern_units_to_pixels:se?[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:[De>>16,_e>>16],u_pixel_coord_lower:[65535&De,65535&_e]}}(0,I,L,w,F,z),{u_matrix:_,u_emissive_strength:d,u_opacity:g}),$g=new Float32Array(a.b9([])),Zm=(_,d,g,w,j,I,L,F,z,H,Z,ne,re,se=[0,0,0],ce,oe,ye)=>{const ge=j.style.light,Pe=ge.properties.get("position"),De=[-Pe.x,-Pe.y,Pe.z],_e=a.dE();ge.properties.get("anchor")==="viewport"&&(a.dF(_e,-j.transform.angle),a.dG(De,De,_e));const Ze=Z.alphaMode==="MASK",$e=ge.properties.get("color").toNonPremultipliedRenderColor(null),Ke=re.paint.get("model-ambient-occlusion-intensity"),Me=re.paint.get("model-color").constantOr(a.aq.white).toNonPremultipliedRenderColor(null);return Me.a=re.paint.get("model-color-mix-intensity").constantOr(0),ye&&(Me.r=ye[0],Me.g=ye[1],Me.b=ye[2],Me.a=ye[3]),oe&&(Me.r=oe.color.r,Me.g=oe.color.g,Me.b=oe.color.b,Me.a=oe.colorMix,ne=oe.emissionStrength,I*=oe.opacity),{u_matrix:_,u_lighting_matrix:d,u_normal_matrix:g,u_node_matrix:w||$g,u_lightpos:De,u_lightintensity:ge.properties.get("intensity"),u_lightcolor:[$e.r,$e.g,$e.b],u_camera_pos:se,u_opacity:I,u_baseTextureIsAlpha:0,u_alphaMask:+Ze,u_alphaCutoff:Z.alphaCutoff,u_baseColorFactor:L.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:F.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:z,u_roughnessFactor:H,u_baseColorTexture:5,u_metallicRoughnessTexture:6,u_normalTexture:7,u_occlusionTexture:8,u_emissionTexture:9,u_lutTexture:10,u_color_mix:Me.toArray01(),u_aoIntensity:Ke,u_emissive_strength:ne,u_occlusionTextureTransform:ce||[0,0,0,0]}},gE=(_,d=$g,g=$g)=>({u_matrix:_,u_instance:d,u_node_matrix:g}),db={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 Wu{constructor(d,g,w,j){this.id=Wu.uniqueIdxCounter,Wu.uniqueIdxCounter++,this.context=d;const I=d.gl;this.buffer=I.createBuffer(),this.dynamicDraw=!!w,this.context.unbindVAO(),d.bindElementBuffer.set(this.buffer),I.bufferData(I.ELEMENT_ARRAY_BUFFER,g.arrayBuffer,this.dynamicDraw?I.DYNAMIC_DRAW:I.STATIC_DRAW),this.dynamicDraw||j||g.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(d){this.id=Wu.uniqueIdxCounter,Wu.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)}}Wu.uniqueIdxCounter=0;const yE={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class YN{constructor(d,g,w,j,I,L){this.length=g.length,this.attributes=w,this.itemSize=g.bytesPerElement,this.dynamicDraw=j,this.instanceCount=L,this.context=d;const F=d.gl;this.buffer=F.createBuffer(),d.bindVertexBuffer.set(this.buffer),F.bufferData(F.ARRAY_BUFFER,g.arrayBuffer,this.dynamicDraw?F.DYNAMIC_DRAW:F.STATIC_DRAW),this.dynamicDraw||I||g.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(d){const g=this.context.gl;this.bind(),g.bufferSubData(g.ARRAY_BUFFER,0,d.arrayBuffer)}enableAttributes(d,g){for(const w of this.attributes){const j=g.getAttributeLocation(d,w.name);j!==-1&&d.enableVertexAttribArray(j)}}setVertexAttribPointers(d,g,w){for(const j of this.attributes){const I=g.getAttributeLocation(d,j.name);if(I!==-1){const L=j.offset+this.itemSize*(w||0);j.type==="Float32"?d.vertexAttribPointer(I,j.components,d.FLOAT,!1,this.itemSize,L):d.vertexAttribIPointer(I,j.components,d[yE[j.type]],this.itemSize,L)}}}setVertexAttribDivisor(d,g,w){for(let j=0;j0&&d.vertexAttribDivisor(I,w)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class T0{constructor(d,g,w,j,I){this.context=d,this.width=g,this.height=w;const L=this.framebuffer=d.gl.createFramebuffer();j>0&&(this.colorAttachment0=new Og(d,L,0)),j>1&&(this.colorAttachment1=new Og(d,L,1)),I&&(this.depthAttachmentType=I,this.depthAttachment=I==="renderbuffer"?new uE(d,L):new DN(d,L))}static createWithTexture(d,g,w,j,I){const L=d.gl;if(d.activeTexture.set(L.TEXTURE1),d.viewport.set([0,0,w,j]),g&&g.width===w&&g.height===j)return L.bindTexture(L.TEXTURE_2D,g.colorAttachment0.get()),d.bindFramebuffer.set(g.framebuffer),g;g&&g.destroy();const F=new a.T(d,{width:w,height:j,data:null},d.extRenderToTextureHalfFloat?d.gl.RGBA16F:d.gl.RGBA8);F.bind(L.LINEAR,L.CLAMP_TO_EDGE);const z=d.createFramebuffer(w,j,1,null);if(z.colorAttachment0.set(F.texture),I){const H=d.createRenderbuffer(L.DEPTH24_STENCIL8,w,j);d.bindFramebuffer.set(z.framebuffer),L.framebufferRenderbuffer(L.FRAMEBUFFER,L.DEPTH_STENCIL_ATTACHMENT,L.RENDERBUFFER,H),z._stencilRbo=H}return z}createColorAttachment(d,g){g===0?this.colorAttachment0=new Og(d,this.framebuffer,0):g===1&&(this.colorAttachment1=new Og(d,this.framebuffer,1))}removeColorAttachment(d,g){const w=this.context.gl;let j;g===0?(j=this.colorAttachment0.get(),this.colorAttachment0=void 0):g===1&&(j=this.colorAttachment1.get(),this.colorAttachment1=void 0),j&&w.deleteTexture(j)}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 zg{constructor(d,g){this.gl=d,this.clearColor=new AN(this),this.clearDepth=new P5(this),this.clearStencil=new W_(this),this.colorMask=new R5(this),this.depthMask=new kN(this),this.stencilMask=new iE(this),this.stencilFunc=new K_(this),this.stencilOp=new sE(this),this.stencilTest=new Wm(this),this.depthRange=new Km(this),this.depthTest=new Lg(this),this.depthFunc=new Pd(this),this.blend=new CN(this),this.blendFunc=new aE(this),this.blendColor=new NN(this),this.blendEquation=new Dg(this),this.cullFace=new Y_(this),this.cullFaceSide=new Z_(this),this.frontFace=new oE(this),this.program=new X_(this),this.activeTexture=new f0(this),this.viewport=new IN(this),this.bindFramebuffer=new PN(this),this.bindRenderbuffer=new RN(this),this.bindTexture=new Mg(this),this.bindVertexBuffer=new LN(this),this.bindElementBuffer=new L5(this),this.bindVertexArrayOES=new D5(this),this.pixelStoreUnpack=new M5(this),this.pixelStoreUnpackPremultiplyAlpha=new lE(this),this.pixelStoreUnpackFlipY=new cE(this),this.options=g?Object.assign({},g):{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=d.getExtension("EXT_texture_filter_anisotropic")||d.getExtension("MOZ_EXT_texture_filter_anisotropic")||d.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=d.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=d.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=d.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=d.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=g&&!!g.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.indexOf("PowerVR")!==-1,this.disableSymbolUBO=g&&!!g.forceDisableSymbolUBO,this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=d.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=d.getExtension("EXT_color_buffer_half_float"),this.extTimerQuery=d.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=d.getParameter(d.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(d.getParameter(d.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=d.getParameter(d.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=d.getExtension("WEBGL_blend_func_extended")}setDefault(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault()}setDirty(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.bindVertexArrayOES.dirty=!0,this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0}createIndexBuffer(d,g,w){return new Wu(this,d,g,w)}createVertexBuffer(d,g,w,j,I){return new YN(this,d,g,w,j,I)}createRenderbuffer(d,g,w){const j=this.gl,I=j.createRenderbuffer();return this.bindRenderbuffer.set(I),j.renderbufferStorage(j.RENDERBUFFER,d,g,w),this.bindRenderbuffer.set(null),I}createFramebuffer(d,g,w,j){return new T0(this,d,g,w,j)}clear({color:d,depth:g,stencil:w,colorMask:j}){const I=this.gl;let L=0;d&&(L|=I.COLOR_BUFFER_BIT,this.clearColor.set(d.toNonPremultipliedRenderColor(null)),this.colorMask.set(j||[!0,!0,!0,!0])),g!==void 0&&(L|=I.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(g),this.depthMask.set(!0)),w!==void 0&&(L|=I.STENCIL_BUFFER_BIT,this.clearStencil.set(w),this.stencilMask.set(255)),I.clear(L)}setCullFace(d){d.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(d.mode),this.frontFace.set(d.frontFace))}setDepthMode(d){d.func!==this.gl.ALWAYS||d.mask?(this.depthTest.set(!0),this.depthFunc.set(d.func),this.depthMask.set(d.mask),this.depthRange.set(d.range)):this.depthTest.set(!1)}setStencilMode(d){d.test.func!==this.gl.ALWAYS||d.mask?(this.stencilTest.set(!0),this.stencilMask.set(d.mask),this.stencilOp.set([d.fail,d.depthFail,d.pass]),this.stencilFunc.set({func:d.test.func,ref:d.ref,mask:d.test.mask})):this.stencilTest.set(!1)}setColorMode(d){a.b6(d.blendFunction,Yr.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 Xm;function br(_,d,g,w,j,I,L){const F=_.context,z=F.gl,H=_.transform,Z=[a.aH(H.center.lng),a.aL(H.center.lat)],ne=g.layout.get("symbol-placement"),re=g.layout.get("text-variable-anchor"),se=g.layout.get("icon-rotation-alignment")==="map",ce=g.layout.get("text-rotation-alignment")==="map",oe=ne!=="point",ye=[];let ge=0,Pe=0;for(let Me=0;Me0){const Lr=a.bb(),yr=Wt;a.cz(Lr,st.placementInvProjMatrix,H.glCoordMatrix),a.cz(Lr,Lr,st.placementViewportMatrix),ye.push({circleArray:Mt,circleOffset:Pe,transform:yr,invTransform:Lr,projection:st.getProjection()}),ge+=Mt.length/4,Pe=ge}if(!Kt)continue;_.terrain&&_.terrain.setupElevationDraw(qe,nr);const kr=bt?[Be.canonical.x,Be.canonical.y,1<=0&&(se[De.associatedIconIndex]={x:Qe,y:xt,z:ft,angle:gt})}else jg($e,ne)}if(H){re.clear();const Pe=_.icon.placedSymbolArray;for(let De=0;De{let ln=[0,0,0];if(ti){const Yi=_.style.directionalLight,Si=_.style.ambientLight;Yi&&Si&&(ln=Gu(_.style,Yi,Si))}return ln},wn=ti=>{if(_.context.disableSymbolUBO)return;ti.push("USE_PAINT_PROPERTIES_UBO");const ln=Math.floor(_.context.maxUniformBlockSize/4),Yi=Math.floor(ln/4);ti.push(`MAX_UBO_SIZE_VEC4 ${Yi}u`)},rn=ti=>{Be.depthOcclusionForSymbolsAndCircles&&(g.hasOcclusionOpacityProperties||_.terrain)&&(ti.push("DEPTH_D24"),ti.push("DEPTH_OCCLUSION"))},Gn=ti=>{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),ti.push("APPLY_LUT_ON_GPU"))},wi=()=>{const ti=qe&&g.layout.get("symbol-placement")!=="point",ln=[];rn(ln),Gn(ln);const Yi=ti||an,Si=Mt.elevationType==="road",Bs=_.shadowRenderer,In=Si&&Qe&&!!Bs&&Bs.enabled,ji=Ur(In),ta=Si&&Qe&&!_.terrain?ot:Ft,Eo=g.paint.get("icon-image-cross-fade");_.terrainRenderModeElevated()&&Qe&&ln.push("PITCH_WITH_MAP_TERRAIN"),kr&&(ln.push("PROJECTION_GLOBE_VIEW"),Yi&&ln.push("PROJECTED_POS_ON_VIEWPORT")),Eo>0&&Mt.hasAnySecondaryIcon&&ln.push("ICON_TRANSITION"),!Mt.icon.zOffsetVertexBuffer||Si&&_.terrain||ln.push("Z_OFFSET"),ge===0&&Pe===0&&De===0&&_e===1||ln.push("COLOR_ADJUSTMENT"),Mt.sdfIcons&&ln.push("RENDER_SDF"),In&&ln.push("RENDER_SHADOWS","NORMAL_OFFSET"),Si&&Qe&&!_.terrain&&Mt.icon.orientationVertexBuffer&&ln.push("ELEVATED_ROADS"),wn(ln);const fa=Ke.disableSymbolUBO?Mt.icon.programConfigurations.get(g.id):null,Ha=_.getOrCreateProgram("symbol",{config:fa,defines:ln}),pc=Kt.imageAtlasTexture?Kt.imageAtlasTexture.size:[0,0],li=Mt.iconSizeData,Lc=a.bj(li,Be.zoom),Dc=Qe||!Be.isOrthographic,Oi=wf(yr,Kt.tileID.canonical,Qe,qe,Be,Mt.getProjection(),Er),Vi=Eg(yr,Kt.tileID.canonical,Qe,qe,Be,Mt.getProjection(),Er),yi=Mt.icon.uboBinder&&Mt.icon.uboBinder.cachedHeader&&256&Mt.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:F,Ns=_.translatePosMatrix(Vi,Kt,yi,H,!0),Bo=_.translatePosMatrix(yr,Kt,yi,H),hs=Yi?E0:Oi,gc=qe&&!Qe&&!ti;let Pf=nr;!bt&&!Be.mercatorFromTransition||qe||(Pf=Th(Be));const sp=kr?Pf:nr,ap=g.getColorAdjustmentMatrix(ge,Pe,De,_e),Wg=ub(li.kind,Lc,gc,Qe,_,Bo,hs,Ns,Ze,!1,pc,[0,0],0,Wt,Lr,et,tn,sp,Mt.getProjection(),ji,bn,ap,Eo,null),Nh=Kt.imageAtlasTexture?Kt.imageAtlasTexture:null,Fd=g.layout.get("icon-size").constantOr(0)!==1||Mt.iconsNeedLinear,Kg=Mt.sdfIcons||_.options.rotating||_.options.zooming||Fd||Dc?Me.LINEAR:Me.NEAREST,Ul=Mt.sdfIcons&&g.paint.get("icon-halo-width").constantOr(1)!==0,Rf=_.terrain&&Qe&&ti?a.b7(a.bb(),Oi):E0;if(ti&&Mt.icon){const Lf=a.bu.getAtTileOffsetFunc(Wt,Be.center.lat,Be.worldSize,Mt.getProjection()),Df=Uu(yr,Kt.tileID.canonical,Qe,qe,Be,Mt.getProjection(),Er),Db=g.layout.get("icon-size-scale-range"),Yg=a.aC(_.scaleFactor,Db[0],Db[1]);hc(Mt,yr,_,!1,Df,Vi,Qe,oe,Lf,Wt,Yg)}return{program:Ha,buffers:Mt.icon,uniformValues:Wg,atlasTexture:Nh,atlasTextureIcon:null,atlasInterpolation:Kg,atlasInterpolationIcon:null,isSDF:Mt.sdfIcons,hasHalo:Ul,depthMode:ta,tile:Kt,renderWithShadows:In,labelPlaneMatrixInv:Rf}},Xi=()=>{const ti=st&&g.layout.get("symbol-placement")!=="point",ln=[],Yi=ti||gt||an,Si=Mt.elevationType==="road",Bs=_.shadowRenderer,In=Si&&xt&&!!Bs&&Bs.enabled,ji=Ur(In),ta=Si&&xt&&!_.terrain?ot:Ft;_.terrainRenderModeElevated()&&xt&&ln.push("PITCH_WITH_MAP_TERRAIN"),kr&&(ln.push("PROJECTION_GLOBE_VIEW"),Yi&&ln.push("PROJECTED_POS_ON_VIEWPORT")),!Mt.text.zOffsetVertexBuffer||Si&&_.terrain||ln.push("Z_OFFSET"),Mt.iconsInText&&ln.push("RENDER_TEXT_AND_SYMBOL"),ln.push("RENDER_SDF"),In&&ln.push("RENDER_SHADOWS","NORMAL_OFFSET"),Si&&xt&&!_.terrain&&Mt.text.orientationVertexBuffer&&ln.push("ELEVATED_ROADS"),rn(ln),wn(ln);const Eo=Ke.disableSymbolUBO?Mt.text.programConfigurations.get(g.id):null,fa=_.getOrCreateProgram("symbol",{config:Eo,defines:ln});let Ha,pc=[0,0],li=null;const Lc=Mt.textSizeData;Mt.iconsInText&&(pc=Kt.imageAtlasTexture?Kt.imageAtlasTexture.size:[0,0],li=Kt.imageAtlasTexture?Kt.imageAtlasTexture:null,Ha=xt||!Be.isOrthographic||_.options.rotating||_.options.zooming||Lc.kind==="composite"||Lc.kind==="camera"?Me.LINEAR:Me.NEAREST);const Dc=Kt.glyphAtlasTexture?Kt.glyphAtlasTexture.size:[0,0],Oi=g.layout.get("text-size-scale-range"),Vi=a.aC(_.scaleFactor,Oi[0],Oi[1]),yi=a.bj(Lc,Be.zoom,Vi),Ns=wf(yr,Kt.tileID.canonical,xt,st,Be,Mt.getProjection(),Er),Bo=Eg(yr,Kt.tileID.canonical,xt,st,Be,Mt.getProjection(),Er),hs=Mt.text.uboBinder&&Mt.text.uboBinder.cachedHeader&&256&Mt.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:z,gc=_.translatePosMatrix(Bo,Kt,hs,Z,!0),Pf=_.translatePosMatrix(yr,Kt,hs,Z),sp=Yi?E0:Ns,ap=st&&!xt&&!ti;let Wg=nr;!bt&&!Be.mercatorFromTransition||st||(Wg=Th(Be));const Nh=ub(Lc.kind,yi,ap,xt,_,Pf,sp,gc,Ze,!0,Dc,pc,0,Wt,Lr,et,tn,kr?Wg:nr,Mt.getProjection(),ji,bn,null,null,Vi),Fd=Kt.glyphAtlasTexture?Kt.glyphAtlasTexture:null,Kg=Me.LINEAR,Ul=g.paint.get("text-halo-width").constantOr(1)!==0,Rf=_.terrain&&xt&&ti?a.b7(a.bb(),Ns):E0;if(ti&&Mt.text){const Lf=a.bu.getAtTileOffsetFunc(Wt,Be.center.lat,Be.worldSize,Mt.getProjection()),Df=Uu(yr,Kt.tileID.canonical,xt,st,Be,Mt.getProjection(),Er);hc(Mt,yr,_,!0,Df,Bo,xt,ye,Lf,Wt,Vi)}return{program:fa,buffers:Mt.text,uniformValues:Nh,atlasTexture:Fd,atlasTextureIcon:li,atlasInterpolation:Kg,atlasInterpolationIcon:Ha,isSDF:!0,hasHalo:Ul,depthMode:ta,tile:Kt,renderWithShadows:In,labelPlaneMatrixInv:Rf}},Ni=Mt.icon.segments.get().length,ei=Mt.text.segments.get().length,gn=Ni&&!L.onlyText?wi():null,yn=ei&&!L.onlyIcons?Xi():null,Ii=g.paint.get("icon-opacity").constantOr(1),ns=g.paint.get("text-opacity").constantOr(1);if(ft&&Mt.canOverlap){Lt=!0;const ti=Ii&&!L.onlyText?Mt.icon.segments.get():[],ln=ns&&!L.onlyIcons?Mt.text.segments.get():[];for(const Yi of ti)St.push({segments:new a.dy([Yi]),sortKey:Yi.sortKey,state:gn});for(const Yi of ln)St.push({segments:new a.dy([Yi]),sortKey:Yi.sortKey,state:yn})}else L.onlyText||St.push({segments:Ii?Mt.icon.segments:new a.dy([]),sortKey:0,state:gn}),L.onlyIcons||St.push({segments:ns?Mt.text.segments:new a.dy([]),sortKey:0,state:yn})}Lt&&St.sort((Wt,Kt)=>Wt.sortKey-Kt.sortKey);for(const Wt of St){const Kt=Wt.state;if(Kt)if(_.terrain?_.terrain.setupElevationDraw(Kt.tile,Kt.program,{useDepthForOcclusion:Be.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:Kt.labelPlaneMatrixInv}):_.setupDepthForOcclusion(Be.depthOcclusionForSymbolsAndCircles,Kt.program),Ke.activeTexture.set(Me.TEXTURE0),Kt.atlasTexture&&Kt.atlasTexture.bind(Kt.atlasInterpolation,Me.CLAMP_TO_EDGE,!0),Kt.atlasTextureIcon&&(Ke.activeTexture.set(Me.TEXTURE1),Kt.atlasTextureIcon&&Kt.atlasTextureIcon.bind(Kt.atlasInterpolationIcon,Me.CLAMP_TO_EDGE,!0)),Kt.renderWithShadows&&_.shadowRenderer.setupShadows(Kt.tile.tileID.toUnwrapped(),Kt.program,"vector-tile"),_.uploadCommonLightUniforms(_.context,Kt.program),Kt.hasHalo){const Mt=Kt.uniformValues;Mt.u_is_halo=1,fb(Kt.buffers,Wt.segments,g,_,Kt.program,Kt.depthMode,j,I,Mt,2),Mt.u_is_halo=0}else{if(Kt.isSDF){const Mt=Kt.uniformValues;Kt.hasHalo&&(Mt.u_is_halo=1,fb(Kt.buffers,Wt.segments,g,_,Kt.program,Kt.depthMode,j,I,Mt,1)),Mt.u_is_halo=0}fb(Kt.buffers,Wt.segments,g,_,Kt.program,Kt.depthMode,j,I,Kt.uniformValues,1)}}}function fb(_,d,g,w,j,I,L,F,z,H){const Z=w.context,ne=Z.gl,re=[_.dynamicLayoutVertexBuffer,_.opacityVertexBuffer,_.iconTransitioningVertexBuffer,_.globeExtVertexBuffer,_.zOffsetVertexBuffer,_.orientationVertexBuffer];_.featureIdBuffer&&re.push(_.featureIdBuffer);const se=_.uboBinder?null:_.programConfigurations.get(g.id);if(_.uboBinder){_.uboBinder.layer=g;const ye=w.transform.zoom,ge=w.style.getBrightness?w.style.getBrightness():null,Pe=_.uboBinder.getConstantUniformValues(ye,ge);z.u_spp_fill_np_color=Pe.fill_np_color,z.u_spp_halo_np_color=Pe.halo_np_color,z.u_spp_opacity=Pe.opacity,z.u_spp_halo_width=Pe.halo_width,z.u_spp_halo_blur=Pe.halo_blur,z.u_spp_emissive_strength=Pe.emissive_strength,z.u_spp_occlusion_opacity=Pe.occlusion_opacity,z.u_spp_z_offset=Pe.z_offset;const De=g.paint.get(_.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),_e=_.uboBinder.cachedHeader&&256&_.uboBinder.cachedHeader.dataDrivenMask&&De==="map"?w.transform.angle:0;z.u_spp_translate_rotation=[Math.cos(_e),Math.sin(_e)]}const{batchIndices:ce,batchSegments:oe}=_.getBatchGrouping(d);for(const ye of ce){const ge=oe.get(ye);_.uboBinder&&_.uboBinder.bind(Z,j.program,ye),j.draw(w,ne.TRIANGLES,I,L,F,Gr.disabled,z,g.id,_.layoutVertexBuffer,_.indexBuffer,ge,g.paint,w.transform.zoom,se,re,H)}}function mb(_,d,g,w,j,I){const L=g.paint.get("line-width"),F=g.paint.get("line-emissive-strength").isConstant(),z=g.paint.get("line-emissive-strength").constantOr(0),H=g.paint.get("line-occlusion-opacity"),Z=g.layout.get("line-elevation-reference"),ne=g.layout.get("line-width-unit")==="meters",re=Z==="sea",se=!(!_.terrain||!_.terrain.enabled),ce=_.context,oe=ce.gl;if(g.hasElevatedBuckets&&_.transform.projection.name==="globe")return;const ye=g.layout.get("line-cross-slope"),ge=ye!==void 0,Pe=ye<1,De=j||_.colorModeForDrapableLayerRenderPass(F?z:null),_e=_.terrain&&_.terrain.renderingToTexture||I,Ze=_e?1:a.o.devicePixelRatio,$e=g.paint.get("line-dasharray"),Ke=$e.constantOr(1),Me=g.layout.get("line-cap"),Be=$e.constantOr(null),qe=Me.constantOr(null),st=g.paint.get("line-pattern"),Qe=st.constantOr(1),xt=g.paint.get("line-pattern-cross-fade"),ft=st.constantOr(null),Lt=g.paint.get("line-opacity").constantOr(1);let Ft=!Qe&&Lt!==1||_.depthOcclusion&&H>0&&H<1;const ot=g.paint.get("line-gradient"),et=Qe?"linePattern":"line",gt=a.dU(g);let bt;if(_e&&_.terrain&&_.terrain.clipOrMaskOverlapStencilType()&&(Ft=!1),H!==0&&_.depthOcclusion){const Mt=g.paint._values["line-opacity"];Mt&&Mt.value&&Mt.value.kind==="constant"?bt=Mt.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&>.push("VARIABLE_LINE_WIDTH"),_e&&(_.emissiveMode!=="dual-source-blending"||F?_.emissiveMode==="mrt-fallback"&>.push("USE_MRT1"):gt.push("DUAL_SOURCE_BLENDING"));const St={},nr=(Mt,kr,Lr,yr,Er,Hr)=>{for(const an of Mt){const tn=d.getTile(an);if(Qe&&!tn.patternsLoaded())continue;const bn=tn.getBucket(g);if(!bn||bn.elevationType!=="none"&&!Er||bn.elevationType==="none"&&Er)continue;_.prepareDrawTile();const Ur=[...kr],wn=_.shadowRenderer,rn=bn.elevationType==="road"&&!!wn&&wn.enabled;let Gn=[0,0,0];if(rn){const In=_.style.directionalLight,ji=_.style.ambientLight;In&&ji&&(Gn=Gu(_.style,In,ji)),Ur.push("RENDER_SHADOWS","NORMAL_OFFSET")}const wi=bn.programConfigurations.get(g.id);let Xi=!1;if(ft&&tn.imageAtlas){const In=a.dV.from(ft),ji=In.getPrimary().scaleSelf(Ze).toString(),ta=tn.imageAtlas.patternPositions.get(ji),Eo=In.getSecondary(),fa=Eo?tn.imageAtlas.patternPositions.get(Eo.scaleSelf(Ze).toString()):null;Xi=!!ta&&!!fa,ta&&wi.setConstantPatternPositions(ta,fa)}xt>0&&(Xi||wi.getPatternTransitionVertexBuffer("line-pattern"))&&Ur.push("LINE_PATTERN_TRANSITION"),bn.elevationGroundScaleVertexBuffer&&Ur.push("ELEVATION_GROUND_SCALE");const Ni=_.isTileAffectedByFog(an),ei=_.getOrCreateProgram(et,{config:wi,defines:Ur,overrideFog:Ni});if(!Qe&&Be&&qe&&tn.lineAtlas){const In=tn.lineAtlas.getDash(Be,qe);In&&wi.setConstantPatternPositions(In)}rn&&wn.setupShadows(tn.tileID.toUnwrapped(),ei,"vector-tile");let[gn,yn]=g.paint.get("line-trim-offset");(qe==="round"||qe==="square")&&gn!==yn&&(gn===0&&(gn-=1),yn===1&&(yn+=1));const Ii=_e?an.projMatrix:null,ns=ne?1/bn.tileToMeter/a.aA(tn,1,_.transform.zoom):1,ti=ne?1/bn.tileToMeter/a.aA(tn,1,Math.floor(_.transform.zoom)):1,ln=Ke?g.paint._values["line-floorwidth"]:null;let Yi;if(ln&&ln.value.kind==="constant"){const In=bn.zoom;In in St||(St[In]=Math.max(.01,g.widthExpression().evaluate({zoom:In}))),Yi=ln.value.value;const ji=Math.floor(_.transform.zoom);ln.value.value=St[In]*Math.pow(2,ji-tn.tileID.overscaledZ)}const Si=Qe?a.dW(_,tn,g,Ii,Ze,ns,ti,[gn,yn],Gn,xt):a.dX(_,tn,g,Ii,bn.lineClipsArray.length,Ze,ns,ti,[gn,yn],Gn);if(ot){const In=bn.gradients[g.id];let ji=In.texture;if(g.gradientVersion!==In.version){let ta=256;if(g.stepInterpolant){const Eo=d.getSource().maxzoom,fa=an.canonical.z===Eo?Math.ceil(1<<_.transform.maxZoom-an.canonical.z):1;ta=a.aC(a.dY(bn.maxLineLength/a.an*1024*fa),256,ce.maxTextureSize)}In.gradient=a.dZ({expression:g.gradientExpression(),evaluationKey:"lineProgress",resolution:ta,image:In.gradient||void 0,clips:bn.lineClipsArray}),In.texture?In.texture.update(In.gradient):In.texture=new a.T(ce,In.gradient,oe.RGBA8),In.version=g.gradientVersion,ji=In.texture}ce.activeTexture.set(oe.TEXTURE1),ji.bind(g.stepInterpolant?oe.NEAREST:oe.LINEAR,oe.CLAMP_TO_EDGE)}Ke&&(ce.activeTexture.set(oe.TEXTURE0),tn.lineAtlasTexture&&tn.lineAtlasTexture.bind(oe.LINEAR,oe.REPEAT),wi.updatePaintBuffers()),Qe&&(ce.activeTexture.set(oe.TEXTURE0),tn.imageAtlasTexture&&tn.imageAtlasTexture.bind(oe.LINEAR,oe.CLAMP_TO_EDGE),wi.updatePaintBuffers()),Er&&_.terrain.setupElevationDraw(tn,ei),_.uploadCommonUniforms(ce,ei,an.toUnwrapped());const Bs=In=>{bt!=null&&(bt.value=Lt*H),ei.draw(_,oe.TRIANGLES,Lr,In,De,Gr.disabled,Si,g.id,bn.layoutVertexBuffer,bn.indexBuffer,bn.segments,g.paint,_.transform.zoom,wi,[bn.layoutVertexBuffer2,bn.patternVertexBuffer,bn.zOffsetVertexBuffer,bn.elevationGroundScaleVertexBuffer]),bt!=null&&(bt.value=Lt)};if(Ft&&!Er){const In=_.stencilModeForClipping(an).ref;In===0&&_e&&ce.clear({stencil:0});const ji={func:oe.EQUAL,mask:255};Si.u_alpha_discard_threshold=.8,Bs(new Jr(ji,In,255,oe.KEEP,oe.KEEP,oe.INVERT)),Si.u_alpha_discard_threshold=0,Bs(new Jr(ji,In,255,oe.KEEP,oe.KEEP,oe.KEEP))}else Si.u_alpha_discard_threshold=Ft&&Er&&Hr?.8:0,Bs(Er?yr:_.stencilModeForClipping(an));Yi!==void 0&&(ln.value.value=Yi)}};let Wt=_.depthModeForSublayer(0,Ir.ReadOnly);const Kt=new Ir(_.depthOcclusion?oe.GREATER:oe.LEQUAL,Ir.ReadOnly,_.depthRangeFor3D);if(g.hasNonElevatedBuckets){const Mt=!_e&&_.terrain;H!==0&&Mt?a.w(`Occlusion opacity for layer ${g.id} is supported on terrain only if the layer has line-z-offset enabled.`):Mt?a.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${g.id}.`):nr(w,gt,Wt,Jr.disabled,!1,!0)}if(g.hasElevatedBuckets){Z==="hd-road-markup"?se||(Wt=Kt,gt.push("ELEVATED_ROADS")):(gt.push("ELEVATED"),Wt=Kt,ge&>.push(Pe?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),re&>.push("ELEVATION_REFERENCE_SEA"));const Mt=Ft?_.stencilModeFor3D():Jr.disabled;_.forceTerrainMode=!0,nr(w,gt,Wt,Mt,!0,!0),Ft&&nr(w,gt,Wt,Mt,!0,!1),_.forceTerrainMode=!1}Ft&&(_.resetStencilClippingMasks(),_e&&ce.clear({stencil:0})),H===0||_.depthOcclusion||_e||_.layersWithOcclusionOpacity.push(_.currentLayer)}const Eh={additive:{clearColor:new a.aq(0,0,0,0),colorMode:Yr.additive,compositeUniformValue:1},multiply:{clearColor:new a.aq(1,1,1,1),colorMode:Yr.multiply,compositeUniformValue:0}};function xE(_,d){const g=1<<_.canonical.z,w=(d.x*g-_.canonical.x-_.wrap*g)*a.an,j=(d.y*g-_.canonical.y)*a.an,I=a.d_(d.z,d.y);return a.cQ(w,j,I)}function j0(_,d,g,w,j){if(!g.layout||g.layout.get("fill-elevation-reference")==="none"||g.paint.get("fill-opacity").constantOr(1)===0)return;const I=_.context.gl,L=new Ir(_.context.gl.LEQUAL,Ir.ReadWrite,_.depthRangeFor3D),F=new Ir(_.context.gl.GREATER,Ir.ReadWrite,_.depthRangeFor3D),z=function(se){let ce=.01;return se.isOrthographic&&(ce=a.am(1e-4,ce,a.cL(se.pitch>=qm?1:se.pitch/qm))),2*ce}(_.transform),H=_.transform.getFreeCameraOptions().position,Z="elevatedStructuresDepthReconstruct",ne=_.getOrCreateProgram(Z,{defines:["DEPTH_RECONSTRUCTION"]}),re=_.getOrCreateProgram(Z);for(const se of w){const ce=d.getTile(se),oe=ce.getBucket(g);if(!oe)continue;const ye=oe.elevatedStructures;if(!ye)continue;const ge=oe.elevationBufferData.heightRange,Pe=xE(se.toUnwrapped(),H),De=_.translatePosMatrix(se.projMatrix,ce,g.paint.get("fill-translate"),g.paint.get("fill-translate-anchor"));let _e,Ze,$e,Ke;if(j==="initialize"){if(!ge||ge.min>=1||ye.depthSegments.segments[0].primitiveLength===0)continue;_e=b0(De,Pe,z,1,0),Ze=L,$e=ye.depthSegments,Ke=ne}else if(j==="reset"){if(!ge||ge.min>=0||ye.maskSegments.segments[0].primitiveLength===0)continue;_e=b0(De,Pe,0,0,1),Ze=F,$e=ye.maskSegments,Ke=ne}else if(j==="geometry"){if(ye.depthSegments.segments[0].primitiveLength===0)continue;_e=b0(De,Pe,z,1,0),Ze=L,$e=ye.depthSegments,Ke=re}Ke.draw(_,I.TRIANGLES,Ze,Jr.disabled,Yr.disabled,Gr.disabled,_e,g.id,ye.vertexBuffer,ye.indexBuffer,$e,g.paint,_.transform.zoom)}}function A0(_,d,g,w){const{painter:j,sourceCache:I,layer:L,coords:F,colorMode:z,elevationType:H,terrainEnabled:Z,pass:ne}=_,re=j.context.gl,se=L.paint.get("fill-pattern"),ce=L.paint.get("fill-pattern-cross-fade"),oe=se.constantOr(null);let ye=H;H!=="road"||d&&!Z||(ye="none");const ge=ye==="road",Pe=_.painter.shadowRenderer,De=ge&&!!Pe&&Pe.enabled,_e=new Ir(j.context.gl.LEQUAL,Ir.ReadOnly,j.depthRangeFor3D);let Ze=[0,0,0];if(De){const Be=j.style.directionalLight,qe=j.style.ambientLight;Be&&qe&&(Ze=Gu(j.style,Be,qe))}const $e=se&&se.constantOr(1),Ke=j.terrain&&j.terrain.renderingToTexture,Me=(Be,qe)=>{let st,Qe,xt,ft,Lt;qe?(st=$e&&!L.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",xt=re.LINES):(st=$e?"fillPattern":"fill",xt=re.TRIANGLES);for(const Ft of F){const ot=I.getTile(Ft);if($e&&!ot.patternsLoaded())continue;const et=ot.getBucket(L);if(!et)continue;const gt=d?et.elevationBufferData:et.bufferData;if(gt.isEmpty())continue;j.prepareDrawTile();const bt=gt.programConfigurations.get(L.id),St=j.isTileAffectedByFog(Ft),nr=[],Wt=[];ge&&(nr.push("ELEVATED_ROADS"),Wt.push(gt.elevatedLayoutVertexBuffer)),De&&nr.push("RENDER_SHADOWS","NORMAL_OFFSET"),Ke&&g&&nr.push("USE_MRT1"),$e&&(j.context.activeTexture.set(re.TEXTURE0),ot.imageAtlasTexture&&ot.imageAtlasTexture.bind(re.LINEAR,re.CLAMP_TO_EDGE),bt.updatePaintBuffers());let Kt=!1;if(oe&&ot.imageAtlas){const Er=ot.imageAtlas,Hr=a.dV.from(oe),an=Hr.getPrimary().scaleSelf(a.o.devicePixelRatio).toString(),tn=Hr.getSecondary(),bn=Er.patternPositions.get(an),Ur=tn?Er.patternPositions.get(tn.scaleSelf(a.o.devicePixelRatio).toString()):null;Kt=!!bn&&!!Ur,bn&&bt.setConstantPatternPositions(bn,Ur)}ce>0&&(Kt||bt.getPatternTransitionVertexBuffer("fill-pattern"))&&nr.push("FILL_PATTERN_TRANSITION");const Mt=j.getOrCreateProgram(st,{config:bt,overrideFog:St,defines:nr}),kr=j.translatePosMatrix(Ft.projMatrix,ot,L.paint.get("fill-translate"),L.paint.get("fill-translate-anchor"));De&&Pe.setupShadows(ot.tileID.toUnwrapped(),Mt,"vector-tile");const Lr=L.paint.get("fill-emissive-strength");if(qe){ft=gt.lineIndexBuffer,Lt=gt.lineSegments;const Er=j.terrain&&j.terrain.renderingToTexture?j.terrain.drapeBufferSize:[re.drawingBufferWidth,re.drawingBufferHeight];Qe=st==="fillOutlinePattern"&&$e?Bg(kr,Lr,j,ot,Er,Ze,ce):$N(kr,Lr,Er,Ze)}else ft=gt.indexBuffer,Lt=gt.triangleSegments,Qe=$e?ib(kr,Lr,j,ot,Ze,ce):nb(kr,Lr,Ze);j.uploadCommonUniforms(j.context,Mt,Ft.toUnwrapped());let yr=Be;(H==="road"&&!Z||H==="offset")&&(yr=_e),Mt.draw(j,xt,yr,w||j.stencilModeForClipping(Ft),z,Gr.disabled,Qe,L.id,gt.layoutVertexBuffer,ft,Lt,L.paint,j.transform.zoom,bt,Wt)}};j.renderPass===ne&&Me(j.depthModeForSublayer(1,j.renderPass==="opaque"?Ir.ReadWrite:Ir.ReadOnly),!1),ye==="none"&&j.renderPass==="translucent"&&L.paint.get("fill-antialias")&&Me(j.depthModeForSublayer(L.getPaintProperty("fill-outline-color")?2:0,Ir.ReadOnly),!0)}function Qm(_,d,g,w,j,I,L,F){g.resetLayerRenderingStats(_);const z=_.context,H=z.gl,Z=_.transform,ne=g.paint.get("fill-extrusion-pattern"),re=g.paint.get("fill-extrusion-pattern-cross-fade"),se=ne.constantOr(null),ce=ne.constantOr(1),oe=g.paint.get("fill-extrusion-opacity"),ye=_.style.enable3dLights(),ge=g.paint.get(ye&&!ce?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),Pe=[g.paint.get("fill-extrusion-ambient-occlusion-intensity"),ge],De=g.layout.get("fill-extrusion-edge-radius"),_e=De>0&&!g.paint.get("fill-extrusion-rounded-roof"),Ze=_e?0:De,$e=Z.projection.name==="globe"?a.e1():0,Ke=Z.projection.name==="globe",Me=Ke?a.al(Z.zoom):0,Be=[a.aH(Z.center.lng),a.aL(Z.center.lat)],qe=g.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",st=g.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(qe?null:g.lut).toArray01().slice(0,3),Qe=g.paint.get("fill-extrusion-flood-light-intensity"),xt=g.paint.get("fill-extrusion-vertical-scale"),ft=g.paint.get("fill-extrusion-line-width").constantOr(1)!==0,Lt=g.paint.get("fill-extrusion-height-alignment"),Ft=g.paint.get("fill-extrusion-base-alignment"),ot=Ma(_,g.paint.get("fill-extrusion-cutoff-fade-range")),et=g.paint.get("fill-extrusion-front-cutoff"),gt=pb(Z.pitch,et,!!_.terrain),bt=gt[2]<1;bt&&(_.maxFrontCutoffRawStart=Math.max(_.maxFrontCutoffRawStart,et[0]));const St=[];let nr;Ke&&St.push("PROJECTION_GLOBE_VIEW"),Pe[0]>0&&St.push("FAUX_AO"),_e&&St.push("ZERO_ROOF_RADIUS"),F&&St.push("HAS_CENTROID"),Qe>0&&St.push("FLOOD_LIGHT"),ot.shouldRenderCutoff&&St.push("RENDER_CUTOFF"),bt&&St.push("RENDER_FRONT_CUTOFF"),ft&&St.push("RENDER_WALL_MODE");const Wt=_.renderPass==="shadow",Kt=_.shadowRenderer,Mt=Wt&&!!Kt,kr=Wt?Gr.disabled:Gr.backCCW;_.shadowRenderer&&(_.shadowRenderer.useNormalOffset=!0);let Lr=[0,0,0];if(Kt){const Hr=_.style.directionalLight,an=_.style.ambientLight;Hr&&an&&(Lr=Gu(_.style,Hr,an)),Wt||(St.push("RENDER_SHADOWS"),Kt.useNormalOffset&&St.push("NORMAL_OFFSET")),nr=St.concat(["SHADOWS_SINGLE_CASCADE"])}const yr=Mt?"fillExtrusionDepth":ce?"fillExtrusionPattern":"fillExtrusion",Er=g.getLayerRenderingStats();for(const Hr of w){const an=d.getTile(Hr),tn=an.getBucket(g);if(!tn||tn.projection.name!==Z.projection.name)continue;let bn=!1;Kt&&(bn=Kt.getMaxCascadeForTile(Hr.toUnwrapped())===0);const Ur=_.isTileAffectedByFog(Hr),wn=tn.programConfigurations.get(g.id);let rn=!1;if(se&&an.imageAtlas){const yn=an.imageAtlas,Ii=a.dV.from(se),ns=Ii.getPrimary().scaleSelf(a.o.devicePixelRatio).toString(),ti=Ii.getSecondary(),ln=yn.patternPositions.get(ns),Yi=ti?yn.patternPositions.get(ti.scaleSelf(a.o.devicePixelRatio).toString()):null;rn=!!ln&&!!Yi,ln&&wn.setConstantPatternPositions(ln,Yi)}re>0&&(rn||wn.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&St.push("FILL_EXTRUSION_PATTERN_TRANSITION");const Gn=_.getOrCreateProgram(yr,{config:wn,defines:bn?nr:St,overrideFog:Ur});if(_.terrain&&_.terrain.setupElevationDraw(an,Gn,{useMeterToDem:!0}),!tn.centroidVertexBuffer){const yn=Gn.getAttributeLocation(H,"a_centroid_pos");yn!==-1&&H.vertexAttribI4ui(yn,0,0,0,0)}!Wt&&Kt&&Kt.setupShadows(an.tileID.toUnwrapped(),Gn,"vector-tile"),ce&&(_.context.activeTexture.set(H.TEXTURE0),an.imageAtlasTexture&&an.imageAtlasTexture.bind(H.LINEAR,H.CLAMP_TO_EDGE),wn.updatePaintBuffers());const wi=g.paint.get("fill-extrusion-vertical-gradient"),Xi=1/tn.tileToMeter;let Ni;if(Wt&&Kt){if(gb(an.tileID,tn.maxHeight,_))continue;const yn=Kt.calculateShadowPassMatrixFromTile(an.tileID.toUnwrapped());Ni=B5(yn,Ze,Xi,xt,Lt,Ft)}else{const yn=_.translatePosMatrix(Hr.expandedProjMatrix,an,g.paint.get("fill-extrusion-translate"),g.paint.get("fill-extrusion-translate-anchor")),Ii=Z.projection.createInversionMatrix(Z,Hr.canonical);Ni=ce?$5(yn,_,wi,oe,Pe,Ze,Xi,Hr,an,$e,Lt,Ft,Me,Be,Ii,st,xt,re):BN(yn,_,wi,oe,Pe,Ze,Xi,Hr,$e,Lt,Ft,Me,Be,Ii,st,xt,Qe,Lr,gt)}_.uploadCommonUniforms(z,Gn,Hr.toUnwrapped(),null,ot);let ei=tn.segments;if(Z.projection.name==="mercator"&&!Wt&&(ei=tn.getVisibleSegments(an.tileID,_.terrain,_.transform.getFrustum(0)),!ei.get().length))continue;if(Er)if(Wt)for(const yn of ei.get())Er.numRenderedVerticesInShadowPass+=yn.primitiveLength;else for(const yn of ei.get())Er.numRenderedVerticesInTransparentPass+=yn.primitiveLength;const gn=[];(_.terrain||F)&&gn.push(tn.centroidVertexBuffer),Ke&&gn.push(tn.layoutVertexExtBuffer),ft&&gn.push(tn.wallVertexBuffer),Gn.draw(_,z.gl.TRIANGLES,j,I,L,kr,Ni,g.id,tn.layoutVertexBuffer,tn.indexBuffer,ei,g.paint,_.transform.zoom,wn,gn)}_.shadowRenderer&&(_.shadowRenderer.useNormalOffset=!1)}class vE{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function pb(_,d,g){if(!(d[2]<1)||g)return[0,0,1];const w=180*_/Math.PI;if(w<15)return[-.5,d[1],d[2]];const j=Math.min(1,Math.max(0,(w-15)/5)),I=j*j*(3-2*j);return[-.5*(1-I)+d[0]*I,d[1],d[2]]}function Ld(_,d,g,w,j,I,L,F,z,H,Z,ne,re,se,ce,oe,ye,ge,Pe,De,_e){const Ze=d.context,$e=Ze.gl,Ke=d.transform,Me=d.transform.zoom,Be=[],qe=_.translate,st=_.translateAnchor,Qe=_.edgeRadius,xt=Ma(d,_.cutoffFadeRange);Z==="clear"?(Be.push("CLEAR_SUBPASS"),De&&(Be.push("CLEAR_FROM_TEXTURE"),Ze.activeTexture.set($e.TEXTURE0),De.bind($e.LINEAR,$e.CLAMP_TO_EDGE))):Z==="sdf"?Be.push("SDF_SUBPASS"):Z==="emissive"&&(Be.push("USE_MRT1"),Ze.activeTexture.set($e.TEXTURE0),De.bind($e.LINEAR,$e.CLAMP_TO_EDGE)),ge&&Be.push("HAS_CENTROID"),xt.shouldRenderCutoff&&Be.push("RENDER_CUTOFF");const ft=(Lt,Ft,ot,et,gt)=>{let bt=Be;Ft.groundRadiusBuffer!=null&&(bt=Be.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const St=Ft.programConfigurations.get(w.id),nr=d.isTileAffectedByFog(Lt),Wt=d.getOrCreateProgram("fillExtrusionGroundEffect",{config:St,defines:bt,overrideFog:nr}),Kt=((kr,Lr,yr,Er,Hr,an,tn,bn,Ur,wn,rn)=>({u_matrix:Lr,u_opacity:yr,u_ao_pass:Er?1:0,u_meter_to_tile:Hr,u_ao:an,u_flood_light_intensity:tn,u_flood_light_color:bn,u_attenuation:Ur,u_edge_radius:wn,u_fb:0,u_fb_size:rn,u_dynamic_offset:1}))(0,et,ne,H,gt,[re,se*gt],ce,oe,ye,Me>=17?0:Qe*gt,De?De.size[0]:0),Mt=[];ge&&Mt.push(Ft.hiddenByLandmarkVertexBuffer),Ft.groundRadiusBuffer!=null&&Mt.push(Ft.groundRadiusBuffer),d.uploadCommonUniforms(Ze,Wt,Lt.toUnwrapped(),null,xt),Wt.draw(d,Ze.gl.TRIANGLES,I,L,F,z,Kt,w.id,Ft.vertexBuffer,Ft.indexBuffer,ot,w.paint,Me,St,Mt)};for(const Lt of j){const Ft=g.getTile(Lt),ot=Ft.getBucket(w);if(!ot||ot.projection.name!==Ke.projection.name||!ot.groundEffect||ot.groundEffect&&!ot.groundEffect.hasData())continue;const et=ot.groundEffect,gt=1/ot.tileToMeter;{const bt=d.translatePosMatrix(Lt.projMatrix,Ft,qe,st),St=et.getDefaultSegment();ft(Lt,et,St,bt,gt)}if(Pe)for(let bt=0;bt<4;bt++){const St=a.d$[bt](Lt),nr=g.getTile(St);if(!nr)continue;const Wt=nr.getBucket(w);if(!Wt||Wt.projection.name!==Ke.projection.name||!Wt.groundEffect||Wt.groundEffect&&!Wt.groundEffect.hasData())continue;const Kt=Wt.groundEffect;let Mt,kr;bt===0?(Mt=[-a.an,0,0],kr=1):bt===1?(Mt=[a.an,0,0],kr=0):bt===2?(Mt=[0,-a.an,0],kr=3):(Mt=[0,a.an,0],kr=2);const Lr=Kt.regionSegments[kr];if(!Lr)continue;const yr=new Float32Array(16);a.bx(yr,Lt.projMatrix,Mt),ft(Lt,Kt,Lr,d.translatePosMatrix(yr,Ft,qe,st),gt)}}}function XN(_,d,g,w,j,I,L){w.centroidVertexArray.length===0&&w.createCentroidsBuffer();const F=I?I.findDEMTileFor(g):null;if(!(F&&F.dem||L))return;I&&F&&F.dem&&w.selfDEMTileTimestamp!==F.dem._timestamp&&(w.borderDoneWithNeighborZ=[-1,-1,-1,-1],w.selfDEMTileTimestamp=F.dem._timestamp);const z=(ge,Pe)=>{(ge.flags|Pe.flags)&a.e3?(ge.flags|=a.e3,Pe.flags|=a.e3):(ge.flags&=~a.e3,Pe.flags&=~a.e3)},H=ge=>new a.P(Math.ceil((ge+a.e4)*a.e5),0),Z=(ge,Pe,De)=>{const _e=Math.ceil((ge+a.e4)*a.e5),Ze=Math.floor(Math.max(0,Math.min(a.an-1,De))/4);return new a.P(_e,Ze<<5|(3&Pe)<<3|7)},ne=ge=>{const Pe=d.getSource().minzoom,De=Ze=>{const $e=d.getTileByID(Ze);if($e&&$e.hasData())return $e.getBucket(j)},_e=[0,-1,1];for(const Ze of _e){if(ge.overscaledZ+Ze(re[0]=Math.min(ge.min.y,Pe.min.y),re[1]=Math.max(ge.max.y,Pe.max.y),re[2]=a.an-Pe.min.x>ge.max.x?Pe.min.x-a.an:ge.max.x,re),ce=(ge,Pe)=>(re[0]=Math.min(ge.min.x,Pe.min.x),re[1]=Math.max(ge.max.x,Pe.max.x),re[2]=a.an-Pe.min.y>ge.max.y?Pe.min.y-a.an:ge.max.y,re),oe=[(ge,Pe)=>se(ge,Pe),(ge,Pe)=>se(Pe,ge),(ge,Pe)=>ce(ge,Pe),(ge,Pe)=>ce(Pe,ge)],ye=(ge,Pe,De,_e,Ze,$e,Ke)=>{if(!I)return 0;const Me=[[$e?De:ge,$e?ge:De,0],[$e?De:Pe,$e?Pe:De,0]],Be=Ke<0?a.an+Ke:Ke,qe=[$e?Be:(ge+Pe)/2,$e?(ge+Pe)/2:Be,0];return De===0&&Ke<0||De!==0&&Ke>0?I.getForTilePoints(Ze,[qe],!0,_e):Me.push(qe),I.getForTilePoints(g,Me,!0,F),Math.max(Me[0][2],Me[1][2],qe[2])/I.exaggeration()};for(let ge=0;ge<4;ge++){const Pe=w.borderFeatureIndices[ge];if(Pe.length===0)continue;const De=a.d$[ge](g),_e=ne(De);if(!(_e&&_e instanceof a.e0))continue;const Ze=I?I.findDEMTileFor(De):null;if(!(Ze&&Ze.dem||L)||(I&&Ze&&Ze.dem&&w.borderDEMTileTimestamp[ge]!==Ze.dem._timestamp&&(w.borderDoneWithNeighborZ[ge]=-1,w.borderDEMTileTimestamp[ge]=Ze.dem._timestamp),w.borderDoneWithNeighborZ[ge]===_e.canonical.z))continue;_e.centroidVertexArray.length===0&&_e.createCentroidsBuffer();const $e=(ge<2?1:5)-ge,Ke=_e.borderDoneWithNeighborZ[$e]!==w.canonical.z,Me=_e.borderFeatureIndices[$e];let Be=0;if(w.canonical.z!==_e.canonical.z){for(const xt of Pe)w.showCentroid(w.featuresOnBorder[xt]);if(Ke)for(const xt of Me)_e.showCentroid(_e.featuresOnBorder[xt]);w.borderDoneWithNeighborZ[ge]=_e.canonical.z,_e.borderDoneWithNeighborZ[$e]=w.canonical.z;continue}const qe=new Map,st=new Set,Qe=new Set;for(let xt=0;xt1||ot.intersectsCount()>1;{let Wt=0;if(Ze&&Ze.dem&&!nr){const Kt=oe[ge](Lt,et),Mt=ge%2?a.an-1:0;Wt=ye(Kt[0],Math.min(a.an-1,Kt[1]),Mt,Ze,De,ge<2,Kt[2])}Lt.centroidXY=Z(Wt,ge,St),et.centroidXY=Z(Wt,$e,St)}if(w.writeCentroidToBuffer(Lt),_e.writeCentroidToBuffer(et),ft.buildingId!==void 0){for(const Wt of w.centroidData)Wt.buildingId===ft.buildingId&&Wt!==Lt&&(Wt.centroidXY=Lt.centroidXY,w.writeCentroidToBuffer(Wt));for(const Wt of _e.centroidData)Wt.buildingId===ft.buildingId&&Wt!==et&&(Wt.centroidXY=et.centroidXY,_e.writeCentroidToBuffer(Wt))}}for(const xt of Pe){if(st.has(xt))continue;const ft=w.featuresOnBorder[xt],Lt=w.centroidData[ft.centroidDataIndex],Ft=ft.borders[ge];let ot;for(;BeFt[0]+3||et[0]>Ft[0]-3)break;_e.showCentroid(ot),Be++}if(ot&&BeFt[1]-3||(gt++,++Be===Me.length))break;ot=_e.featuresOnBorder[Me[Be]]}for(;et=Me.length){w.showCentroid(ft);continue}ot=_e.featuresOnBorder[Me[et]];let bt=!1;if(gt>=1){const Wt=ot.borders[$e];Math.abs(Ft[0]-Wt[0])<3&&Math.abs(Ft[1]-Wt[1])<3&&(gt=1,bt=!0,Be=et+1)}else if(gt===0){w.showCentroid(ft);continue}const St=_e.centroidData[ot.centroidDataIndex];L&&bt&&z(Lt,St);const nr=ft.intersectsCount()>1||ot.intersectsCount()>1;if(gt>1)Be=et,Lt.centroidXY=St.centroidXY=new a.P(0,0);else if(Ze&&Ze.dem&&!nr){const Wt=oe[ge](Lt,St),Kt=ge%2?a.an-1:0,Mt=ye(Wt[0],Math.min(a.an-1,Wt[1]),Kt,Ze,De,ge<2,Wt[2]);Lt.centroidXY=St.centroidXY=H(Mt)}else nr?Lt.centroidXY=St.centroidXY=new a.P(0,0):(Lt.centroidXY=w.encodeBorderCentroid(ft),St.centroidXY=_e.encodeBorderCentroid(ot));w.writeCentroidToBuffer(Lt),_e.writeCentroidToBuffer(St)}else w.showCentroid(ft)}w.borderDoneWithNeighborZ[ge]=_e.canonical.z,_e.borderDoneWithNeighborZ[$e]=w.canonical.z}(w.needsCentroidUpdate||!w.centroidVertexBuffer&&w.centroidVertexArray.length!==0)&&w.uploadCentroid(_)}const QN=[1,0,0],JN=[0,1,0],_E=[0,0,1];function gb(_,d,g){const w=g.transform,j=g.shadowRenderer;if(!j)return!0;const I=_.toUnwrapped(),L=w.tileSize*j._cascades[g.currentShadowCascade].scale;let F=d;if(w.elevation){const ce=w.elevation.getMinMaxForTile(_);ce&&(F+=ce.max)}const z=w.scaleZoom(L);F/=a.e2(w.center.lat,z);const H=[...j.shadowDirection];H[2]=-H[2];const Z=j.computeSimplifiedTileShadowVolume(I,F,L,H);if(!Z)return!1;const ne=[QN,JN,_E,H,[H[0],0,H[2]],[0,H[1],H[2]]],re=a.cl.fromInvProjectionMatrix(w.invProjMatrix,w.worldSize,z,w.projection.name!=="globe"),se=j.getCurrentCascadeFrustum();return re.intersectsPrecise(Z.vertices,Z.planes,ne)===0||se.intersectsPrecise(Z.vertices,Z.planes,ne)===0}function k0(_){const{painter:d,source:g,layer:w,coords:j}=_;let I=_.defines;const L=d.context,F=d.renderPass==="shadow",z=d.renderPass==="light-beam",H=d.shadowRenderer,Z=a.e2(d.transform.center.lat,d.transform.zoom),ne=Ma(d,w.paint.get("building-cutoff-fade-range"));ne.shouldRenderCutoff&&(I=I.concat("RENDER_CUTOFF"));const re=w.paint.get("building-front-cutoff"),se=re[2]<1&&!d.terrain,ce=pb(d.transform.pitch,re,!!d.terrain);se&&(I=I.concat("RENDER_FRONT_CUTOFF"),d.maxFrontCutoffRawStart=Math.max(d.maxFrontCutoffRawStart,re[0])),_.floodLightIntensity>0&&(I=I.concat("FLOOD_LIGHT"));for(const oe of j){const ye=g.getTile(oe),ge=ye.getBucket(w);if(!ge)continue;H&&H.getMaxCascadeForTile(oe.toUnwrapped())===0&&(I=I.concat("SHADOWS_SINGLE_CASCADE"));const Pe=ge.programConfigurations.get(w.id);let De,_e,Ze,$e=d.translatePosMatrix(oe.expandedProjMatrix,ye,[0,0],"map");if($e=a.cC(a.bb(),$e,[1,1,_.verticalScale]),F&&H){if(gb(ye.tileID,ge.maxHeight*Z,d))continue;let Me=H.calculateShadowPassMatrixFromTile(ye.tileID.toUnwrapped());Me=a.cC(a.bb(),Me,[1,1,_.verticalScale]),Ze=ob(Me),De=_e=d.getOrCreateProgram("buildingDepth",{config:Pe,defines:I,overrideFog:!1})}else if(z)De=_e=d.getOrCreateProgram("buildingBloom",{config:Pe,defines:I,overrideFog:!1}),Ze=ab($e);else{const Me=d.transform.calculatePosMatrix(oe.toUnwrapped(),d.transform.worldSize);a.cC(Me,Me,[1,1,_.verticalScale]);const Be=a.bb();a.cC(Be,Me,[1,-1,1/Z]),a.b7(Be,Be),a.e6(Be,Be);const qe=d.transform.getFreeCameraOptions().position,st=1<{if(z){const qe=Me.entranceBloom;Be.draw(d,L.gl.TRIANGLES,_.depthMode,Jr.disabled,_.blendMode,Gr.disabled,Ze,w.id,qe.layoutVertexBuffer,qe.indexBuffer,qe.segmentsBucket,w.paint,d.transform.zoom,Pe,[qe.layoutAttenuationBuffer,qe.layoutColorBuffer])}else{const qe=Me.segmentsBucket;let st=[Me.layoutNormalBuffer,Me.layoutCentroidBuffer,Me.layoutColorBuffer,Me.layoutFloodLightDataBuffer];Me.layoutFacadePaintBuffer&&(st=st.concat([Me.layoutFacadeDataBuffer,Me.layoutFacadeVerticalRangeBuffer,Me.layoutFacadePaintBuffer])),Be.draw(d,L.gl.TRIANGLES,_.depthMode,Jr.disabled,_.blendMode,F?Gr.disabled:Gr.backCW,Ze,w.id,Me.layoutVertexBuffer,Me.indexBuffer,qe,w.paint,d.transform.zoom,Pe,st)}};d.uploadCommonUniforms(L,_e,oe.toUnwrapped(),null,ne),ge.buildingWithoutFacade&&Ke(ge.buildingWithoutFacade,_e),ge.buildingWithFacade&&(De!==_e&&d.uploadCommonUniforms(L,De,oe.toUnwrapped(),null,ne),Ke(ge.buildingWithFacade,De))}}function bE(_,d,g,w,j,I,L,F,z,H,Z,ne,re,se){const ce=_.context.gl,oe=_.depthModeForSublayer(1,Ir.ReadOnly,ce.LEQUAL,!0),ye=.1*(1-(ge=Z))+3*ge;var ge;const Pe=_._showOverdrawInspector,De=ne,_e=new vE;Pe||Ld(_e,_,d,g,w,oe,new Jr({func:ce.ALWAYS,mask:255},255,255,ce.KEEP,ce.KEEP,ce.REPLACE),new Yr([ce.ONE,ce.ONE,ce.ONE,ce.ONE],a.aq.transparent,[!1,!1,!1,!0],ce.MIN),Gr.disabled,j,"sdf",I,L,F,z,H,ye,De,!1,void 0);{const Ze=Pe?Jr.disabled:new Jr({func:ce.EQUAL,mask:255},255,255,ce.KEEP,ce.DECR,ce.DECR),$e=Pe?_.colorModeForRenderPass():new Yr([ce.ONE_MINUS_DST_ALPHA,ce.DST_ALPHA,ce.ONE,ce.ONE],a.aq.transparent,[!0,!0,!0,!0]);Ld(_e,_,d,g,w,oe,Ze,$e,Gr.disabled,j,"color",I,L,F,z,H,ye,De,!1,void 0)}}function wE(_){return[_[0]*a.e7,_[1]*a.e7,_[2]*a.e7,0]}function yb(_,d,g,w,j,I,L,F,z){const H=w.getSource(),Z=g.globeSharedBuffers;if(!Z)return;let ne,re,se;if(d&&(ne=w.getTile(d)),H instanceof a.aV?(re=H.texture,se=a.dw(0,0,g.transform)):ne&&d&&(re=ne.texture,se=a.dw(d.canonical.z,d.canonical.x,g.transform)),!re||!se)return;_||(se=a.cC(a.bb(),se,[1,-1,1]));const ce=g.context,oe=ce.gl,ye=j.paint.get("raster-resampling")==="nearest"?oe.NEAREST:oe.LINEAR,ge=g.colorModeForDrapableLayerRenderPass(I),Pe=L.defines;Pe.push("GLOBE_POLES");const De=new Ir(oe.LEQUAL,Ir.ReadWrite,g.depthRangeFor3D),_e=Float32Array.from(g.transform.expandedFarZProjMatrix),Ze=Float32Array.from(a.du(a.dv(new a.cn(0,0,0))));g.terrain&&g.terrain.prepareDrawTile(),ce.activeTexture.set(oe.TEXTURE0),re.bind(ye,oe.CLAMP_TO_EDGE),ce.activeTexture.set(oe.TEXTURE1),re.bind(ye,oe.CLAMP_TO_EDGE),"useMipmap"in re&&ce.extTextureFilterAnisotropic&&g.transform.pitch>20&&oe.texParameterf(oe.TEXTURE_2D,ce.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,ce.extTextureFilterAnisotropicMax);const[$e,Ke,Me,Be]=d?Z.getPoleBuffers(d.canonical.z,!1):Z.getPoleBuffers(0,!0),qe=j.paint.get("raster-elevation");let st;_?(st=$e,g.renderDefaultNorthPole=qe!==0):(st=Ke,g.renderDefaultSouthPole=qe!==0);const Qe=wE(L.mix),xt=((Lt,Ft,ot,et,gt,bt,St,nr,Wt,Kt,Mt,kr,Lr,yr)=>GN(Lt,Ft,ot,et,new Float32Array(16),new Float32Array(9),[0,0],gt,[0,0],[0,0,0,0],1,{opacity:1,mix:0},St,[0,0],Wt,2,Mt,kr,Lr,1,0,yr))(g,_e,Ze,se,a.al(g.transform.zoom),0,j,0,qe,0,Qe,L.offset,L.range,I),ft=g.getOrCreateProgram("raster",{defines:Pe});g.uploadCommonUniforms(ce,ft,null),ft.draw(g,oe.TRIANGLES,De,z,ge,F,xt,j.id,st,Me,Be)}function SE(_){if(_.isOrthographic)return[0,0,0,0];const d=_._nearZ,g=_.projection.farthestPixelDistance(_),w=g-d,j=.2*_.height,I=d+j;return[d,g,(I-j-d)/w,(I-d)/w]}function eI(_,d,g,w){if(_)return d instanceof Fm&&_ instanceof Bm?d.getTextureDescriptor(_,g,!0):{texture:_.texture,mix:wE(w.mix),offset:w.offset,buffer:0,tileSize:1}}var TE=a.e8([{name:"a_index",type:"Int16",components:1}]);class tI{constructor(d,g,w,j){const I={width:w[0],height:w[1],data:null},L=d.gl;this.targetColorTexture=new a.T(d,I,L.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new a.T(d,I,L.RGBA8,{useMipmap:!1}),this.context=d,this.updateParticleTexture(g,j),this.lastInvalidatedAt=0}updateParticleTexture(d,g){if(this.particleTextureDimension===g.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const w=this.context.gl,j=g.width*g.height;this.particleTexture0=new a.T(this.context,g,w.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new a.T(this.context,g,w.RGBA8,{premultiply:!1,useMipmap:!1});const I=new a.e9;I.reserve(j);for(let L=0;L0){const Qe=a.ec(g.canonical,z),xt=a.ed(Qe);re=a.aD(new Float32Array(16),z.globeMatrix,xt),a.aD(re,z.projMatrix,re)}const se=a.bb();se[12]+=2*j/(a.o.devicePixelRatio*z.width),se[13]+=2*I/(a.o.devicePixelRatio*z.height),a.aD(re,se,re);const ce=_.getOrCreateProgram("debug",{defines:ne}),oe=d.getTileByID(g.key);_.terrain&&_.terrain.setupElevationDraw(oe,ce);const ye=Ir.disabled,ge=Jr.disabled,Pe=_.colorModeForRenderPass(),De="$debug";F.activeTexture.set(H.TEXTURE0),_.emptyTexture.bind(H.LINEAR,H.CLAMP_TO_EDGE),Z?oe._makeGlobeTileDebugBuffers(_.context,z):oe._makeDebugTileBoundsBuffers(_.context,z.projection);const _e=oe._tileDebugBuffer||_.debugBuffer,Ze=oe._tileDebugIndexBuffer||_.debugIndexBuffer,$e=oe._tileDebugSegments||_.debugSegments;if(ce.draw(_,H.LINE_STRIP,ye,ge,Pe,Gr.disabled,w0(re,w.toPremultipliedRenderColor(null)),De,_e,Ze,$e,null,null,null,[oe._globeTileDebugBorderBuffer]),L){const Qe=oe.latestRawTileData,xt=Math.floor((Qe&&Qe.byteLength||0)/1024);let ft=g.canonical.toString();g.overscaledZ!==g.canonical.z&&(ft+=` => ${g.overscaledZ}`),ft+=` ${oe.state}`,ft+=` ${xt}kb`,function(Lt,Ft){Lt.initDebugOverlayCanvas();const ot=Lt.debugOverlayCanvas,et=Lt.context.gl,gt=Lt.debugOverlayCanvas.getContext("2d");gt.clearRect(0,0,ot.width,ot.height),gt.shadowColor="white",gt.shadowBlur=2,gt.lineWidth=1.5,gt.strokeStyle="white",gt.textBaseline="top",gt.font="bold 36px Open Sans, sans-serif",gt.fillText(Ft,5,5),gt.strokeText(Ft,5,5),Lt.debugOverlayTexture.update(ot),Lt.debugOverlayTexture.bind(et.LINEAR,et.CLAMP_TO_EDGE)}(_,ft)}const Ke=d.getTile(g).tileSize,Me=512/Math.min(Ke,512)*(g.overscaledZ/z.zoom)*.5,Be=oe._tileDebugTextBuffer||_.debugBuffer,qe=oe._tileDebugTextIndexBuffer||_.quadTriangleIndexBuffer,st=oe._tileDebugTextSegments||_.debugSegments;ce.draw(_,H.TRIANGLES,ye,ge,Yr.alphaBlended,Gr.disabled,w0(re,a.aq.transparent.toPremultipliedRenderColor(null),Me),De,Be,qe,st,null,null,null,[oe._globeTileDebugTextBuffer])}function nI(_,d,g,w){xb(_,0,d+g/2,_.transform.width,g,w)}function CE(_,d,g,w){xb(_,d-g/2,0,g,_.transform.height,w)}function xb(_,d,g,w,j,I){const L=_.context,F=L.gl;F.enable(F.SCISSOR_TEST),F.scissor(d*a.o.devicePixelRatio,g*a.o.devicePixelRatio,w*a.o.devicePixelRatio,j*a.o.devicePixelRatio),L.clear({color:I}),F.disable(F.SCISSOR_TEST)}const H5=a.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:fc}=H5;function Dd(_,d,g,w){_.emplaceBack(d,g,w)}class tl{constructor(d){this.vertexArray=new a.ee,this.indices=new a.dC,Dd(this.vertexArray,-1,-1,1),Dd(this.vertexArray,1,-1,1),Dd(this.vertexArray,-1,1,1),Dd(this.vertexArray,1,1,1),Dd(this.vertexArray,-1,-1,-1),Dd(this.vertexArray,1,-1,-1),Dd(this.vertexArray,-1,1,-1),Dd(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,fc),this.indexBuffer=d.createIndexBuffer(this.indices),this.segment=a.dy.simpleSegment(0,0,36,12)}}function Ic(_,d,g,w,j,I){const L=_.context.gl,F=d.paint.get("sky-atmosphere-color"),z=d.paint.get("sky-atmosphere-halo-color"),H=d.paint.get("sky-atmosphere-sun-intensity"),Z=((ne,re,se,ce,oe)=>({u_matrix_3f:ne,u_sun_direction:re,u_sun_intensity:se,u_color_tint_r:[ce.r,ce.g,ce.b,ce.a],u_color_tint_m:[oe.r,oe.g,oe.b,oe.a],u_luminance:5e-5}))(a.eg(a.dE(),w),j,H,F.toPremultipliedRenderColor(null),z.toPremultipliedRenderColor(null));L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_CUBE_MAP_POSITIVE_X+I,d.skyboxTexture,0),g.draw(_,L.TRIANGLES,Ir.disabled,Jr.disabled,Yr.unblended,Gr.frontCW,Z,"skyboxCapture",d.skyboxGeometry.vertexBuffer,d.skyboxGeometry.indexBuffer,d.skyboxGeometry.segment)}const iI=a.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class NE{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 w=new a.dC;w.emplaceBack(0,1,2),w.emplaceBack(2,3,0),this.vertexBuffer=d.createVertexBuffer(g,iI.members),this.indexBuffer=d.createIndexBuffer(w),this.segments=a.dy.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const IE=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 PE{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class sI{constructor(d){this.colorModeAlphaBlendedWriteRGB=new Yr([1,Cs,1,Cs],a.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new Yr([1,0,1,0],a.aq.transparent,[!1,!1,!1,!0]),this.params=new PE,this.updateNeeded=!0}update(d){const g=d.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new NE(g);const w=this.params.sizeRange,j=this.params.intensityRange,I=function(Z){const ne=a.em(30),re=[];for(let se=0;se{const Me=I.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Ke&&Me.push("ALPHA_PASS");const Be=d.getOrCreateProgram("globeAtmosphere",{defines:Me}),qe=((Qe,xt,ft,Lt,Ft,ot,et,gt,bt,St,nr,Wt)=>({u_frustum_tl:Qe,u_frustum_tr:xt,u_frustum_br:ft,u_frustum_bl:Lt,u_horizon:Ft,u_transition:ot,u_fadeout_range:et,u_atmosphere_fog_color:gt.toArray01(),u_high_color:bt.toArray01(),u_space_color:St.toArray01(),u_temporal_offset:nr,u_horizon_angle:Wt}))(I.frustumCorners.TL,I.frustumCorners.TR,I.frustumCorners.BR,I.frustumCorners.BL,I.frustumCorners.horizon,F,ye,Z,re,ce,Pe,Ze);d.uploadCommonUniforms(w,Be);const st=this.atmosphereBuffer;st&&Be.draw(d,j.TRIANGLES,L,Jr.disabled,Ke?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,Gr.backCW,qe,Ke?"atmosphere_glow_alpha":"atmosphere_glow",st.vertexBuffer,st.indexBuffer,st.segments)};$e(!1),$e(!0)}drawStars(d,g){const w=a.aC(g.properties.get("star-intensity"),0,1);if(w===0)return;const j=d.context,I=j.gl,L=d.transform,F=d.getOrCreateProgram("stars"),z=a.bL([]);a.bN(z,z,-L._pitch),a.bM(z,z,-L.angle),a.bN(z,z,a.ap(L._center.lat)),a.ek(z,z,-a.ap(L._center.lng));const H=a.bR(new Float32Array(16),z),Z=a.aD([],L.starsProjMatrix,H),ne=a.eg([],H),re=a.el([],ne),se=[0,1,0];a.dG(se,se,re),a.bJ(se,se,this.params.sizeMultiplier);const ce=[1,0,0];a.dG(ce,ce,re),a.bJ(ce,ce,this.params.sizeMultiplier);const oe=(ye=se,ge=ce,Pe=w,{u_matrix:Float32Array.from(Z),u_up:ye,u_right:ge,u_intensity_multiplier:Pe});var ye,ge,Pe;d.uploadCommonUniforms(j,F),this.starsVx&&this.starsIdx&&F.draw(d,I.TRIANGLES,Ir.disabled,Jr.disabled,this.colorModeAlphaBlendedWriteRGB,Gr.disabled,oe,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class jh{constructor(){this.visibleTiles=[]}updateBorders(d,g){const w=[],j=[],I=d._getRenderableCoordinates(!1,!0);for(const z of I){const H=d.getTile(z);if(!H.hasData())continue;const Z=H.getBucket(g);Z&&(Z.isEmpty()||(w.push(z.key),j.push({bucket:Z,tileID:z.canonical})))}let L=w.length!==this.visibleTiles.length;if(!L){w.sort();for(let z=0;zz.tileID.z-H.tileID.z||z.tileID.x-H.tileID.x||z.tileID.y-H.tileID.y);for(const z of j){const H=new Array,Z=new Array,ne=z.bucket;for(const re of ne.featuresOnBorder)F.has(re.featureId)?Z.push(re.footprintIndex):(F.add(re.featureId),H.push(re.footprintIndex));ne.updateFootprintHiddenFlags(H,a.en,!1),ne.updateFootprintHiddenFlags(Z,a.en,!0)}}}function aI(_,d){const g=[..._],w=d.cameraWorldSizeForFog/d.worldSize,j=a.b9([]);return a.cC(j,j,[w,w,1]),a.aD(g,j,g),a.aD(g,d.worldToFogMatrix,g),g}function si(_,d,g,w,j){const I=g.material,L=w.context,{baseColorTexture:F,metallicRoughnessTexture:z}=I.pbrMetallicRoughness,{normalTexture:H,occlusionTexture:Z,emissionTexture:ne}=I;function re(ce,oe,ye){if(ce&&(_.push(oe),L.activeTexture.set(L.gl.TEXTURE0+ye),ce.gfxTexture)){const{minFilter:ge,magFilter:Pe,wrapS:De,wrapT:_e}=ce.sampler;ce.gfxTexture.bindExtraParam(ge,Pe,De,_e)}}re(F,"HAS_TEXTURE_u_baseColorTexture",5),re(z,"HAS_TEXTURE_u_metallicRoughnessTexture",6),re(H,"HAS_TEXTURE_u_normalTexture",7),re(Z,"HAS_TEXTURE_u_occlusionTexture",8),re(ne,"HAS_TEXTURE_u_emissionTexture",9),j&&(j.texture||(j.texture=new a.dR(w.context,j.image,[j.image.height,j.image.height,j.image.height],L.gl.RGBA8)),L.activeTexture.set(L.gl.TEXTURE0+10),j.texture&&j.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)),I.alphaMode!=="OPAQUE"&&I.alphaMode!=="MASK"||_.push("UNPREMULT_TEXTURE_IN_SHADER"),I.defined||_.push("DIFFUSE_SHADED");const se=w.shadowRenderer;se&&(_.push("RENDER_SHADOWS"),se.useNormalOffset&&_.push("NORMAL_OFFSET"))}function Ug(_,d,g,w,j,I){const L=_.modelOpacity,F=d.context,z=new Ir(d.context.gl.LEQUAL,_.isLightMesh?Ir.ReadOnly:Ir.ReadWrite,d.depthRangeFor3D),H=d.transform,Z=_.mesh,ne=Z.material,re=ne.pbrMetallicRoughness,se=d.style.fog;let ce;ce=d.transform.projection.zAxisUnit==="pixels"?[..._.nodeModelMatrix]:a.aD([],w.zScaleMatrix,_.nodeModelMatrix),a.aD(ce,w.negCameraPosMatrix,ce);const oe=a.b7([],ce);a.e6(oe,oe);const ye=g.paint.get("model-color-use-theme").constantOr("default")==="none",ge=g.paint.get("model-emissive-strength").constantOr(0),Pe=Zm(new Float32Array(_.worldViewProjection),new Float32Array(ce),new Float32Array(oe),null,d,L,re.baseColorFactor,ne.emissiveFactor,re.metallicFactor,re.roughnessFactor,ne,ge,g,void 0,void 0,_.materialOverride,_.modelColor),De={defines:[]},_e=[],Ze=d.shadowRenderer;Ze&&(Ze.useNormalOffset=!1),si(De.defines,_e,Z,d,ye?null:g.lut);let $e=null;if(se){const Be=aI(_.nodeModelMatrix,d.transform);if($e=new Float32Array(Be),H.projection.name!=="globe"){const qe=Z.aabb.min,st=Z.aabb.max,[Qe,xt]=se.getOpacityForBounds(Be,qe[0],qe[1],st[0],st[1]);De.overrideFog=Qe>=Ln||xt>=Ln}}const Ke=Ma(d,g.paint.get("model-cutoff-fade-range"));Ke.shouldRenderCutoff&&De.defines.push("RENDER_CUTOFF");const Me=d.getOrCreateProgram("model",De);d.uploadCommonUniforms(F,Me,null,$e,Ke),d.renderPass!=="shadow"&&Ze&&Ze.setupShadowsFromMatrix(_.nodeModelMatrix,Me),Me.draw(d,F.gl.TRIANGLES,z,j,I,Z.material.doubleSided?Gr.disabled:Gr.backCCW,Pe,g.id,Z.vertexBuffer,Z.indexBuffer,Z.segments,g.paint,d.transform.zoom,void 0,_e)}function vb(_,d){return _.style._importedAsBasemap?"basemap":d.scope}function _b(_,d,g,w,j,I,L,F,z,H){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 se=a.aD([],w,re);if(d.meshes)for(const ce of d.meshes){const oe=F.get(ce.material.name);if(oe&&oe.opacity<=0)continue;if(ce.material.alphaMode!=="BLEND"){L.push({mesh:ce,depth:0,modelIndex:j,worldViewProjection:se,nodeModelMatrix:re,isLightMesh:ne,materialOverride:oe,modelOpacity:z,modelColor:H,node:d,modelMatrix:g});continue}const ye=a.ah([],ce.centroid,se);!Z.isOrthographic&&ye[2]<=0||I.push({mesh:ce,depth:ye[2],modelIndex:j,worldViewProjection:se,nodeModelMatrix:re,isLightMesh:ne,materialOverride:oe,modelOpacity:z,modelColor:H,node:d,modelMatrix:g})}if(d.children)for(const ce of d.children)_b(_,ce,g,w,j,I,L,F,z,H)}function Vg(_,d,g,w){const j=g.shadowRenderer;if(!j)return;const I=j.getShadowPassDepthMode(),L=j.calculateShadowPassMatrixFromMatrix(d),F=gE(L);g.getOrCreateProgram("modelDepth").draw(g,g.context.gl.TRIANGLES,I,Jr.disabled,Yr.disabled,Gr.disabled,F,w.id,_.vertexBuffer,_.indexBuffer,_.segments,w.paint,g.transform.zoom,void 0,void 0)}function RE(_,d,g,w){const j=function(Z,ne){if(ne.footprintDebugMesh)return ne.footprintDebugMesh;if(!ne.footprint)return null;const re=Z.context,se=ne.footprint.vertices,ce=ne.footprint.indices,oe=new a.dB;oe.reserve(se.length);for(const qe of se)oe.emplaceBack(qe.x,qe.y);const ye=new a.dC;ye.reserve(ce.length);for(let qe=0;qe0){const re=I.terrain,se=re.findDEMTileFor(F);se&&se.dem?z=a.ex.create(re,F,se):ne=0}if(ne===0&&(L.terrainElevationMin=0,L.terrainElevationMax=0),ne===L.validForExaggeration&&(ne===0||z&&z._demTile&&z._demTile.tileID===L.validForDEMTile.id&&z._dem._timestamp===L.validForDEMTile.timestamp))return!1;for(const re in L.instancesPerModel){const se=L.instancesPerModel[re];for(let ce=0;ceH&&(H=se.max)}const Z=a.aC(w.x,I,L)-w.x,ne=a.aC(w.y,F,z)-w.y,re=a.bU(H,d.center.lat)-w.z;return d._zoomFromMercatorZ(Math.sqrt(Z*Z+ne*ne+re*re))}function rs(_,d,g,w,j,I,L){const F=_.context,z=_.renderPass==="shadow",H=_.shadowRenderer,Z=z&&H?H.getShadowPassDepthMode():new Ir(F.gl.LEQUAL,Ir.ReadWrite,_.depthRangeFor3D),ne=_.isTileAffectedByFog(I),re=_.transform.projection.name==="globe";if(g.meshes)for(const se of g.meshes){const ce=re?[]:["MODEL_POSITION_ON_GPU"],oe=[];let ye,ge,Pe;const De=!re&&w.instancedDataArray.length>20;De&&ce.push("INSTANCED_ARRAYS");const _e=Ma(_,d.paint.get("model-cutoff-fade-range"));if(_e.shouldRenderCutoff&&ce.push("RENDER_CUTOFF"),z&&H)ye=_.getOrCreateProgram("modelDepth",{defines:ce}),ge=gE(L.shadowTileMatrix,L.shadowTileMatrix,Float32Array.from(g.globalMatrix)),Pe=Yr.disabled;else{si(ce,oe,se,_,d.paint.get("model-color-use-theme").constantOr("default")==="none"?null:d.lut),ye=_.getOrCreateProgram("model",{defines:ce,overrideFog:ne});const $e=se.material,Ke=$e.pbrMetallicRoughness,Me=d.paint.get("model-opacity").constantOr(1),Be=d.paint.get("model-emissive-strength").constantOr(0);ge=Zm(I.expandedProjMatrix,Float32Array.from(g.globalMatrix),new Float32Array(16),null,_,Me,Ke.baseColorFactor,$e.emissiveFactor,Ke.metallicFactor,Ke.roughnessFactor,$e,Be,d,j),H&&(L.shadowUniformsInitialized?ye.setShadowUniformValues(F,H.getShadowUniformValues()):(H.setupShadows(I.toUnwrapped(),ye,"model-tile"),L.shadowUniformsInitialized=!0)),Pe=_e.shouldRenderCutoff||Me<1||$e.alphaMode!=="OPAQUE"?Yr.alphaBlended:Yr.unblended}_.uploadCommonUniforms(F,ye,I.toUnwrapped(),null,_e);const Ze=se.material.doubleSided?Gr.disabled:Gr.backCCW;if(De)oe.push(w.instancedDataBuffer),ye.draw(_,F.gl.TRIANGLES,Z,Jr.disabled,Pe,Ze,ge,d.id,se.vertexBuffer,se.indexBuffer,se.segments,d.paint,_.transform.zoom,void 0,oe,w.instancedDataArray.length);else{const $e=z?"u_instance":"u_normal_matrix";for(let Ke=0;Kez[1]?L:z,I[0]=g.max[0],L=a.aE(a.bE(),I,j),F=L[1]z[1]?L:z,I[1]=g.min[1],L=a.aE(a.bE(),I,j),F=L[1]z[1]?L:z;const H=a.aC(w[0],0,1),Z=100*d.pixelsPerMeter*a.aC(w[1],0,1),ne=a.aC(w[2],0,1),re=a.ey(a.bE(),F,z,H),se=Math.tan(.5*d.fovX),ce=-re[2]*se;if(Z===0)return re[1]<-Math.abs(ce)?ne:1;const oe=(-Math.abs(ce)-re[1])/Z,ye=(Pe,De,_e)=>(1-_e)*Pe+_e*De,ge=a.aC(ye(1,ne,oe),ne,1);return ye(1,ge,a.aC((d.pitch-20)/20,0,1))}class wb{}class lI{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(d,g,w){{const ne=this._storage.get(g.id);if(ne)return ne.lastUsedFrameIdx=d,ne.buf}const j=w.gl,I=j.getBufferParameter(j.ELEMENT_ARRAY_BUFFER,j.BUFFER_SIZE),L=new ArrayBuffer(I),F=new Int16Array(L);j.getBufferSubData(j.ELEMENT_ARRAY_BUFFER,0,new Int16Array(L));const z=new a.eA;for(let ne=0;ne30&&(w.buf.destroy(),this._storage.delete(g))}destroy(){for(const[d,g]of this._storage)g.buf.destroy(),this._storage.delete(d)}}class cI{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const Gg=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 uI{constructor(d){this.revealStart=11,this.revealRange=2}}const W5=a.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class dI{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(d,g){const w=d.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const L=new a.eB,F=new a.dC;L.emplaceBack(-1,-1),L.emplaceBack(1,-1),L.emplaceBack(1,1),L.emplaceBack(-1,1),F.emplaceBack(0,1,2),F.emplaceBack(0,2,3),this.vignetteVx=d.context.createVertexBuffer(L,W5.members),this.vignetteIdx=d.context.createIndexBuffer(F)}const j=a.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){d.uploadCommonUniforms(d.context,w);const L={u_vignetteShape:(I={vignetteShape:[g.start,g.range,Math.pow(10,g.fadePower)],vignetteColor:[g.color.r,g.color.g,g.color.b,g.color.a*g.strength]}).vignetteShape,u_vignetteColor:I.vignetteColor};w.draw(d,d.context.gl.TRIANGLES,Ir.disabled,Jr.disabled,Yr.alphaBlended,Gr.disabled,L,"vignette",this.vignetteVx,this.vignetteIdx,j)}var I}}class Sb{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(d,g){const w=d.getFreeCameraOptions().position,j=w.toAltitude(),I=w.toLngLat(),L=a.ap(I.lng),F=a.ap(I.lat),z=d.pixelsPerMeter/g,H=L*a.eD,Z=a.eD*Math.log(Math.tan(Math.PI/4+F/2));if(this._offsetXPrev===void 0)this._offsetXPrev=0,this._offsetYPrev=0,this._elevationPrev=0,this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0;else{const ne=-this._offsetYPrev+Z,re=-this._elevationPrev+j;this._accumulatedOffsetX+=(-this._offsetXPrev+H)*z,this._accumulatedOffsetY+=ne*z,this._accumulatedElevation+=re*z,this._offsetXPrev=H,this._offsetYPrev=Z,this._elevationPrev=j}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function Tb(_,d){return[-(_[0]-Math.floor(_[0]/d)*d),-(_[1]-Math.floor(_[1]/d)*d),-(_[2]-Math.floor(_[2]/d)*d)]}function ME(_){const d=a.em(1323123451230),g=[];for(let w=0;w<_;++w){const j=2*d()-1,I=2*d()-1,L=2*d()-1;g.push(a.cQ(j,I,L))}return g}function kh(_,d,g,w,j){const I=a.aC((j-g)/(w-g),0,1);return(1-I)*_+I*d}class C0{constructor(d){this._movement=new Sb,this._accumulatedTimeFromStart=0,this._prevTime=Date.now()/1e3,this._vignette=new dI,this._ppmScaleFactor=d}destroy(){this.particlesVx&&this.particlesVx.destroy(),this.particlesIdx&&this.particlesIdx.destroy(),this._vignette&&this._vignette.destroy()}updateOnRender(d,g){const w=d.transform;this._movement.update(w,this._ppmScaleFactor);const j=w.starsProjMatrix,I=a.bL([]);a.bN(I,I,a.ap(90)-w._pitch),a.bM(I,I,-w.angle);const L=a.bR(new Float32Array(16),I),F=a.eC(1,0,0,0,0,0,1,0,0,-1,0,0,0,0,0,1),z=a.e6([],F),H=a.aD([],z,L),Z=Date.now()/1e3;return this._accumulatedTimeFromStart+=(Z-this._prevTime)*g,this._prevTime=Z,{projectionMatrix:j,modelviewMatrix:H}}}class N0 extends C0{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 uI("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 w=ME(this.particlesCount),j=new a.eE,I=new a.dC;let L=0;const F=a.em(1323123451230);for(let z=0;zw)return;const j=kh(0,1,g.revealStart,g.revealStart+g.revealRange,w);if(!this.particlesVx||!this.particlesIdx)return;const I=structuredClone(this._params);let L=[-I.direction.x,I.direction.y,-100];a.ay(L,L);const F=structuredClone(this._vignetteParams);F.strength*=j,I.overrideStyleParameters||(I.intensity=d.style.rain.state.density,I.timeFactor=d.style.rain.state.intensity,I.color=structuredClone(d.style.rain.state.color),L=structuredClone(d.style.rain.state.direction),I.screenThinning.intensity=d.style.rain.state.centerThinning,I.dropletSizeX=d.style.rain.state.dropletSize[0],I.dropletSizeYScale=d.style.rain.state.dropletSize[1]/d.style.rain.state.dropletSize[0],I.distortionStrength=100*d.style.rain.state.distortionStrength,F.strength=1,F.color=structuredClone(d.style.rain.state.vignetteColor));const z=this.updateOnRender(d,I.timeFactor),H=d.context,Z=H.gl,ne=d.transform;this.screenTexture&&this.screenTexture.size[0]===d.width&&this.screenTexture.size[1]===d.height||(this.screenTexture=new a.T(H,{width:d.width,height:d.height,data:null},Z.RGBA8)),I.distortionStrength>0&&(H.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(H,re),H.activeTexture.set(Z.TEXTURE0),this.screenTexture.bind(Z.LINEAR,Z.CLAMP_TO_EDGE);const se=[I.color.r,I.color.g,I.color.b,I.color.a],ce=(oe,ye)=>{const ge=Tb(this._movement.getPosition(),oe),Pe=I.dropletSizeX,De=I.dropletSizeX*I.dropletSizeYScale,_e=d.width/2,Ze=d.height/2,$e=kh(0,I.screenThinning.start,0,1,I.screenThinning.intensity),Ke=kh(.001,I.screenThinning.range,0,1,I.screenThinning.intensity),Me=kh(0,I.screenThinning.particleOffset,0,1,I.screenThinning.intensity),Be=(qe={modelview:z.modelviewMatrix,projection:z.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:ge,velocityConeAperture:I.velocityConeAperture,velocity:I.velocity,boxSize:oe,rainDropletSize:[Pe,De],distortionStrength:I.distortionStrength,rainDirection:L,color:se,screenSize:[ne.width,ne.height],thinningCenterPos:[_e,Ze],thinningShape:[$e,Ke,Math.pow(10,I.screenThinning.fadePower)],thinningAffectedRatio:I.screenThinning.affectedRatio,thinningParticleOffset:Me,shapeDirectionalPower:I.shapeDirPower,shapeNormalPower:I.shapeNormalPower,mode:ye?0:1},{u_modelview:Float32Array.from(qe.modelview),u_projection:Float32Array.from(qe.projection),u_time:qe.time,u_cam_pos:qe.camPos,u_texScreen:0,u_velocityConeAperture:qe.velocityConeAperture,u_velocity:qe.velocity,u_boxSize:qe.boxSize,u_rainDropletSize:qe.rainDropletSize,u_distortionStrength:qe.distortionStrength,u_rainDirection:qe.rainDirection,u_color:qe.color,u_screenSize:qe.screenSize,u_thinningCenterPos:qe.thinningCenterPos,u_thinningShape:qe.thinningShape,u_thinningAffectedRatio:qe.thinningAffectedRatio,u_thinningParticleOffset:qe.thinningParticleOffset,u_shapeDirectionalPower:qe.shapeDirectionalPower,u_shapeNormalPower:qe.shapeNormalPower,u_mode:qe.mode});var qe;const st=Math.round(I.intensity*this.particlesCount),Qe=a.dy.simpleSegment(0,0,4*st,2*st);re.draw(d,Z.TRIANGLES,Ir.disabled,Jr.disabled,Yr.alphaBlended,Gr.disabled,Be,"rain_particles",this.particlesVx,this.particlesIdx,Qe)};I.distortionStrength>0&&ce(I.boxSize,!0),ce(I.boxSize,!1),this._vignette.draw(d,F)}}const tp=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 hI extends C0{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 uI("Precipitation > Snow"),this._vignetteParams={strength:.3,start:.78,range:.46,fadePower:.2,color:{r:1,g:1,b:1,a:1}},this.particlesCount=16e3}update(d){const g=d.context;if(!this.particlesVx){const w=ME(this.particlesCount),j=new a.eF,I=new a.dC;let L=0;const F=a.em(1323123451230);for(let z=0;zL)return;const F=kh(0,1,I.revealStart,I.revealStart+I.revealRange,L);j.strength*=F,g.overrideStyleParameters||(g.intensity=d.style.snow.state.density,g.timeFactor=d.style.snow.state.intensity,g.color=structuredClone(d.style.snow.state.color),w=structuredClone(d.style.snow.state.direction),g.screenThinning.intensity=d.style.snow.state.centerThinning,g.billboardSize=2.79*d.style.snow.state.flakeSize,j.strength=1,j.color=structuredClone(d.style.snow.state.vignetteColor));const z=this.updateOnRender(d,g.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const H=d.context,Z=H.gl,ne=d.transform,re=d.getOrCreateProgram("snowParticle");d.uploadCommonUniforms(H,re),((se,ce,oe)=>{const ye=Tb(this._movement.getPosition(),se),ge=ne.width/2,Pe=ne.height/2,De=kh(0,oe.screenThinning.start,0,1,oe.screenThinning.intensity),_e=kh(.001,oe.screenThinning.range,0,1,oe.screenThinning.intensity),Ze=kh(0,oe.screenThinning.particleOffset,0,1,oe.screenThinning.intensity),$e=(Ke={modelview:z.modelviewMatrix,projection:z.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:ye,velocityConeAperture:oe.velocityConeAperture,velocity:oe.velocity,horizontalOscillationRadius:oe.horizontalOscillationRadius,horizontalOscillationRate:oe.horizontalOscillationRate,boxSize:se,billboardSize:1*oe.billboardSize,simpleShapeParameters:[oe.shapeFadeStart,oe.shapeFadePower],screenSize:[ne.width,ne.height],thinningCenterPos:[ge,Pe],thinningShape:[De,_e,Math.pow(10,oe.screenThinning.fadePower)],thinningAffectedRatio:oe.screenThinning.affectedRatio,thinningParticleOffset:Ze,color:[oe.color.r,oe.color.g,oe.color.b,oe.color.a],direction:w},{u_modelview:Float32Array.from(Ke.modelview),u_projection:Float32Array.from(Ke.projection),u_time:Ke.time,u_cam_pos:Ke.camPos,u_velocityConeAperture:Ke.velocityConeAperture,u_velocity:Ke.velocity,u_horizontalOscillationRadius:Ke.horizontalOscillationRadius,u_horizontalOscillationRate:Ke.horizontalOscillationRate,u_boxSize:Ke.boxSize,u_billboardSize:Ke.billboardSize,u_simpleShapeParameters:Ke.simpleShapeParameters,u_screenSize:Ke.screenSize,u_thinningCenterPos:Ke.thinningCenterPos,u_thinningShape:Ke.thinningShape,u_thinningAffectedRatio:Ke.thinningAffectedRatio,u_thinningParticleOffset:Ke.thinningParticleOffset,u_particleColor:Ke.color,u_direction:Ke.direction});var Ke;const Me=Math.round(oe.intensity*this.particlesCount),Be=a.dy.simpleSegment(0,0,4*Me,2*Me);this.particlesVx&&this.particlesIdx&&re.draw(d,Z.TRIANGLES,Ir.disabled,Jr.disabled,Yr.alphaBlended,Gr.disabled,$e,"snow_particles",this.particlesVx,this.particlesIdx,Be)})(g.boxSize,0,g),this._vignette.draw(d,j)}}const fI={symbol:function(_,d,g,w,j){if(_.renderPass!=="translucent")return;const I=Jr.disabled,L=_.colorModeForRenderPass(),F=g.layout.get("text-variable-anchor"),z=g.layout.get("text-size-scale-range"),H=a.aC(_.scaleFactor,z[0],z[1]);F&&function(re,se,ce,oe,ye,ge,Pe,De){const _e=se.transform,Ze=ye==="map",$e=ge==="map";for(const Ke of re){const Me=oe.getTile(Ke),Be=Me.getBucket(ce);if(!Be||!Be.text||!Be.text.segments.get().length)continue;const qe=a.bj(Be.textSizeData,_e.zoom,De),st=$m(Ke,Be.getProjection(),_e),Qe=_e.calculatePixelsToTileUnitsMatrix(Me),xt=wf(st,Me.tileID.canonical,$e,Ze,_e,Be.getProjection(),Qe),ft=Be.hasIconTextFit()&&Be.hasIconData();qe&&ZN(Be,Ze,$e,Pe,_e,xt,Ke,Math.pow(2,_e.zoom-Me.tileID.overscaledZ),qe,ft)}}(w,_,g,d,g.layout.get("text-rotation-alignment"),g.layout.get("text-pitch-alignment"),j,H);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)?hb(_,d,g,w,I,L):(Z&&hb(_,d,g,w,I,L,{onlyIcons:!0}),ne&&hb(_,d,g,w,I,L,{onlyText:!0})),d.map.showCollisionBoxes&&(br(_,d,g,w,g.paint.get("text-translate"),g.paint.get("text-translate-anchor"),!0),br(_,d,g,w,g.paint.get("icon-translate"),g.paint.get("icon-translate-anchor"),!1))},circle:function(_,d,g,w){if(_.renderPass!=="translucent")return;const j=g.paint.get("circle-opacity"),I=g.paint.get("circle-stroke-width"),L=g.paint.get("circle-stroke-opacity"),F=g.layout.get("circle-sort-key").constantOr(1)!==void 0,z=g.paint.get("circle-emissive-strength");if(j.constantOr(1)===0&&(I.constantOr(1)===0||L.constantOr(1)===0))return;const H=_.context,Z=H.gl,ne=_.transform,re=!(!_.terrain||!_.terrain.enabled),se=g.layout.get("circle-elevation-reference"),ce=_.depthModeForSublayer(0,Ir.ReadOnly),oe=new Ir(_.context.gl.LEQUAL,Ir.ReadOnly,_.depthRangeFor3D),ye=se==="none"||re?ce:oe,ge=Jr.disabled,Pe=_.colorModeForDrapableLayerRenderPass(z),De=ne.projection.name==="globe",_e=[a.aH(ne.center.lng),a.aL(ne.center.lat)],Ze=[];for(let Ke=0;KeKe.sortKey-Me.sortKey);const $e={useDepthForOcclusion:ne.depthOcclusionForSymbolsAndCircles};for(const Ke of Ze){const{programConfiguration:Me,program:Be,layoutVertexBuffer:qe,dynamicBuffers:st,indexBuffer:Qe,uniformValues:xt,tile:ft}=Ke.state,Lt=Ke.segments;_.terrain&&_.terrain.setupElevationDraw(ft,Be,$e),_.uploadCommonUniforms(H,Be,ft.tileID.toUnwrapped()),Be.draw(_,Z.TRIANGLES,ye,ge,Pe,Gr.disabled,xt,g.id,qe,Qe,Lt,g.paint,ne.zoom,Me,st)}},heatmap:function(_,d,g,w){if(g.paint.get("heatmap-opacity")!==0)if(_.renderPass==="offscreen"){const j=_.context,I=j.gl,L=Jr.disabled,F=new Yr([I.ONE,I.ONE,I.ONE,I.ONE],a.aq.transparent,[!0,!0,!0,!0]),z=_.transform.projection.name==="globe"?.5:.25;g.heatmapFbo=T0.createWithTexture(j,g.heatmapFbo,_.width*z,_.height*z),j.clear({color:a.aq.transparent});const H=_.transform,Z=H.projection.name==="globe",ne=Z?["PROJECTION_GLOBE_VIEW"]:[],re=Z?Gr.frontCCW:Gr.disabled,se=[a.aH(H.center.lng),a.aL(H.center.lat)];for(let ce=0;ce({u_image:0,u_color_ramp:1,u_opacity:ne.paint.get("heatmap-opacity")}))(0,I),I.id,j.viewportBuffer,j.quadTriangleIndexBuffer,j.viewportSegments,I.paint,j.transform.zoom)}(_,g))},line:function(_,d,g,w){const j=g.paint.get("line-opacity"),I=g.paint.get("line-width");if(j.constantOr(1)===0||I.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(F,z,H,Z,ne){if(F.renderPass!=="translucent")return;const re=F.context,se=re.gl,ce=F.terrain;if(!ce)return;const oe=re.bindFramebuffer.current,ye=F.emissiveMode==="mrt-fallback";H.lineBlendDrapeFbo=T0.createWithTexture(re,H.lineBlendDrapeFbo,ce.drapeBufferSize[0],ce.drapeBufferSize[1],!0),H.lineBlendDrapeStencil=H.lineBlendDrapeFbo._stencilRbo,ye&&se.drawBuffers([se.COLOR_ATTACHMENT0]),re.clear({color:Eh[ne].clearColor,depth:1,stencil:0});const ge=F.currentStencilSource,Pe=F._tileClippingMaskIDs,De=F.nextStencilID;F.currentStencilSource=void 0,F._tileClippingMaskIDs={},F.nextStencilID=1;const _e=F._terrain;F._terrain=null,F._renderTileClippingMasks(H,z,Z),mb(F,z,H,Z,Eh[ne].colorMode,!0),F._terrain=_e,F.currentStencilSource=ge,F._tileClippingMaskIDs=Pe,F.nextStencilID=De,re.bindFramebuffer.set(oe),ye&&se.drawBuffers([se.COLOR_ATTACHMENT0,se.COLOR_ATTACHMENT1]);const Ze=ce.drapeBufferSize;re.viewport.set([0,0,Ze[0],Ze[1]]);const $e=H.lineBlendDrapeFbo;if(!$e)return;re.activeTexture.set(se.TEXTURE0),se.bindTexture(se.TEXTURE_2D,$e.colorAttachment0.get());const Ke=ne==="additive"?1:H.paint.get("line-opacity").constantOr(1),Me=H.paint.get("line-emissive-strength").constantOr(0),Be=ne==="additive"?F.colorModeForDrapableLayerRenderPass(Me):Eh[ne].colorMode;F.getOrCreateProgram("lineBlendComposite").draw(F,se.TRIANGLES,Ir.disabled,Jr.disabled,Be,Gr.disabled,sb(0,Ke,Eh[ne].compositeUniformValue),H.id,F.viewportBuffer,F.quadTriangleIndexBuffer,F.viewportSegments,H.paint,F.transform.zoom)}(_,d,g,w,L):_.renderPass==="offscreen"?void function(F,z,H,Z,ne){const re=F.context,se=Math.ceil(F.width),ce=Math.ceil(F.height);H.lineBlendFbo=T0.createWithTexture(re,H.lineBlendFbo,se,ce,!0),H.lineBlendStencil=H.lineBlendFbo._stencilRbo,re.clear({color:Eh[ne].clearColor,depth:1,stencil:0});const oe=F.currentStencilSource,ye=F._tileClippingMaskIDs,ge=F.nextStencilID;F.currentStencilSource=void 0,F._tileClippingMaskIDs={},F.nextStencilID=1,F._renderTileClippingMasks(H,z,Z);const Pe=F.renderPass;F.renderPass="translucent",mb(F,z,H,Z,Eh[ne].colorMode),F.renderPass=Pe,F.currentStencilSource=oe,F._tileClippingMaskIDs=ye,F.nextStencilID=ge,re.viewport.set([0,0,F.width,F.height])}(_,d,g,w,L):_.renderPass==="translucent"?void function(F,z,H){const Z=F.context,ne=Z.gl,re=z.lineBlendFbo;if(!re)return;Z.activeTexture.set(ne.TEXTURE0),ne.bindTexture(ne.TEXTURE_2D,re.colorAttachment0.get());const se=H==="additive"?1:z.paint.get("line-opacity").constantOr(1),ce=H==="additive"?F.colorModeForDrapableLayerRenderPass(z.paint.get("line-emissive-strength").constantOr(0)):Eh[H].colorMode;F.getOrCreateProgram("lineBlendComposite").draw(F,ne.TRIANGLES,Ir.disabled,Jr.disabled,ce,Gr.disabled,sb(0,se,Eh[H].compositeUniformValue),z.id,F.viewportBuffer,F.quadTriangleIndexBuffer,F.viewportSegments,z.paint,F.transform.zoom)}(_,g,L):void 0;_.renderPass==="translucent"&&mb(_,d,g,w)},fill:function(_,d,g,w){const j=g.paint.get("fill-color"),I=g.paint.get("fill-opacity");if(I.constantOr(1)===0)return;const L=g.paint.get("fill-emissive-strength"),F=_.colorModeForDrapableLayerRenderPass(L),z=g.paint.get("fill-pattern"),H=_.opaquePassEnabledForLayer()&&!z.constantOr(1)&&j.constantOr(a.aq.transparent).a===1&&I.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:w,colorMode:F,elevationType:Z,terrainEnabled:ne,pass:H};if(_.renderPass==="shadow")return void(_.shadowRenderer&&Z==="road"&&!ne&&function(ce){const{painter:oe,sourceCache:ye,layer:ge,coords:Pe}=ce,De=oe.context.gl,_e=ce.painter.shadowRenderer;for(const Ze of Pe){const $e=ye.getTile(Ze),Ke=$e.getBucket(ge);if(!Ke)continue;const Me=Ke.elevatedStructures;if(!Me||!Me.shadowCasterSegments||Me.shadowCasterSegments.segments[0].primitiveLength===0)continue;oe.prepareDrawTile();const Be=Ke.bufferData.programConfigurations.get(ge.id),qe=oe.isTileAffectedByFog(Ze),st=oe.getOrCreateProgram("elevatedStructuresDepth",{config:Be,overrideFog:qe}),Qe=_e.calculateShadowPassMatrixFromTile($e.tileID.toUnwrapped());oe.uploadCommonUniforms(oe.context,st,Ze.toUnwrapped());const xt=zN(Qe,0);st.draw(oe,De.TRIANGLES,_e.getShadowPassDepthMode(),Jr.disabled,Yr.disabled,Gr.disabled,xt,ge.id,Me.vertexBuffer,Me.indexBuffer,Me.shadowCasterSegments,ge.paint,oe.transform.zoom,Be)}}(re));const se=_.emissiveMode==="mrt-fallback";if(Z!=="offset"){if(A0(re,!1,se),Z==="road"){const ce=!ne&&_.renderPass==="translucent";ce&&j0(_,d,g,w,"geometry"),A0(re,!0,se,Jr.disabled),ce&&function(oe){const{painter:ye,sourceCache:ge,layer:Pe,coords:De,colorMode:_e}=oe,Ze=ye.context.gl,$e=oe.painter.shadowRenderer,Ke=!!$e&&$e.enabled,Me=new Ir(ye.context.gl.LEQUAL,Ir.ReadOnly,ye.depthRangeFor3D);let Be=[0,0,0];if(Ke){const st=ye.style.directionalLight,Qe=ye.style.ambientLight;st&&Qe&&(Be=Gu(ye.style,st,Qe))}const qe=st=>{for(const Qe of De){const xt=ge.getTile(Qe),ft=xt.getBucket(Pe);if(!ft)continue;const Lt=ft.elevatedStructures;if(!Lt)continue;let Ft,ot;if(st?(Ft=Lt.renderableBridgeSegments,ot=Lt.bridgeProgramConfigurations.get(Pe.id)):(Ft=Lt.renderableTunnelSegments,ot=Lt.tunnelProgramConfigurations.get(Pe.id)),!Ft||Ft.segments[0].primitiveLength===0)continue;ot.updatePaintBuffers(),ye.prepareDrawTile();const et=ye.isTileAffectedByFog(Qe),gt=[];Ke&>.push("RENDER_SHADOWS","NORMAL_OFFSET");const bt=ye.getOrCreateProgram("elevatedStructures",{config:ot,overrideFog:et,defines:gt}),St=ye.translatePosMatrix(Qe.projMatrix,xt,Pe.paint.get("fill-translate"),Pe.paint.get("fill-translate-anchor"));Ke&&$e.setupShadows(xt.tileID.toUnwrapped(),bt,"vector-tile");const nr=UN(St,Be);ye.uploadCommonUniforms(ye.context,bt,Qe.toUnwrapped()),bt.draw(ye,Ze.TRIANGLES,Me,Jr.disabled,_e,Gr.backCCW,nr,Pe.id,Lt.vertexBuffer,Lt.indexBuffer,Ft,Pe.paint,ye.transform.zoom,ot,[Lt.vertexBufferNormal])}};qe(!0),qe(!1)}(re)}}else A0(re,!1,se,_.stencilModeFor3D())},"fill-extrusion":function(_,d,g,w){const j=g.paint.get("fill-extrusion-opacity"),I=_.context,L=I.gl,F=_.terrain,z=F&&F.renderingToTexture;if(j===0)return;const H=_.emissiveMode==="mrt-fallback",Z=_.conflationActive&&_.style.isLayerClipped(g,d.getSource()),ne=_.style.order.indexOf(g.fqid);if(Z&&function(re,se,ce,oe,ye){for(const ge of oe){const Pe=se.getTile(ge).getBucket(ce);Pe&&(Pe.updateReplacement(ge,re.replacementSource,ye),Pe.uploadCentroid(re.context))}}(_,d,g,w,ne),F||Z)for(const re of w){const se=d.getTile(re).getBucket(g);se&&XN(_.context,d,re,se,g,F,Z)}if(_.renderPass==="shadow"&&_.shadowRenderer){if(F&&j<.65&&g._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof a.af)return;const re=_.shadowRenderer.getShadowPassDepthMode();Qm(_,d,g,w,re,Jr.disabled,Yr.disabled,Z)}else if(_.renderPass==="translucent"){const re=!g.paint.get("fill-extrusion-pattern").constantOr(1),se=g.paint.get("fill-extrusion-color").constantOr(a.aq.white);if(!z&&se.a!==0){const ce=new Ir(_.context.gl.LEQUAL,Ir.ReadWrite,_.depthRangeFor3D);j===1&&re?Qm(_,d,g,w,ce,Jr.disabled,Yr.unblended,Z):(Qm(_,d,g,w,ce,Jr.disabled,Yr.disabled,Z),Qm(_,d,g,w,ce,_.stencilModeFor3D(),_.colorModeForRenderPass(),Z),_.resetStencilClippingMasks())}if(_.style.enable3dLights()&&re&&(!F&&_.transform.projection.name!=="globe"||z)){const ce=g.paint.get("fill-extrusion-opacity"),oe=g.paint.get("fill-extrusion-ambient-occlusion-intensity"),ye=g.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),ge=g.paint.get("fill-extrusion-flood-light-intensity"),Pe=g.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",De=g.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Pe?null:g.lut).toArray01().slice(0,3),_e=oe>0&&ye>0,Ze=ge>0,$e=(Be,qe,st)=>(1-st)*Be+st*qe,Ke=new vE;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 Me=Be=>{const qe=_.depthModeForSublayer(1,Ir.ReadOnly,L.LEQUAL,!0),st=g.paint.get(Be?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Qe=$e(.1,3,st),xt=_._showOverdrawInspector;if(!xt){const ft=new Jr({func:L.ALWAYS,mask:255},255,255,L.KEEP,L.KEEP,L.REPLACE),Lt=new Yr([L.ONE,L.ONE,L.ONE,L.ONE],a.aq.transparent,[!1,!1,!1,!0],L.MIN);Ld(Ke,_,d,g,w,qe,ft,Lt,Gr.disabled,Be,"sdf",ce,oe,ye,ge,De,Qe,Z,!1)}{const ft=xt?Jr.disabled:new Jr({func:L.EQUAL,mask:255},255,255,L.KEEP,L.DECR,L.DECR),Lt=xt?_.colorModeForRenderPass():new Yr([L.ONE_MINUS_DST_ALPHA,L.DST_ALPHA,L.ONE,L.ONE],a.aq.transparent,[!0,!0,!0,!0]);Ld(Ke,_,d,g,w,qe,ft,Lt,Gr.disabled,Be,"color",ce,oe,ye,ge,De,Qe,Z,!1)}};if(z){const Be=()=>{const st=F.drapeBufferSize[0],Qe=F.drapeBufferSize[1];let xt=F.framebufferCopyTexture;return xt&&(!xt||xt.size[0]===st&&xt.size[1]===Qe)||(xt&&xt.destroy(),xt=F.framebufferCopyTexture=new a.T(I,new a.q({width:st,height:Qe}),L.RGBA8)),xt.bind(L.LINEAR,L.CLAMP_TO_EDGE),L.copyTexSubImage2D(L.TEXTURE_2D,0,0,0,0,0,st,Qe),xt},qe=(st,Qe,xt)=>{const ft=_.depthModeForSublayer(1,Ir.ReadOnly,L.LEQUAL,!1),Lt=g.paint.get(st?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Ft=$e(.1,3,Lt);{const ot=new Yr([L.ONE,L.ONE,L.ONE,L.ONE],a.aq.transparent,[!1,!1,!1,!0]);Ld(Ke,_,d,g,w,ft,Jr.disabled,ot,Gr.disabled,st,"clear",ce,oe,ye,ge,De,Ft,Z,Qe)}{const ot=new Jr({func:L.ALWAYS,mask:255},255,255,L.KEEP,L.KEEP,L.REPLACE),et=new Yr([L.ONE,L.ONE,L.ONE,L.ONE],a.aq.transparent,[!1,!1,!1,!0],L.MIN);Ld(Ke,_,d,g,w,ft,ot,et,Gr.disabled,st,"sdf",ce,oe,ye,ge,De,Ft,Z,Qe)}H&&!st&&(xt=Be());{const ot=st?L.ZERO:L.ONE_MINUS_DST_ALPHA,et=new Jr({func:L.EQUAL,mask:255},255,255,L.KEEP,L.DECR,L.DECR),gt=new Yr([ot,L.DST_ALPHA,L.ONE_MINUS_DST_ALPHA,L.ZERO],a.aq.transparent,[!0,!0,!0,!0]);Ld(Ke,_,d,g,w,ft,et,gt,Gr.disabled,st,"color",ce,oe,ye,ge,De,Ft,Z,Qe)}if(!H||st){const ot=new Yr([L.ONE,L.ONE,L.ONE,st?L.ZERO:L.ONE],a.aq.transparent,[!1,!1,!1,!0],st?L.FUNC_ADD:L.MAX);Ld(Ke,_,d,g,w,ft,Jr.disabled,ot,Gr.disabled,st,"clear",ce,oe,ye,ge,De,Ft,Z,Qe,xt)}else{L.drawBuffers([L.NONE,L.COLOR_ATTACHMENT1]);const ot=new Jr({func:L.EQUAL,mask:255},254,255,L.KEEP,L.DECR,L.DECR),et=new Yr([L.ONE,L.ONE,L.ONE,L.ONE],a.aq.transparent,[!0,!1,!1,!1],L.MAX);Ld(Ke,_,d,g,w,ft,ot,et,Gr.disabled,st,"emissive",ce,oe,ye,ge,De,Ft,Z,Qe,xt),L.drawBuffers([L.COLOR_ATTACHMENT0])}};if(_e||Ze){let st;_.prepareDrawTile(),H&&!_e||(st=Be()),_e&&qe(!0,!1,st),Ze&&qe(!1,!0,st)}}else _e&&Me(!0),Ze&&Me(!1),(_e||Ze)&&_.resetStencilClippingMasks()}}},building:function(_,d,g,w){_.currentLayer<_.firstLightBeamLayer&&(_.firstLightBeamLayer=_.currentLayer);const j=g.paint.get("building-ambient-occlusion-ground-intensity"),I=g.paint.get("building-ambient-occlusion-ground-radius"),L=g.paint.get("building-ambient-occlusion-ground-attenuation"),F=g.paint.get("building-opacity");if(F<=0)return;let z=j>0&&I>0,H=!0;const Z=g.paint.get("building-vertical-scale");if(Z<=0)return;_.shadowRenderer||(H=!1);const ne=_.conflationActive&&_.style.isLayerClipped(g,d.getSource()),re=_.style.order.indexOf(g.fqid);if(function(se,ce,oe,ye,ge,Pe){for(const De of Pe){const _e=ce.getTile(De).getBucket(oe);_e&&(ge&&_e.updateReplacement(De,se.replacementSource,ye),_e.uploadUpdatedIndexBuffer(se.context))}}(_,d,g,re,ne,w),function(se,ce,oe,ye){for(const ge of ye){const Pe=ce.getTile(ge).getBucket(oe);Pe&&Pe.needsEvaluation()&&Pe.uploadUpdatedColorBuffer(se.context)}}(_,d,g,w),g.resetLayerRenderingStats(_),_.shadowRenderer&&(_.shadowRenderer.useNormalOffset=!0),_.renderPass==="shadow"&&_.shadowRenderer){const se=[],ce=_.shadowRenderer.getShadowPassDepthMode();k0({painter:_,source:d,layer:g,coords:w,defines:se,blendMode:Yr.disabled,depthMode:ce,opacity:F,verticalScale:Z,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(_.renderPass==="translucent"){let se=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];H&&(se=se.concat("RENDER_SHADOWS")),_.shadowRenderer&&_.shadowRenderer.useNormalOffset&&(se=se.concat("NORMAL_OFFSET"));const ce=g.paint.get("building-facade-emissive-chance"),oe=g.paint.get("building-ambient-occlusion-intensity"),ye=g.paint.get("building-flood-light-intensity"),ge=g.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",Pe=g.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(ge?null:g.lut).toArray01().slice(0,3),De=g.paint.get("building-flood-light-ground-attenuation"),_e=ye>0,Ze=new Ir(_.context.gl.LEQUAL,Ir.ReadWrite,_.depthRangeFor3D);F<1&&k0({painter:_,source:d,layer:g,coords:w,defines:se,blendMode:Yr.disabled,depthMode:Ze,opacity:F,verticalScale:Z,facadeEmissiveChance:ce,facadeAOIntensity:oe,floodLightIntensity:ye,floodLightColor:Pe,depthOnly:!0});const $e=_.colorModeForRenderPass();k0({painter:_,source:d,layer:g,coords:w,defines:se,blendMode:$e,depthMode:Ze,opacity:F,verticalScale:Z,facadeEmissiveChance:ce,facadeAOIntensity:oe,floodLightIntensity:ye,floodLightColor:Pe});const Ke=g.paint.get("building-front-cutoff");pb(_.transform.pitch,Ke,!!_.terrain),z&&bE(_,d,g,w,!0,F,j,I,ye,Pe,L,ne),_e&&bE(_,d,g,w,!1,F,j,I,ye,Pe,De,ne)}else if(_.renderPass==="light-beam"){const se=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],ce=new Ir(_.context.gl.LEQUAL,Ir.ReadOnly,_.depthRangeFor3D);k0({painter:_,source:d,layer:g,coords:w,defines:se,blendMode:Yr.alphaBlended,depthMode:ce,opacity:F,verticalScale:Z,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}_.shadowRenderer&&(_.shadowRenderer.useNormalOffset=!1),_.resetStencilClippingMasks()},hillshade:function(_,d,g,w){if(_.renderPass!=="offscreen"&&_.renderPass!=="translucent"||_.style.disableElevatedTerrain)return;const j=_.context,I=_.terrain&&_.terrain.renderingToTexture,[L,F]=_.renderPass!=="translucent"||I?[{},w]:_.stencilConfigForOverlap(w);for(const z of F){const H=d.getTile(z);if(H.needsHillshadePrepare&&_.renderPass==="offscreen")I5(_,H,g);else if(_.renderPass==="translucent"){const Z=_.depthModeForSublayer(0,Ir.ReadOnly),ne=g.paint.get("hillshade-emissive-strength"),re=_.colorModeForDrapableLayerRenderPass(ne),se=I&&_.terrain?_.terrain.stencilModeForRTTOverlap(z):L[z.overscaledZ];N5(_,z,H,g,Z,se,re)}}j.viewport.set([0,0,_.width,_.height]),_.resetStencilClippingMasks()},raster:function(_,d,g,w,j,I){if(_.renderPass!=="translucent")return;const L=g.paint.get("raster-opacity");if(L===0)return;const F=_.transform.projection.name==="globe",z=g.paint.get("raster-elevation")!==0,H=z&&F,Z=_.terrain&&_.terrain.exaggeration()>0&&z&&g.paint.get("raster-elevation-reference")==="ground",ne=!F&&Z;if(_.renderElevatedRasterBackface&&!H)return;const re=_.context,se=re.gl,ce=d.getSource(),oe=function(Be,qe,st,Qe,xt){const ft=qe.paint.get("raster-color"),Lt=Be.type==="raster-array",Ft=[],ot=qe.paint.get("raster-resampling"),et=qe.paint.get("raster-color-mix");let gt=qe.paint.get("raster-color-range");const bt=[et[0],et[1],et[2],0],St=et[3];let nr=ot==="nearest"?Qe.NEAREST:Qe.LINEAR;if(Lt&&(Ft.push("RASTER_ARRAY"),ft||Ft.push("RASTER_COLOR"),ot==="linear"&&Ft.push("RASTER_ARRAY_LINEAR"),nr=Qe.NEAREST,!gt&&Be.rasterLayers)){const Wt=Be.rasterLayers.find(({id:Kt})=>Kt===qe.sourceLayer);Wt&&Wt.fields&&Wt.fields.range&&(gt=Wt.fields.range)}if(gt=gt||[0,1],ft){Ft.push("RASTER_COLOR"),st.activeTexture.set(Qe.TEXTURE2),qe.updateColorRamp(gt);let Wt=qe.colorRampTexture;Wt||(Wt=qe.colorRampTexture=new a.T(st,qe.colorRamp,Qe.RGBA8)),Wt.bind(nr,Qe.CLAMP_TO_EDGE)}return xt&&Ft.push("USE_MRT1"),{mix:bt,range:gt,offset:St,defines:Ft,resampling:nr}}(ce,g,re,se,_.terrain&&_.terrain.renderingToTexture&&_.emissiveMode==="mrt-fallback");if(ce instanceof a.aV&&!w.length&&!F)return;const ye=g.paint.get("raster-emissive-strength"),ge=_.colorModeForDrapableLayerRenderPass(ye),Pe=_.terrain&&_.terrain.renderingToTexture,De=!_.options.moving,_e=g.paint.get("raster-resampling")==="nearest"?se.NEAREST:se.LINEAR;if(ce instanceof a.aV&&!w.length&&(ce.onNorthPole||ce.onSouthPole)){const Be=z?_.stencilModeFor3D():Jr.disabled;return void yb(!!ce.onNorthPole,null,_,d,g,ye,oe,Gr.disabled,Be)}if(!w.length)return;const[Ze,$e]=ce instanceof a.aV||Pe?[{},w]:_.stencilConfigForOverlap(w),Ke=$e[$e.length-1].overscaledZ;H&&oe.defines.push("PROJECTION_GLOBE_VIEW"),z&&oe.defines.push("RENDER_CUTOFF","ELEVATED"),Z&&oe.defines.push("ELEVATION_REFERENCE_GROUND");const Me=(Be,qe,st)=>{for(const Qe of Be){const xt=Qe.toUnwrapped(),ft=d.getTile(Qe);if(Pe&&(!ft||!ft.hasData()))continue;re.activeTexture.set(se.TEXTURE0);const Lt=eI(ft,ce,g,oe);if(!Lt||!Lt.texture)continue;const{texture:Ft,mix:ot,offset:et,tileSize:gt,buffer:bt}=Lt;let St,nr;Pe?(St=Ir.disabled,nr=Qe.projMatrix):z?(St=new Ir(se.LEQUAL,Ir.ReadWrite,_.depthRangeFor3D),nr=F?Float32Array.from(_.transform.expandedFarZProjMatrix):_.transform.calculateProjMatrix(xt,De)):(St=_.depthModeForSublayer(Qe.overscaledZ-Ke,L===1?Ir.ReadWrite:Ir.ReadOnly,se.LESS),nr=_.transform.calculateProjMatrix(xt,De));const Wt=_.terrain&&Pe?_.terrain.stencilModeForRTTOverlap(Qe):Ze[Qe.overscaledZ],Kt=I?0:g.paint.get("raster-fade-duration");ft.registerFadeDuration(Kt);const Mt=d.findLoadedParent(Qe,0),kr=v0(ft,Mt,d,_.transform,Kt);let Lr,yr;!kr.isFading&&ft.refreshedUponExpiration&&(ft.refreshedUponExpiration=!1),_.terrain&&_.terrain.prepareDrawTile(),re.activeTexture.set(se.TEXTURE0),Ft.bind(_e,se.CLAMP_TO_EDGE),re.activeTexture.set(se.TEXTURE1),Mt?(Mt.texture&&Mt.texture.bind(_e,se.CLAMP_TO_EDGE),Lr=Math.pow(2,Mt.tileID.overscaledZ-ft.tileID.overscaledZ),yr=[ft.tileID.canonical.x*Lr%1,ft.tileID.canonical.y*Lr%1]):Ft.bind(_e,se.CLAMP_TO_EDGE),"useMipmap"in Ft&&re.extTextureFilterAnisotropic&&_.transform.pitch>20&&se.texParameterf(se.TEXTURE_2D,re.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,re.extTextureFilterAnisotropicMax);const Er=_.transform;let Hr;const an=z?SE(Er):[0,0,0,0];let tn,bn,Ur,wn,rn,Gn=0;if(H&&ce instanceof a.aV&&ce.coordinates.length>3)tn=Float32Array.from(a.du(a.dv(new a.cn(0,0,0)))),bn=Float32Array.from(Er.globeMatrix),Ur=Float32Array.from(a.dq(Er)),wn=[a.aH(Er.center.lng),a.aL(Er.center.lat)],Hr=ce.elevatedGlobePerspectiveTransform,rn=ce.elevatedGlobeGridMatrix||new Float32Array(9);else if(H){const ei=a.dr(Qe.canonical);Gn=a.ds(ei.getCenter().lat),tn=Float32Array.from(a.du(a.dv(Qe.canonical))),bn=Float32Array.from(Er.globeMatrix),Ur=Float32Array.from(a.dq(Er)),wn=[a.aH(Er.center.lng),a.aL(Er.center.lat)],Hr=[0,0],rn=Float32Array.from(a.dt(Qe.canonical,ei,Gn,Er.worldSize/Er._pixelsPerMercatorPixel))}else Hr=ce instanceof a.aV?ce.perspectiveTransform:[0,0],tn=new Float32Array(16),bn=new Float32Array(9),Ur=new Float32Array(16),wn=[0,0],rn=new Float32Array(9);const wi=GN(_,nr,tn,bn,Ur,rn,yr||[0,0],a.al(_.transform.zoom),wn,an,Lr||1,kr,g,Hr,z?g.paint.get("raster-elevation"):0,2,ot,et,oe.range,gt,bt,ye),Xi=_.isTileAffectedByFog(Qe),Ni=_.getOrCreateProgram("raster",{defines:oe.defines,overrideFog:Xi});if(_.uploadCommonUniforms(re,Ni,xt),ce instanceof a.aV){const ei=ce.elevatedGlobeVertexBuffer,gn=ce.elevatedGlobeIndexBuffer;if(Pe||!F)ce.boundsBuffer&&ce.boundsSegments&&Ni.draw(_,se.TRIANGLES,St,Jr.disabled,ge,Gr.disabled,wi,g.id,ce.boundsBuffer,_.quadTriangleIndexBuffer,ce.boundsSegments);else if(ei&&gn){const yn=Er.zoom<=a.cJ?ce.elevatedGlobeSegments:ce.getSegmentsForLongitude(Er.center.lng);yn&&Ni.draw(_,se.TRIANGLES,St,Jr.disabled,ge,qe,wi,g.id,ei,gn,yn)}}else if(H){St=new Ir(se.LEQUAL,Ir.ReadOnly,_.depthRangeFor3D);const ei=_.globeSharedBuffers;if(ei){Z&&(_.terrain.setupElevationDraw(ft,Ni),_.uploadCommonUniforms(re,Ni,ft.tileID.toUnwrapped()));const[gn,yn,Ii]=ei.getGridBuffers(Gn,!1),ns=Ni.getAttributeLocation(se,"a_texture_pos");ns!==-1&&se.vertexAttribI4ui(ns,0,0,0,0),Ni.draw(_,se.TRIANGLES,St,st||Wt,_.colorModeForRenderPass(),qe,wi,g.id,gn,yn,Ii)}}else if(ne)St=new Ir(se.LEQUAL,Ir.ReadWrite,_.depthRangeFor3D),_.terrain.setupElevationDraw(ft,Ni),_.uploadCommonUniforms(re,Ni,ft.tileID.toUnwrapped()),Er.pitch>20&&Ni.draw(_,se.TRIANGLES,St,Jr.disabled,Yr.disabled,Gr.frontCCW,wi,g.id,_.terrain.gridBuffer,_.terrain.gridIndexBuffer,_.terrain.gridSegments),Ni.draw(_,se.TRIANGLES,St,Wt,ge,Gr.backCCW,wi,g.id,_.terrain.gridBuffer,_.terrain.gridIndexBuffer,_.terrain.gridSegments);else{const{tileBoundsBuffer:ei,tileBoundsIndexBuffer:gn,tileBoundsSegments:yn}=_.getTileBoundsBuffers(ft);Ni.draw(_,se.TRIANGLES,St,Wt,ge,Gr.disabled,wi,g.id,ei,gn,yn)}}if(!(ce instanceof a.aV)&&H)for(const Qe of Be){const xt=Qe.canonical.y===(1<a.d$[bt](xt));ot.push(xt);const et=xt.canonical.x,gt=xt.canonical.y;for(const bt of ot){const St=_e.getTile(qe?bt.wrapped():bt);if(!St)continue;const nr=St.rasterParticleState;if(!nr)continue;const Wt=bt.canonical.x+(1<Ke.tileID)),se&&(H.activeTexture.set(Z.TEXTURE0),_.imageManager.bind(_.context,g.scope));const $e=[];if(_.terrain&&_.terrain.renderingToTexture&&_.emissiveMode==="mrt-fallback"&&$e.push("USE_MRT1"),z){const Ke=_.getOrCreateProgram(De,{overrideFog:!1,overrideRtt:!0,defines:$e}),Me=new Float32Array(a.b9([])),Be=new a.aR(0,0,0,0,0),qe=se?Nf(Me,F,L,_,0,g.scope,ce,z,{tileID:Be,tileSize:re}):S0(Me,F,L,j.toPremultipliedRenderColor(I?null:g.lut));return void Ke.draw(_,Z.TRIANGLES,ge,ye,Pe,Gr.disabled,qe,g.id,_.viewportBuffer,_.quadTriangleIndexBuffer,_.viewportSegments)}for(const Ke of Ze){const Me=_.isTileAffectedByFog(Ke),Be=_.getOrCreateProgram(De,{overrideFog:Me,defines:$e}),qe=Ke.toUnwrapped(),st=w?Ke.projMatrix:_.transform.calculateProjMatrix(qe);_.prepareDrawTile();const Qe=d?d.getTile(Ke):_e?_e[Ke.key]:new a.b0(Ke,re,ne.zoom,_),xt=se?Nf(st,F,L,_,0,g.scope,ce,z,{tileID:Ke,tileSize:re}):S0(st,F,L,j.toPremultipliedRenderColor(I?null:g.lut));_.uploadCommonUniforms(H,Be,qe);const{tileBoundsBuffer:ft,tileBoundsIndexBuffer:Lt,tileBoundsSegments:Ft}=_.getTileBoundsBuffers(Qe);Be.draw(_,Z.TRIANGLES,ge,ye,Pe,Gr.disabled,xt,g.id,ft,Lt,Ft)}},sky:function(_,d,g){const w=_._atmosphere?a.al(_.transform.zoom):1,j=g.paint.get("sky-opacity")*w;if(j===0)return;const I=_.context,L=g.paint.get("sky-type"),F=new Ir(I.gl.LEQUAL,Ir.ReadOnly,[0,1]),z=_.frameCounter/1e3%1;L==="atmosphere"?_.renderPass==="offscreen"?g.needsSkyboxCapture(_)&&(function(H,Z){const ne=H.context,re=ne.gl;let se=Z.skyboxFbo;if(!se){se=Z.skyboxFbo=ne.createFramebuffer(32,32,1,null),Z.skyboxGeometry=new tl(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 ge=0;ge<6;++ge)re.texImage2D(re.TEXTURE_CUBE_MAP_POSITIVE_X+ge,0,re.RGBA,32,32,0,re.RGBA,re.UNSIGNED_BYTE,null)}ne.bindFramebuffer.set(se.framebuffer),ne.viewport.set([0,0,32,32]);const ce=Z.getCenter(H,!0),oe=H.getOrCreateProgram("skyboxCapture"),ye=new Float64Array(16);a.b9(ye),a.ef(ye,ye,.5*-Math.PI),Ic(H,Z,oe,ye,ce,0),a.b9(ye),a.ef(ye,ye,.5*Math.PI),Ic(H,Z,oe,ye,ce,1),a.b9(ye),a.cE(ye,ye,.5*-Math.PI),Ic(H,Z,oe,ye,ce,2),a.b9(ye),a.cE(ye,ye,.5*Math.PI),Ic(H,Z,oe,ye,ce,3),a.b9(ye),Ic(H,Z,oe,ye,ce,4),a.b9(ye),a.ef(ye,ye,Math.PI),Ic(H,Z,oe,ye,ce,5),ne.viewport.set([0,0,H.width,H.height])}(_,g),g.markSkyboxValid(_)):_.renderPass==="sky"&&function(H,Z,ne,re,se){const ce=H.context,oe=ce.gl,ye=H.transform,ge=H.getOrCreateProgram("skybox");ce.activeTexture.set(oe.TEXTURE0),oe.bindTexture(oe.TEXTURE_CUBE_MAP,Z.skyboxTexture);const Pe=((De,_e,Ze,$e,Ke)=>({u_matrix:De,u_sun_direction:_e,u_cubemap:0,u_opacity:$e,u_temporal_offset:Ke}))(ye.skyboxMatrix,Z.getCenter(H,!1),0,re,se);H.uploadCommonUniforms(ce,ge),ge.draw(H,oe.TRIANGLES,ne,Jr.disabled,H.colorModeForRenderPass(),Gr.backCW,Pe,"skybox",Z.skyboxGeometry.vertexBuffer,Z.skyboxGeometry.indexBuffer,Z.skyboxGeometry.segment)}(_,g,F,j,z):L==="gradient"&&_.renderPass==="sky"&&function(H,Z,ne,re,se){const ce=H.context,oe=ce.gl,ye=H.transform,ge=H.getOrCreateProgram("skyboxGradient");Z.skyboxGeometry||(Z.skyboxGeometry=new tl(ce)),ce.activeTexture.set(oe.TEXTURE0);let Pe=Z.colorRampTexture;Pe||(Pe=Z.colorRampTexture=new a.T(ce,Z.colorRamp,oe.RGBA8)),Pe.bind(oe.LINEAR,oe.CLAMP_TO_EDGE);const De=((_e,Ze,$e,Ke,Me)=>({u_matrix:_e,u_color_ramp:0,u_center_direction:Ze,u_radius:a.ap($e),u_opacity:Ke,u_temporal_offset:Me}))(ye.skyboxMatrix,Z.getCenter(H,!1),Z.paint.get("sky-gradient-radius"),re,se);H.uploadCommonUniforms(ce,ge),ge.draw(H,oe.TRIANGLES,ne,Jr.disabled,H.colorModeForRenderPass(),Gr.backCW,De,"skyboxGradient",Z.skyboxGeometry.vertexBuffer,Z.skyboxGeometry.indexBuffer,Z.skyboxGeometry.segment)}(_,g,F,j,z)},custom:function(_,d,g,w){const j=_.context,I=g.implementation;if(!_.transform.projection.unsupportedLayers||!_.transform.projection.unsupportedLayers.includes("custom")||_.terrain&&(_.terrain.renderingToTexture||_.renderPass==="offscreen")&&g.isDraped(d)){if(_.renderPass==="offscreen"){const L=I.prerender;if(L){if(_.setCustomLayerDefaults(),j.setColorMode(_.colorModeForRenderPass()),_.transform.projection.name==="globe"){const F=_.transform.pointMerc;L.call(I,j.gl,_.transform.customLayerMatrix(),_.transform.getProjection(),_.transform.globeToMercatorMatrix(),a.al(_.transform.zoom),[F.x,F.y],_.transform.pixelsPerMeterRatio)}else L.call(I,j.gl,_.transform.customLayerMatrix());j.setDirty(),_.setBaseState()}}else if(_.renderPass==="translucent"){if(_.terrain&&_.terrain.renderingToTexture){const F=I.renderToTile;if(F){const z=w[0].canonical,H={x:z.x+w[0].wrap*(I.wrapTileId?0:1<{H&&(H.useNormalOffset=!0,Z||(H.enabled=!0))},re=d.getSource();if(_.renderPass==="light-beam"&&re.type!=="batched-model")return;if(re.type==="vector"||re.type==="geojson")return function(_e,Ze,$e,Ke,Me){const Be=_e.transform,qe=Be.projection.name==="globe",st=Be.getFreeCameraOptions().position;if(!_e.modelManager)return;const Qe=_e.modelManager;$e.modelManager=Qe;const xt=_e.shadowRenderer;if(!$e._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const ft=$e._unevaluatedLayout._values["model-id"],Lt=Object.assign({},$e.layout.get("model-id").parameters),Ft=_e.style.order.indexOf($e.fqid),ot=$e.paint.get("model-opacity").constantOr(1);for(const et of Ke){const gt=Ze.getTile(et).getBucket($e);if(!gt||gt.projection.name!==Be.projection.name)continue;const bt=gt.getModelUris();if(bt&&!gt.modelsRequested&&(Qe.addModelsFromBucket(bt,Me),gt.modelsRequested=!0),qe)Lt.zoom=et.overscaledZ;else{const yr=qg(et,Be);Lt.zoom=yr}const St=ft.possiblyEvaluate(Lt);if(Qt(_e,gt,et),Ht.shadowUniformsInitialized=!1,Ht.useSingleShadowCascade=!!xt&&xt.getMaxCascadeForTile(et.toUnwrapped())===0,_e.renderPass==="shadow"&&xt){if(_e.currentShadowCascade===1&>.isInsideFirstShadowMapFrustum)continue;const yr=Be.calculatePosMatrix(et.toUnwrapped(),Be.worldSize);if(Ht.tileMatrix.set(yr),Ht.shadowTileMatrix=Float32Array.from(xt.calculateShadowPassMatrixFromMatrix(yr)),Ht.aabb.min=[0,0,0],Ht.aabb.max[0]=Ht.aabb.max[1]=a.an,Ht.aabb.max[2]=0,oI(gt,Ht,_e,$e.scope))continue}const nr=1<0&&_e.style.isLayerClipped($e,Ze.getSource())&>.updateReplacement(et,_e.replacementSource,Ft,$e.scope)&&(gt.uploaded=!1,gt.upload(_e.context));let Kt=0;const Mt=new Array,kr=new Array,Lr=new Array;for(let yr in gt.instancesPerModel){const Er=gt.instancesPerModel[yr];Er.features.length>0&&!qe&&(yr=St.evaluate(Er.features[0].feature,{}));const Hr=Qe.getModel(yr,Me);if(Hr||Qe.hasURLBeenRequested(yr)||gt.modelUris.includes(yr)||(gt.modelUris.push(yr),gt.modelsRequested=!1),Hr&&Hr.uploaded)if(qe){const an=a.bJ([],[st.x,st.y,st.z],_e.transform.worldSize);a.eo(an,an);for(let tn=0;tn0&&wn.elevationUpdate(yr.terrain,tn,Ur,Hr.source),wn.needsReEvaluation(yr,bn,Hr)&&wn.evaluate(Hr))}})(_e,Ze,$e,Ke),function(){const yr=new Map;let Er,Hr,an;Mt?(Er=Ke.length-1,Hr=-1,an=-1):(Er=0,Hr=Ke.length,an=1);const tn=new Float64Array(16),bn=a.ce(),Ur=new a.P(0,0);for(let wn=Er;wn!==Hr;wn+=an){const rn=Ke[wn],Gn=Ze.getTile(rn).getBucket($e);if(!Gn||!Gn.uploaded)continue;let wi=!1;st&&(wi=st.getMaxCascadeForTile(rn.toUnwrapped())===0);const Xi=Be.calculatePosMatrix(rn.toUnwrapped(),Be.worldSize),Ni=Gn.modelTraits;!nr&&Mt&&(a.b7(tn,Xi),a.ah(bn,xt,tn),Ur.x=bn[0],Ur.y=bn[1]);const ei=[];Gn.setFilter($e.filter);for(const gn of Gn.getNodesInfo()){if(gn.hiddenByReplacement||!gn.node.meshes)continue;const yn=gn.node;let Ii=0;_e.terrain&&yn.elevation&&(Ii=yn.elevation*_e.terrain.exaggeration());const ns=(()=>{const Ha=gn.aabb;return St.min=[...Ha.min],St.max=[...Ha.max],St.min[2]+=Ii,St.max[2]+=Ii,a.ah(St.min,St.min,Xi),a.ah(St.max,St.max,Xi),St})(),ti=gn.evaluatedScale;if(ti[0]<=1&&ti[1]<=1&&ti[2]<=1&&ns.intersects(Wt)===0)continue;if(!nr&&Mt){const Ha=.16666666666666666;gn.cameraCollisionOpacity=xt[0]>ns.min[0]&&xt[0]ns.min[1]&&xt[1]!Mt||gn.opacity===1&&yn.opacity===1?gn.depthyn.depth?-1:1);for(const gn of ei){const yn=gn.nodeInfo,Ii=yn.node;if(_e._debugParams.show3DModelFootprints&&Ii.footprint){const In=Ii.id||Ii.name||"footprint";yr.has(In)||yr.set(In,{node:Ii,mvp:gn.wvpForTile})}let ns=a.aD([],ot,gn.tileModelMatrix);a.aD(ns,Lt,ns);const ti=a.b7([],ns);a.e6(ti,ti),a.cC(ti,ti,nt),ns=a.aD(ns,ns,Ii.globalMatrix);const ln=_e.renderPass==="light-beam",Yi=$e.paint.get("model-color-use-theme").constantOr("default")==="none",Si=Ni&a.ez.HasMapboxMeshFeatures,Bs=Si?0:yn.evaluatedRMEA[0][2];for(let In=0;In=Ln||gc>=Ln}}const li=ji.material;let Lc;li.occlusionTexture&&li.occlusionTexture.offsetScale&&(Lc=li.occlusionTexture.offsetScale,fa.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const Dc=_e.getOrCreateProgram("model",fa);!nr&&st&&st.setupShadowsFromMatrix(gn.tileModelMatrix,Dc,st.useNormalOffset),_e.uploadCommonUniforms(Me,Dc,null,pc);const Oi=li.pbrMetallicRoughness;Oi.metallicFactor=.9,Oi.roughnessFactor=.5;const Vi=Zm(new Float32Array(Eo),new Float32Array(ns),new Float32Array(ti),new Float32Array(Ii.globalMatrix),_e,gn.opacity,Oi.baseColorFactor,li.emissiveFactor,Oi.metallicFactor,Oi.roughnessFactor,li,Bs,$e,[0,0,0],Lc);!ta&&(yn.hasTranslucentParts||gn.opacity<1)&&Dc.draw(_e,Me.gl.TRIANGLES,gt,Jr.disabled,Yr.disabled,Gr.backCCW,Vi,$e.id,ji.vertexBuffer,ji.indexBuffer,ji.segments,$e.paint,_e.transform.zoom,void 0,Ha),Dc.draw(_e,Me.gl.TRIANGLES,ta?bt:gt,Jr.disabled,ta||gn.opacity<1||yn.hasTranslucentParts?Yr.alphaBlended:Yr.unblended,Gr.backCCW,Vi,$e.id,ji.vertexBuffer,ji.indexBuffer,ji.segments,$e.paint,_e.transform.zoom,void 0,Ha)}}}if(_e._debugParams.show3DModelFootprints&&yr.size>0){const wn=Array.from(yr.keys()).sort();for(const rn of wn){const{node:Gn,mvp:wi}=yr.get(rn);RE(_e,0,Gn,wi)}}}()}(_,d,g,w),void ne();if(re.type!=="model")return;const se=re.getModels(),ce=[],oe=_.transform.getFreeCameraOptions().position,ye=a.bJ([],[oe.x,oe.y,oe.z],_.transform.worldSize);a.eo(ye,ye);const ge=[],Pe=[];let De=0;for(const _e of se){const Ze=d.getFeatureState("",_e.id),$e={type:"Unknown",id:_e.id,properties:_e.featureProperties},Ke=g.paint.get("model-rotation").evaluate($e,Ze),Me=g.paint.get("model-scale").evaluate($e,Ze),Be=g.paint.get("model-translation").evaluate($e,Ze),qe=g.paint.get("model-opacity").evaluate($e,Ze);LE(g,_e.id,Ze,_e.featureProperties,_e.nodeOverrideNames,_e.nodeOverrides),ep(g,_e.id,Ze,_e.featureProperties,_e.materialOverrideNames,_e.materialOverrides),_e.nodeOverrides.size>0&&_e.computeBoundsAndApplyParent(),_e.computeModelMatrix(_,Ke,Me,Be,F,L,!1);const st=a.b9([]),Qe=a.e2(_e.position.lat,_.transform.zoom),xt=a.bP([],[1,1,1/Qe]);a.bx(st,st,ye),ce.push({zScaleMatrix:xt,negCameraPosMatrix:st});for(const ft of _e.nodes)_b(_,ft,_e.matrix,_.transform.expandedFarZProjMatrix,De,ge,Pe,_e.materialOverrides,qe);De++}if(ge.sort((_e,Ze)=>Ze.depth-_e.depth),_.renderPass!=="shadow"){if(_._debugParams.show3DModelFootprints){const _e=_.transform.projMatrix,Ze=new Map,$e=(Me,Be)=>{if(Me.footprint){const qe=Me.id||Me.name||"footprint";if(!Ze.has(qe)){const st=a.aD([],_e,Be);Ze.set(qe,{node:Me,mvp:st})}}};for(const Me of Pe)$e(Me.node,Me.modelMatrix);for(const Me of ge)$e(Me.node,Me.modelMatrix);const Ke=Array.from(Ze.keys()).sort();for(const Me of Ke){const{node:Be,mvp:qe}=Ze.get(Me);RE(_,0,Be,qe)}}Ah(_,g,ge,Pe,ce),ne()}else{for(const _e of Pe)Vg(_e.mesh,_e.nodeModelMatrix,_,g);for(const _e of ge)Vg(_e.mesh,_e.nodeModelMatrix,_,g);ne()}}},OE={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 w=d.getVisibleCoordinates();for(const j of w){const I=d.getTile(j).getBucket(_);if(I&&(I.elevationType!=="none"?_.hasElevatedBuckets=!0:_.hasNonElevatedBuckets=!0,_.hasElevatedBuckets&&_.hasNonElevatedBuckets))break}}}else _.hasNonElevatedBuckets=!0},model:function(_,d,g){const w=d.getSource();if(!w.loaded())return;if(w.type==="vector"||w.type==="geojson")return void(g.modelManager&&g.modelManager.upload(g,vb(g,_)));if(w.type==="batched-model"||w.type!=="model")return;const j=w.getModels();for(const I of j)I.upload(g.context)},raster:function(_,d,g){const w=d.getSource();if(!(w instanceof Fm&&w.loaded()))return;const j=_.sourceLayer||w.rasterLayerIds&&w.rasterLayerIds[0];if(!j)return;const I=_.paint.get("raster-array-band")||w.getInitialBand(j);if(I==null)return;const L=d.getIds().map(F=>d.getTileByID(F));for(const F of L)F.updateNeeded(_.id,I)&&w.prepareTile(F,j,_.id,I)},"raster-particle":function(_,d,g){const w=d.getSource();if(!(w instanceof Fm&&w.loaded()))return;const j=_.sourceLayer||w.rasterLayerIds&&w.rasterLayerIds[0];if(!j)return;const I=_.paint.get("raster-particle-array-band")||w.getInitialBand(j);if(I==null)return;const L=d.getIds().map(F=>d.getTileByID(F));for(const F of L)F.updateNeeded(_.id,I)&&w.prepareTile(F,j,_.id,I)}},FE={fill:j0},BE={fill:function(_,d,g,w){if(!g.layout||g.layout.get("fill-elevation-reference")==="none"||g.paint.get("fill-opacity").constantOr(1)===0)return;const j=_.context.gl,I=new Ir(j.LEQUAL,Ir.ReadOnly,_.depthRangeFor3D),L=new Jr({func:j.ALWAYS,mask:255},255,255,j.KEEP,j.KEEP,j.REPLACE),F=_.transform.getFreeCameraOptions().position,z=_.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const H of w){const Z=d.getTile(H),ne=Z.getBucket(g);if(!ne)continue;const re=ne.elevatedStructures;if(!re||re.depthSegments.segments[0].primitiveLength===0)continue;const se=xE(H.toUnwrapped(),F),ce=_.translatePosMatrix(H.projMatrix,Z,g.paint.get("fill-translate"),g.paint.get("fill-translate-anchor")),oe=b0(ce,se,0,1,0);z.draw(_,j.TRIANGLES,I,L,Yr.disabled,Gr.disabled,oe,g.id,re.vertexBuffer,re.indexBuffer,re.depthSegments,g.paint,_.transform.zoom)}}};class K5{constructor(d,g,w,j,I){this.context=new zg(d,g),this.transform=w,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 z of L)this._debugParams.enabledLayers[z]=!0;for(const z of L);this.occlusionParams=new cI,this.setup(),this.numSublayers=fu.maxUnderzooming+fu.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 o0(this),this._wireframeDebugCache=new lI,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const F=new a.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new a.T(this.context,F,d.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=j,this.maxFrontCutoffRawStart=0,this.worldview=I,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(d,g){const w=!!d&&!!d.terrain&&this.transform.projection.supportsTerrain;if(!(w||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new _0(this,d));const j=this._terrain;this.transform.elevation=w?j:null,j.update(d,this.transform,g),this.transform.elevation&&!j.enabled&&(this.transform.elevation=null)}_updateFog(d){const g=d.fog;if(!g||this.transform.projection.name==="globe"||g.getOpacity(this.transform.pitch)<1||g.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[w,j]=g.getFovAdjustedRange(this.transform._fov);if(w>j)return void(this.transform.fogCullDistSq=null);const I=w+.78*(j-w);this.transform.fogCullDistSq=I*I}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(d){d&&!this._terrain&&(this._terrain=new _0(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 w of this.style.order)this.style._mergedLayers[w].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 w=new a.dB;w.emplaceBack(0,0),w.emplaceBack(a.an,0),w.emplaceBack(0,a.an),w.emplaceBack(a.an,a.an),this.debugBuffer=d.createVertexBuffer(w,a.dx.members),this.debugSegments=a.dy.simpleSegment(0,0,4,5);const j=new a.dB;j.emplaceBack(-1,-1),j.emplaceBack(1,-1),j.emplaceBack(-1,1),j.emplaceBack(1,1),this.viewportBuffer=d.createVertexBuffer(j,a.dx.members),this.viewportSegments=a.dy.simpleSegment(0,0,4,2);const I=new a.eH;I.emplaceBack(0,0,0,0),I.emplaceBack(a.an,0,a.an,0),I.emplaceBack(0,a.an,0,a.an),I.emplaceBack(a.an,a.an,a.an,a.an),this.mercatorBoundsBuffer=d.createVertexBuffer(I,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 F=new a.eJ;for(const H of[0,1,3,2,0])F.emplaceBack(H);this.debugIndexBuffer=d.createIndexBuffer(F),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 z=this.context.gl;this.stencilClearMode=new Jr({func:z.ALWAYS,mask:0},0,255,z.ZERO,z.ZERO,z.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(d){return d._makeTileBoundsBuffers(this.context,this.transform.projection),d._tileBoundsBuffer?{tileBoundsBuffer:d._tileBoundsBuffer,tileBoundsIndexBuffer:d._tileBoundsIndexBuffer,tileBoundsSegments:d._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const d=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,d.TRIANGLES,Ir.disabled,this.stencilClearMode,Yr.disabled,Gr.disabled,x0(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(d,g,w){if(!g||this.currentStencilSource===g.id||!d.isTileClipped()||!w||w.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let F=!1;for(const z of w)if(this._tileClippingMaskIDs[z.key]===void 0){F=!0;break}if(!F)return}this.currentStencilSource=g.id;const j=this.context,I=j.gl;this.nextStencilID+w.length>256&&this.clearStencil(),j.setColorMode(Yr.disabled),j.setDepthMode(Ir.disabled);const L=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const F of w){const z=g.getTile(F),H=this._tileClippingMaskIDs[F.key]=this.nextStencilID++,{tileBoundsBuffer:Z,tileBoundsIndexBuffer:ne,tileBoundsSegments:re}=this.getTileBoundsBuffers(z);L.draw(this,I.TRIANGLES,Ir.disabled,new Jr({func:I.ALWAYS,mask:0},H,255,I.KEEP,I.KEEP,I.REPLACE),Yr.disabled,Gr.disabled,x0(F.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 Jr({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 Jr({func:g.EQUAL,mask:255},this._tileClippingMaskIDs[d.key],0,g.KEEP,g.KEEP,g.REPLACE)}stencilConfigForOverlap(d){const g=this.context.gl,w=d.sort((L,F)=>F.overscaledZ-L.overscaledZ),j=w[w.length-1].overscaledZ,I=w[0].overscaledZ-j+1;if(I>1){this.currentStencilSource=void 0,this.nextStencilID+I>256&&this.clearStencil();const L={};for(let F=0;Fthis._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce((d,g)=>d+g/this._fpsHistory.length,0))}render(d,g){const w=a.o.now();this._dt=w-this._timeStamp,this._timeStamp=w,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=d.map.repaint,this.style=d,this.options=g;const j=this.style._mergedLayers,I=!(!this.terrain||!this.terrain.enabled),L=()=>this.style._getOrder(I).filter(ot=>{const et=j[ot];return!(et.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[et.type]});let F=L(),z=!1,H=!1,Z=null,ne=0,re=!1;for(const ot of F){const et=j[ot];et.visibility!=="none"&&(et.type==="circle"?z=!0:et.type==="building"?(Z=et,++ne):et.type==="symbol"&&(et.hasOcclusionOpacityProperties?H=!0:z=!0))}this.updateEmissiveMode();let se=F.map(ot=>j[ot]);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 ot in ce){const et=ce[ot];et.used&&(et.prepare(this.context),et.getSource().usedInConflation&&++ne)}let oe=!1;for(const ot of se)ot.isHidden(this.transform.zoom)||(ot.type==="clip"&&(oe=!0),this.prepareLayer(ot));const ye={},ge={},Pe={},De={},_e={};for(const ot in ce){const et=ce[ot];ye[ot]=et.getVisibleCoordinates(),ge[ot]=ye[ot].slice().reverse(),Pe[ot]=et.getVisibleCoordinates(!0).reverse(),De[ot]=et.getShadowCasterCoordinates(),_e[ot]=et.sortCoordinatesByDistance(ye[ot])}const Ze=ot=>{const et=this.style.getLayerSourceCache(ot);return et&&et.used?et.getSource():null};if(ne||oe||this._clippingActiveLastFrame){const ot=[],et=[];let gt=0;for(const bt of se)this.isSourceForClippingOrConflation(bt,Ze(bt))&&(ot.push(bt),et.push(gt)),gt++;if(ot&&(oe||ot.length>1)||this._clippingActiveLastFrame){oe=!1;const bt=[];for(let St=0;St0){const bt=Ze(et);bt&&(this.minCutoffZoom=Math.max(bt.minzoom,this.minCutoffZoom)),et.minzoom&&(this.minCutoffZoom=Math.max(et.minzoom,this.minCutoffZoom))}et.is3D(I)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=ot),this._lastOcclusionLayer=ot)}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(Pe),this.opaquePassCutoff=0,F=L(),se=F.map(ot=>j[ot]));const Ke=this._shadowRenderer;if(Ke){Ke.updateShadowParameters(this.transform,this.style.directionalLight);for(const ot in ce)for(const et of ye[ot]){let gt={min:0,max:0};this.terrain&&(gt=this.terrain.getMinMaxForTile(et)||gt),Ke.addShadowReceiver(et.toUnwrapped(),gt.min,gt.max)}}this.transform.projection.name!=="globe"||this.globeSharedBuffers||(this.globeSharedBuffers=new a.eL(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new sI(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const Me=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),Be=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(Me&&!this._snow&&(this._snow=new hI(this)),!Me&&this._snow&&(this._snow.destroy(),delete this._snow),Be&&!this._rain&&(this._rain=new N0(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 jh);const ot=this.style.getLayerSourceCache(Z);this.buildingTileBorderManager.updateBorders(ot,Z)}if(!xr.has(this.context.gl))return;this.renderPass="offscreen";for(const ot of se){const et=d.getLayerSourceCache(ot);if(!ot.hasOffscreenPass()||ot.isHidden(this.transform.zoom))continue;const gt=et?ge[et.id]:void 0;(ot.type==="custom"||ot.type==="raster"||ot.type==="raster-particle"||ot.isSky()||gt&>.length)&&this.renderLayer(this,et,ot,gt)}this.depthRangeFor3D=[0,1-(se.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,De)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const qe=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),st=(()=>{if(g.showOverdrawInspector)return a.aq.black;const ot=this.style.fog;if(ot&&this.transform.projection.supportsFog){const et=this.style.getLut(ot.scope);if(!qe){const gt=ot.properties.get("color-use-theme")==="none",bt=ot.properties.get("color").toNonPremultipliedRenderColor(gt?null:et).toArray01();return new a.aq(...bt)}if(qe){const gt=ot.properties.get("space-color-use-theme")==="none",bt=ot.properties.get("space-color").toNonPremultipliedRenderColor(gt?null:et).toArray01();return new a.aq(...bt)}}return a.aq.transparent})();if(this.context.clear({color:st,depth:1}),this.clearStencil(),this._showOverdrawInspector=g.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&qe&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=F.length-1;this.currentLayer>=0;this.currentLayer--){const ot=se[this.currentLayer],et=d.getLayerSourceCache(ot);if(ot.isSky())continue;const gt=et?(ot.is3D(I)?_e:ge)[et.id]:void 0;this._renderTileClippingMasks(ot,et,gt),this.renderLayer(this,et,ot,gt)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&qe&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||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 gt=this.currentLayer;this.depthOcclusion=!0;for(const bt of this.layersWithOcclusionOpacity){this.currentLayer=bt;const St=se[this.currentLayer],nr=d.getLayerSourceCache(St),Wt=nr?ge[nr.id]:void 0;this.terrain||this._renderTileClippingMasks(St,nr,nr?ye[nr.id]:void 0),this.renderLayer(this,nr,St,Wt)}this.depthOcclusion=!1,this.currentLayer=gt,this.renderPass="translucent",this.layersWithOcclusionOpacity=[]}++this.currentLayer}}if(this.terrain&&this.terrain.postRender(),this._snow&&this._snow.draw(this),this._rain&&this._rain.draw(this),this.options.showTileBoundaries||this.options.showQueryGeometry||this.options.showTileAABBs){let ot=null;se.forEach(et=>{const gt=d.getLayerSourceCache(et);gt&&!et.isHidden(this.transform.zoom)&>.getVisibleCoordinates().length&&(!ot||ot.getSource().maxzoom0?g.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(d,g,w){const j=w===void 0?this.terrain&&this.terrain.renderingToTexture:w,I=[];return this.style&&this.style.enable3dLights()&&(d==="globeRaster"||d==="terrainRaster"?(I.push("LIGHTING_3D_MODE"),I.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):j||I.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(I.push("TERRAIN"),this.linearFloatFilteringSupported()&&I.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&I.push("GLOBE"),!this._fogVisible||j||g!==void 0&&!g||I.push("FOG"),j&&I.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&I.push("OVERDRAW_INSPECTOR"),I}getOrCreateProgram(d,g){this.cache=this.cache||{};const w=g&&g.defines||[],j=g&&g.config,I=this.currentGlobalDefines(d,g&&g.overrideFog,g&&g.overrideRtt).concat(w),L=Ym.cacheKey(SN[d],d,I,j);return this.cache[L]||(this.cache[L]=new Ym(this.context,d,SN[d],j,db[d],I)),this.cache[L]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.frontFace.setDefault(),this.context.cullFaceSide.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){const d=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(d.FUNC_ADD)}initDebugOverlayCanvas(){this.debugOverlayCanvas==null&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new 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 w=this.style.directionalLight,j=this.style.ambientLight;if(w&&j){const I=((L,F,z)=>{const H=L.properties.get("direction"),Z=L.properties.get("color-use-theme")==="none",ne=L.properties.get("color").toNonPremultipliedRenderColor(Z?null:z.getLut(L.scope)).toArray01(),re=L.properties.get("intensity"),se=F.properties.get("color-use-theme")==="none",ce=F.properties.get("color").toNonPremultipliedRenderColor(se?null:z.getLut(F.scope)).toArray01(),oe=F.properties.get("intensity"),ye=[H.x,H.y,H.z],ge=a.dD(ce,oe),Pe=a.dD(ne,re);return{u_lighting_ambient_color:ge,u_lighting_directional_dir:ye,u_lighting_directional_color:Pe,u_ground_radiance:fE(ye,Pe,ge)}})(w,j,this.style);g.setLightsUniformValues(d,I)}}}uploadCommonUniforms(d,g,w,j,I){if(this.uploadCommonLightUniforms(d,g),this.terrain&&this.terrain.renderingToTexture)return;const L=this.style.fog;if(L){const F=L.getOpacity(this.transform.pitch),z=((H,Z,ne,re,se,ce,oe,ye,ge,Pe,De,_e)=>{const Ze=H.transform,$e=Z.properties.get("color-use-theme")==="none",Ke=Z.properties.get("color").toNonPremultipliedRenderColor($e?null:H.style.getLut(Z.scope)).toArray01();Ke[3]=re;const Me=H.frameCounter/1e3%1,[Be,qe]=Z.properties.get("vertical-range");return{u_fog_matrix:ne?Ze.calculateFogTileMatrix(ne):_e||H.identityMat,u_fog_range:Z.getFovAdjustedRange(Ze._fov),u_fog_color:Ke,u_fog_horizon_blend:Z.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(Be,qe),qe],u_fog_temporal_offset:Me,u_frustum_tl:se,u_frustum_tr:ce,u_frustum_br:oe,u_frustum_bl:ye,u_globe_pos:ge,u_globe_radius:Pe,u_viewport:De,u_globe_transition:a.al(Ze.zoom),u_is_globe:+(Ze.projection.name==="globe")}})(this,L,w,F,this.transform.frustumCorners.TL,this.transform.frustumCorners.TR,this.transform.frustumCorners.BR,this.transform.frustumCorners.BL,this.transform.globeCenterInViewSpace,this.transform.globeRadius,[this.transform.width*a.o.devicePixelRatio,this.transform.height*a.o.devicePixelRatio],j);g.setFogUniformValues(d,z)}I&&g.setCutoffUniformValues(d,I.uniformValues)}setTileLoadedFlag(d){this.tileLoaded=d}saveCanvasCopy(){const d=this.canvasCopy();d&&(this.frameCopies.push(d),this.tileLoaded=!1)}canvasCopy(){const d=this.context.gl,g=d.createTexture();return d.bindTexture(d.TEXTURE_2D,g),d.copyTexImage2D(d.TEXTURE_2D,0,d.RGBA,0,0,d.drawingBufferWidth,d.drawingBufferHeight,0),g}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const d=this.style&&this.style.fog;return!!d&&d.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const d=this._backgroundTiles,g=this._backgroundTiles={},w=this.transform.coveringTiles({tileSize:512});for(const j of w)g[j.key]=d[j.key]||new a.b0(j,512,this.transform.tileZoom,this,void 0,this.worldview);return g}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(d,g){return!(!d.is3D(!(!this.terrain||!this.terrain.enabled))||d.type!=="clip"&&d.type!=="building"&&(d.minzoom&&d.minzoom>this.transform.zoom||(this.style._clipLayerPresent||d.sourceLayer!=="building"&&d.sourceLayer!=="procedural_buildings")&&(!g||g.type!=="batched-model")))}isTileAffectedByFog(d){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let g=this._cachedTileFogOpacities[d.key];return g||(this._cachedTileFogOpacities[d.key]=g=this.style.fog.getOpacityForTile(d)),g[0]>=Ln||g[1]>=Ln}setupDepthForOcclusion(d,g,w){const j=this.context,I=j.gl,L=!!w;var F;w||(w={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0}),j.activeTexture.set(I.TEXTURE3),d&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(I.NEAREST,I.CLAMP_TO_EDGE),w.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],w.u_depth_range_unpack=[2/((F=this.depthRangeFor3D)[1]-F[0]),-1-2*F[0]/(F[1]-F[0])],w.u_occluder_half_size=.5*this.occlusionParams.occluderSize,w.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(I.NEAREST,I.CLAMP_TO_EDGE),j.activeTexture.set(I.TEXTURE0),L||g.setTerrainUniformValues(j,w)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const d=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=d?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function $E(_,d){let g=!1,w=null;const j=()=>{w=null,g&&(_(),w=setTimeout(j,d),g=!1)};return()=>(g=!0,w||j(),w)}class Y5{constructor(d){this._hashName=d&&encodeURIComponent(d),a.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=$E(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=rl(d);if(this._hashName){const w=this._hashName;let j=!1;const I=location.hash.slice(1).split("&").map(L=>{const F=L.split("=")[0];return F===w?(j=!0,`${F}=${g}`):L}).filter(L=>L);return j||I.push(`${w}=${g}`),`#${I.join("&")}`}return`#${g}`}_getCurrentHash(){const d=location.hash.replace("#","");if(this._hashName){let g;return d.split("&").map(w=>w.split("=")).forEach(w=>{w[0]===this._hashName&&(g=w)}),(g&&g[1]||"").split("/")}return d.split("/")}_onHashChange(){const d=this._map;if(!d)return!1;const g=this._getCurrentHash();if(g.length>=3&&!g.some(w=>isNaN(Number(w)))){const w=d.dragRotate.isEnabled()&&d.touchZoomRotate.isEnabled()?+(g[3]||0):d.getBearing();return d.jumpTo({center:[+g[2],+g[1]],zoom:+g[0],bearing:w,pitch:+(g[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function rl(_,d){const g=_.getCenter(),w=Math.round(100*_.getZoom())/100,j=Math.ceil((w*Math.LN2+Math.log(512/360/.5))/Math.LN10),I=Math.pow(10,j),L=Math.round(g.lng*I)/I,F=Math.round(g.lat*I)/I,z=_.getBearing(),H=_.getPitch();let Z=d?`/${L}/${F}/${w}`:`${w}/${F}/${L}`;return(z||H)&&(Z+="/"+Math.round(10*z)/10),H&&(Z+=`/${Math.round(H)}`),Z}const Eb={linearity:.3,easing:a.eN(0,0,.3,1)},I0=Object.assign({deceleration:2500,maxSpeed:1400},Eb),Z5=Object.assign({deceleration:20,maxSpeed:1400},Eb),Gi=Object.assign({deceleration:1e3,maxSpeed:360},Eb),Rn=Object.assign({deceleration:1e3,maxSpeed:90},Eb);class mI{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:I}of this._inertiaBuffer)g.zoom+=I.zoomDelta||0,g.bearing+=I.bearingDelta||0,g.pitch+=I.pitchDelta||0,I.panDelta&&g.pan._add(I.panDelta),I.around&&(g.around=I.around),I.pinchAround&&(g.pinchAround=I.pinchAround);const w=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,j={};if(g.pan.mag()){const I=Md(g.pan.mag(),w,Object.assign({},I0,d||{}));j.offset=g.pan.mult(I.amount/g.pan.mag()),j.center=this._map.transform.center,mc(j,I)}if(g.zoom){const I=Md(g.zoom,w,Z5);j.zoom=this._map.transform.zoom+I.amount,mc(j,I)}if(g.bearing){const I=Md(g.bearing,w,Gi);j.bearing=this._map.transform.bearing+a.aC(I.amount,-179,179),mc(j,I)}if(g.pitch){const I=Md(g.pitch,w,Rn);j.pitch=this._map.transform.pitch+I.amount,mc(j,I)}if(j.zoom||j.bearing){const I=g.pinchAround===void 0?g.around:g.pinchAround;j.around=I?this._map.unproject(I):this._map.getCenter()}return this.clear(),j.noMoveStart=!0,j}}function mc(_,d){(!_.duration||_.durationg.unproject(z)),F=I.reduce((z,H,Z,ne)=>z.add(H.div(ne.length)),new a.P(0,0));super(d,{points:I,point:F,lngLats:L,lngLat:g.unproject(F),originalEvent:w}),this._defaultPrevented=!1}}class zE extends a.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(d,g){super("wheel",{originalEvent:g}),this._defaultPrevented=!1}}class UE{constructor(d,g){this._map=d,this._clickTolerance=g.clickTolerance}reset(){this._mousedownPos=void 0}wheel(d){return this._firePreventable(new zE(this._map,d))}mousedown(d,g){return this._mousedownPos=g,this._firePreventable(new To(d.type,this._map,d))}mouseup(d){this._map.fire(new To(d.type,this._map,d))}preclick(d){const g=new MouseEvent("preclick",d);this._map.fire(new To(g.type,this._map,g))}click(d,g){this._mousedownPos&&this._mousedownPos.dist(g)>=this._clickTolerance||(this.preclick(d),this._map.fire(new To(d.type,this._map,d)))}dblclick(d){return this._firePreventable(new To(d.type,this._map,d))}mouseover(d){this._map.fire(new To(d.type,this._map,d))}mouseout(d){this._map.fire(new To(d.type,this._map,d))}touchstart(d){return this._firePreventable(new Pc(d.type,this._map,d))}touchmove(d){this._map.fire(new Pc(d.type,this._map,d))}touchend(d){this._map.fire(new Pc(d.type,this._map,d))}touchcancel(d){this._map.fire(new Pc(d.type,this._map,d))}_firePreventable(d){if(this._map.fire(d),d.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class VE{constructor(d){this._map=d}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(d){this._map.fire(new To(d.type,this._map,d))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new To("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(d){this._delayContextMenu?this._contextMenuEvent=d:this._map.fire(new To(d.type,this._map,d)),this._map.listens("contextmenu")&&d.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class qE{constructor(d,g){this._map=d,this._el=d.getCanvasContainer(),this._container=d.getContainer(),this._clickTolerance=g.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(d,g){this.isEnabled()&&d.shiftKey&&d.button===0&&(V(),this._startPos=this._lastPos=g,this._active=!0)}mousemoveWindow(d,g){if(!this._active)return;const w=g,j=this._startPos,I=this._lastPos;if(!j||!I||I.equals(w)||!this._box&&w.dist(j){this._box&&(this._box.style.transform=`translate(${L}px,${z}px)`,this._box.style.width=F-L+"px",this._box.style.height=H-z+"px")})}mouseupWindow(d,g){if(!this._active)return;const w=this._startPos,j=g;if(w&&d.button===0){if(this.reset(),Y(),w.x!==j.x||w.y!==j.y)return this._map.fire(new a.C("boxzoomend",{originalEvent:d})),{cameraAnimation:I=>I.fitScreenCoordinates(w,j,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",d)}}keydown(d){this._active&&d.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",d))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),G(),delete this._startPos,delete this._lastPos}_fireEvent(d,g){return this._map.fire(new a.C(d,{originalEvent:g}))}}function P0(_,d){const g={};for(let w=0;w<_.length;w++)g[_[w].identifier]=d[w];return g}class xu{constructor(d){this.reset(),this.numTouches=d.numTouches}reset(){this.centroid=void 0,this.startTime=0,this.touches={},this.aborted=!1}touchstart(d,g,w){(this.centroid||w.length>this.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=d.timeStamp),w.length===this.numTouches&&(this.centroid=function(j){const I=new a.P(0,0);for(const L of j)I._add(L);return I.div(j.length)}(g),this.touches=P0(w,g)))}touchmove(d,g,w){if(this.aborted||!this.centroid)return;const j=P0(w,g);for(const I in this.touches){const L=j[I];(!L||L.dist(this.touches[I])>30)&&(this.aborted=!0)}}touchend(d,g,w){if((!this.centroid||d.timeStamp-this.startTime>500)&&(this.aborted=!0),w.length===0){const j=!this.aborted&&this.centroid;if(this.reset(),j)return j}}}class Od{constructor(d){this.singleTap=new xu(d),this.numTaps=d.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(d,g,w){this.singleTap.touchstart(d,g,w)}touchmove(d,g,w){this.singleTap.touchmove(d,g,w)}touchend(d,g,w){const j=this.singleTap.touchend(d,g,w);if(j){const I=d.timeStamp-this.lastTime<500,L=!this.lastTap||this.lastTap.dist(j)<30;if(I&&L||this.reset(),this.count++,this.lastTime=d.timeStamp,this.lastTap=j,this.count===this.numTaps)return this.reset(),j}}}class Hg{constructor(){this._zoomIn=new Od({numTouches:1,numTaps:2}),this._zoomOut=new Od({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(d,g,w){this._zoomIn.touchstart(d,g,w),this._zoomOut.touchstart(d,g,w)}touchmove(d,g,w){this._zoomIn.touchmove(d,g,w),this._zoomOut.touchmove(d,g,w)}touchend(d,g,w){const j=this._zoomIn.touchend(d,g,w),I=this._zoomOut.touchend(d,g,w);return j?(this._active=!0,d.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:L=>L.easeTo({duration:300,zoom:L.getZoom()+1,around:L.unproject(j)},{originalEvent:d})}):I?(this._active=!0,d.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:L=>L.easeTo({duration:300,zoom:L.getZoom()-1,around:L.unproject(I)},{originalEvent:d})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const jb=0,GE=2,HE={[jb]:1,[GE]:2},Ch={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class R0{constructor(d){this.reset(),this._clickTolerance=d.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(d,g){return!1}_move(d,g){return{}}mousedown(d,g){if(this._lastPoint)return;const w=ee(d);this._correctButton(d,w)&&(this._lastPoint=g,this._eventButton=w)}mousemoveWindow(d,g){const w=this._lastPoint;if(w){if(d.preventDefault(),this._eventButton!=null&&function(j,I){const L=HE[I];return j.buttons===void 0||(j.buttons&L)!==L}(d,this._eventButton))this.reset();else if(this._moved||!(g.dist(w)0&&(this._active=!0);const j=P0(w,g),I=new a.P(0,0),L=new a.P(0,0);let F=0;for(const H in j){const Z=j[H],ne=this._touches[H];ne&&(I._add(Z),L._add(Z.sub(ne)),F++,j[H]=Z)}if(this._touches=j,F{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class D0{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(d){}_move(d,g,w){return{}}touchstart(d,g,w){this._firstTwoTouches||w.length<2||(this._firstTwoTouches=[w[0].identifier,w[1].identifier],this._start([g[0],g[1]]))}touchmove(d,g,w){const j=this._firstTwoTouches;if(!j)return;d.preventDefault();const[I,L]=j,F=_s(w,g,I),z=_s(w,g,L);if(!F||!z)return;const H=this._aroundCenter?null:F.add(z).div(2);return this._move([F,z],H,d)}touchend(d,g,w){if(!this._firstTwoTouches)return;const[j,I]=this._firstTwoTouches,L=_s(w,g,j),F=_s(w,g,I);L&&F||(this._active&&Y(),this.reset())}touchcancel(){this.reset()}enable(d){this._enabled=!0,this._aroundCenter=!!d&&d.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function _s(_,d,g){for(let w=0;w<_.length;w++)if(_[w].identifier===g)return d[w]}function kb(_,d){return Math.log2(_/d)}class KE extends D0{reset(){super.reset(),this._distance=0,this._startDistance=0}_start(d){this._startDistance=this._distance=d[0].dist(d[1])}_move(d,g){const w=this._distance;if(this._distance=d[0].dist(d[1]),this._active||!(Math.abs(kb(this._distance,this._startDistance))<.1))return this._active=!0,{zoomDelta:kb(this._distance,w),pinchAround:g}}}function Cb(_,d){return 180*_.angleWith(d)/Math.PI}class rp extends D0{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 w=this._vector;if(this._vector=d[0].sub(d[1]),w&&(this._active||!this._isBelowThreshold(this._vector)))return this._active=!0,{bearingDelta:Cb(this._vector,w),pinchAround:g}}_isBelowThreshold(d){this._minDiameter=Math.min(this._minDiameter,d.mag());const g=25/(Math.PI*this._minDiameter)*360,w=this._startVector;if(!w)return!1;const j=Cb(d,w);return Math.abs(j)Math.abs(_.x)}class YE extends D0{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,M0(d[0].sub(d[1]))&&(this._valid=!1)}_move(d,g,w){const j=this._lastPoints;if(!j)return;const I=d[0].sub(j[0]),L=d[1].sub(j[1]);return this._map._cooperativeGestures&&!a.eO()&&w.touches.length<3||(this._valid=this.gestureBeginsVertically(I,L,w.timeStamp),!this._valid)?void 0:(this._lastPoints=d,this._active=!0,{pitchDelta:(I.y+L.y)/2*-.5})}gestureBeginsVertically(d,g,w){if(this._valid!==void 0)return this._valid;const j=d.mag()>=2,I=g.mag()>=2;if(!j&&!I)return;if(!j||!I)return this._firstMove==null&&(this._firstMove=w),w-this._firstMove<100&&void 0;const L=d.y>0==g.y>0;return M0(d)&&M0(g)&&L}}const ZE={panStep:100,bearingStep:15,pitchStep:10};class np{constructor(){const d=ZE;this._panStep=d.panStep,this._bearingStep=d.bearingStep,this._pitchStep=d.pitchStep,this._rotationDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(d){if(d.altKey||d.ctrlKey||d.metaKey)return;let g=0,w=0,j=0,I=0,L=0;switch(d.keyCode){case 61:case 107:case 171:case 187:g=1;break;case 189:case 109:case 173:g=-1;break;case 37:d.shiftKey?w=-1:(d.preventDefault(),I=-1);break;case 39:d.shiftKey?w=1:(d.preventDefault(),I=1);break;case 38:d.shiftKey?j=1:(d.preventDefault(),L=-1);break;case 40:d.shiftKey?j=-1:(d.preventDefault(),L=1);break;default:return}return this._rotationDisabled&&(w=0,j=0),{cameraAnimation:F=>{const z=F.getZoom();F.easeTo({duration:300,easeId:"keyboardHandler",easing:XE,zoom:g?Math.round(z)+g*(d.shiftKey?2:1):z,bearing:F.getBearing()+w*this._bearingStep,pitch:F.getPitch()+j*this._pitchStep,offset:[-I*this._panStep,-L*this._panStep],center:F.getCenter()},{originalEvent:d})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0}enableRotation(){this._rotationDisabled=!1}}function XE(_){return _*(2-_)}const ip=4.000244140625,QE=1/450;class Nb{constructor(d,g){this._map=d,this._el=d.getCanvasContainer(),this._handler=g,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=QE,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 w=a.o.now(),j=w-(this._lastWheelEventTime||0);this._lastWheelEventTime=w,g!==0&&g%ip===0?this._type="wheel":g!==0&&Math.abs(g)<4?this._type="trackpad":j>400?(this._type=null,this._lastValue=g,this._timeout=window.setTimeout(this._onTimeout,40,d)):this._type||(this._type=Math.abs(j*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 H=this._type==="wheel"&&Math.abs(this._delta)>ip?this._wheelZoomRate:this._defaultZoomRate;let Z=2/(1+Math.exp(-Math.abs(this._delta*H)));this._delta<0&&Z!==0&&(Z=1/Z);const ne=g(),re=Math.pow(2,ne),se=typeof this._targetZoom=="number"?d.zoomScale(this._targetZoom):re;this._targetZoom=Math.min(d.maxZoom,Math.max(d.minZoom,d.scaleZoom(se*Z))),this._type==="wheel"&&(this._startZoom=ne,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const w=typeof this._targetZoom=="number"?this._targetZoom:g(),j=this._startZoom,I=this._easing;let L,F=!1;if(this._type==="wheel"&&j&&I){const H=Math.min((a.o.now()-this._lastWheelEventTime)/200,1),Z=I(H);L=a.am(j,w,Z),H<1?this._frameId||(this._frameId=!0):F=!0}else L=w,F=!0;this._active=!0,F&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let z=L-g();return z*this._lastDelta<0&&(z=0),{noInertia:!0,needsRenderFrame:!F,zoomDelta:z,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(d){let g=a.eP;if(this._prevEase){const w=this._prevEase,j=(a.o.now()-w.start)/w.duration,I=w.easing(j+.01)-w.easing(j),L=.27/Math.sqrt(I*I+1e-4)*.01,F=Math.sqrt(.0729-L*L);g=a.eN(L,F,.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=P("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=/(Mac|iPad)/i.test(navigator.userAgent)?this._map._getUIString("ScrollZoomBlocker.CmdMessage"):this._map._getUIString("ScrollZoomBlocker.CtrlMessage"),this._alertContainer.style.fontSize=`${Math.max(10,Math.min(24,Math.floor(.05*this._el.clientWidth)))}px`)}_showBlockerAlert(){this._alertContainer.style.visibility="visible",this._alertContainer.classList.add("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.setAttribute("role","alert"),clearTimeout(this._alertTimer),this._alertTimer=window.setTimeout(()=>{this._alertContainer.classList.remove("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.removeAttribute("role")},200)}}class Ib{constructor(d,g){this._clickZoom=d,this._tapZoom=g}enable(){this._clickZoom.enable(),this._tapZoom.enable()}disable(){this._clickZoom.disable(),this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class Pb{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(d,g){return d.preventDefault(),{cameraAnimation:w=>{w.easeTo({duration:300,zoom:w.getZoom()+(d.shiftKey?-1:1),around:w.unproject(g)},{originalEvent:d})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class pI{constructor(){this._tap=new Od({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(d,g,w){this._swipePoint||(this._tapTime&&d.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?w.length>0&&(this._swipePoint=g[0],this._swipeTouch=w[0].identifier):this._tap.touchstart(d,g,w))}touchmove(d,g,w){if(this._tapTime){if(this._swipePoint){if(w[0].identifier!==this._swipeTouch)return;const j=g[0],I=j.y-this._swipePoint.y;return this._swipePoint=j,d.preventDefault(),this._active=!0,{zoomDelta:I/128}}}else this._tap.touchmove(d,g,w)}touchend(d,g,w){this._tapTime?this._swipePoint&&w.length===0&&this.reset():this._tap.touchend(d,g,w)&&(this._tapTime=d.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class JE{constructor(d,g,w){this._el=d,this._mousePan=g,this._touchPan=w}enable(d){this._inertiaOptions=d||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("mapboxgl-touch-drag-pan")}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("mapboxgl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class gI{constructor(d,g,w){this._pitchWithRotate=d.pitchWithRotate,this._mouseRotate=g,this._mousePitch=w}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}}class yI{constructor(d,g,w,j){this._el=d,this._touchZoom=g,this._touchRotate=w,this._tapDragZoom=j,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 O0=_=>_.zoom||_.drag||_.pitch||_.rotate;class xI extends a.C{}class vI{constructor(){this.constants=[1,1,.01],this.radius=0}setup(d,g){const w=a.ax([],g,d);this.radius=a.ai(w[2]<0?a.eR([],w,this.constants):[w[0],w[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 w=a.bJ([],[0,0,1],a.bi(g,[0,0,1])),j=a.bJ([],a.ay([],[g[0],g[1],0]),this.radius),I=a.cT([],g,a.bJ([],a.ax([],a.cT([],j,w),g),2));g[0]=I[0],g[1]=I[1]}return g}}function F0(_){return _.panDelta&&_.panDelta.mag()||_.zoomDelta||_.bearingDelta||_.pitchDelta}class _I{constructor(d,g){this._map=d,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new mI(d),this._bearingSnap=g.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new vI,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(g),a.aZ(["handleEvent","handleWindowEvent"],this);const w=this._el;this._listeners=[[w,"touchstart",{passive:!0}],[w,"touchmove",{passive:!1}],[w,"touchend",void 0],[w,"touchcancel",void 0],[w,"mousedown",void 0],[w,"mousemove",void 0],[w,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[w,"mouseover",void 0],[w,"mouseout",void 0],[w,"dblclick",void 0],[w,"click",void 0],[w,"keydown",{capture:!1}],[w,"keyup",void 0],[w,"wheel",{passive:!1}],[w,"contextmenu",void 0],[window,"blur",void 0]];for(const[j,I,L]of this._listeners){const F=j===document?this.handleWindowEvent:this.handleEvent;j.addEventListener(I,F,L)}}destroy(){for(const[d,g,w]of this._listeners){const j=d===document?this.handleWindowEvent:this.handleEvent;d.removeEventListener(g,j,w)}}_addDefaultHandlers(d){const g=this._map,w=g.getCanvasContainer();this._add("mapEvent",new UE(g,d));const j=g.boxZoom=new qE(g,d);this._add("boxZoom",j);const I=new Hg,L=new Pb;g.doubleClickZoom=new Ib(L,I),this._add("tapZoom",I),this._add("clickZoom",L);const F=new pI;this._add("tapDragZoom",F);const z=g.touchPitch=new YE(g);this._add("touchPitch",z);const H=new Ab(d),Z=new L0(d);g.dragRotate=new gI(d,H,Z),this._add("mouseRotate",H,["mousePitch"]),this._add("mousePitch",Z,["mouseRotate"]);const ne=new vu(d),re=new WE(g,d);g.dragPan=new JE(w,ne,re),this._add("mousePan",ne),this._add("touchPan",re,["touchZoom","touchRotate"]);const se=new rp,ce=new KE;g.touchZoomRotate=new yI(w,ce,se,F),this._add("touchRotate",se,["touchPan","touchZoom"]),this._add("touchZoom",ce,["touchPan","touchRotate"]),this._add("blockableMapEvent",new VE(g));const oe=g.scrollZoom=new Nb(g,this);this._add("scrollZoom",oe,["mousePan"]);const ye=g.keyboard=new np;this._add("keyboard",ye);for(const ge of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])d.interactive&&d[ge]&&g[ge].enable(d[ge])}_add(d,g,w){this._handlers.push({handlerName:d,handler:g,allowed:w}),this._handlersById[d]=g}stop(d){if(!this._updatingCamera){for(const{handler:g}of this._handlers)g.reset();this._inertia.clear(),this._fireEvents({},{},d),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:d}of this._handlers)if(d.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!O0(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(d,g,w){for(const j in d)if(j!==w&&(!g||g.indexOf(j)<0))return!0;return!1}handleWindowEvent(d){this.handleEvent(d,`${d.type}Window`)}_getMapTouches(d){const g=[];for(const w of d)this._el.contains(w.target)&&g.push(w);return g}handleEvent(d,g){this._updatingCamera=!0;const w=d.type==="renderFrame",j=w?void 0:d,I={needsRenderFrame:!1},L={},F={},z=d.touches?this._getMapTouches(d.touches):void 0,H=z?Q(this._el,z):w?void 0:J(this._el,d);for(const{handlerName:re,handler:se,allowed:ce}of this._handlers){if(!se.isEnabled())continue;let oe;this._blockedByActive(F,ce,re)?se.reset():se[g||d.type]&&(oe=se[g||d.type](d,H,z),this.mergeHandlerResult(I,L,oe,re,j),oe&&oe.needsRenderFrame&&this._triggerRenderFrame()),(oe||se.isActive())&&(F[re]=se)}const Z={};for(const re in this._previousActiveHandlers)F[re]||(Z[re]=j);this._previousActiveHandlers=F,(Object.keys(Z).length||F0(I))&&(this._changes.push([I,L,Z]),this._triggerRenderFrame()),(Object.keys(F).length||F0(I))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:ne}=I;ne&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],ne(this._map))}mergeHandlerResult(d,g,w,j,I){if(!w)return;Object.assign(d,w);const L={handlerName:j,originalEvent:w.originalEvent||I};w.zoomDelta!==void 0&&(g.zoom=L),w.panDelta!==void 0&&(g.drag=L),w.pitchDelta!==void 0&&(g.pitch=L),w.bearingDelta!==void 0&&(g.rotate=L)}_applyChanges(){const d={},g={},w={};for(const[j,I,L]of this._changes)j.panDelta&&(d.panDelta=(d.panDelta||new a.P(0,0))._add(j.panDelta)),j.zoomDelta&&(d.zoomDelta=(d.zoomDelta||0)+j.zoomDelta),j.bearingDelta&&(d.bearingDelta=(d.bearingDelta||0)+j.bearingDelta),j.pitchDelta&&(d.pitchDelta=(d.pitchDelta||0)+j.pitchDelta),j.around!==void 0&&(d.around=j.around),j.aroundCoord!==void 0&&(d.aroundCoord=j.aroundCoord),j.pinchAround!==void 0&&(d.pinchAround=j.pinchAround),j.noInertia&&(d.noInertia=j.noInertia),Object.assign(g,I),Object.assign(w,L);this._updateMapTransform(d,g,w),this._changes=[]}_updateMapTransform(d,g,w){const j=this._map,I=j.transform,L=Pe=>[Pe.x,Pe.y,Pe.z];if((()=>{const Pe=this._eventsInProgress.drag;return Pe&&!this._handlersById[Pe.handlerName].isActive()})()&&!F0(d)){const Pe=I.zoom;I.cameraElevationReference="sea",this._originalZoom!=null&&I._orthographicProjectionAtLowPitch&&I.projection.name!=="globe"&&I.pitch===0?(I.cameraElevationReference="ground",I.zoom=this._originalZoom):(I.recenterOnTerrain(),I.cameraElevationReference="ground"),Pe!==I.zoom&&this._map._update(!0)}if(I._isCameraConstrained&&j._stop(!0),!F0(d))return void this._fireEvents(g,w,!0);let{panDelta:F,zoomDelta:z,bearingDelta:H,pitchDelta:Z,around:ne,aroundCoord:re,pinchAround:se}=d;I._isCameraConstrained&&(z>0&&(z=0),I._isCameraConstrained=!1),se!==void 0&&(ne=se),(z||(Pe=>g[Pe]&&!this._eventsInProgress[Pe])("drag"))&&ne&&(this._dragOrigin=L(I.pointCoordinate3D(ne)),this._originalZoom=I.zoom,this._trackingEllipsoid.setup(I._camera.position,this._dragOrigin)),I.cameraElevationReference="sea",j._stop(!0),ne=ne||j.transform.centerPoint,H&&(I.bearing+=H),Z&&(I.pitch+=Z),I._updateCameraState();const ce=[0,0,0];if(F)if(I.projection.name==="mercator"){const Pe=this._trackingEllipsoid.projectRay(I.screenPointToMercatorRay(ne).dir),De=this._trackingEllipsoid.projectRay(I.screenPointToMercatorRay(ne.sub(F)).dir);ce[0]=De[0]-Pe[0],ce[1]=De[1]-Pe[1]}else{const Pe=I.pointCoordinate(ne);if(I.projection.name==="globe"){F=F.rotate(-I.angle);const De=I._pixelsPerMercatorPixel/I.worldSize;ce[0]=-F.x*a.eQ(a.bV(Pe.y))*De,ce[1]=-F.y*a.eQ(I.center.lat)*De}else{const De=I.pointCoordinate(ne.sub(F));Pe&&De&&(ce[0]=De.x-Pe.x,ce[1]=De.y-Pe.y)}}const oe=I.zoom,ye=[0,0,0];if(z){const Pe=L(re||I.pointCoordinate3D(ne)),De={dir:a.ay([],a.ax([],Pe,I._camera.position))};if(De.dir[2]<0){const _e=I.zoomDeltaToMovement(Pe,z);a.bJ(ye,De.dir,_e)}}const ge=a.cT(ce,ce,ye);I._translateCameraConstrained(ge),z&&Math.abs(I.zoom-oe)>1e-4&&I.recenterOnTerrain(),I.cameraElevationReference="ground",this._map._update(),d.noInertia||this._inertia.record(d),this._fireEvents(g,w,!0)}_fireEvents(d,g,w){const j=O0(this._eventsInProgress),I=O0(d),L={};for(const Z in d){const{originalEvent:ne}=d[Z];this._eventsInProgress[Z]||(L[`${Z}start`]=ne),this._eventsInProgress[Z]=d[Z]}!j&&I&&this._fireEvent("movestart",I.originalEvent);for(const Z in L)this._fireEvent(Z,L[Z]);I&&this._fireEvent("move",I.originalEvent);for(const Z in d){const{originalEvent:ne}=d[Z];this._fireEvent(Z,ne)}const F={};let z;for(const Z in this._eventsInProgress){const{handlerName:ne,originalEvent:re}=this._eventsInProgress[Z];this._handlersById[ne].isActive()||(delete this._eventsInProgress[Z],z=g[ne]||re,F[`${Z}end`]=z)}for(const Z in F)this._fireEvent(Z,F[Z]);const H=O0(this._eventsInProgress);if(w&&(j||I)&&!H){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 xI("renderFrame",{timeStamp:d})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const ej="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class bI 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,w){return d=a.P.convert(d).mult(-1),this.panTo(this.transform.center,Object.assign({offset:d},g),w)}panTo(d,g,w){return this.easeTo(Object.assign({center:d},g),w)}getZoom(){return this.transform.zoom}setZoom(d,g){return this.jumpTo({zoom:d},g),this}zoomTo(d,g,w){return this.easeTo(Object.assign({zoom:d},g),w)}zoomIn(d,g){return this.zoomTo(this.getZoom()+1,d,g),this}zoomOut(d,g){return this.zoomTo(this.getZoom()-1,d,g),this}getBearing(){return this.transform.bearing}setBearing(d,g){return this.jumpTo({bearing:d},g),this}getPadding(){return this.transform.padding}setPadding(d,g){return this.jumpTo({padding:d},g),this}rotateTo(d,g,w){return this.easeTo(Object.assign({bearing:d},g),w)}resetNorth(d,g){return this.rotateTo(0,Object.assign({duration:1e3},d),g),this}resetNorthPitch(d,g){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},d),g),this}snapToNorth(d,g){return Math.abs(this.getBearing())d.aspect?w/(2*Math.tan(.5*d.fovX)*d.aspect):j/(2*Math.tan(.5*d.fovY)*d.aspect)}_cameraForBoundsOnGlobe(d,g,w,j,I,L){const F=d.clone(),z=this._extendCameraOptions(L);F.bearing=j,F.pitch=I;const H=a.aU.convert(g),Z=a.aU.convert(w),ne=.5*(H.lat+Z.lat),re=.5*(H.lng+Z.lng),se=a.eT(ne,re),ce=a.ay([],se),oe=a.ay([],a.bh([],ce,[0,1,0])),ye=a.bh([],oe,ce),ge=[oe[0],oe[1],oe[2],0,ye[0],ye[1],ye[2],0,ce[0],ce[1],ce[2],0,0,0,0,1],Pe=[se,a.eT(H.lat,H.lng),a.eT(Z.lat,H.lng),a.eT(Z.lat,Z.lng),a.eT(H.lat,Z.lng),a.eT(ne,H.lng),a.eT(ne,Z.lng),a.eT(H.lat,re),a.eT(Z.lat,re)];let De=a.cU.fromPoints(Pe.map(bt=>[a.bi(oe,bt),a.bi(ye,bt),a.bi(ce,bt)]));const _e=a.ah([],De.center,ge);a.eU(_e)===0&&a.eV(_e,0,0,1),a.ay(_e,_e),a.bJ(_e,_e,a.aF),F.center=a.eW(_e);const Ze=F.getWorldToCameraMatrix(),$e=a.b7(new Float64Array(16),Ze);De=a.cU.applyTransform(De,a.aD([],Ze,ge));const Ke=this._extendAABB(De,F,z,j);if(!Ke)return void a.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");De=Ke,a.ah(_e,_e,Ze);const Me=.5*(De.max[2]-De.min[2]),Be=this._minimumAABBFrustumDistance(F,De),qe=a.bJ([],[0,0,1],Me),st=a.cT(qe,_e,qe),Qe=Be+(F.pitch===0?0:a.bf(_e,st)),xt=F.globeCenterInViewSpace,ft=a.ax([],_e,[xt[0],xt[1],xt[2]]);a.ay(ft,ft),a.bJ(ft,ft,Qe);const Lt=a.cT([],_e,ft);a.ah(Lt,Lt,$e);const Ft=a.eD/a.aF,ot=a.ai(Lt),et=a.bU(Math.max(ot*Ft-a.eD,Number.EPSILON),0),gt=Math.min(F.zoomFromMercatorZAdjusted(et),z.maxZoom);return gt>.5*(a.cJ+a.cv)?(F.setProjection({name:"mercator"}),F.zoom=gt,this._cameraForBounds(F,g,w,j,I,L)):{center:F.center,zoom:gt,bearing:j,pitch:I}}_extendAABB(d,g,w,j){const I=.5*((w.padding.left||0)+(w.padding.right||0)),L=.5*((w.padding.top||0)+(w.padding.bottom||0)),F=L,z=I,H=I,Z=L,ne=g.width-(z+H),re=g.height-(F+Z),se=a.ax([],d.max,d.min),ce=Math.min(ne/se[0],re/se[1]),oe=Math.min(g.scaleZoom(g.scale*ce),w.maxZoom);if(isNaN(oe))return null;const ye=g.scale/g.zoomScale(oe),ge=new a.cU([d.min[0]-z*ye,d.min[1]-Z*ye,d.min[2]],[d.max[0]+H*ye,d.max[1]+F*ye,d.max[2]]),Pe=(typeof w.offset.x=="number"&&typeof w.offset.y=="number"?new a.P(w.offset.x,w.offset.y):a.P.convert(w.offset)).rotate(-a.ap(j));return ge.center[0]-=Pe.x*ye,ge.center[1]+=Pe.y*ye,ge}queryTerrainElevation(d,g){const w=this.transform.elevation;return w?(g=Object.assign({},{exaggerated:!0},g),w.getAtPoint(a.ag.fromLngLat(d),null,g.exaggerated)):null}_cameraForBounds(d,g,w,j,I,L){if(d.projection.name==="globe")return this._cameraForBoundsOnGlobe(d,g,w,j,I,L);const F=d.clone(),z=this._extendCameraOptions(L);F.bearing=j,F.pitch=I;const H=a.aU.convert(g),Z=a.aU.convert(w),ne=new a.aU(H.lng,Z.lat),re=new a.aU(Z.lng,H.lat),se=F.project(H),ce=F.project(Z),oe=this.queryTerrainElevation(H),ye=this.queryTerrainElevation(Z),ge=this.queryTerrainElevation(ne),Pe=this.queryTerrainElevation(re),De=[[se.x,se.y,Math.min(oe||0,ye||0,ge||0,Pe||0)],[ce.x,ce.y,Math.max(oe||0,ye||0,ge||0,Pe||0)]];let _e=a.cU.fromPoints(De);const Ze=F.getWorldToCameraMatrix(),$e=a.b7(new Float64Array(16),Ze);_e=a.cU.applyTransform(_e,Ze);const Ke=this._extendAABB(_e,F,z,j);if(!Ke)return void a.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");_e=Ke;const Me=.5*a.ax([],_e.max,_e.min)[2],Be=this._minimumAABBFrustumDistance(F,_e),qe=[0,0,1,0];a.aE(qe,qe,Ze),a.eX(qe,qe);const st=a.bJ([],qe,Be+Me),Qe=a.cT([],_e.center,st);a.ah(_e.center,_e.center,$e),a.ah(Qe,Qe,$e);const xt=F.unproject(new a.P(_e.center[0],_e.center[1])),ft=a.eY(F.projection,xt),Lt=Math.pow(2,ft),Ft=Math.min(F._zoomFromMercatorZ(Qe[2]*F.pixelsPerMeter*Lt/F.worldSize),z.maxZoom);return F.mercatorFromTransition&&Ft<.5*(a.cJ+a.cv)?(F.setProjection({name:"globe"}),F.zoom=Ft,this._cameraForBounds(F,g,w,j,I,L)):{center:xt,zoom:Ft,bearing:j,pitch:I}}fitBounds(d,g,w){const j=this.cameraForBounds(d,g);return this._fitInternal(j,g,w)}fitScreenCoordinates(d,g,w,j,I){const L=a.P.convert(d),F=a.P.convert(g),z=new a.P(Math.min(L.x,F.x),Math.min(L.y,F.y)),H=new a.P(Math.max(L.x,F.x),Math.max(L.y,F.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(L,F))return this;const Z=this.transform.pointLocation3D(z),ne=this.transform.pointLocation3D(H),re=this.transform.pointLocation3D(new a.P(z.x,H.y)),se=this.transform.pointLocation3D(new a.P(H.x,z.y)),ce=[Math.min(Z.lng,ne.lng,re.lng,se.lng),Math.min(Z.lat,ne.lat,re.lat,se.lat)],oe=[Math.max(Z.lng,ne.lng,re.lng,se.lng),Math.max(Z.lat,ne.lat,re.lat,se.lat)],ye=j&&j.pitch?j.pitch:this.getPitch(),ge=this._cameraForBounds(this.transform,ce,oe,w,ye,j);return this._fitInternal(ge,j,I)}_fitInternal(d,g,w){return d?(g=Object.assign(d,g)).linear?this.easeTo(g,w):this.flyTo(g,w):this}jumpTo(d,g){this.stop();const w=d.preloadOnly?this.transform.clone():this.transform;let j=!1,I=!1,L=!1;"zoom"in d&&w.zoom!==+d.zoom&&(j=!0,w.zoom=+d.zoom),d.center!==void 0&&(w.center=a.aU.convert(d.center)),"bearing"in d&&w.bearing!==+d.bearing&&(I=!0,w.bearing=+d.bearing),"pitch"in d&&w.pitch!==+d.pitch&&(L=!0,w.pitch=+d.pitch);const F=typeof d.padding=="number"?this._extendPadding(d.padding):d.padding;if(d.padding!=null&&!w.isPaddingEqual(F))if(d.retainPadding===!1){const z=w.clone();z.padding=F,w.setLocationAtPoint(w.center,z.centerPoint)}else w.padding=F;return d.preloadOnly?(this._preloadTiles(w),this):(this.fire(new a.C("movestart",g)).fire(new a.C("move",g)),j&&this.fire(new a.C("zoomstart",g)).fire(new a.C("zoom",g)).fire(new a.C("zoomend",g)),I&&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(ej),this.transform.getFreeCameraOptions()}setFreeCameraOptions(d,g){const w=this.transform;if(!w.projection.supportsFreeCamera)return a.w(ej),this;this.stop();const j=w.zoom,I=w.pitch,L=w.bearing;w.setFreeCameraOptions(d);const F=j!==w.zoom,z=I!==w.pitch,H=L!==w.bearing;return this.fire(new a.C("movestart",g)).fire(new a.C("move",g)),F&&this.fire(new a.C("zoomstart",g)).fire(new a.C("zoom",g)).fire(new a.C("zoomend",g)),H&&this.fire(new a.C("rotatestart",g)).fire(new a.C("rotate",g)).fire(new a.C("rotateend",g)),z&&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 w=this.transform,j=this.getZoom(),I=this.getBearing(),L=this.getPitch(),F=this.getPadding(),z="zoom"in d?+d.zoom:j,H="bearing"in d?this._normalizeBearing(d.bearing,I):I,Z="pitch"in d?+d.pitch:L,ne=this._extendPadding(d.padding),re=a.P.convert(d.offset);let se,ce,oe;if(w.projection.name==="globe"){const qe=a.ag.fromLngLat(w.center),st=re.rotate(-w.angle);qe.x+=st.x/w.worldSize,qe.y+=st.y/w.worldSize;const Qe=qe.toLngLat(),xt=a.aU.convert(d.center||Qe);this._normalizeCenter(xt),se=w.centerPoint.add(st),ce=new a.P(qe.x,qe.y).mult(w.worldSize),oe=new a.P(a.aH(xt.lng),a.aL(xt.lat)).mult(w.worldSize).sub(ce)}else{se=w.centerPoint.add(re);const qe=w.pointLocation(se),st=a.aU.convert(d.center||qe);this._normalizeCenter(st),ce=w.project(qe),oe=w.project(st).sub(ce)}const ye=w.zoomScale(z-j);let ge,Pe;d.around&&(ge=a.aU.convert(d.around),Pe=w.locationPoint(ge));const De=this._zooming||z!==j,_e=this._rotating||I!==H,Ze=this._pitching||Z!==L,$e=!w.isPaddingEqual(ne),Ke=d.retainPadding===!1?w.clone():w,Me=qe=>st=>{if(De&&(qe.zoom=a.am(j,z,st)),_e&&(qe.bearing=a.am(I,H,st)),Ze&&(qe.pitch=a.am(L,Z,st)),$e&&(Ke.interpolatePadding(F,ne,st),se=Ke.centerPoint.add(re)),ge)qe.setLocationAtPoint(ge,Pe);else{const Qe=qe.zoomScale(qe.zoom-j),xt=z>j?Math.min(2,ye):Math.max(.5,ye),ft=Math.pow(xt,1-st),Lt=qe.unproject(ce.add(oe.mult(st*ft)).mult(Qe));qe.setLocationAtPoint(qe.renderWorldCopies?Lt.wrap():Lt,se)}return d.preloadOnly||this._fireMoveEvents(g),qe};if(d.preloadOnly){const qe=this._emulate(Me,d.duration,w);return this._preloadTiles(qe),this}const Be={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=De,this._rotating=_e,this._pitching=Ze,this._padding=$e,this._easeId=d.easeId,this._prepareEase(g,d.noMoveStart,Be),this._ease(Me(w),qe=>{w.cameraElevationReference==="sea"&&w.recenterOnTerrain(),this._afterEase(g,qe)},d),this}_prepareEase(d,g,w={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),g||w.moving||this.fire(new a.C("movestart",d)),this._zooming&&!w.zooming&&this.fire(new a.C("zoomstart",d)),this._rotating&&!w.rotating&&this.fire(new a.C("rotatestart",d)),this._pitching&&!w.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 w=this._zooming,j=this._rotating,I=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,w&&this.fire(new a.C("zoomend",d)),j&&this.fire(new a.C("rotateend",d)),I&&this.fire(new a.C("pitchend",d)),this.fire(new a.C("moveend",d))}flyTo(d,g){if(this._prefersReducedMotion(d)){const bt=a.aJ(d,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(bt,g)}this.stop(),d=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:a.eP},d);const w=this.transform,j=this.getZoom(),I=this.getBearing(),L=this.getPitch(),F=this.getPadding(),z="zoom"in d?a.aC(+d.zoom,w.minZoom,w.maxZoom):j,H="bearing"in d?this._normalizeBearing(d.bearing,I):I,Z="pitch"in d?+d.pitch:L,ne=this._extendPadding(d.padding),re=w.zoomScale(z-j),se=a.P.convert(d.offset);let ce=w.centerPoint.add(se);const oe=w.pointLocation(ce),ye=a.aU.convert(d.center||oe);this._normalizeCenter(ye);const ge=w.project(oe),Pe=w.project(ye).sub(ge);let De=d.curve;const _e=Math.max(w.width,w.height),Ze=_e/re,$e=Pe.mag();if("minZoom"in d){const bt=a.aC(Math.min(d.minZoom,j,z),w.minZoom,w.maxZoom),St=_e/w.zoomScale(bt-j);De=Math.sqrt(St/$e*2)}const Ke=De*De;function Me(bt){const St=(Ze*Ze-_e*_e+(bt?-1:1)*Ke*Ke*$e*$e)/(2*(bt?Ze:_e)*Ke*$e);return Math.log(Math.sqrt(St*St+1)-St)}function Be(bt){return(Math.exp(bt)-Math.exp(-bt))/2}function qe(bt){return(Math.exp(bt)+Math.exp(-bt))/2}const st=Me(0);let Qe=function(bt){return qe(st)/qe(st+De*bt)},xt=function(bt){return _e*((qe(st)*(Be(St=st+De*bt)/qe(St))-Be(st))/Ke)/$e;var St},ft=(Me(1)-st)/De;if(Math.abs($e)<1e-6||!isFinite(ft)){if(Math.abs(_e-Ze)<1e-6)return this.easeTo(d,g);const bt=Ze<_e?-1:1;ft=Math.abs(Math.log(Ze/_e))/De,xt=function(){return 0},Qe=function(St){return Math.exp(bt*De*St)}}d.duration="duration"in d?+d.duration:1e3*ft/("screenSpeed"in d?+d.screenSpeed/De:+d.speed),d.maxDuration&&d.duration>d.maxDuration&&(d.duration=0);const Lt=I!==H,Ft=Z!==L,ot=!w.isPaddingEqual(ne),et=d.retainPadding===!1?w.clone():w,gt=bt=>St=>{const nr=St*ft,Wt=1/Qe(nr);bt.zoom=St===1?z:j+bt.scaleZoom(Wt),Lt&&(bt.bearing=a.am(I,H,St)),Ft&&(bt.pitch=a.am(L,Z,St)),ot&&(et.interpolatePadding(F,ne,St),ce=et.centerPoint.add(se));const Kt=St===1?ye:bt.unproject(ge.add(Pe.mult(xt(nr))).mult(Wt));return bt.setLocationAtPoint(bt.renderWorldCopies?Kt.wrap():Kt,ce),bt._updateCameraOnTerrain(),d.preloadOnly||this._fireMoveEvents(g),bt};if(d.preloadOnly){const bt=this._emulate(gt,d.duration,w);return this._preloadTiles(bt),this}return this._zooming=!0,this._rotating=Lt,this._pitching=Ft,this._padding=ot,this._prepareEase(g,!1),this._ease(gt(w),()=>this._afterEase(g),d),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(d){}_cancelRenderFrame(d){}_stop(d,g){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const w=this._onEaseEnd;this._onEaseEnd=void 0,w.call(this,g)}if(!d){const w=this.handlers;w&&w.stop(!1)}return this}_ease(d,g,w){w.animate===!1||w.duration===0?(d(1),g()):(this._easeStart=a.o.now(),this._easeOptions=w,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 w=Math.abs(d-g);return Math.abs(d-360-g)180?-360:w<-180?360:0}_prefersReducedMotion(d){return this._respectPrefersReducedMotion&&a.o.prefersReducedMotion&&!(d&&d.essential)}_emulate(d,g,w){const j=Math.ceil(15*g/1e3),I=[],L=d(w.clone());for(let F=0;F<=j;F++){const z=L(F/j);I.push(z.clone())}return I}_preloadTiles(d,g){}}class tj{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,w=d._getUIString("AttributionControl.ToggleAttribution");this._map=d,this._container=P("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=P("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",w);const j=P("span","mapboxgl-ctrl-icon",this._compactButton);return j.setAttribute("aria-hidden","true"),j.setAttribute("title",w),this._innerContainer=P("div","mapboxgl-ctrl-attrib-inner",this._container),g&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),g===void 0&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0}_toggleAttribution(){this._container.classList.contains("mapboxgl-compact-show")?(this._container.classList.remove("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","false")):(this._container.classList.add("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","true"))}_updateEditLink(){let d=this._editLink;d||(d=this._editLink=this._container.querySelector(".mapbox-improve-map"));const g=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||a.g.ACCESS_TOKEN}];if(d){const w=g.reduce((j,I,L)=>(I.value&&(j+=`${I.key}=${I.value}${Lj.length-I.length),d=d.filter((j,I)=>{for(let L=I+1;L=0)return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?d=[...this.options.customAttribution,...d]:d.unshift(this.options.customAttribution));const w=d.map(j=>function(I){const L=new DOMParser().parseFromString(I,"text/html");return Array.from(L.body.querySelectorAll("*")).reverse().forEach(F=>{const z=F.textContent||"";if(F.tagName!=="A")return void F.replaceWith(...F.childNodes);const H=F.getAttribute("href");if(!H||!/^(https?:|mailto:)/i.test(H))return void F.replaceWith(L.createTextNode(z));const Z=L.createElement("a");Z.href=H,Z.textContent=z,Z.rel="noopener nofollow";const ne=F.getAttribute("class");ne&&(Z.className=ne),F.replaceWith(Z)}),L.body.innerHTML}(j)).join(" | ");w!==this._attribHTML&&(this._attribHTML=w,d.length?(this._innerContainer.innerHTML=w,this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null)}_updateCompact(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact","mapboxgl-compact-show")}}class rj{constructor(){a.aZ(["_updateLogo","_updateCompact"],this)}onAdd(d){this._map=d,this._container=P("div","mapboxgl-ctrl");const g=P("a","mapboxgl-ctrl-logo");return g.target="_blank",g.rel="noopener nofollow",g.href="https://www.mapbox.com/",g.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),g.setAttribute("rel","noopener nofollow"),this._container.appendChild(g),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact)}getDefaultPosition(){return"bottom-left"}_updateLogo(d){d&&d.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const d=this._map.style._sourceCaches;if(Object.entries(d).length===0)return!0;for(const g in d){const w=d[g].getSource();if(w.hasOwnProperty("mapbox_logo")&&!w.mapbox_logo)return!1}return!0}_updateCompact(){const d=this._container.children;if(d.length){const g=d[0];this._map.getCanvasContainer().offsetWidth<250?g.classList.add("mapboxgl-compact"):g.classList.remove("mapboxgl-compact")}}}class wI{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(d){const g=++this._id;return this._queue.push({callback:d,id:g,cancelled:!1}),g}remove(d){const g=this._currentlyRunning,w=g?this._queue.concat(g):this._queue;for(const j of w)if(j.id===d)return void(j.cancelled=!0)}run(d=0){const g=this._currentlyRunning=this._queue;this._queue=[];for(const w of g)if(!w.cancelled&&(w.callback(d),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class X5{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,w){this._start=this.getValue(g),this._end=d,this._startTime=g,this._endTime=g+w}}const Q5={"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 Ci extends a.C{constructor(d,g,w,j){const{point:I,lngLat:L,originalEvent:F,target:z}=d;super(d.type,{point:I,lngLat:L,originalEvent:F,target:z}),this.preventDefault=()=>{d.preventDefault()},this.id=g,this.interaction=w,this.feature=j}}class Rb{constructor(d){this.map=d,this.interactionsByType=new Map,this.delegatedInteractions=new Map,this.typeById=new Map,this.filters=new Map,this.handleType=this.handleType.bind(this),this.handleMove=this.handleMove.bind(this),this.handleOut=this.handleOut.bind(this),this.hoveredFeatures=new Map,this.prevHoveredFeatures=new Map}add(d,g){if(this.typeById.has(d))throw new Error(`Interaction id "${d}" already exists.`);const w=g.filter;let j=g.type;w&&this.filters.set(d,a.dg(w)),j==="mouseover"&&(j="mouseenter"),j==="mouseout"&&(j="mouseleave");const I=this.interactionsByType.get(j)||new Map;j==="mouseenter"||j==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(d,g)):I.size===0&&this.map.on(j,this.handleType),I.size===0&&this.interactionsByType.set(j,I),I.set(d,g),this.typeById.set(d,j)}get(d){const g=this.typeById.get(d);if(!g)return;const w=this.interactionsByType.get(g);return w?w.get(d):void 0}remove(d){const g=this.typeById.get(d);if(!g)return;this.typeById.delete(d),this.filters.delete(d);const w=this.interactionsByType.get(g);w&&(w.delete(d),g==="mouseenter"||g==="mouseleave"?(this.delegatedInteractions.delete(d),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):w.size===0&&this.map.off(g,this.handleType))}queryTargets(d,g){const w=[];for(const[j,I]of g)I.target&&w.push({targetId:j,target:I.target,filter:this.filters.get(j)});return this.map.style.queryRenderedTargets(d,w,this.map.transform)}handleMove(d){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const g=this.queryTargets(d.point,Array.from(this.delegatedInteractions).reverse());g.length&&(d.type="mouseenter",this.handleType(d,g));const w=new Map;for(const[j,{feature:I}]of this.prevHoveredFeatures)this.hoveredFeatures.has(j)||w.set(I.id,I);w.size&&(d.type="mouseleave",this.handleType(d,Array.from(w.values())))}handleOut(d){const g=Array.from(this.hoveredFeatures.values()).map(({feature:w})=>w);g.length&&(d.type="mouseleave",this.handleType(d,g)),this.hoveredFeatures.clear()}handleType(d,g){const w=d.type==="mouseenter";if(w&&!this.interactionsByType.has(d.type))return void a.w("mouseenter interaction required for mouseleave to work.");const j=Array.from(this.interactionsByType.get(d.type)).reverse(),I=!!g;g=g||this.queryTargets(d.point,j);let L=!1;const F=new Set;for(const z of g){for(const[H,Z]of j){if(!Z.target)continue;const ne=z.variants?z.variants[H]:null;if(ne){for(const re of ne){if(Id(re,z,F,H))continue;const se=new a.di(z,re),ce=MT(re,z,H);I&&se.id!==void 0&&(se.state=this.map.getFeatureState(se));const oe=w?this.prevHoveredFeatures.get(ce):null,ye=new Ci(d,H,Z,se),ge=oe?oe.stop:Z.handler(ye);if(w&&this.hoveredFeatures.set(ce,{feature:z,stop:ge}),ge!==!1){L=!0;break}}if(L)break}}if(L)break}if(!L)for(const[z,H]of j){const{handler:Z,target:ne}=H;if(!ne&&Z(new Ci(d,z,H,null))!==!1)break}}}function J5(_,d){if(Array.isArray(_)&&Array.isArray(d)){const g=new Set(_),w=new Set(d);return g.size===w.size&&_.every(j=>w.has(j))}return a.b6(_,d)}const e4={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},t4={showCompass:!0,showZoom:!0,visualizePitch:!1};class B0{constructor(d,g,w=!1){this._clickTolerance=10,this.element=g,this.mouseRotate=new Ab({clickTolerance:d.dragRotate._mouseRotate._clickTolerance}),this.map=d,w&&(this.mousePitch=new L0({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),V()}move(d,g){const w=this.map,j=this.mouseRotate.mousemoveWindow(d,g),I=j&&j.bearingDelta;if(I&&w.setBearing(w.getBearing()+I),this.mousePitch){const L=this.mousePitch.mousemoveWindow(d,g),F=L&&L.pitchDelta;F&&w.setPitch(w.getPitch()+F)}}off(){const d=this.element;d.removeEventListener("mousedown",this.mousedown),d.removeEventListener("touchstart",this.touchstart),d.removeEventListener("touchmove",this.touchmove),d.removeEventListener("touchend",this.touchend),d.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){G(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(d){this.down(Object.assign({},d,{button:d.button,type:d.type,ctrlKey:!0,preventDefault:()=>d.preventDefault()}),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(w).distSqr(d)180;){const w=g.locationPoint3D(_);if(w.x>=0&&w.y>=0&&w.x<=g.width&&w.y<=g.height)break;_.lng>g.center.lng?_.lng-=360:_.lng+=360}return _}const $0={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%)"},Rc={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class _u 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:w="center",color:j="#3FB1CE",scale:I=1,draggable:L=!1,clickTolerance:F=0,rotation:z=Rc.rotation,rotationAlignment:H=Rc.rotationAlignment,pitchAlignment:Z=Rc.pitchAlignment,occludedOpacity:ne=Rc.occludedOpacity,altitude:re=Rc.altitude}=d||{};this._anchor=w,this._color=j,this._scale=I,this._draggable=L,this._clickTolerance=F,this._rotation=z,this._rotationAlignment=H,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",oe=>{oe.preventDefault()}),this._element.addEventListener("mousedown",oe=>{oe.preventDefault()});const se=this._element.classList;for(const oe in $0)se.remove(`mapboxgl-marker-anchor-${oe}`);se.add(`mapboxgl-marker-anchor-${this._anchor}`);const ce=d&&d.className?d.className.trim().split(/\s+/):[];se.add(...ce),this._popup=null}_createDefaultMarker(){const d=P("div"),g=R("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},d);if(this._altitude===0){const w=R("radialGradient",{id:"shadowGradient"},R("defs",{},g));R("stop",{offset:"10%","stop-opacity":.4},w),R("stop",{offset:"100%","stop-opacity":.05},w),R("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},g)}return R("path",{fill:this._color,d:"M27,13.5C27,19.07 20.25,27 14.75,34.5C14.02,35.5 12.98,35.5 12.25,34.5C6.75,27 0,19.22 0,13.5C0,6.04 6.04,0 13.5,0C20.96,0 27,6.04 27,13.5Z"},g),R("path",{opacity:.25,d:"M13.5,0C6.04,0 0,6.04 0,13.5C0,19.22 6.75,27 12.25,34.5C13,35.52 14.02,35.5 14.75,34.5C20.25,27 27,19.07 27,13.5C27,6.04 20.96,0 13.5,0ZM13.5,1C20.42,1 26,6.58 26,13.5C26,15.9 24.5,19.18 22.22,22.74C19.95,26.3 16.71,30.14 13.94,33.91C13.74,34.18 13.61,34.32 13.5,34.44C13.39,34.32 13.26,34.18 13.06,33.91C10.28,30.13 7.41,26.31 5.02,22.77C2.62,19.23 1,15.95 1,13.5C1,6.58 6.58,1 13.5,1Z"},g),R("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},g),d}addTo(d){return d===this._map||(this.remove(),this._map=d,d.getCanvasContainer().appendChild(this._element),d.on("move",this._updateMoving),d.on("moveend",this._update),d.on("remove",this._clearFadeTimer),d._addMarker(this),this.setDraggable(this._draggable),this._update(),d.on("click",this._onMapClick)),this}remove(){const d=this._map;return d&&(d.off("click",this._onMapClick),d.off("move",this._updateMoving),d.off("moveend",this._update),d.off("mousedown",this._addDragHandler),d.off("touchstart",this._addDragHandler),d.off("mouseup",this._onUp),d.off("touchend",this._onUp),d.off("mousemove",this._onMove),d.off("touchmove",this._onMove),d.off("remove",this._clearFadeTimer),d._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(d){return this._lngLat=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||Rc.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 j=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":[j,-1*(38.1-13.5+j)],"bottom-right":[-j,-1*(38.1-13.5+j)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=d,d._marker=this,d._altitude=this._altitude,this._lngLat&&this._popup.setLngLat(this._lngLat),this._element.setAttribute("role","button"),this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress),this._element.setAttribute("aria-expanded","false")}return this}_onKeyPress(d){const g=d.code,w=d.charCode||d.keyCode;g!=="Space"&&g!=="Enter"&&w!==32&&w!==13||this.togglePopup()}_onMapClick(d){const g=d.originalEvent.target,w=this._element;this._popup&&(g===w||w.contains(g))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const d=this._popup;return d?(d.isOpen()?(d.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(d.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const d=this._map,g=this._pos;if(!d||!g)return!1;const w=d.unproject(g,this._altitude),j=d.getFreeCameraOptions();if(!j.position)return!1;const I=j.position.toLngLat();return I.distanceTo(w)<.9*I.distanceTo(this._lngLat)}_evaluateOpacity(){const d=this._map;if(!d)return;const g=this._pos;if(!g||g.x<0||g.x>d.transform.width||g.y<0||g.y>d.transform.height)return void this._clearFadeTimer();const w=d.unproject(g,this._altitude);let j;d._showingGlobe()&&a.e$(d.transform,this._lngLat)?j=0:(j=1-d._queryFogOpacity(w),d.transform._terrainEnabled()&&d.getTerrain()&&this._behindTerrain()&&(j*=this._occludedOpacity)),this._element.style.opacity=`${j}`,this._element.style.pointerEvents=j>0?"auto":"none",this._popup&&this._popup._setOpacity(j),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) ${$0[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${g.x}px,${g.y}px) `}_calculateXYTransform(){const d=this._pos,g=this._map,w=this.getPitchAlignment();if(!g||!d||w!=="map")return"";if(!g._showingGlobe()){const z=g.getPitch();return z?`rotateX(${z}deg)`:""}const j=a.cH(a.f0(g.transform,this._lngLat)),I=d.sub(a.f1(g.transform)),L=Math.abs(I.x)+Math.abs(I.y);if(L===0)return"";const F=j/L;return`rotateX(${-I.y*F}deg) rotateY(${I.x*F}deg)`}_calculateZTransform(){const d=this._pos,g=this._map;if(!g||!d)return"";let w=0;const j=this.getRotationAlignment();if(j==="map")if(g._showingGlobe()){const I=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(I);w=a.cH(Math.atan2(L.y,L.x))-90}else w=-g.getBearing();else if(j==="horizon"){const I=a.aj(4,6,g.getZoom()),L=a.f1(g.transform);L.y+=I*g.transform.height;const F=d.sub(L),z=a.cH(Math.atan2(F.y,F.x));w=(z>90?z-270:z+90)*(1-I)}return w+=this._rotation,w?`rotateZ(${w}deg)`:""}_update(d){cancelAnimationFrame(this._updateFrameId);const g=this._map;g&&(g.transform.renderWorldCopies&&(this._lngLat=nj(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 w=this._pointerdownPos,j=this._positionDelta;if(w&&j){if(!this._isDragging){const I=this._clickTolerance||g._clickTolerance;if(d.point.dist(w)_.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 a0(_.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 wI,this._domRenderTaskQueue=new wI,this._controls=[],this._markers=[],this._popups=[],this._mapId=a.r(),this._locale=Object.assign({},Q5,_.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 X5(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=_.scaleFactor,this._requestManager=new je(_.transformRequest,_.accessToken,_.testMode);const g=Te(_.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 w=document.getElementById(_.container);if(!w)throw new Error(`Container '${_.container.toString()}' not found.`);this._container=w}else{if(!(_.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=_.container}if(this._container.childNodes.length>0&&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 _I(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 Y5(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 w=_.bounds;w&&(this.resize(),this.fitBounds(w,Object.assign({},_.fitBoundsOptions,{duration:0})))}this.resize(),_.attributionControl&&this.addControl(new tj({customAttribution:_.customAttribution})),this._logoControl=new rj,this.addControl(this._logoControl,_.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",w=>{this._update(w.dataType==="style"),this.fire(new a.C(`${w.dataType}data`,w))}),this.on("dataloading",w=>{this.fire(new a.C(`${w.dataType}dataloading`,w))}),this._interactions=new Rb(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 w=this._controlPositions[d];return d.indexOf("bottom")!==-1?w.insertBefore(g,w.firstChild):w.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 w=this.transform.getProjection().name==="mercator"&&g!==this.transform.mercatorFromTransition;return(d||w)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(_,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 w=j=>{let I=[];if(Array.isArray(d)){const L=d.filter(F=>this.getLayer(F));I=L.length?this.queryRenderedFeatures(j,{layers:L}):[]}else I=this.queryRenderedFeatures(j,{target:d});return I};if(_==="mouseenter"||_==="mouseover"){let j=!1;return{listener:g,targets:d,delegates:{mousemove:L=>{const F=w(L.point);F.length?j||(j=!0,g.call(this,new To(_,this,L.originalEvent,{features:F}))):j=!1},mouseout:()=>{j=!1}}}}if(_==="mouseleave"||_==="mouseout"){let j=!1;return{listener:g,targets:d,delegates:{mousemove:F=>{w(F.point).length?j=!0:j&&(j=!1,g.call(this,new To(_,this,F.originalEvent)))},mouseout:F=>{j&&(j=!1,g.call(this,new To(_,this,F.originalEvent)))}}}}{const j=I=>{const L=w(I.point);L.length&&(I.features=L,g.call(this,I),delete I.features)};return{listener:g,targets:d,delegates:{[_]:j}}}}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 w=this._createDelegatedListener(_,d,g);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[_]=this._delegatedListeners[_]||[],this._delegatedListeners[_].push(w);for(const j in w.delegates)this.on(j,w.delegates[j]);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 w=this._createDelegatedListener(_,d,g);for(const j in w.delegates)this.once(j,w.delegates[j]);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 w=this._delegatedListeners?this._delegatedListeners[_]:void 0;return w&&(j=>{for(let I=0;I{if(g){const j=typeof g=="string"?g:g instanceof Error?g.message:g.error;a.w(`Unable to perform style diff: ${j}. Rebuilding the style from scratch.`),this._updateStyle(_,d)}else w&&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 yu(this,g).load(_),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new yu(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:w=!1,stretchX:j,stretchY:I,content:L}={}){this._lazyInitEmptyStyle();const F=a.I.from(_);if(d instanceof HTMLImageElement||ImageBitmap&&d instanceof ImageBitmap){const{width:z,height:H,data:Z}=a.o.getImageData(d);this.style.addImage(F,{data:new a.q({width:z,height:H},Z),pixelRatio:g,stretchX:j,stretchY:I,content:L,sdf:w,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:z,height:H}=d,Z=d;this.style.addImage(F,{data:new a.q({width:z,height:H},new Uint8Array(Z.data)),pixelRatio:g,stretchX:j,stretchY:I,content:L,sdf:w,usvg:!1,version:0,userImage:Z}),Z.onAdd&&Z.onAdd(this,_)}}updateImage(_,d){this._lazyInitEmptyStyle();const g=a.I.from(_),w=this.style.getImage(g);if(!w)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 j=d instanceof HTMLImageElement||ImageBitmap&&d instanceof ImageBitmap?a.o.getImageData(d):d,{width:I,height:L,data:F}=j;if(I===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(I!==(w.usvg?w.icon.usvg_tree.width:w.data.width)||L!==(w.usvg?w.icon.usvg_tree.height:w.data.height))return void this.fire(new a.B(new Error(`The width and height of the updated image (${I}, ${L}) must be that same as the previous version of the image (${w.data.width}, ${w.data.height})`)));const z=!(d instanceof HTMLImageElement||ImageBitmap&&d instanceof ImageBitmap);let H=!1;w.usvg?(w.data=new a.q({width:I,height:L},new Uint8Array(F)),w.usvg=!1,w.icon=void 0,H=!0):w.data.replace(F,z),this.style.updateImage(g,w,H)}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,w)=>{d(g,w)})}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,w={}){return this._isValidId(_)?(this.style.setPaintProperty(_,d,g,w),this._update(!0)):this}getPaintProperty(_,d){return this._isValidId(_)?this.style.getPaintProperty(_,d):null}setLayoutProperty(_,d,g,w={}){return this._isValidId(_)?(this.style.setLayoutProperty(_,d,g,w),this._update(!0)):this}getLayoutProperty(_,d){return this._isValidId(_)?this.style.getLayoutProperty(_,d):null}setLayerProperty(_,d,g,w={}){return this._isValidId(_)?(d==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(_,d,g,w),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,w,j,I=this._container;for(;I&&(!w||!j);){const L=window.getComputedStyle(I).transform;L&&L!=="none"&&(g=L.match(/matrix.*\((.+)\)/)[1].split(", "),g[0]&&g[0]!=="0"&&g[0]!=="1"&&(w=g[0]),g[3]&&g[3]!=="0"&&g[3]!=="1"&&(j=g[3])),I=I.parentElement}this._containerWidth=w?Math.abs(_/w):_,this._containerHeight=j?Math.abs(d/j):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=P("div","mapboxgl-canary",_)).style.visibility="hidden",this._detectMissingCSS();const d=this._canvasContainer=P("div","mapboxgl-canvas-container",_);this._canvas=P("canvas","mapboxgl-canvas",d),this._interactive&&(d.classList.add("mapboxgl-interactive"),this._canvas.setAttribute("tabindex","0")),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region"),this._updateContainerDimensions(),this._resizeCanvas(this._containerWidth,this._containerHeight);const g=this._controlContainer=P("div","mapboxgl-control-container",_),w=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(j=>{w[j]=P("div",`mapboxgl-ctrl-${j}`,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({},k.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),d=this._canvas.getContext("webgl2",_);d?(rr(d,!0),this.painter=new K5(d,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",g=>{if(g.dataType==="source"){const w=this.transform.elevation?this.transform.elevation._source():null;w&&g.sourceCacheId===w.id&&this.style&&this.style._setLabelPlacementStale(),this.painter.setTileLoadedFlag(!0)}}),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,w=a.o.now(),j=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(d=j.createQuery(),j.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 I=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const z=this.transform.zoom,H=this.transform.pitch,Z=a.o.now(),ne=new a.ae(z,{now:Z,fadeDuration:I,pitch:H,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(w),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):L=this._updateAverageElevation(w),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,I,this._crossSourceCollisions,this.painter.replacementSource)),this.style&&this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showParseStatus:this.showParseStatus,wireframe:{terrain:this.showTerrainWireframe,layers2D:this.showLayers2DWireframe,layers3D:this.showLayers3DWireframe},showOverdrawInspector:this._showOverdrawInspector,showQueryGeometry:!!this._showQueryGeometry,showTileAABBs:this.showTileAABBs,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:I,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming}),this.fire(new a.C("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,y.mark(p.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 z=a.o.now()-w;j.endQuery(g.TIME_ELAPSED_EXT),setTimeout(()=>{const H=j.getQueryParameter(d,j.QUERY_RESULT)/1e6;j.deleteQuery(d),this.fire(new a.C("gpu-timing-frame",{cpuTime:z,gpuTime:H}))},50)}if(this.listens("gpu-timing-layer")){const z=this.painter.collectGpuTimers();setTimeout(()=>{const H=this.painter.queryGpuTimers(z);this.fire(new a.C("gpu-timing-layer",{layerTimes:H}))},50)}if(this.listens("gpu-timing-deferred-render")){const z=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const H=this.painter.queryGpuTimeDeferredRender(z);this.fire(new a.C("gpu-timing-deferred-render",{gpuTime:H}))},50)}const F=this._sourcesDirty||this._styleDirty||this._placementDirty||L;if(F||this._repaint)this.triggerRepaint();else{const z=this.idle();if(z&&(L=this._updateAverageElevation(w,!0)),L)this.triggerRepaint();else if(this._triggerFrame(!1),z&&(this.fire(new a.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const H=this._calculateSpeedIndex();this.fire(new a.C("speedindexcompleted",{speedIndex:H})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||F||(this._fullyLoaded=!0,y.mark(p.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=j=>(this.transform.averageElevation=j,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&g(0);const w=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(w||(d||_-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(_)){const j=this.transform.averageElevation;let I=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(I)?I=0:this._averageElevationLastSampledAt=_;const L=Math.abs(j-I);if(L>1){if(this._isInitialLoad||w)return this._averageElevation.jumpTo(I),g(I);this._averageElevation.easeTo(I,_,300)}else if(L>1e-4)return this._averageElevation.jumpTo(I),g(I)}return!!this._averageElevation.isEasing(_)&&g(this._averageElevation.getValue(_))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const _=this.painter.context.gl;rr(_,!1),this._logoControl instanceof rj&&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(){ur(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,_=>{_&&(_.message!==Se&&_.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),Et(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&Gt(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Pt(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){_t(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,w=g.createFramebuffer();function j(I){g.framebufferTexture2D(g.FRAMEBUFFER,g.COLOR_ATTACHMENT0,g.TEXTURE_2D,I,0);const L=new Uint8Array(g.drawingBufferWidth*g.drawingBufferHeight*4);return g.readPixels(0,0,g.drawingBufferWidth,g.drawingBufferHeight,g.RGBA,g.UNSIGNED_BYTE,L),L}return g.bindFramebuffer(g.FRAMEBUFFER,w),this._canvasPixelComparison(j(_),d.canvasCopies.map(j),d.timeStamps)}_canvasPixelComparison(_,d,g){let w=g[1]-g[0];const j=_.length/4;for(let I=0;I{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,w)=>g._preloadTiles(_,w),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(_){this._trackResize&&this.resize({originalEvent:_})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(_){this._showTileBoundaries!==_&&(this._showTileBoundaries=_,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({},t4,_),this._container=P("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})}),P("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",d=>{this._map&&this._map.zoomOut({},{originalEvent:d})}),P("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(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=P("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const _=this._map;if(!_)return;const d=_.getZoom(),g=d===_.getMaxZoom(),w=d===_.getMinZoom();this._zoomInButton.disabled=g,this._zoomOutButton.disabled=w,this._zoomInButton.setAttribute("aria-disabled",g.toString()),this._zoomOutButton.setAttribute("aria-disabled",w.toString())}_rotateCompassArrow(){const _=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 B0(_,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=P("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},z0,_),a.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=$E(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(_){return this._map=_,this._container=P("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkGeolocationSupport(this._setupUI),this._container}onRemove(){this._clearRequestTimeout(),this._geolocationWatchID!==void 0&&(this.options.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off("zoom",this._onZoom),this._map=void 0,this._numberOfWatches=0,this._noTimeout=!1}_checkGeolocationSupport(_){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,w=this._map.getBearing(),j=Object.assign({bearing:w},this.options.fitBoundsOptions);this._map.fitBounds(d.toBounds(g),j,{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=P("button","mapboxgl-ctrl-geolocate",this._container),P("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=P("div","mapboxgl-user-location"),this._dotElement.appendChild(P("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(P("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new _u({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=P("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new _u({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=_??z0.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:tj,ScaleControl:class{constructor(_={}){this.options=Object.assign({},ha,_),a.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const _=this.options.maxWidth||100,d=this._map,g=d._containerHeight/2,w=d._containerWidth/2-_/2,j=d.unproject([w,g]),I=d.unproject([w+_,g]),L=j.distanceTo(I);if(this.options.unit==="imperial"){const F=3.2808*L;F>5280?this._setScale(_,F/5280,"mile"):this._setScale(_,F,"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 w=function(I){const L=Math.pow(10,`${Math.floor(I)}`.length-1);let F=I/L;return F=F>=10?10:F>=5?5:F>=3?3:F>=2?2:F>=1?1:function(z){const H=Math.pow(10,Math.ceil(-Math.log(z)/Math.LN10));return Math.round(z*H)/H}(F),L*F}(d),j=w/d;this._container.innerHTML=g!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:g}).format(w):`${w} ${bu[g]}`,this._container.style.width=_*j+"px"})}onAdd(_){return this._map=_,this._language=_.getLanguage(),this._container=P("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=P("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=P("button","mapboxgl-ctrl-fullscreen",this._controlContainer);P("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=P("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.style.display="none",this._map.on("styledata",this._onStyleData),this._updateConnection(),this._container}_onStyleData(){this._updateConnection()}_updateConnection(){if(this._map&&this._map.style&&this._map.style.indoorManager){const _=this._map.style.indoorManager;_.off("selector-update",this._onIndoorUpdate),_.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(_.getControlState())}}_createButton(_,d){const g=P("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((w,j)=>w.id!==_.floors[j].id);if(g&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),_.selectedFloorId){if(_.selectedFloorId!==this._lastSelectedFloorId||g){const w=_.floors.findIndex(j=>j.id===_.selectedFloorId);if(w!==-1){const j=_.floors.length;let I,L;j<=5?(I=0,L=j-1):this._visibleFloorStart===0?(I=0,L=3):this._visibleFloorStart>=j-3?(I=j-3-1,L=j-1):(I=this._visibleFloorStart,L=this._visibleFloorStart+3-1),wL&&(this._visibleFloorStart=w-2)}}this._lastSelectedFloorId=_.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const _=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);P("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 w=this._visibleFloorStart===0,j=this._visibleFloorStart>=g-3;if(w)this._createFloorButton(d[0]);else{const L=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);P("span","mapboxgl-ctrl-icon",L).setAttribute("aria-hidden","true"),this._container.appendChild(L)}let I=[];if(I=w?d.slice(1,4):j?d.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):d.slice(this._visibleFloorStart,this._visibleFloorStart+3),I.forEach(L=>this._createFloorButton(L)),j)this._createFloorButton(d[g-1]);else{const L=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);P("span","mapboxgl-ctrl-icon",L).setAttribute("aria-hidden","true"),this._container.appendChild(L)}}_createFloorButton(_){const d=this._createButton("mapboxgl-ctrl-level-button",()=>{const I=_.id;this._model&&this._model.selectedFloorId===I&&this._model.activeFloorsVisible||this._map&&(this._model&&!this._model.activeFloorsVisible&&this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.setActiveFloorsVisibility(!0),this._map._selectIndoorFloor(I))}),g=(_.name||"").trim(),w=_.zIndex.toString(),j=g?Array.from(g).slice(0,3).join(""):w;this._setButtonTitle(d,j),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(U0),_),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 w;for(g.innerHTML=_;w=g.firstChild,w;)d.appendChild(w);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=P("div","mapboxgl-popup-content",this._container||void 0);if(d.appendChild(_),this.options.closeButton){const g=this._closeButton=P("button","mapboxgl-popup-close-button",d);g.type="button",g.setAttribute("aria-label","Close popup"),g.innerHTML='',g.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(_){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,w=this._pos;if(!d||!g||!w)return"bottom";const j=g.offsetWidth,I=g.offsetHeight,L=w.xd.transform.width-j/2;if(w.y+_d.transform.height-I){if(L)return"bottom-left";if(F)return"bottom-right"}return L?"left":F?"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 w=this._container;if(w||(w=this._container=P("div","mapboxgl-popup",d.getContainer()),this._tip=P("div","mapboxgl-popup-tip",w),w.appendChild(g)),this.options.maxWidth&&w.style.maxWidth!==this.options.maxWidth&&(w.style.maxWidth=this.options.maxWidth),d.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=nj(this._lngLat,this._pos,d.transform)),!this._trackPointer||_){const j=this._pos=this._trackPointer&&_ instanceof a.P?_:d.project(this._lngLat,this._altitude),I=Lb(this.options.offset),L=this._anchor=this._getAnchor(I.y),F=Lb(this.options.offset,L),z=j.add(F).round();d._requestDomTask(()=>{this._container&&L&&(this._container.style.transform=`${$0[L]} translate(${z.x}px,${z.y}px)`)})}if(!this._marker&&d._showingGlobe()){const j=a.e$(d.transform,this._lngLat)?0:1;this._setOpacity(j)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const _=this._container.querySelector(r4);_&&_.focus()}_onClose(){this.remove()}_setOpacity(_){this._container&&(this._container.style.opacity=`${_}`),this._content&&(this._content.style.pointerEvents=_?"auto":"none")}},Marker:_u,Style:yu,LngLat:a.aU,LngLatBounds:a.aK,Point:a.P,MercatorCoordinate:a.ag,FreeCameraOptions:i0,Evented:a.E,config:a.g,prewarm:function(){En().acquire(Pr)},clearPrewarmedResources:function(){const _=Nt;_&&(_.isPreloaded()&&_.numActive()===1?(_.release(Pr),Nt=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 dr.workerCount},set workerCount(_){dr.workerCount=_},get maxParallelImageRequests(){return a.g.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(_){a.g.MAX_PARALLEL_IMAGE_REQUESTS=_},clearStorage(_){a.f7(_)},get workerUrl(){return jt.workerUrl},set workerUrl(_){jt.workerUrl=_},get workerClass(){return jt.workerClass},set workerClass(_){jt.workerClass=_},get workerParams(){return jt.workerParams},set workerParams(_){jt.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})})(H_e);var vXe=H_e.exports;const th=ds(vXe),ane={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"},one={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 _Xe(t){return t>=1e6?`$${(t/1e6).toFixed(1)}M`:`$${(t/1e3).toFixed(0)}K`}function bXe({listings:t,isLoading:e}){const r=Hs(),n=C.useRef(null),i=C.useRef(null),o=C.useRef([]),[c,a]=C.useState(""),[f,p]=C.useState(!0);return C.useEffect(()=>{(async()=>{p(!0);try{const{data:T}=await Re.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();T!=null&&T.value&&a(T.value)}catch(T){console.error("Error fetching mapbox token:",T)}p(!1)})()},[]),C.useEffect(()=>{if(!n.current||!c||i.current)return;th.accessToken=c;const v=t.filter(k=>k.latitude!=null&&k.longitude!=null);let T=[-98.5795,39.8283],E=4;if(v.length>0){const k=v.reduce((R,D)=>R+D.longitude,0)/v.length,P=v.reduce((R,D)=>R+D.latitude,0)/v.length;T=[k,P],E=v.length===1?12:10}return i.current=new th.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:E,center:T}),i.current.addControl(new th.NavigationControl,"top-right"),()=>{var k;(k=i.current)==null||k.remove(),i.current=null}},[c]),C.useEffect(()=>{if(!i.current||!c)return;o.current.forEach(T=>T.remove()),o.current=[];const v=t.filter(T=>T.latitude!=null&&T.longitude!=null);if(v.forEach(T=>{var V,G,W;const E=ane[T.status]||"#10B981",k=((V=T.photos)==null?void 0:V.find(Y=>Y.is_primary))||((G=T.photos)==null?void 0:G[0]),R=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${T.slug||T.id}`:`/public/listing/${T.slug||T.id}`,D=document.createElement("div");D.className="cursor-pointer",D.innerHTML=`
`;const M=new th.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${k!=null&&k.photo_url?``:""}
${_Xe(T.price)}
${T.property_address||""}
${T.city}, ${T.state}
${one[T.status]||T.status} ${T.bedrooms?`${T.bedrooms} bed`:""} ${T.bathrooms?`${T.bathrooms} bath`:""}
${(W=T.agent)!=null&&W.name?`
Listed by ${T.agent.name}
`:""}
Click to view details →
`),B=new th.Marker(D).setLngLat([T.longitude,T.latitude]).setPopup(M).addTo(i.current);o.current.push(B)}),v.length>1){const T=new th.LngLatBounds;v.forEach(E=>T.extend([E.longitude,E.latitude])),i.current.fitBounds(T,{padding:60,maxZoom:13})}else v.length===1&&i.current.flyTo({center:[v[0].longitude,v[0].latitude],zoom:12})},[t,c]),C.useEffect(()=>(window.__navigateToPublicListing__=v=>{r(v)},()=>{delete window.__navigateToPublicListing__}),[r]),f||e?s.jsx(ml,{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(ane).map(([v,T])=>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:T}}),s.jsx("span",{className:"text-xs text-gray-600",children:one[v]})]},v))}),s.jsx("div",{ref:n,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const ez={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"},wXe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},_w="#0d0d0d",lne="#1a1a1a",Qi="#c9a84c",dy="#f0d78c";function K_e(){const[t,e]=C.useState(""),[r,n]=C.useState(!1),[i,o]=C.useState(!1),[c,a]=C.useState(!1),[f,p]=C.useState(-1),y=C.useRef(null),[v,T]=C.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:E}=eXe(),k=C.useMemo(()=>{if(!E)return[];const le=t.trim().toLowerCase(),pe=[...E.cities.map(je=>({label:je.label,value:je.city,type:"city",count:je.count})),...E.neighborhoods.map(je=>({label:je.label,value:je.neighborhood,type:"neighborhood",count:je.count})),...E.zips.map(je=>({label:`ZIP ${je.label}`,value:je.zip,type:"zip",count:je.count}))];return(le?pe.filter(je=>je.label.toLowerCase().includes(le)||je.value.toLowerCase().includes(le)):pe).slice(0,8)},[E,t]);C.useEffect(()=>{const le=pe=>{y.current&&!y.current.contains(pe.target)&&a(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[]);const{data:P,isLoading:R}=JZe({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}),D=le=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(le),M=()=>{T({status:"",propertyType:"",minPrice:"",maxPrice:""}),e("")},B=t||v.status||v.propertyType||v.minPrice||v.maxPrice,V=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),G=le=>V?`/${le.slug||le.id}`:`/public/listing/${le.slug||le.id}`,{featured:W,restListings:Y,luxeCount:J,cities:Q,activeCount:ee}=C.useMemo(()=>{const le=P||[],pe=le.filter(tt=>tt.status==="active"),Se=pe.length>0?pe:le,je=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[Le,Ae,be]=je.split("-").map(Number),me=Math.floor(Date.UTC(Le,Ae-1,be)/864e5),Te=Se.length>0?Se[me%Se.length]:void 0,Ne=le.filter(tt=>!Te||tt.id!==Te.id),Ee=Array.from(new Set(le.map(tt=>tt.city).filter(Boolean))).slice(0,8),we=le.filter(tt=>(tt.price||0)>=1e6).length,He=pe.length;return{featured:Te,restListings:Ne,luxeCount:we,cities:Ee,activeCount:He}},[P]);return s.jsxs(s.Fragment,{children:[s.jsxs(Zo,{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:_w,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: ${Qi}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${Qi}, 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(Wr,{to:"/",className:"flex items-center gap-3",children:[s.jsx("img",{src:sne,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(Wr,{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 ${Qi}`,color:Qi},children:"About LevelUp"})]}),s.jsx("button",{type:"button",onClick:()=>o(le=>!le),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${Qi}`,color:Qi},"aria-label":"Toggle menu","aria-expanded":i,children:i?s.jsx(Os,{className:"w-5 h-5"}):s.jsx(QS,{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(Wr,{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 ${Qi}`,color:Qi},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:xXe,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:Qi}}),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:dy},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 ${Qi}`,backdropFilter:"blur(12px)"},children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(xd,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:Qi}}),s.jsx(Br,{placeholder:"City, neighborhood, or ZIP",value:t,onChange:le=>{e(le.target.value),a(!0),p(-1)},onFocus:()=>a(!0),onKeyDown:le=>{if(!(!c||k.length===0))if(le.key==="ArrowDown")le.preventDefault(),p(pe=>Math.min(pe+1,k.length-1));else if(le.key==="ArrowUp")le.preventDefault(),p(pe=>Math.max(pe-1,0));else if(le.key==="Enter"&&f>=0){le.preventDefault();const pe=k[f];e(pe.value),a(!1)}else le.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(lMe,{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:Qi,color:_w},onClick:()=>a(!1),children:[s.jsx(xd,{className:"h-5 w-5"}),s.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),c&&k.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:Qi},children:"Suggestions"}),s.jsx("ul",{className:"max-h-80 overflow-y-auto",children:k.map((le,pe)=>s.jsx("li",{children:s.jsxs("button",{type:"button",onMouseEnter:()=>p(pe),onClick:()=>{e(le.value),a(!1)},className:"w-full flex items-center justify-between gap-3 px-5 py-3 text-left transition",style:{background:f===pe?"rgba(201,168,76,0.12)":"transparent"},children:[s.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[le.type==="city"&&s.jsx(Es,{className:"h-4 w-4 shrink-0",style:{color:Qi}}),le.type==="neighborhood"&&s.jsx(_o,{className:"h-4 w-4 shrink-0",style:{color:Qi}}),le.type==="zip"&&s.jsx(va,{className:"h-4 w-4 shrink-0",style:{color:Qi}}),s.jsx("span",{className:"text-white/90 truncate",children:le.label})]}),s.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[le.count," ",le.count===1?"listing":"listings"]})]})},`${le.type}-${le.value}-${pe}`))})]}),c&&t.trim()&&k.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(ba,{value:v.status||"all",onValueChange:le=>T({...v,status:le==="all"?"":le}),children:[s.jsx(oa,{className:"lu-input-dark",children:s.jsx(wa,{})}),s.jsxs(la,{children:[s.jsx(mn,{value:"all",children:"Any status"}),Object.entries(ez).map(([le,pe])=>s.jsx(mn,{value:le,children:pe},le))]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),s.jsxs(ba,{value:v.propertyType||"all",onValueChange:le=>T({...v,propertyType:le==="all"?"":le}),children:[s.jsx(oa,{className:"lu-input-dark",children:s.jsx(wa,{})}),s.jsxs(la,{children:[s.jsx(mn,{value:"all",children:"Any type"}),Object.entries(wXe).map(([le,pe])=>s.jsx(mn,{value:le,children:pe},le))]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),s.jsx(Br,{type:"number",placeholder:"No min",value:v.minPrice,onChange:le=>T({...v,minPrice:le.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(Br,{type:"number",placeholder:"No max",value:v.maxPrice,onChange:le=>T({...v,maxPrice:le.target.value}),className:"lu-input-dark"})]}),B&&s.jsx("div",{className:"sm:col-span-2 md:col-span-4 flex justify-end",children:s.jsxs(Bt,{variant:"ghost",size:"sm",onClick:M,className:"text-white/70 hover:text-white gap-1",children:[s.jsx(Os,{className:"h-4 w-4"})," Clear all"]})})]})]}),s.jsx("div",{className:"lu-hero-stats mt-14 grid grid-cols-3 gap-6 max-w-2xl",children:[{label:"Listings",value:((P==null?void 0:P.length)??0).toString()},{label:"Active Now",value:ee.toString()},{label:"Luxury $1M+",value:J.toString()}].map(le=>s.jsxs("div",{children:[s.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:dy},children:le.value}),s.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:le.label})]},le.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(yl,{className:"h-4 w-4 animate-bounce"})]})]})]}),Q.length>0&&s.jsx("section",{className:"py-8 overflow-hidden",style:{background:lne,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((le,pe)=>s.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[le,s.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:Qi}})]},pe))})}),W&&s.jsx("section",{id:"featured",className:"py-20 md:py-28",children:s.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[s.jsxs("div",{className:"flex items-end justify-between mb-10 md:mb-14",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx(xs,{className:"h-4 w-4",style:{color:Qi}}),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:dy},children:"standout"}),"."]})]}),s.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),s.jsx(Wr,{to:G(W),className:"group block",children:s.jsxs("div",{className:"grid lg:grid-cols-5 gap-6 lg:gap-10 items-stretch",children:[s.jsxs("div",{className:"lg:col-span-3 relative overflow-hidden rounded-2xl aspect-[4/3] bg-black",children:[(()=>{var pe,Se;const le=((pe=W.photos)==null?void 0:pe.find(je=>je.is_primary))||((Se=W.photos)==null?void 0:Se[0]);return le?s.jsx("img",{src:le.photo_url,alt:W.property_address||W.city,className:"w-full h-full object-cover lu-img-zoom"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(va,{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:Qi,color:_w},children:ez[W.status]||"Featured"})]}),s.jsxs("div",{className:"lg:col-span-2 flex flex-col justify-center",children:[s.jsxs("div",{className:"lu-eyebrow text-white/60 mb-4 flex items-center gap-2",children:[s.jsx(Es,{className:"h-3.5 w-3.5",style:{color:Qi}}),W.city,W.state?`, ${W.state}`:""]}),W.property_address&&s.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:W.property_address}),s.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:dy},children:D(W.price)}),s.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[W.bedrooms&&s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(XS,{className:"h-4 w-4",style:{color:Qi}}),W.bedrooms," bd"]}),W.bathrooms&&s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(__,{className:"h-4 w-4",style:{color:Qi}}),W.bathrooms," ba"]}),W.square_footage&&s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(C9,{className:"h-4 w-4",style:{color:Qi}}),W.square_footage.toLocaleString()," sf"]})]}),W.description&&s.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:W.description}),s.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:Qi},children:["View Residence ",s.jsx(Ds,{className:"h-4 w-4"})]})]})]})})]})}),s.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:lne},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:Qi}}),s.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),s.jsx("span",{className:"h-px w-10",style:{background:Qi}})]}),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:dy},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."})]}),R?s.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map((le,pe)=>s.jsxs("div",{className:"space-y-3",children:[s.jsx(ml,{className:"aspect-[4/5] bg-white/5"}),s.jsx(ml,{className:"h-6 w-32 bg-white/5"}),s.jsx(ml,{className:"h-4 w-full bg-white/5"})]},pe))}):Y.length>0?s.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:Y.map(le=>{var Se,je,Le,Ae,be;const pe=((Se=le.photos)==null?void 0:Se.find(me=>me.is_primary))||((je=le.photos)==null?void 0:je[0]);return s.jsxs(Wr,{to:G(le),className:"group lu-card-hover block",children:[s.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden bg-black mb-5 rounded-lg",children:[pe?s.jsx("img",{src:pe.photo_url,alt:le.property_address||le.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(va,{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:Qi,border:`1px solid ${Qi}`},children:ez[le.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:[le.bedrooms&&s.jsxs("span",{children:[le.bedrooms," bd"]}),le.bathrooms&&s.jsxs("span",{children:[le.bathrooms," ba"]}),le.square_footage&&s.jsxs("span",{children:[le.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(Es,{className:"h-3 w-3",style:{color:Qi}}),le.city,le.state?`, ${le.state}`:""]}),s.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:dy},children:D(le.price)}),le.property_address&&s.jsx("p",{className:"text-white/70 text-sm truncate",children:le.property_address}),((Le=le.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(_o,{className:"h-3 w-3"}),le.agent.name,(((Ae=le.agent.brokerage)==null?void 0:Ae.name)||le.agent.brokerage_name)&&s.jsxs("span",{className:"truncate",children:["· ",((be=le.agent.brokerage)==null?void 0:be.name)||le.agent.brokerage_name]})]})]})]},le.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 ${Qi}`},children:s.jsx(va,{className:"h-8 w-8",style:{color:Qi}})}),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."}),B&&s.jsx(Bt,{onClick:M,style:{background:Qi,color:_w},className:"hover:brightness-110",children:"Clear filters"})]})]})}),P&&P.length>0&&s.jsx("section",{id:"map",className:"py-20 md:py-28",children:s.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[s.jsx("div",{className:"flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-10",children:s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx("span",{className:"h-px w-10",style:{background:Qi}}),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:dy},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(bXe,{listings:P,isLoading:R})})]})}),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%, ${_w} 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:Qi}}),s.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),s.jsx("span",{className:"h-px w-10",style:{background:Qi}})]}),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:dy},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:Qi,color:_w},children:["Explore LevelUp",s.jsx(Ds,{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:sne,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(NZe,{}),s.jsx(IZe,{})]})}const SXe=Object.freeze(Object.defineProperty({__proto__:null,default:K_e},Symbol.toStringTag,{value:"Module"})),TXe=C.lazy(()=>Fe(()=>import("./PublicHomeValue-ex2MdmMp.js"),[]));function EXe(){const t=ki(),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(K_e,{}):n==="home-value"||n==="whats-my-home-worth"?s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(TXe,{})}):n.startsWith("public/")?null:s.jsx(xH,{slugOverride:n})}const jXe=C.lazy(()=>Fe(()=>import("./CommercialMarketplace-RoWQOXFE.js"),[]));function AXe(){const e=ki().pathname.slice(1);return e?e.startsWith("public/")?null:s.jsx(xH,{slugOverride:e}):s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"min-h-screen bg-[#0a0d12]"}),children:s.jsx(jXe,{})})}function Q3({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 kXe=t=>mr({queryKey:["agent-card-public",t],queryFn:async()=>{if(!t)throw new Error("No slug provided");const{data:e,error:r}=await Re.from("agent_cards").select("*").eq("slug",t).eq("is_published",!0).single();if(r)throw r;const{data:n}=await Re.from("profiles").select("name, email, phone, brokerage_id").eq("id",e.user_id).single();let i=null;if(n!=null&&n.brokerage_id){const{data:a}=await Re.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 Re.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 Re.storage.from("avatars").list(`${e.user_id}`);if(f&&f.length>0){const{data:p}=Re.storage.from("avatars").getPublicUrl(`${e.user_id}/${f[0].name}`);o=`${p.publicUrl}?t=${Date.now()}`}}}catch{}const c={...n||{name:null,email:null,phone:null,brokerage_id:null},email:e.display_email||(n==null?void 0:n.email)||null};return{...e,social_links:e.social_links||[],profile:c,brokerage_name:e.brokerage_display_name||i,avatar_url:o}},enabled:!!t}),YGt=()=>mr({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:t,error:e}=await Re.from("agent_cards").select("*").order("created_at",{ascending:!1});if(e)throw e;return t}}),ZGt=t=>mr({queryKey:["agent-card",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Re.from("agent_cards").select("*").eq("user_id",t).maybeSingle();if(r)throw r;return e},enabled:!!t}),XGt=()=>{const t=Ar();return Sr({mutationFn:async e=>{const{data:r,error:n}=await Re.from("agent_cards").insert(e).select().single();if(n)throw n;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-cards-admin"]}),t.invalidateQueries({queryKey:["agent-card"]}),Vt.success("Agent card created")},onError:e=>Vt.error(e.message)})},QGt=()=>{const t=Ar();return Sr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Re.from("agent_cards").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["agent-cards-admin"]}),t.invalidateQueries({queryKey:["agent-card"]}),Vt.success("Agent card updated")},onError:e=>Vt.error(e.message)})},es=async(t,e,r,n)=>{const i=new URLSearchParams(window.location.search);await Re.from("agent_card_interactions").insert({card_id:t,interaction_type:e,interaction_detail:r||null,referrer:document.referrer||null,user_agent:navigator.userAgent||null,utm_source:i.get("utm_source")||null,utm_medium:i.get("utm_medium")||null,utm_campaign:i.get("utm_campaign")||null,metadata:{}})},CXe=async(t,e)=>{const{error:r}=await Re.from("agent_card_leads").insert({card_id:t,...e});if(r)throw r},JGt=t=>mr({queryKey:["agent-card-analytics",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Re.from("agent_card_interactions").select("interaction_type, interaction_detail, created_at").eq("card_id",t).order("created_at",{ascending:!1}).limit(500);if(r)throw r;const{data:n,error:i}=await Re.from("agent_card_leads").select("*").eq("card_id",t).order("created_at",{ascending:!1});if(i)throw i;const o=(e==null?void 0:e.filter(f=>f.interaction_type==="card_view").length)||0,c=(e==null?void 0:e.filter(f=>f.interaction_type==="button_click").length)||0,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 J3({open:t,onOpenChange:e,cardId:r,type:n,agentName:i}){const[o,c]=C.useState(""),[a,f]=C.useState(""),[p,y]=C.useState(""),[v,T]=C.useState(""),[E,k]=C.useState(""),[P,R]=C.useState(!1),D=async M=>{if(M.preventDefault(),!o.trim()){Vt.error("Please enter your name");return}R(!0);try{await CXe(r,{lead_type:n,name:o.trim(),email:a.trim()||void 0,phone:p.trim()||void 0,message:E.trim()||void 0,intent:v||void 0}),es(r,"lead_submitted",n),Re.functions.invoke("card-lead-notify",{body:{cardId:r,leadType:n,name:o.trim(),email:a.trim()||void 0,phone:p.trim()||void 0,message:E.trim()||void 0,intent:v||void 0}}).catch(B=>console.error("Card lead notify failed:",B)),Vt.success(n==="booking"?"Request sent! They'll be in touch soon.":n==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),e(!1),c(""),f(""),y(""),T(""),k("")}catch{Vt.error("Something went wrong. Please try again.")}finally{R(!1)}};return s.jsx(lo,{open:t,onOpenChange:e,children:s.jsxs(qa,{className:"sm:max-w-md rounded-2xl",children:[s.jsxs(xl,{children:[s.jsx(Xo,{children:n==="booking"?"Book a Call":n==="connect"?"Connect with Me":"Refer a Friend"}),s.jsx(wd,{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:D,className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"lead-name",children:"Name *"}),s.jsx(Br,{id:"lead-name",value:o,onChange:M=>c(M.target.value),placeholder:"Your name",required:!0})]}),s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"lead-phone",children:"Phone"}),s.jsx(Br,{id:"lead-phone",type:"tel",value:p,onChange:M=>y(M.target.value),placeholder:"(555) 123-4567"})]}),s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"lead-email",children:"Email"}),s.jsx(Br,{id:"lead-email",type:"email",value:a,onChange:M=>f(M.target.value),placeholder:"you@example.com"})]}),n==="booking"&&s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"lead-intent",children:"I'm looking to..."}),s.jsxs(ba,{value:v,onValueChange:T,children:[s.jsx(oa,{children:s.jsx(wa,{placeholder:"Select one"})}),s.jsxs(la,{children:[s.jsx(mn,{value:"buy",children:"Buy a home"}),s.jsx(mn,{value:"sell",children:"Sell my home"}),s.jsx(mn,{value:"both",children:"Buy & Sell"}),s.jsx(mn,{value:"other",children:"Something else"})]})]})]}),n!=="connect"&&s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"lead-message",children:n==="referral"?"Tell us about them":"Message (optional)"}),s.jsx(Br,{id:"lead-message",value:E,onChange:M=>k(M.target.value),placeholder:n==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),s.jsx(Bt,{type:"submit",className:"w-full rounded-2xl",disabled:P,children:P?"Sending...":"Submit"})]})]})})}const NXe=t=>mr({queryKey:["card-blocks",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Re.from("card_blocks").select("*").eq("card_id",t).eq("is_visible",!0).order("sort_order",{ascending:!0});if(r)throw r;return e||[]},enabled:!!t}),e9t=t=>mr({queryKey:["card-blocks-all",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Re.from("card_blocks").select("*").eq("card_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]},enabled:!!t}),t9t=()=>{const t=Ar();return Sr({mutationFn:async e=>{const{data:r,error:n}=await Re.from("card_blocks").insert(e).select().single();if(n)throw n;return r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["card-blocks",r.card_id]}),t.invalidateQueries({queryKey:["card-blocks-all",r.card_id]}),Vt.success("Block added")},onError:e=>Vt.error(e.message)})},r9t=()=>{const t=Ar();return Sr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Re.from("card_blocks").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["card-blocks"]}),t.invalidateQueries({queryKey:["card-blocks-all"]}),Vt.success("Block updated")},onError:e=>Vt.error(e.message)})},n9t=()=>{const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("card_blocks").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["card-blocks"]}),t.invalidateQueries({queryKey:["card-blocks-all"]}),Vt.success("Block removed")},onError:e=>Vt.error(e.message)})};function IXe(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 PXe(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 RXe={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 LXe({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=PXe(r.video_url),o=n||!!i,c=n?IXe(r.video_url):i||r.video_url;return s.jsx("div",{className:RXe[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 DXe={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 MXe({block:t,variant:e}){const n=t.config.testimonials||[],[i,o]=C.useState(0);if(n.length===0)return null;const c=DXe[e],a=n[i];return s.jsxs("div",{className:c.container,children:[s.jsxs("div",{className:c.card,children:[s.jsx(tMe,{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(Cm,{className:"h-4 w-4"})}),s.jsx("div",{className:"flex gap-1.5",children:n.map((f,p)=>s.jsx("div",{className:`h-1.5 w-1.5 rounded-full transition-colors cursor-pointer ${p===i?c.dot:c.dotInactive}`,onClick:()=>o(p)},p))}),s.jsx("button",{onClick:()=>o(f=>(f+1)%n.length),className:c.nav,children:s.jsx(jd,{className:"h-4 w-4"})})]})]})}const OXe={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 FXe({block:t,variant:e}){const n=t.config.tags||[];if(n.length===0)return null;const i=OXe[e];return s.jsx("div",{className:i.container,children:n.map((o,c)=>s.jsx("span",{className:i.tag,children:o},c))})}const BXe={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 $Xe({block:t,cardId:e,variant:r}){const i=t.config.links||[];if(i.length===0)return null;const o=BXe[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:()=>es(e,"button_click",`custom_link_${c.label}`),className:o.link,children:[s.jsx("span",{children:c.label}),s.jsx(b_,{className:`h-4 w-4 ${o.icon}`})]},a))})}const zXe={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 UXe({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 VXe={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 qXe({block:t,cardId:e,variant:r}){const i=t.config.platforms||[],o=VXe[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=zXe[c.platform.toLowerCase()];return!f||!c.url?null:s.jsx("a",{href:c.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>es(e,"button_click",`social_${c.platform}`),className:o.linkClass,title:f.label,children:s.jsx(UXe,{path:f.icon,color:f.color})},a)})})]})}function eF({cardId:t,variant:e}){const{data:r}=NXe(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(LXe,{block:c,variant:e},c.id);case"testimonials":return s.jsx(MXe,{block:c,variant:e},c.id);case"specialties":return s.jsx(FXe,{block:c,variant:e},c.id);case"custom_links":return s.jsx($Xe,{block:c,cardId:t,variant:e},c.id);default:return null}}),o&&s.jsx(qXe,{block:o,cardId:t,variant:e})]})}async function GXe(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 HXe(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 tF(t){const{first:e,last:r}=HXe(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 GXe(t.avatarUrl);if(a){const p={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[a.mimeType]||"JPEG";n.push(`PHOTO;ENCODING=b;TYPE=${p}:${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),Vt.success("Contact saved!")}function WXe({card:t}){var D;const[e,r]=C.useState(!1),[n,i]=C.useState("booking"),o=((D=t.profile)==null?void 0:D.name)||"Agent",c=o.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2),a=(M,B)=>{es(t.id,"button_click",M),B()},f=()=>a("call",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`tel:${t.profile.phone}`:Vt.error("Phone number not available")}),p=()=>a("text",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`sms:${t.profile.phone}`:Vt.error("Phone number not available")}),y=()=>a("email",()=>{var M;(M=t.profile)!=null&&M.email?window.location.href=`mailto:${t.profile.email}`:Vt.error("Email not available")}),v=()=>{t.booking_url?a("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),es(t.id,"button_click","book"))},T=()=>{var M,B;es(t.id,"contact_saved"),tF({name:o,phone:(M=t.profile)==null?void 0:M.phone,email:(B=t.profile)==null?void 0:B.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},E=async()=>{es(t.id,"share_event");const M=`https://cards.relevelup.com/${t.slug}`,B="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${o}`,text:B,url:M})}catch{}else await navigator.clipboard.writeText(M),Vt.success("Link copied!")},k=()=>{i("referral"),r(!0),es(t.id,"button_click","refer")},P=()=>{i("connect"),r(!0),es(t.id,"button_click","connect")},R={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return 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(vd,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[s.jsx(_d,{src:t.avatar_url||void 0,alt:o}),s.jsx(bd,{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(Bt,{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(ri,{className:"h-5 w-5"}),s.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),s.jsxs(Bt,{onClick:p,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[s.jsx(fh,{className:"h-5 w-5"}),s.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),s.jsxs(Bt,{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(mi,{className:"h-5 w-5"}),s.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),s.jsxs(Bt,{onClick:v,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[s.jsx(oo,{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(lc,{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(Q3,{card:t,variant:"standard"}),s.jsx(eF,{cardId:t.id,variant:"standard"}),s.jsxs("div",{className:"space-y-2 mb-6",children:[t.show_save_contact&&s.jsxs(Bt,{variant:"ghost",onClick:T,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx(sc,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),t.show_leave_review&&t.review_source_url&&s.jsxs(Bt,{variant:"ghost",onClick:()=>{es(t.id,"button_click","review"),window.open(t.review_source_url,"_blank")},className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx(lc,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),t.show_refer_friend&&s.jsxs(Bt,{variant:"ghost",onClick:k,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx(fl,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),s.jsxs(Bt,{variant:"ghost",onClick:P,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx(JO,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),s.jsxs(Bt,{variant:"ghost",onClick:E,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx(SC,{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((M,B)=>s.jsx("a",{href:M.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>es(t.id,"button_click",`social_${M.platform}`),className:"h-10 w-10 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-lg transition-colors",children:R[M.platform.toLowerCase()]||"🔗"},B))}),s.jsx("div",{className:"text-center",children:s.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),s.jsx(J3,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:o})]})}function KXe({card:t}){var D;const[e,r]=C.useState(!1),[n,i]=C.useState("booking"),o=((D=t.profile)==null?void 0:D.name)||"Agent",c=o.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2),a=(M,B)=>{es(t.id,"button_click",M),B()},f=()=>a("call",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`tel:${t.profile.phone}`:Vt.error("Phone number not available")}),p=()=>a("text",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`sms:${t.profile.phone}`:Vt.error("Phone number not available")}),y=()=>a("email",()=>{var M;(M=t.profile)!=null&&M.email?window.location.href=`mailto:${t.profile.email}`:Vt.error("Email not available")}),v=()=>{t.booking_url?a("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),es(t.id,"button_click","book"))},T=()=>{var M,B;es(t.id,"contact_saved"),tF({name:o,phone:(M=t.profile)==null?void 0:M.phone,email:(B=t.profile)==null?void 0:B.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},E=async()=>{es(t.id,"share_event");const M=`https://cards.relevelup.com/${t.slug}`,B="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${o}`,text:B,url:M})}catch{}else await navigator.clipboard.writeText(M),Vt.success("Link copied!")},k=()=>{i("referral"),r(!0),es(t.id,"button_click","refer")},P=()=>{i("connect"),r(!0),es(t.id,"button_click","connect")},R={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return 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(vd,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[s.jsx(_d,{src:t.avatar_url||void 0,alt:o}),s.jsx(bd,{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:ri,label:"Call",handler:f},{icon:fh,label:"Text",handler:p},{icon:mi,label:"Email",handler:y}].map(({icon:M,label:B,handler:V})=>s.jsxs("button",{onClick:V,className:"flex flex-col items-center gap-1.5 py-4 bg-[#1e2636] hover:bg-[#252d3f] border border-[#c9a84c]/20 rounded-xl transition-colors",children:[s.jsx(M,{className:"h-5 w-5 text-[#c9a84c]"}),s.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:B})]},B))}),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(oo,{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(lc,{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(Q3,{card:t,variant:"luxury"}),s.jsx(eF,{cardId:t.id,variant:"luxury"}),s.jsxs("div",{className:"space-y-1 mb-6",children:[t.show_save_contact&&s.jsxs("button",{onClick:T,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx(sc,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&s.jsxs("button",{onClick:()=>{es(t.id,"button_click","review"),window.open(t.review_source_url,"_blank")},className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx(lc,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),t.show_refer_friend&&s.jsxs("button",{onClick:k,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx(fl,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),s.jsxs("button",{onClick:P,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx(JO,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),s.jsxs("button",{onClick:E,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx(SC,{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((M,B)=>s.jsx("a",{href:M.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>es(t.id,"button_click",`social_${M.platform}`),className:"h-10 w-10 rounded-full bg-[#1e2636] border border-[#c9a84c]/20 hover:border-[#c9a84c]/50 flex items-center justify-center text-lg transition-colors",children:R[M.platform.toLowerCase()]||"🔗"},B))}),s.jsx("div",{className:"text-center",children:s.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),s.jsx(J3,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:o})]})}function YXe({card:t}){var B,V,G,W;const[e,r]=C.useState(!1),[n,i]=C.useState("booking"),o=((B=t.profile)==null?void 0:B.name)||"Agent",c=o.split(" ").map(Y=>Y[0]).join("").toUpperCase().slice(0,2),a={accent:((V=t.bold_theme_colors)==null?void 0:V.accent)||"#ff5722",dark:((G=t.bold_theme_colors)==null?void 0:G.dark)||"#1a1a2e",button:((W=t.bold_theme_colors)==null?void 0:W.button)||"#ff5722"},f=(Y,J)=>{const Q=parseInt(Y.replace("#",""),16),ee=Math.max(0,(Q>>16)-J),le=Math.max(0,(Q>>8&255)-J),pe=Math.max(0,(Q&255)-J);return`#${(ee<<16|le<<8|pe).toString(16).padStart(6,"0")}`};f(a.accent,25),f(a.dark,-20),f(a.button,25);const p=(Y,J)=>{es(t.id,"button_click",Y),J()},y=()=>p("call",()=>{var Y;(Y=t.profile)!=null&&Y.phone?window.location.href=`tel:${t.profile.phone}`:Vt.error("Phone number not available")}),v=()=>p("text",()=>{var Y;(Y=t.profile)!=null&&Y.phone?window.location.href=`sms:${t.profile.phone}`:Vt.error("Phone number not available")}),T=()=>p("email",()=>{var Y;(Y=t.profile)!=null&&Y.email?window.location.href=`mailto:${t.profile.email}`:Vt.error("Email not available")}),E=()=>{t.booking_url?p("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),es(t.id,"button_click","book"))},k=()=>{var Y,J;es(t.id,"contact_saved"),tF({name:o,phone:(Y=t.profile)==null?void 0:Y.phone,email:(J=t.profile)==null?void 0:J.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},P=async()=>{es(t.id,"share_event");const Y=`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:Y})}catch{}else await navigator.clipboard.writeText(Y),Vt.success("Link copied!")},R=()=>{i("referral"),r(!0),es(t.id,"button_click","refer")},D=()=>{i("connect"),r(!0),es(t.id,"button_click","connect")},M={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return 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(vd,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${a.accent}`},children:[s.jsx(_d,{src:t.avatar_url||void 0,alt:o}),s.jsx(bd,{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:ri,label:"Call",handler:y},{icon:fh,label:"Text",handler:v},{icon:mi,label:"Email",handler:T}].map(({icon:Y,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(Y,{className:"h-5 w-5"}),s.jsx("span",{className:"text-xs",children:J})]},J))}),s.jsxs("button",{onClick:E,className:"w-full h-14 text-base font-black rounded-2xl mb-6 text-white transition-opacity hover:opacity-90 flex items-center justify-center gap-2 uppercase tracking-wide",style:{backgroundColor:a.button},children:[s.jsx(oo,{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(lc,{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(Q3,{card:t,variant:"bold"}),s.jsx(eF,{cardId:t.id,variant:"bold"}),s.jsxs("div",{className:"space-y-1 mb-6",children:[t.show_save_contact&&s.jsxs("button",{onClick:k,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:a.dark},children:[s.jsx(sc,{className:"h-4 w-4",style:{color:a.accent}})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&s.jsxs("button",{onClick:()=>{es(t.id,"button_click","review"),window.open(t.review_source_url,"_blank")},className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:a.dark},children:[s.jsx(lc,{className:"h-4 w-4",style:{color:a.accent}})," Leave a Review"]}),t.show_refer_friend&&s.jsxs("button",{onClick:R,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:a.dark},children:[s.jsx(fl,{className:"h-4 w-4",style:{color:a.accent}})," Refer a Friend"]}),s.jsxs("button",{onClick:D,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:a.dark},children:[s.jsx(JO,{className:"h-4 w-4",style:{color:a.accent}})," Connect with Me"]}),s.jsxs("button",{onClick:P,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:a.dark},children:[s.jsx(SC,{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((Y,J)=>s.jsx("a",{href:Y.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>es(t.id,"button_click",`social_${Y.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:M[Y.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(J3,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:o})]})}function ZXe({card:t}){var D;const[e,r]=C.useState(!1),[n,i]=C.useState("booking"),o=((D=t.profile)==null?void 0:D.name)||"Agent",c=o.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2),a=(M,B)=>{es(t.id,"button_click",M),B()},f=()=>a("call",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`tel:${t.profile.phone}`:Vt.error("Phone number not available")}),p=()=>a("text",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`sms:${t.profile.phone}`:Vt.error("Phone number not available")}),y=()=>a("email",()=>{var M;(M=t.profile)!=null&&M.email?window.location.href=`mailto:${t.profile.email}`:Vt.error("Email not available")}),v=()=>{t.booking_url?a("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),es(t.id,"button_click","book"))},T=()=>{var M,B;es(t.id,"contact_saved"),tF({name:o,phone:(M=t.profile)==null?void 0:M.phone,email:(B=t.profile)==null?void 0:B.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},E=async()=>{es(t.id,"share_event");const M=`https://cards.relevelup.com/${t.slug}`,B="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${o}`,text:B,url:M})}catch{}else await navigator.clipboard.writeText(M),Vt.success("Link copied!")},k=()=>{i("referral"),r(!0),es(t.id,"button_click","refer")},P=()=>{i("connect"),r(!0),es(t.id,"button_click","connect")},R={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return 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(vd,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[s.jsx(_d,{src:t.avatar_url||void 0,alt:o}),s.jsx(bd,{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:ri,label:"Call",handler:f},{icon:fh,label:"Text",handler:p},{icon:mi,label:"Email",handler:y}].map(({icon:M,label:B,handler:V})=>s.jsxs("button",{onClick:V,className:"flex flex-col items-center gap-1.5 py-4 bg-white hover:bg-[#e8e3db] border border-[#d4cfc5] rounded-lg transition-colors shadow-sm",children:[s.jsx(M,{className:"h-5 w-5 text-[#1b3a4b]"}),s.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:B})]},B))}),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(oo,{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(lc,{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(Q3,{card:t,variant:"classic"}),s.jsx(eF,{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:T,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx(sc,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&s.jsxs("button",{onClick:()=>{es(t.id,"button_click","review"),window.open(t.review_source_url,"_blank")},className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx(lc,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),t.show_refer_friend&&s.jsxs("button",{onClick:k,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx(fl,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),s.jsxs("button",{onClick:P,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx(JO,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),s.jsxs("button",{onClick:E,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx(SC,{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((M,B)=>s.jsx("a",{href:M.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>es(t.id,"button_click",`social_${M.platform}`),className:"h-10 w-10 rounded-full bg-white border border-[#d4cfc5] hover:bg-[#e8e3db] flex items-center justify-center text-lg transition-colors shadow-sm",children:R[M.platform.toLowerCase()]||"🔗"},B))}),s.jsx("div",{className:"text-center",children:s.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),s.jsx(J3,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:o})]})}function XXe({card:t}){switch(t.theme){case"luxury":return s.jsx(KXe,{card:t});case"bold":return s.jsx(YXe,{card:t});case"classic":return s.jsx(ZXe,{card:t});case"standard":default:return s.jsx(WXe,{card:t})}}function QXe(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 JXe(t){return`https://docs.google.com/gview?url=${encodeURIComponent(t)}&embedded=true`}function eQe(){if(typeof window>"u")return null;const t=QXe(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:JXe(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(_m,{className:"h-3.5 w-3.5"})," See Disclosures"]})]})}):null}function tQe(){const t=ki();C.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(rQe,{slug:e})}function rQe({slug:t}){return s.jsx(nQe,{slug:t})}function nQe({slug:t}){var o;const{data:e,isLoading:r,error:n}=kXe(t);if(C.useEffect(()=>{e!=null&&e.id&&es(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(ml,{className:"h-28 w-28 rounded-full"}),s.jsx(ml,{className:"h-6 w-48"}),s.jsx(ml,{className:"h-4 w-36"})]}),s.jsx(ml,{className:"h-12 w-full"}),s.jsx(ml,{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(Zo,{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(eQe,{}),s.jsx(XXe,{card:e})]})}function iQe({presentationId:t,ctaLabel:e,agentName:r,prefillName:n,prefillEmail:i,prefillPhone:o}){const[c,a]=C.useState(n||""),[f,p]=C.useState(i||""),[y,v]=C.useState(o||""),[T,E]=C.useState(""),[k,P]=C.useState(""),[R,D]=C.useState(!1),[M,B]=C.useState(!1),V=async G=>{if(G.preventDefault(),!c.trim()){Vt.error("Please enter your name");return}D(!0);try{const{error:W}=await Re.from("smart_presentation_leads").insert({presentation_id:t,name:c.trim(),email:f.trim()||null,phone:y.trim()||null,intent:T||null,message:k.trim()||null});if(W)throw W;try{await Re.rpc("log_presentation_view",{p_presentation_id:t,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}Re.functions.invoke("presentation-lead-notify",{body:{presentationId:t,name:c.trim(),email:f.trim()||void 0,phone:y.trim()||void 0,intent:T||void 0,message:k.trim()||void 0}}).catch(Y=>console.error("Presentation lead notify failed:",Y)),B(!0)}catch{Vt.error("Something went wrong. Please try again.")}finally{D(!1)}};return M?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(no,{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:V,className:"space-y-4 max-w-md mx-auto",children:[s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"pres-lead-name",children:"Name *"}),s.jsx(Br,{id:"pres-lead-name",value:c,onChange:G=>a(G.target.value),placeholder:"Your name",required:!0})]}),s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"pres-lead-phone",children:"Phone"}),s.jsx(Br,{id:"pres-lead-phone",type:"tel",value:y,onChange:G=>v(G.target.value),placeholder:"(555) 123-4567"})]}),s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"pres-lead-email",children:"Email"}),s.jsx(Br,{id:"pres-lead-email",type:"email",value:f,onChange:G=>p(G.target.value),placeholder:"you@example.com"})]}),s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),s.jsxs(ba,{value:T,onValueChange:E,children:[s.jsx(oa,{children:s.jsx(wa,{placeholder:"Select one"})}),s.jsxs(la,{children:[s.jsx(mn,{value:"buy",children:"Buy a home"}),s.jsx(mn,{value:"sell",children:"Sell my home"}),s.jsx(mn,{value:"both",children:"Buy & Sell"}),s.jsx(mn,{value:"other",children:"Something else"})]})]})]}),s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"pres-lead-message",children:"Message (optional)"}),s.jsx(Br,{id:"pres-lead-message",value:k,onChange:G=>P(G.target.value),placeholder:"Anything you'd like us to know"})]}),s.jsx(Bt,{type:"submit",className:"w-full text-lg py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",disabled:R,children:R?"Sending...":e})]})}function sQe(){const t=ki();C.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(aQe,{shareToken:e})}function aQe({shareToken:t}){var k;const[e,r]=C.useState(null),[n,i]=C.useState(!0),[o,c]=C.useState(0),[a,f]=C.useState(!1);C.useEffect(()=>{p()},[t]);const p=async()=>{const{data:P,error:R}=await Re.from("smart_presentations").select("*").eq("share_token",t).eq("status","published").single();if(R||!P){f(!0),i(!1);return}const{data:D}=await Re.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",P.owner_user_id).single();let M;if(D!=null&&D.brokerage_id){const{data:V}=await Re.from("brokerages").select("name").eq("id",D.brokerage_id).single();M=(V==null?void 0:V.name)||void 0}let B=null;if(P.contact_id){const{data:V}=await Re.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",P.contact_id).single();B=V}r({...P,owner_name:D==null?void 0:D.name,owner_email:D==null?void 0:D.email,owner_phone:D==null?void 0:D.phone,owner_avatar:D==null?void 0:D.avatar_url,owner_title:(D==null?void 0:D.title)||void 0,brokerage_name:M,contact_name:B?[B.first_name,B.last_name].filter(Boolean).join(" "):void 0,contact_email:(B==null?void 0:B.email)||void 0,contact_phone:(B==null?void 0:B.phone)||void 0}),i(!1);try{await Re.rpc("log_presentation_view",{p_presentation_id:P.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},y=async()=>{if(e){try{await Re.rpc("log_presentation_view",{p_presentation_id:e.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}e.cta_url&&window.open(e.cta_url,"_blank")}},v=P=>{const R=P.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(R)return`https://www.youtube.com/embed/${R[1]}?rel=0`;if(P.includes("iframe.mediadelivery.net/play/")){const B=P.replace("/play/","/embed/"),V=B.includes("?")?"&":"?";return`${B}${V}responsive=true`}if(P.includes("iframe.mediadelivery.net")){const B=P.includes("?")?"&":"?";return`${P}${B}responsive=true`}const D=P.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(D)return`https://www.loom.com/embed/${D[1]}`;const M=P.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return M?`https://iframe.mediadelivery.net/embed/${M[1]}/${M[2]}?responsive=true`:P};if(n)return 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(ml,{className:"h-12 w-3/4 mx-auto"}),s.jsx(ml,{className:"h-64 w-full"}),s.jsx(ml,{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 T=e.sections.filter(P=>P.is_visible!==!1),E=T[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:[E!=null&&E.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(E.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):E!=null&&E.image_url?s.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:s.jsx("img",{src:E.image_url,alt:E.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:E==null?void 0:E.icon}),s.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:E==null?void 0:E.title}),s.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:E==null?void 0:E.description})]}),(E==null?void 0:E.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:E.text}})]}),s.jsx("div",{className:"md:col-span-2 space-y-3",children:T.map((P,R)=>s.jsx("button",{onClick:()=>c(R),className:qt("w-full text-left p-4 rounded-xl border transition-all",o===R?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children: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(R+1).padStart(2,"0"),"."]}),s.jsxs("div",{children:[s.jsx("span",{className:"mr-2",children:P.icon}),s.jsx("span",{className:"font-semibold text-gray-900",children:P.title}),s.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:P.description})]})]})},R))})]}),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?"}),(k=e.cta_url)!=null&&k.trim()?s.jsxs(Bt,{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(b_,{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(iQe,{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 i9t(){const{user:t}=Hn(),e=Li(),{data:r}=hT();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 Re.from("open_houses").select("*").eq("agent_id",e).order("event_date",{ascending:!1});if(i)throw i;let o=n||[];if((r==null?void 0:r.role)==="team_leader"&&r.teamId){const{data:c,error:a}=await Re.rpc("get_team_open_houses",{_user_id:e});if(!a&&c){const f=[...new Set(c.map(v=>v.agent_id))],p={};if(f.length>0){const{data:v}=await Re.from("profiles").select("id, name").in("id",f);v==null||v.forEach(T=>{T.name&&(p[T.id]=T.name)})}const y=c.map(v=>({...v,agent_name:p[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 s9t(t){const{user:e}=Hn();return mr({queryKey:["open-house",t],queryFn:async()=>{const{data:r,error:n}=await Re.from("open_houses").select("*").eq("id",t).single();if(n)throw n;return r},enabled:!!e&&!!t})}function a9t(t){const{user:e}=Hn(),r=Ar();return C.useEffect(()=>{if(!t)return;const n=`visitors-${t}-${Math.random().toString(36).slice(2,10)}`,i=Re.channel(n).on("postgres_changes",{event:"*",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${t}`},()=>{r.invalidateQueries({queryKey:["open-house-visitors",t]}),r.invalidateQueries({queryKey:["open-houses"]})}).subscribe();return()=>{Re.removeChannel(i)}},[t,r]),mr({queryKey:["open-house-visitors",t],queryFn:async()=>{const{data:n,error:i}=await Re.from("open_house_visitors").select("*").eq("open_house_id",t).order("created_at",{ascending:!1});if(i)throw i;return n},enabled:!!e&&!!t})}function o9t(){const t=Ar(),e=Li();return Sr({mutationFn:async r=>{const{data:n,error:i}=await Re.from("open_houses").insert({...r,agent_id:e}).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["open-houses"]}),Ts({title:"Open house created!"})},onError:r=>{Ts({title:"Error",description:r.message,variant:"destructive"})}})}function l9t(){const t=Ar();return Sr({mutationFn:async({id:e,...r})=>{const{error:n}=await Re.from("open_houses").update(r).eq("id",e);if(n)throw n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["open-houses"]}),t.invalidateQueries({queryKey:["open-house",r.id]})}})}function c9t(){const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("open_houses").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["open-houses"]}),Ts({title:"Open house deleted"})}})}function Y_e(t){return mr({queryKey:["public-open-house",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("open_houses").select("*, profiles:agent_id(name, avatar_url, title, email, phone)").eq("slug",t).eq("is_active",!0).single();if(r)throw r;let n=null;if(e.agent_id){const{data:i}=await Re.from("agent_cards").select("slug").eq("user_id",e.agent_id).eq("is_published",!0).maybeSingle();i&&(n=i.slug)}return{...e,agent_card_slug:n}},enabled:!!t})}function u9t(t){const{user:e}=Hn();return mr({queryKey:["survey-questions",t],queryFn:async()=>{const{data:r,error:n}=await Re.from("open_house_survey_questions").select("*").eq("open_house_id",t).order("sort_order");if(n)throw n;return r},enabled:!!e&&!!t})}function oQe(t){return mr({queryKey:["public-survey-questions",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("open_house_survey_questions").select("*").eq("open_house_id",t).eq("is_active",!0).order("sort_order");if(r)throw r;return e},enabled:!!t})}function lQe(){return Sr({mutationFn:async t=>{const{error:e}=await Re.from("open_house_survey_responses").insert(t);if(e)throw e}})}function d9t(t){const{user:e}=Hn();return mr({queryKey:["survey-responses",t],queryFn:async()=>{const{data:r,error:n}=await Re.from("open_house_survey_questions").select("*").eq("open_house_id",t).order("sort_order");if(n)throw n;const i=(r||[]).map(a=>a.id);if(i.length===0)return{questions:[],responses:[]};const{data:o,error:c}=await Re.from("open_house_survey_responses").select("*").in("question_id",i).order("created_at",{ascending:!1});if(c)throw c;return{questions:r,responses:o||[]}},enabled:!!e&&!!t})}function h9t(){const t=Ar();return Sr({mutationFn:async e=>{const{data:r,error:n}=await Re.from("open_house_survey_questions").insert(e).select().single();if(n)throw n;return r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function f9t(){const t=Ar();return Sr({mutationFn:async({id:e,open_house_id:r,...n})=>{const{error:i}=await Re.from("open_house_survey_questions").update(n).eq("id",e);if(i)throw i},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function m9t(){const t=Ar();return Sr({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Re.from("open_house_survey_questions").delete().eq("id",e);if(n)throw n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function p9t(){const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.rpc("seed_default_survey_questions",{_open_house_id:e});if(r)throw r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["survey-questions",r]})}})}function cQe(){return Sr({mutationFn:async t=>{const e=crypto.randomUUID(),{error:r}=await Re.from("open_house_visitors").insert({...t,id:e});if(r)throw r;return{id:e}}})}function uQe(){return Sr({mutationFn:async({visitor_id:t,...e})=>{const{error:r}=await Re.from("open_house_visitors").update(e).eq("id",t);if(r)throw r}})}function dQe(){return Sr({mutationFn:async t=>{await Re.rpc("increment_open_house_scan",{_slug:t})}})}async function Z_e(t){const{data:e,error:r}=await Re.from("open_house_rooms").select("*").eq("open_house_id",t).order("sort_order");if(r)throw r;const n=e||[];if(n.length===0)return[];const i=n.map(f=>f.id),{data:o,error:c}=await Re.from("open_house_room_media").select("*").in("room_id",i).order("sort_order");if(c)throw c;const a={};return(o||[]).forEach(f=>{var y;const p=f;(a[y=p.room_id]||(a[y]=[])).push(p)}),n.map(f=>({...f,media:a[f.id]||[]}))}function g9t(t){const{user:e}=Hn();return mr({queryKey:["open-house-rooms",t],queryFn:()=>Z_e(t),enabled:!!e&&!!t})}function hQe(t){return mr({queryKey:["public-open-house-rooms",t],queryFn:()=>Z_e(t),enabled:!!t})}function y9t(){const t=Ar();return Sr({mutationFn:async e=>{const{data:r,error:n}=await Re.from("open_house_rooms").insert(e).select().single();if(n)throw n;return r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function x9t(){const t=Ar();return Sr({mutationFn:async({id:e,open_house_id:r,...n})=>{const{error:i}=await Re.from("open_house_rooms").update(n).eq("id",e);if(i)throw i},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function v9t(){const t=Ar();return Sr({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Re.from("open_house_rooms").delete().eq("id",e);if(n)throw n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function _9t(){const t=Ar();return Sr({mutationFn:async({open_house_id:e,...r})=>{const{data:n,error:i}=await Re.from("open_house_room_media").insert(r).select().single();if(i)throw i;return n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function b9t(){const t=Ar();return Sr({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Re.from("open_house_room_media").delete().eq("id",e);if(n)throw n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function w9t(){const t=Ar();return Sr({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 S9t(){const t=Ar();return Sr({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,p)=>{const y=a.get(f);return y?{...y,sort_order:p}:null}).filter(Boolean)}})),{prev:o,key:i}},onError:(e,r,n)=>{n!=null&&n.prev&&t.setQueryData(n.key,n.prev)},onSettled:(e,r,n)=>{t.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function T9t(t){const{user:e}=Hn();return mr({queryKey:["open-house-leads",t],queryFn:async()=>{const{data:r,error:n}=await Re.from("open_house_leads").select("*").eq("open_house_id",t).order("created_at",{ascending:!1});if(n)throw n;return r||[]},enabled:!!e&&!!t})}function E9t(){const t=Ar();return Sr({mutationFn:async({id:e,status:r,open_house_id:n})=>{const{error:i}=await Re.from("open_house_leads").update({status:r}).eq("id",e);if(i)throw i;return{open_house_id:n}},onSuccess:e=>{t.invalidateQueries({queryKey:["open-house-leads",e.open_house_id]})}})}var rF="Switch",[fQe,j9t]=Qo(rF),[mQe,pQe]=fQe(rF),X_e=C.forwardRef((t,e)=>{const{__scopeSwitch:r,name:n,checked:i,defaultChecked:o,required:c,disabled:a,value:f="on",onCheckedChange:p,form:y,...v}=t,[T,E]=C.useState(null),k=Yn(e,B=>E(B)),P=C.useRef(!1),R=T?y||!!T.closest("form"):!0,[D,M]=yd({prop:i,defaultProp:o??!1,onChange:p,caller:rF});return s.jsxs(mQe,{scope:r,checked:D,disabled:a,children:[s.jsx(nn.button,{type:"button",role:"switch","aria-checked":D,"aria-required":c,"data-state":tbe(D),"data-disabled":a?"":void 0,disabled:a,value:f,...v,ref:k,onClick:Or(t.onClick,B=>{M(V=>!V),R&&(P.current=B.isPropagationStopped(),P.current||B.stopPropagation())})}),R&&s.jsx(ebe,{control:T,bubbles:!P.current,name:n,value:f,checked:D,required:c,disabled:a,form:y,style:{transform:"translateX(-100%)"}})]})});X_e.displayName=rF;var Q_e="SwitchThumb",J_e=C.forwardRef((t,e)=>{const{__scopeSwitch:r,...n}=t,i=pQe(Q_e,r);return s.jsx(nn.span,{"data-state":tbe(i.checked),"data-disabled":i.disabled?"":void 0,...n,ref:e})});J_e.displayName=Q_e;var gQe="SwitchBubbleInput",ebe=C.forwardRef(({__scopeSwitch:t,control:e,checked:r,bubbles:n=!0,...i},o)=>{const c=C.useRef(null),a=Yn(c,o),f=UC(r),p=IC(e);return C.useEffect(()=>{const y=c.current;if(!y)return;const v=window.HTMLInputElement.prototype,E=Object.getOwnPropertyDescriptor(v,"checked").set;if(f!==r&&E){const k=new Event("click",{bubbles:n});E.call(y,r),y.dispatchEvent(k)}},[f,r,n]),s.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:r,...i,tabIndex:-1,ref:a,style:{...i.style,...p,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});ebe.displayName=gQe;function tbe(t){return t?"checked":"unchecked"}var rbe=X_e,yQe=J_e;const gT=C.forwardRef(({className:t,...e},r)=>s.jsx(rbe,{className:qt("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(yQe,{className:qt("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")})}));gT.displayName=rbe.displayName;const xQe=["Excellent","Good","Neutral","Bad","Very Bad"],vQe=[5,4,3,2,1];function _Qe({questions:t,visitorId:e,onComplete:r,onSkip:n}){const i=lQe(),[o,c]=C.useState({}),a=t.filter(T=>T.question_type==="rating"),f=t.filter(T=>T.question_type!=="rating"),p=(T,E)=>{c(k=>({...k,[T]:{rating_value:E}}))},y=(T,E)=>{c(k=>({...k,[T]:{text_value:E}}))},v=async()=>{const T=Object.entries(o).filter(([,E])=>E.rating_value!=null||E.text_value&&E.text_value.trim()).map(([E,k])=>{var P;return{visitor_id:e,question_id:E,rating_value:k.rating_value??null,text_value:((P=k.text_value)==null?void 0:P.trim())||null}});if(T.length>0)try{await i.mutateAsync(T)}catch{}r()};return 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"}),xQe.map(T=>s.jsx("div",{className:"w-12 text-center",children:s.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:T})},T))]}),a.map(T=>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:T.question_text}),vQe.map(E=>{var k;return s.jsx("div",{className:"w-12 flex justify-center",children:s.jsx("button",{type:"button",onClick:()=>p(T.id,E),className:`w-6 h-6 rounded-full border-2 transition-all ${((k=o[T.id])==null?void 0:k.rating_value)===E?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},E)})]},T.id))]}),f.map(T=>{var E;return s.jsxs("div",{children:[s.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:T.question_text}),s.jsx(Ad,{value:((E=o[T.id])==null?void 0:E.text_value)||"",onChange:k=>y(T.id,k.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},T.id)}),s.jsx(Bt,{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(su,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}function JV(t){return/iframe\.mediadelivery\.net\/embed\//.test(t)}function bQe({rooms:t}){var P;const[e,r]=C.useState(((P=t[0])==null?void 0:P.id)||""),[n,i]=C.useState(null),[o,c]=C.useState(null),a=C.useRef({}),f=t.find(R=>R.id===n)||t[0],p=o!==null?f==null?void 0:f.media[o]:null,y=(f==null?void 0:f.media.length)??0,v=()=>{c(null),i(null)},T=()=>c(R=>R===null||y===0?R:(R-1+y)%y),E=()=>c(R=>R===null||y===0?R:(R+1)%y);C.useEffect(()=>{if(o===null)return;const R=D=>{D.key==="Escape"?v():D.key==="ArrowLeft"?T():D.key==="ArrowRight"&&E()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[o,y]),C.useEffect(()=>{const R=new IntersectionObserver(D=>{const M=D.filter(B=>B.isIntersecting).sort((B,V)=>B.boundingClientRect.top-V.boundingClientRect.top);M[0]&&r(M[0].target.dataset.roomId||"")},{rootMargin:"-90px 0px -55% 0px"});return Object.values(a.current).forEach(D=>D&&R.observe(D)),()=>R.disconnect()},[t]);const k=R=>{r(R);const D=a.current[R];D&&window.scrollTo({top:D.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(R=>s.jsxs("button",{onClick:()=>k(R.id),className:qt("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",e===R.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[R.name,s.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:R.media.length})]},R.id))})}),t.map(R=>s.jsxs("section",{"data-room-id":R.id,ref:D=>{a.current[R.id]=D},className:"mt-10 first:mt-6",children:[s.jsx("h3",{className:"text-2xl font-bold",children:R.name}),R.description&&s.jsx("p",{className:"text-white/60 mt-1.5 text-sm max-w-2xl",children:R.description}),R.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:R.media.map((D,M)=>s.jsx("button",{onClick:()=>{i(R.id),c(M)},className:qt("relative aspect-[3/2] rounded-xl overflow-hidden bg-white/5 group",M===0&&R.media.length!==2&&"col-span-2 aspect-[16/9]"),children:D.kind==="video"?s.jsxs(s.Fragment,{children:[JV(D.url)?s.jsx("div",{className:"absolute inset-0 bg-slate-900"}):s.jsx("video",{src:D.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(sA,{className:"h-6 w-6 text-slate-900"})})})]}):s.jsx("img",{src:D.url,alt:R.name,loading:"lazy",className:"w-full h-full object-cover group-hover:scale-[1.03] transition-transform duration-500"})},D.id))})]},R.id)),p&&f&&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:R=>{R.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:R=>{R.stopPropagation(),T()},className:"absolute left-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Previous",children:s.jsx(Cm,{className:"h-6 w-6"})}),p.kind==="video"?JV(p.url)?s.jsx("iframe",{src:`${p.url}?autoplay=true`,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full max-w-5xl aspect-video rounded-lg",onClick:R=>R.stopPropagation()},p.url):s.jsx("video",{src:p.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:R=>R.stopPropagation()},p.url):s.jsx("img",{src:p.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:R=>R.stopPropagation()}),y>1&&s.jsx("button",{onClick:R=>{R.stopPropagation(),E()},className:"absolute right-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Next",children:s.jsx(jd,{className:"h-6 w-6"})})]})]}):null}function wQe({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((p,y)=>{e.push({type:"media",roomId:f.id,roomName:f.name,url:p.url,kind:p.kind,index:y,total:f.media.length})})});const r=C.useRef(null),[n,i]=C.useState(0);C.useEffect(()=>{const f=r.current;if(!f)return;let p=0;const y=()=>{cancelAnimationFrame(p),p=requestAnimationFrame(()=>{const v=Math.round(f.scrollLeft/f.clientWidth);i(v)})};return f.addEventListener("scroll",y,{passive:!0}),()=>{f.removeEventListener("scroll",y),cancelAnimationFrame(p)}},[]);const o=f=>{const p=r.current;p&&p.scrollTo({left:f*p.clientWidth,behavior:"smooth"})};if(!e.length)return null;const c=(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 p=e.findIndex(v=>v.roomId===f.id),y=c===f.id;return s.jsx("button",{onClick:()=>o(p),className:qt("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,p)=>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"?JV(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]})]})]})},p))}),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(Cm,{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(jd,{className:"h-4 w-4"})]})]})]})}const tz={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:fh},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:oo},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:_m},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:$p}},SQe=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function TQe(t){return t==null||t<=0?null:`$${t.toLocaleString("en-US")}`}function EQe({openHouse:t,visitorId:e,visitorName:r,visitorEmail:n,visitorPhone:i,previewMode:o=!1}){var tr;const c=t.profiles,a=((tr=c==null?void 0:c.name)==null?void 0:tr.split(" ").map(_t=>_t[0]).join("").slice(0,2))||"?",f=t.brand_color_override||null,[p,y]=C.useState(null),[v,T]=C.useState(""),[E,k]=C.useState(n||""),[P,R]=C.useState(i||""),[D,M]=C.useState(!1),[B,V]=C.useState(null),[G,W]=C.useState(""),[Y,J]=C.useState(""),[Q,ee]=C.useState(""),[le,pe]=C.useState([]),[Se,je]=C.useState(""),[Le,Ae]=C.useState(""),[be,me]=C.useState(""),[Te,Ne]=C.useState(""),Ee=TQe(t.price),we=t.tour_mode==="rooms",{data:He=[]}=hQe(we?t.id:void 0),tt=[t.enable_question&&"question",t.enable_showing&&"showing",t.enable_disclosures&&"disclosure",t.enable_offer&&"offer"].filter(Boolean),at=_t=>{y(_t),T(""),W(""),J(""),ee(""),pe([]),je(""),Ae(""),me(""),Ne("")},Et=()=>{y(null)},vt=_t=>{pe(cr=>cr.includes(_t)?cr.filter(Tr=>Tr!==_t):[...cr,_t])},Gt=_t=>_t==="showing"?{preferred_date:G||null,preferred_time:Y||null,alternate_date:Q||null}:_t==="disclosure"?{requested_documents:le}:_t==="offer"?{offer_amount:Se||null,financing:Le||null,timeline:be||null,pre_approved:Te||null}:{},pt=p?p==="showing"?!!G:p==="question"?v.trim().length>0:!0:!1,Pt=async()=>{if(p){if(o){Ts({title:"Preview mode",description:"Lead not sent — this is just a preview."}),V(p),setTimeout(()=>{y(null),V(null)},1500);return}M(!0);try{const _t=Gt(p),{error:cr}=await Re.from("open_house_leads").insert({open_house_id:t.id,visitor_id:e,action_type:p,payload:{message:v.trim()||null,email:E.trim()||null,phone:P.trim()||null,visitor_name:r,..._t}});if(cr)throw cr;Re.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:t.id,visitor_id:e,action_type:p,message:v.trim()||null,visitor_name:r,visitor_email:E.trim()||null,visitor_phone:P.trim()||null,extras:_t}}).catch(()=>{}),V(p),Ts({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{Et(),V(null)},1400)}catch(_t){Ts({title:"Something went wrong",description:_t.message,variant:"destructive"})}finally{M(!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(Es,{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(XS,{className:"h-4 w-4"}),t.beds," bd"]}),t.baths!=null&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(__,{className:"h-4 w-4"}),t.baths," ba"]}),t.sqft!=null&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(C9,{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(vd,{className:"h-12 w-12 ring-2 ring-white/20",style:f?{boxShadow:`0 0 0 2px ${f}`}:void 0,children:[s.jsx(_d,{src:c.avatar_url||"",alt:c.name||""}),s.jsx(bd,{className:"bg-white/10 text-white",children:a})]}),t.co_host_name&&s.jsxs(vd,{className:"h-12 w-12 -ml-6 ring-2 ring-slate-950",children:[s.jsx(_d,{src:t.co_host_photo_url||"",alt:t.co_host_name}),s.jsx(bd,{className:"bg-white/10 text-white",children:String(t.co_host_name).split(" ").map(_t=>_t[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(ri,{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(mi,{className:"h-4 w-4"})})]})]}),we&&He.length>0&&s.jsxs("div",{className:"mt-8",children:[s.jsx(bQe,{rooms:He}),s.jsx(wQe,{rooms:He})]}),tt.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:tt.map(_t=>{const cr=tz[_t],Tr=cr.icon;return s.jsxs("button",{onClick:()=>at(_t),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:cr.label})]},_t)})})]}),s.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),s.jsx(_xe,{open:!!p,onOpenChange:_t=>!_t&&Et(),children:s.jsx(T7,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:p&&s.jsxs(s.Fragment,{children:[s.jsxs(wxe,{className:"text-left",children:[s.jsx(Sxe,{children:tz[p].title}),s.jsxs(Txe,{children:[(c==null?void 0:c.name)||"The agent"," will be notified by email."]})]}),B===p?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(oc,{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(Mr,{className:"text-xs",children:"Email"}),s.jsx(Br,{type:"email",value:E,onChange:_t=>k(_t.target.value),placeholder:"you@example.com",className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs",children:"Phone"}),s.jsx(Br,{type:"tel",value:P,onChange:_t=>R(_t.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),p==="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(Mr,{className:"text-xs",children:"Preferred date *"}),s.jsx(Br,{type:"date",value:G,onChange:_t=>W(_t.target.value),className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs",children:"Preferred time"}),s.jsx(Br,{type:"time",value:Y,onChange:_t=>J(_t.target.value),className:"mt-1"})]})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs",children:"Alternate date (optional)"}),s.jsx(Br,{type:"date",value:Q,onChange:_t=>ee(_t.target.value),className:"mt-1"})]})]}),p==="disclosure"&&s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs",children:"Which documents? (select all that apply)"}),s.jsx("div",{className:"mt-2 space-y-2",children:SQe.map(_t=>s.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[s.jsx(WC,{checked:le.includes(_t),onCheckedChange:()=>vt(_t)}),s.jsx("span",{children:_t})]},_t))})]}),p==="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(Mr,{className:"text-xs",children:"Estimated offer"}),s.jsx(Br,{value:Se,onChange:_t=>je(_t.target.value),placeholder:"$",className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs",children:"Financing"}),s.jsxs(ba,{value:Le,onValueChange:Ae,children:[s.jsx(oa,{className:"mt-1",children:s.jsx(wa,{placeholder:"Select..."})}),s.jsxs(la,{children:[s.jsx(mn,{value:"Cash",children:"Cash"}),s.jsx(mn,{value:"Conventional",children:"Conventional"}),s.jsx(mn,{value:"FHA",children:"FHA"}),s.jsx(mn,{value:"VA",children:"VA"}),s.jsx(mn,{value:"Other",children:"Other"})]})]})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs",children:"Timeline"}),s.jsxs(ba,{value:be,onValueChange:me,children:[s.jsx(oa,{className:"mt-1",children:s.jsx(wa,{placeholder:"Select..."})}),s.jsxs(la,{children:[s.jsx(mn,{value:"ASAP",children:"ASAP"}),s.jsx(mn,{value:"30 days",children:"30 days"}),s.jsx(mn,{value:"60 days",children:"60 days"}),s.jsx(mn,{value:"90+ days",children:"90+ days"})]})]})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs",children:"Pre-approved?"}),s.jsxs(ba,{value:Te,onValueChange:Ne,children:[s.jsx(oa,{className:"mt-1",children:s.jsx(wa,{placeholder:"Select..."})}),s.jsxs(la,{children:[s.jsx(mn,{value:"Yes",children:"Yes"}),s.jsx(mn,{value:"No",children:"No"}),s.jsx(mn,{value:"In progress",children:"In progress"})]})]})]})]})]}),s.jsxs("div",{children:[s.jsxs(Mr,{className:"text-xs",children:["Message",p==="question"?" *":" (optional)"]}),s.jsx(Ad,{value:v,onChange:_t=>T(_t.target.value),placeholder:tz[p].placeholder,rows:4,className:"mt-1"})]}),s.jsx(Bt,{onClick:Pt,disabled:D||!pt,className:"w-full h-12 text-white hover:opacity-90",style:f?{backgroundColor:f}:void 0,children:D?s.jsx(su,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const jQe=mg({first_name:Ai().trim().min(1,"First name is required").max(50),last_name:Ai().trim().max(50).optional(),email:Ai().trim().email("Please enter a valid email").max(255).optional().or(rM("")),phone:Ai().trim().max(20).optional().or(rM(""))}),AQe=[{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 nbe({slug:t}={}){var ar;const e=Pm(),r=t||e.slug,[n]=Px(),i=n.get("kiosk")==="1"||n.get("mode")==="kiosk",o=8,{data:c,isLoading:a,error:f}=Y_e(r),p=cQe(),y=uQe(),v=dQe(),T=C.useRef(!1),[E,k]=C.useState("welcome"),[P,R]=C.useState(null),[D,M]=C.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[B,V]=C.useState(""),[G,W]=C.useState(!1),[Y,J]=C.useState(!1),[Q,ee]=C.useState(""),[le,pe]=C.useState(""),[Se,je]=C.useState(o),[Le,Ae]=C.useState(!1),[be,me]=C.useState(null),Te=c==null?void 0:c.agent_card_slug,Ne=Te?`https://cards.relevelup.com/${Te}${c!=null&&c.disclosure_pdf_url?`?oh_disclosure=${encodeURIComponent(c.disclosure_pdf_url)}`:""}`:null,Ee=E==="done"&&!i&&!!Ne&&!!(c!=null&&c.auto_forward_to_card);C.useEffect(()=>{if(!Ee||Le){me(null);return}let Nt=c!=null&&c.disclosure_pdf_url?10:3;me(Nt);const gr=setInterval(()=>{if(Nt-=1,Nt<=0){clearInterval(gr),window.location.href=Ne;return}me(Nt)},1e3);return()=>clearInterval(gr)},[Ee,Le,Ne,c==null?void 0:c.disclosure_pdf_url]);const we=C.useCallback(()=>{R(null),M({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),V(""),W(!1),J(!1),ee(""),pe(""),je(o),k(i?"info":"welcome")},[i]),He=C.useCallback((Nt,gr)=>{c!=null&&c.id&&Re.functions.invoke("guestbook-lead-notify",{body:{open_house_id:c.id,visitor_id:Nt,first_name:gr.first_name??D.first_name,last_name:gr.last_name??D.last_name,email:gr.email??D.email,phone:gr.phone??D.phone,visitor_intent:gr.visitor_intent??B,message:gr.message,wants_market_updates:gr.wants_market_updates??G,has_agent:gr.has_agent??Y,working_with_agent_name:gr.working_with_agent_name??Q,visitor_address:gr.visitor_address??D.visitor_address}}).catch(En=>console.error("Guest book lead notify failed:",En))},[c==null?void 0:c.id,D,B,G,Y,Q]);C.useEffect(()=>{if(!i||E!=="done")return;je(o);const Nt=setInterval(()=>{je(gr=>gr<=1?(clearInterval(Nt),we(),0):gr-1)},1e3);return()=>clearInterval(Nt)},[i,E,we]),C.useEffect(()=>{if(!i)return;k(gr=>gr==="welcome"?"info":gr);let Nt=null;return(async()=>{var gr,En;try{Nt=await((En=(gr=navigator.wakeLock)==null?void 0:gr.request)==null?void 0:En.call(gr,"screen"))}catch{}})(),()=>{var gr;try{(gr=Nt==null?void 0:Nt.release)==null||gr.call(Nt)}catch{}}},[i]);const tt=C.useCallback(()=>{var gr;const Nt=document.documentElement;document.fullscreenElement||(gr=Nt.requestFullscreen||Nt.webkitRequestFullscreen)==null||gr.call(Nt).catch(()=>{})},[]),{data:at,isLoading:Et}=oQe(c==null?void 0:c.id),vt=!!(c!=null&&c.enable_survey),Gt=(c==null?void 0:c.ask_visitor_intent)!==!1,pt=(c==null?void 0:c.ask_visitor_address)===!0;C.useEffect(()=>{if(!r||!(c!=null&&c.id)||T.current)return;const Nt=`oh_scan_${c.id}`;if(sessionStorage.getItem(Nt)){T.current=!0;return}T.current=!0,sessionStorage.setItem(Nt,"1"),v.mutate(r)},[r,c==null?void 0:c.id]),C.useEffect(()=>{E==="pending_survey"&&(Et||k(vt&&((at==null?void 0:at.length)??0)>0?"survey":"done"))},[E,Et,vt,at]);const Pt=Nt=>{if(!Nt)return"";const[gr,En]=Nt.split(":"),ni=parseInt(gr),ii=ni>=12?"PM":"AM";return`${ni>12?ni-12:ni||12}:${En} ${ii}`},tr=async()=>{pe("");const Nt=jQe.safeParse(D);if(!Nt.success){pe(Nt.error.issues[0].message);return}if(!D.email&&!D.phone){pe("Please provide either an email or phone number");return}const gr=(c==null?void 0:c.kind)==="virtual";let En=null;if(!P&&(c!=null&&c.id))try{const ni=await p.mutateAsync({open_house_id:c.id,first_name:D.first_name.trim(),last_name:D.last_name.trim()||void 0,email:D.email.trim()||void 0,phone:D.phone.trim()||void 0,visitor_address:pt&&D.visitor_address.trim()?D.visitor_address.trim():void 0,wants_market_updates:G,has_agent:Y,working_with_agent_name:Y&&Q.trim()?Q.trim():void 0,partial_signin:gr?!1:Gt});En=ni.id,R(ni.id)}catch{if(gr){pe("We could not start the virtual tour. Please try again.");return}}if(gr){Gt?k("intent"):(En&&He(En,{}),k("done"));return}if(!Gt){En&&He(En,{}),vt?!Et&&at&&at.length>0?k("survey"):k("pending_survey"):k("done");return}k("intent")},_t=async Nt=>{V(Nt);try{let gr=P;if(gr?await y.mutateAsync({visitor_id:gr,visitor_intent:Nt,wants_market_updates:G,has_agent:Y,working_with_agent_name:Y&&Q.trim()?Q.trim():null,partial_signin:!1}):(gr=(await p.mutateAsync({open_house_id:c.id,first_name:D.first_name.trim(),last_name:D.last_name.trim()||void 0,email:D.email.trim()||void 0,phone:D.phone.trim()||void 0,visitor_address:pt&&D.visitor_address.trim()?D.visitor_address.trim():void 0,visitor_intent:Nt,wants_market_updates:G,has_agent:Y,working_with_agent_name:Y&&Q.trim()?Q.trim():void 0,partial_signin:!1})).id,R(gr)),gr&&He(gr,{visitor_intent:Nt,wants_market_updates:G,has_agent:Y,working_with_agent_name:Y&&Q.trim()?Q.trim():null}),(c==null?void 0:c.kind)==="virtual"){k("done");return}vt?!Et&&at&&at.length>0?k("survey"):k("pending_survey"):k("done")}catch{pe("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(va,{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 cr=c.profiles,Tr=((ar=cr==null?void 0:cr.name)==null?void 0:ar.split(" ").map(Nt=>Nt[0]).join("").slice(0,2))||"?",sn=c.event_type==="community",ur=c.kind==="virtual",xr=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(ur&&(xr||E==="done"))return!xr&&!P?s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center",children:s.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})}):s.jsxs(s.Fragment,{children:[s.jsxs(Zo,{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"})]}),xr&&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(EQe,{openHouse:c,visitorId:xr?"preview":P,visitorName:xr?"Preview Visitor":`${D.first_name} ${D.last_name}`.trim(),visitorEmail:xr?"":D.email,visitorPhone:xr?"":D.phone,previewMode:xr})]});const vn=`${ur?"Virtual Open House":sn?"Community Event":"Open House"} — ${c.property_address}`,jt=[[c.city,c.state].filter(Boolean).join(", "),c.event_date?Ri(new Date(c.event_date+"T00:00:00"),"EEE, MMM d"):null,cr!=null&&cr.name?`Hosted by ${cr.name}`:null].filter(Boolean).join(" · "),er=c.photo_url||"",Pr=er&&er.includes("/storage/v1/object/public/")?er.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":er||"https://dashboard.relevelup.com/og-image.png",dr=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${r}`;return s.jsxs(s.Fragment,{children:[s.jsxs(Zo,{children:[s.jsx("title",{children:vn}),s.jsx("meta",{name:"description",content:jt||`Sign in to ${c.property_address}`}),s.jsx("meta",{property:"og:type",content:"website"}),s.jsx("meta",{property:"og:title",content:vn}),s.jsx("meta",{property:"og:description",content:jt||`Sign in to ${c.property_address}`}),s.jsx("meta",{property:"og:image",content:Pr}),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:dr}),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:vn}),s.jsx("meta",{name:"twitter:description",content:jt||`Sign in to ${c.property_address}`}),s.jsx("meta",{name:"twitter:image",content:Pr}),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(vd,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[s.jsx(_d,{src:(cr==null?void 0:cr.avatar_url)||"",alt:(cr==null?void 0:cr.name)||""}),s.jsx(bd,{className:"bg-white/10 text-white text-lg",children:Tr})]}),s.jsx("p",{className:"text-white/60 text-sm",children:cr==null?void 0:cr.name}),(cr==null?void 0:cr.title)&&s.jsx("p",{className:"text-white/40 text-xs",children:cr.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(Es,{className:"h-3 w-3"}),c.city,c.state?`, ${c.state}`:""," ",c.zip]}),!ur&&s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(oo,{className:"h-3 w-3"}),Ri(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(Dl,{className:"h-3 w-3"}),Pt(c.start_time),c.end_time?` – ${Pt(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:sn?s.jsx(_o,{className:"h-5 w-5 text-white"}):s.jsx(va,{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(Es,{className:"h-3 w-3"}),c.city,c.state?`, ${c.state}`:""," ",c.zip]}),!ur&&s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(oo,{className:"h-3 w-3"}),Ri(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(Dl,{className:"h-3 w-3"}),Pt(c.start_time),c.end_time?` – ${Pt(c.end_time)}`:""]})]})]})]})]})}),s.jsxs("div",{className:"p-6",children:[E==="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(Bt,{onClick:()=>k("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",s.jsx(Ds,{className:"h-5 w-5 ml-2"})]}),s.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),E==="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:()=>k("welcome"),className:"text-slate-400 hover:text-slate-600",children:s.jsx(dx,{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(Mr,{className:"text-slate-600 text-xs",children:"First Name *"}),s.jsx(Br,{value:D.first_name,onChange:Nt=>M(gr=>({...gr,first_name:Nt.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-slate-600 text-xs",children:"Last Name"}),s.jsx(Br,{value:D.last_name,onChange:Nt=>M(gr=>({...gr,last_name:Nt.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-slate-600 text-xs",children:"Email"}),s.jsx(Br,{type:"email",value:D.email,onChange:Nt=>M(gr=>({...gr,email:Nt.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-slate-600 text-xs",children:"Phone"}),s.jsx(Br,{type:"tel",value:D.phone,onChange:Nt=>M(gr=>({...gr,phone:Nt.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),pt&&s.jsxs("div",{children:[s.jsx(Mr,{className:"text-slate-600 text-xs",children:"Your Home Address"}),s.jsx(Br,{value:D.visitor_address,onChange:Nt=>M(gr=>({...gr,visitor_address:Nt.target.value})),placeholder:"Street, City, State ZIP",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoComplete:"street-address"})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer pt-1",children:[s.jsx("input",{type:"checkbox",checked:G,onChange:Nt=>W(Nt.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:Y?"Yes":"No"}),s.jsx(gT,{checked:Y,onCheckedChange:J})]})]}),Y&&s.jsx(Br,{value:Q,onChange:Nt=>ee(Nt.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),le&&s.jsx("p",{className:"text-destructive text-sm",children:le}),s.jsxs(Bt,{onClick:tr,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",s.jsx(Ds,{className:"h-5 w-5 ml-2"})]})]}),E==="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:()=>k("info"),className:"text-slate-400 hover:text-slate-600",children:s.jsx(dx,{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:AQe.map(Nt=>s.jsxs("button",{onClick:()=>_t(Nt.value),disabled:p.isPending,className:"flex flex-col items-center gap-2 p-5 rounded-xl border-2 border-slate-200 hover:border-slate-900 hover:bg-slate-50 transition-all text-center group",children:[s.jsx("span",{className:"text-2xl",children:Nt.emoji}),s.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Nt.label})]},Nt.value))}),le&&s.jsx("p",{className:"text-destructive text-sm text-center",children:le})]}),E==="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..."})]}),E==="survey"&&P&&at&&s.jsx(_Qe,{questions:at,visitorId:P,onComplete:()=>k("done"),onSkip:()=>k("done")}),E==="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(oc,{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, ",D.first_name,". ",sn?"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:()=>Ae(!0),className:"inline-flex items-center justify-center gap-2 px-5 py-3 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 font-medium text-sm transition-colors",children:[s.jsx(_m,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),Ne&&s.jsxs("a",{href:Ne,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(Ds,{className:"h-4 w-4"}),"View ",cr!=null&&cr.name?`${cr.name.split(" ")[0]}'s`:"My"," Business Card"]})]}),Ne&&be!==null&&!Le&&s.jsxs("p",{className:"text-xs text-slate-400",children:["Opening the business card in ",be,"s…"," ",s.jsx("button",{type:"button",className:"underline",onClick:()=>Ae(!0),children:"Stay here"})]}),(cr==null?void 0:cr.name)&&s.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",s.jsx("strong",{className:"text-slate-600",children:cr.name})]}),i&&s.jsxs("div",{className:"pt-4 space-y-3",children:[s.jsx(Bt,{onClick:we,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 ",Se,"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(dMe,{className:"h-3 w-3"})," Tablet Mode"]}),s.jsx("button",{onClick:tt,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(VDe,{className:"h-3 w-3"})})]})]})})]})}const kQe=Object.freeze(Object.defineProperty({__proto__:null,default:nbe},Symbol.toStringTag,{value:"Module"}));function A9t(t){return mr({queryKey:["open-house-rsvps",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("open_house_rsvps").select("*").eq("open_house_id",t).order("created_at",{ascending:!1});if(r)throw r;return e||[]},enabled:!!t})}function CQe(){const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("open_house_rsvps").insert({open_house_id:e.open_house_id,first_name:e.first_name,last_name:e.last_name||null,email:e.email||null,phone:e.phone||null,has_agent:e.has_agent??!1,working_with_agent_name:e.working_with_agent_name||null,message:e.message||null});if(r)throw r;return null},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["open-house-rsvps",r.open_house_id]})}})}function k9t(t){const e=Ar();return Sr({mutationFn:async r=>{const{error:n}=await Re.from("open_house_rsvps").delete().eq("id",r);if(n)throw n},onSuccess:()=>e.invalidateQueries({queryKey:["open-house-rsvps",t]})})}function C9t(t){const e=Ar();return Sr({mutationFn:async({id:r,checkedIn:n})=>{const{error:i}=await Re.from("open_house_rsvps").update({checked_in_at:n?new Date().toISOString():null}).eq("id",r);if(i)throw i},onSuccess:()=>e.invalidateQueries({queryKey:["open-house-rsvps",t]})})}const NQe=mg({first_name:Ai().trim().min(1,"First name is required").max(50),last_name:Ai().trim().max(50).optional(),email:Ai().trim().email("Please enter a valid email").max(255),phone:Ai().trim().max(20).optional().or(rM("")),message:Ai().trim().max(500).optional().or(rM(""))}),rz=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}`},IQe=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 ibe({slug:t}={}){const e=Pm(),r=t||e.slug,{data:n,isLoading:i,error:o}=Y_e(r),c=CQe(),[a,f]=C.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[p,y]=C.useState(!1),[v,T]=C.useState(""),[E,k]=C.useState(""),[P,R]=C.useState(!1),D=C.useMemo(()=>IQe(n==null?void 0:n.event_date),[n==null?void 0:n.event_date]),M=C.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]),B=n==null?void 0:n.profiles,V=[n==null?void 0:n.city,n==null?void 0:n.state].filter(Boolean).join(", "),G=async()=>{k("");const J=NQe.safeParse(a);if(!J.success){k(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:p,working_with_agent_name:p&&v.trim()?v.trim():void 0,message:a.message.trim()||void 0}),R(!0)}catch(Q){k((Q==null?void 0:Q.message)||"Something went wrong. Please try again.")}},W=C.useMemo(()=>{if(!n||!D)return"";const J=je=>String(je).padStart(2,"0"),Q=`${D.getFullYear()}${J(D.getMonth()+1)}${J(D.getDate())}`,ee=(n.start_time||"12:00").slice(0,5).replace(":","")+"00",le=(n.end_time||"14:00").slice(0,5).replace(":","")+"00",pe=encodeURIComponent(`Open House — ${n.property_address}`),Se=encodeURIComponent([n.property_address,V,n.zip].filter(Boolean).join(", "));return`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${pe}&dates=${Q}T${ee}/${Q}T${le}&location=${Se}`},[n,D,V]);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(va,{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 Y=`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent([n.property_address,V,n.zip].filter(Boolean).join(", "))}`;return s.jsxs("div",{className:"min-h-screen bg-[#f6f2ee]",children:[s.jsxs(Zo,{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}${D?` on ${Ri(D,"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:[M&&s.jsx("img",{src:M,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}),V&&s.jsxs("p",{className:"mt-1 text-white/70",children:[V," ",n.zip||""]}),s.jsxs("div",{className:"mt-4 flex flex-wrap gap-x-5 gap-y-2 text-sm text-white/85",children:[D&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(oo,{className:"h-4 w-4 text-[#d4b978]"}),Ri(D,"EEEE, MMMM d, yyyy")]}),n.start_time&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Dl,{className:"h-4 w-4 text-[#d4b978]"}),rz(n.start_time),n.end_time?` – ${rz(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(xR,{icon:s.jsx(va,{className:"h-4 w-4"}),label:"Price",value:`$${Number(n.price).toLocaleString()}`}):null,n.beds?s.jsx(xR,{icon:s.jsx(TDe,{className:"h-4 w-4"}),label:"Beds",value:String(n.beds)}):null,n.baths?s.jsx(xR,{icon:s.jsx(__,{className:"h-4 w-4"}),label:"Baths",value:String(n.baths)}):null,n.sqft?s.jsx(xR,{icon:s.jsx(QO,{className:"h-4 w-4"}),label:"Sq Ft",value:Number(n.sqft).toLocaleString()}):null]}),n.property_description&&s.jsx("p",{className:"text-[15px] leading-relaxed text-[#3a4a51] whitespace-pre-line",children:n.property_description}),s.jsx("section",{id:"rsvp",className:"rounded-2xl bg-white shadow-[0_10px_40px_rgba(15,28,34,0.08)] overflow-hidden",children:P?s.jsxs("div",{className:"p-8 sm:p-12 text-center",children:[s.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-emerald-500/10",children:s.jsx(oc,{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 ",D?Ri(D,"EEEE, MMMM d"):"soon",n.start_time?` at ${rz(n.start_time)}`:"",". A confirmation reminder will land in your inbox before the event."]}),s.jsxs("div",{className:"mt-6 flex flex-wrap justify-center gap-3",children:[W&&s.jsx(Bt,{asChild:!0,className:"bg-[#1b3a4b] hover:bg-[#25505f]",children:s.jsxs("a",{href:W,target:"_blank",rel:"noreferrer",children:[s.jsx(cme,{className:"mr-2 h-4 w-4"}),"Add to calendar"]})}),s.jsx(Bt,{asChild:!0,variant:"outline",children:s.jsxs("a",{href:Y,target:"_blank",rel:"noreferrer",children:[s.jsx(Es,{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(Mr,{htmlFor:"rsvp-first",children:"First name *"}),s.jsx(Br,{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(Mr,{htmlFor:"rsvp-last",children:"Last name"}),s.jsx(Br,{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(Mr,{htmlFor:"rsvp-email",children:"Email *"}),s.jsx(Br,{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(Mr,{htmlFor:"rsvp-phone",children:"Phone"}),s.jsx(Br,{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(gT,{checked:p,onCheckedChange:y})]}),p&&s.jsx(Br,{value:v,onChange:J=>T(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(Mr,{htmlFor:"rsvp-msg",children:"Anything you'd like us to know?"}),s.jsx(Ad,{id:"rsvp-msg",rows:3,value:a.message,onChange:J=>f(Q=>({...Q,message:J.target.value})),className:"resize-y"})]}),E&&s.jsx("p",{className:"mt-3 text-sm text-destructive",children:E}),s.jsx(Bt,{onClick:G,disabled:c.isPending,className:"mt-6 h-12 w-full bg-gradient-to-r from-[#1b3a4b] to-[#406E71] text-base hover:opacity-95",children:c.isPending?"Reserving…":s.jsxs(s.Fragment,{children:["RSVP for this open house",s.jsx(Ds,{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."})]})}),(B==null?void 0:B.name)&&s.jsxs("section",{className:"rounded-2xl bg-white/70 border border-[#e4dcd3] p-5 flex items-center gap-4",children:[s.jsxs(vd,{className:"h-14 w-14",children:[s.jsx(_d,{src:B.avatar_url||void 0,alt:B.name}),s.jsx(bd,{children:B.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:B.name}),B.title&&s.jsx("p",{className:"text-sm text-[#5b6b72]",children:B.title}),s.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-4 text-sm text-[#406E71]",children:[B.phone&&s.jsx("a",{href:`tel:${B.phone}`,children:B.phone}),B.email&&s.jsx("a",{href:`mailto:${B.email}`,className:"truncate",children:B.email})]})]})]}),s.jsx("div",{className:"text-center",children:s.jsxs("a",{href:Y,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-sm text-[#406E71] hover:underline",children:[s.jsx(Es,{className:"h-4 w-4"}),"Get directions to ",n.property_address]})})]})]})}function xR({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 PQe=Object.freeze(Object.defineProperty({__proto__:null,default:ibe},Symbol.toStringTag,{value:"Module"}));function N9t(t){const{user:e}=Hn();return mr({queryKey:["cohost-tokens",t],queryFn:async()=>{const{data:r,error:n}=await Re.from("open_house_cohost_tokens").select("*").eq("open_house_id",t).order("created_at",{ascending:!1});if(n)throw n;return r},enabled:!!e&&!!t})}function I9t(){const t=Ar(),{user:e}=Hn();return Sr({mutationFn:async({openHouseId:r,label:n})=>{const{data:i,error:o}=await Re.from("open_house_cohost_tokens").insert({open_house_id:r,label:n||null,created_by:e.id,expires_at:new Date(Date.now()+864e5).toISOString()}).select().single();if(o)throw o;return i},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["cohost-tokens",n.openHouseId]})}})}function P9t(){const t=Ar();return Sr({mutationFn:async({id:e,openHouseId:r})=>{const{error:n}=await Re.from("open_house_cohost_tokens").update({is_active:!1}).eq("id",e);if(n)throw n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["cohost-tokens",r.openHouseId]})}})}function RQe(t){return mr({queryKey:["cohost-validate",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("open_house_cohost_tokens").select("*, open_houses(*)").eq("token",t).eq("is_active",!0).single();if(r)throw r;if(e.expires_at&&new Date(e.expires_at)-1&&t.splice(r,1)}const Em=(t,e,r)=>r>e?e:r{},fS=()=>{};const _x={},abe=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function obe(t){return typeof t=="object"&&t!==null}const lbe=t=>/^0[^.\s]+$/u.test(t);function cbe(t){let e;return()=>(e===void 0&&(e=t()),e)}const ch=t=>t,DQe=(t,e)=>r=>e(t(r)),YC=(...t)=>t.reduce(DQe),pk=(t,e,r)=>{const n=e-t;return n===0?1:(r-t)/n};class wH{constructor(){this.subscriptions=[]}add(e){return bH(this.subscriptions,e),()=>aM(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,ih=t=>t/1e3;function ube(t,e){return e?t*(1e3/e):0}const dbe=(t,e,r)=>(((1-3*r+3*e)*t+(3*r-6*e))*t+3*e)*t,MQe=1e-7,OQe=12;function FQe(t,e,r,n,i){let o,c,a=0;do c=e+(r-e)/2,o=dbe(c,n,i)-t,o>0?r=c:e=c;while(Math.abs(o)>MQe&&++aFQe(o,0,1,t,r);return o=>o===0||o===1?o:dbe(i(o),e,n)}const hbe=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,fbe=t=>e=>1-t(1-e),mbe=ZC(.33,1.53,.69,.99),SH=fbe(mbe),pbe=hbe(SH),gbe=t=>t>=1?1:(t*=2)<1?.5*SH(t):.5*(2-Math.pow(2,-10*(t-1))),TH=t=>1-Math.sin(Math.acos(t)),ybe=fbe(TH),xbe=hbe(TH),BQe=ZC(.42,0,1,1),$Qe=ZC(0,0,.58,1),vbe=ZC(.42,0,.58,1),zQe=t=>Array.isArray(t)&&typeof t[0]!="number",_be=t=>Array.isArray(t)&&typeof t[0]=="number",cne={linear:ch,easeIn:BQe,easeInOut:vbe,easeOut:$Qe,circIn:TH,circInOut:xbe,circOut:ybe,backIn:SH,backInOut:pbe,backOut:mbe,anticipate:gbe},UQe=t=>typeof t=="string",une=t=>{if(_be(t)){fS(t.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[e,r,n,i]=t;return ZC(e,r,n,i)}else if(UQe(t))return fS(cne[t]!==void 0,`Invalid easing type '${t}'`,"invalid-easing-type"),cne[t];return t},vR=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],dne={value:null,addProjectionMetrics:null};function VQe(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 p(v){c.has(v)&&(y.schedule(v),t()),f++,v(a)}const y={schedule:(v,T=!1,E=!1)=>{const P=E&&i?r:n;return T&&c.add(v),P.add(v),v},cancel:v=>{n.delete(v),c.delete(v)},process:v=>{if(a=v,i){o=!0;return}i=!0;const T=r;r=n,n=T,r.forEach(p),e&&dne.value&&dne.value.frameloop[e].push(f),f=0,r.clear(),i=!1,o&&(o=!1,y.process(v))}};return y}const qQe=40;function bbe(t,e){let r=!1,n=!0;const i={delta:0,timestamp:0,isProcessing:!1},o=()=>r=!0,c=vR.reduce((B,V)=>(B[V]=VQe(o,e?V:void 0),B),{}),{setup:a,read:f,resolveKeyframes:p,preUpdate:y,update:v,preRender:T,render:E,postRender:k}=c,P=()=>{const B=_x.useManualTiming,V=B?i.timestamp:performance.now();r=!1,B||(i.delta=n?1e3/60:Math.max(Math.min(V-i.timestamp,qQe),1)),i.timestamp=V,i.isProcessing=!0,a.process(i),f.process(i),p.process(i),y.process(i),v.process(i),T.process(i),E.process(i),k.process(i),i.isProcessing=!1,r&&e&&(n=!1,t(P))},R=()=>{r=!0,n=!0,i.isProcessing||t(P)};return{schedule:vR.reduce((B,V)=>{const G=c[V];return B[V]=(W,Y=!1,J=!1)=>(r||R(),G.schedule(W,Y,J)),B},{}),cancel:B=>{for(let V=0;V(RL===void 0&&Xc.set(Wl.isProcessing||_x.useManualTiming?Wl.timestamp:performance.now()),RL),set:t=>{RL=t,queueMicrotask(GQe)}},wbe=t=>e=>typeof e=="string"&&e.startsWith(t),Sbe=wbe("--"),HQe=wbe("var(--"),EH=t=>HQe(t)?WQe.test(t.split("/*")[0].trim()):!1,WQe=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function hne(t){return typeof t!="string"?!1:t.split("/*")[0].includes("var(--")}const yT={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},gk={...yT,transform:t=>Em(0,1,t)},_R={...yT,default:1},hA=t=>Math.round(t*1e5)/1e5,jH=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function KQe(t){return t==null}const YQe=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,AH=(t,e)=>r=>!!(typeof r=="string"&&YQe.test(r)&&r.startsWith(t)||e&&!KQe(r)&&Object.prototype.hasOwnProperty.call(r,e)),Tbe=(t,e,r)=>n=>{if(typeof n!="string")return n;const[i,o,c,a]=n.match(jH);return{[t]:parseFloat(i),[e]:parseFloat(o),[r]:parseFloat(c),alpha:a!==void 0?parseFloat(a):1}},ZQe=t=>Em(0,255,t),iz={...yT,transform:t=>Math.round(ZQe(t))},jv={test:AH("rgb","red"),parse:Tbe("red","green","blue"),transform:({red:t,green:e,blue:r,alpha:n=1})=>"rgba("+iz.transform(t)+", "+iz.transform(e)+", "+iz.transform(r)+", "+hA(gk.transform(n))+")"};function XQe(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 e8={test:AH("#"),parse:XQe,transform:jv.transform},XC=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),xy=XC("deg"),ym=XC("%"),Pn=XC("px"),QQe=XC("vh"),JQe=XC("vw"),fne={...ym,parse:t=>ym.parse(t)/100,transform:t=>ym.transform(t*100)},Qw={test:AH("hsl","hue"),parse:Tbe("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:r,alpha:n=1})=>"hsla("+Math.round(t)+", "+ym.transform(hA(e))+", "+ym.transform(hA(r))+", "+hA(gk.transform(n))+")"},Ho={test:t=>jv.test(t)||e8.test(t)||Qw.test(t),parse:t=>jv.test(t)?jv.parse(t):Qw.test(t)?Qw.parse(t):e8.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?jv.transform(t):Qw.transform(t),getAnimatableNone:t=>{const e=Ho.parse(t);return e.alpha=0,Ho.transform(e)}},eJe=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function tJe(t){var e,r;return isNaN(t)&&typeof t=="string"&&(((e=t.match(jH))==null?void 0:e.length)||0)+(((r=t.match(eJe))==null?void 0:r.length)||0)>0}const Ebe="number",jbe="color",rJe="var",nJe="var(",mne="${}",iJe=/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 mS(t){const e=t.toString(),r=[],n={color:[],number:[],var:[]},i=[];let o=0;const a=e.replace(iJe,f=>(Ho.test(f)?(n.color.push(o),i.push(jbe),r.push(Ho.parse(f))):f.startsWith(nJe)?(n.var.push(o),i.push(rJe),r.push(f)):(n.number.push(o),i.push(Ebe),r.push(parseFloat(f))),++o,mne)).split(mne);return{values:r,split:a,indexes:n,types:i}}function sJe(t){return mS(t).values}function Abe({split:t,types:e}){const r=t.length;return n=>{let i="";for(let o=0;otypeof t=="number"?0:Ho.test(t)?Ho.getAnimatableNone(t):t,lJe=(t,e)=>typeof t=="number"?e!=null&&e.trim().endsWith("/")?t:0:oJe(t);function cJe(t){const e=mS(t);return Abe(e)(e.values.map((n,i)=>lJe(n,e.split[i])))}const ff={test:tJe,parse:sJe,createTransformer:aJe,getAnimatableNone:cJe};function sz(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 uJe({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=sz(f,a,t+1/3),o=sz(f,a,t),c=sz(f,a,t-1/3)}return{red:Math.round(i*255),green:Math.round(o*255),blue:Math.round(c*255),alpha:n}}function oM(t,e){return r=>r>0?e:t}const La=(t,e,r)=>t+(e-t)*r,az=(t,e,r)=>{const n=t*t,i=r*(e*e-n)+n;return i<0?0:Math.sqrt(i)},dJe=[e8,jv,Qw],hJe=t=>dJe.find(e=>e.test(t));function pne(t){const e=hJe(t);if(iF(!!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===Qw&&(r=uJe(r)),r}const gne=(t,e)=>{const r=pne(t),n=pne(e);if(!r||!n)return oM(t,e);const i={...r};return o=>(i.red=az(r.red,n.red,o),i.green=az(r.green,n.green,o),i.blue=az(r.blue,n.blue,o),i.alpha=La(r.alpha,n.alpha,o),jv.transform(i))},t8=new Set(["none","hidden"]);function fJe(t,e){return t8.has(t)?r=>r<=0?t:e:r=>r>=1?e:t}function mJe(t,e){return r=>La(t,e,r)}function kH(t){return typeof t=="number"?mJe:typeof t=="string"?EH(t)?oM:Ho.test(t)?gne:yJe:Array.isArray(t)?kbe:typeof t=="object"?Ho.test(t)?gne:pJe:oM}function kbe(t,e){const r=[...t],n=r.length,i=t.map((o,c)=>kH(o)(o,e[c]));return o=>{for(let c=0;c{for(const o in n)r[o]=n[o](i);return r}}function gJe(t,e){const r=[],n={color:0,var:0,number:0};for(let i=0;i{const r=ff.createTransformer(e),n=mS(t),i=mS(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?t8.has(t)&&!i.values.length||t8.has(e)&&!n.values.length?fJe(t,e):YC(kbe(gJe(n,i),i.values),r):(iF(!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"),oM(t,e))};function Cbe(t,e,r){return typeof t=="number"&&typeof e=="number"&&typeof r=="number"?La(t,e,r):kH(t)(t,e)}const xJe=t=>{const e=({timestamp:r})=>t(r);return{start:(r=!0)=>ia.update(e,r),stop:()=>bx(e),now:()=>Wl.isProcessing?Wl.timestamp:Xc.now()}},Nbe=(t,e,r=10)=>{let n="";const i=Math.max(Math.round(e/r),2);for(let o=0;o=lM?1/0:e}function vJe(t,e=100,r){const n=r({...t,keyframes:[0,e]}),i=Math.min(CH(n),lM);return{type:"keyframes",ease:o=>n.next(i*o).value/e,duration:ih(i)}}const Ja={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 r8(t,e){return t*Math.sqrt(1-e*e)}const _Je=12;function bJe(t,e,r){let n=r;for(let i=1;i<_Je;i++)n=n-t(n)/e(n);return n}const oz=.001;function wJe({duration:t=Ja.duration,bounce:e=Ja.bounce,velocity:r=Ja.velocity,mass:n=Ja.mass}){let i,o;iF(t<=Ou(Ja.maxDuration),"Spring duration must be 10 seconds or less","spring-duration-limit");let c=1-e;c=Em(Ja.minDamping,Ja.maxDamping,c),t=Em(Ja.minDuration,Ja.maxDuration,ih(t)),c<1?(i=p=>{const y=p*c,v=y*t,T=y-r,E=r8(p,c),k=Math.exp(-v);return oz-T/E*k},o=p=>{const v=p*c*t,T=v*r+r,E=Math.pow(c,2)*Math.pow(p,2)*t,k=Math.exp(-v),P=r8(Math.pow(p,2),c);return(-i(p)+oz>0?-1:1)*((T-E)*k)/P}):(i=p=>{const y=Math.exp(-p*t),v=(p-r)*t+1;return-oz+y*v},o=p=>{const y=Math.exp(-p*t),v=(r-p)*(t*t);return y*v});const a=5/t,f=bJe(i,o,a);if(t=Ou(t),isNaN(f))return{stiffness:Ja.stiffness,damping:Ja.damping,duration:t};{const p=Math.pow(f,2)*n;return{stiffness:p,damping:c*2*Math.sqrt(n*p),duration:t}}}const SJe=["duration","bounce"],TJe=["stiffness","damping","mass"];function yne(t,e){return e.some(r=>t[r]!==void 0)}function EJe(t){let e={velocity:Ja.velocity,stiffness:Ja.stiffness,damping:Ja.damping,mass:Ja.mass,isResolvedFromDuration:!1,...t};if(!yne(t,TJe)&&yne(t,SJe))if(e.velocity=0,t.visualDuration){const r=t.visualDuration,n=2*Math.PI/(r*1.2),i=n*n,o=2*Em(.05,1,1-(t.bounce||0))*Math.sqrt(i);e={...e,mass:Ja.mass,stiffness:i,damping:o}}else{const r=wJe({...t,velocity:0});e={...e,...r,mass:Ja.mass},e.isResolvedFromDuration=!0}return e}function cM(t=Ja.visualDuration,e=Ja.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:p,mass:y,duration:v,velocity:T,isResolvedFromDuration:E}=EJe({...r,velocity:-ih(r.velocity||0)}),k=T||0,P=p/(2*Math.sqrt(f*y)),R=c-o,D=ih(Math.sqrt(f/y)),M=Math.abs(R)<5;n||(n=M?Ja.restSpeed.granular:Ja.restSpeed.default),i||(i=M?Ja.restDelta.granular:Ja.restDelta.default);let B,V,G,W,Y,J;if(P<1)G=r8(D,P),W=(k+P*D*R)/G,B=ee=>{const le=Math.exp(-P*D*ee);return c-le*(W*Math.sin(G*ee)+R*Math.cos(G*ee))},Y=P*D*W+R*G,J=P*D*R-W*G,V=ee=>Math.exp(-P*D*ee)*(Y*Math.sin(G*ee)+J*Math.cos(G*ee));else if(P===1){B=le=>c-Math.exp(-D*le)*(R+(k+D*R)*le);const ee=k+D*R;V=le=>Math.exp(-D*le)*(D*ee*le-k)}else{const ee=D*Math.sqrt(P*P-1);B=je=>{const Le=Math.exp(-P*D*je),Ae=Math.min(ee*je,300);return c-Le*((k+P*D*R)*Math.sinh(Ae)+ee*R*Math.cosh(Ae))/ee};const le=(k+P*D*R)/ee,pe=P*D*le-R*ee,Se=P*D*R-le*ee;V=je=>{const Le=Math.exp(-P*D*je),Ae=Math.min(ee*je,300);return Le*(pe*Math.sinh(Ae)+Se*Math.cosh(Ae))}}const Q={calculatedDuration:E&&v||null,velocity:ee=>Ou(V(ee)),next:ee=>{if(!E&&P<1){const pe=Math.exp(-P*D*ee),Se=Math.sin(G*ee),je=Math.cos(G*ee),Le=c-pe*(W*Se+R*je),Ae=Ou(pe*(Y*Se+J*je));return a.done=Math.abs(Ae)<=n&&Math.abs(c-Le)<=i,a.value=a.done?c:Le,a}const le=B(ee);if(E)a.done=ee>=v;else{const pe=Ou(V(ee));a.done=Math.abs(pe)<=n&&Math.abs(c-le)<=i}return a.value=a.done?c:le,a},toString:()=>{const ee=Math.min(CH(Q),lM),le=Nbe(pe=>Q.next(ee*pe).value,ee,30);return ee+"ms "+le},toTransition:()=>{}};return Q}cM.applyToOptions=t=>{const e=vJe(t,100,cM);return t.ease=e.ease,t.duration=Ou(e.duration),t.type="keyframes",t};const jJe=5;function Ibe(t,e,r){const n=Math.max(e-jJe,0);return ube(r-t(n),e-n)}function n8({keyframes:t,velocity:e=0,power:r=.8,timeConstant:n=325,bounceDamping:i=10,bounceStiffness:o=500,modifyTarget:c,min:a,max:f,restDelta:p=.5,restSpeed:y}){const v=t[0],T={done:!1,value:v},E=J=>a!==void 0&&Jf,k=J=>a===void 0?f:f===void 0||Math.abs(a-J)-P*Math.exp(-J/n),B=J=>D+M(J),V=J=>{const Q=M(J),ee=B(J);T.done=Math.abs(Q)<=p,T.value=T.done?D:ee};let G,W;const Y=J=>{E(T.value)&&(G=J,W=cM({keyframes:[T.value,k(T.value)],velocity:Ibe(B,J,T.value),damping:i,stiffness:o,restDelta:p,restSpeed:y}))};return Y(0),{calculatedDuration:null,next:J=>{let Q=!1;return!W&&G===void 0&&(Q=!0,V(J),Y(J)),G!==void 0&&J>=G?W.next(J-G):(!Q&&V(J),T)}}}function AJe(t,e,r){const n=[],i=r||_x.mix||Cbe,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=AJe(e,n,i),f=a.length,p=y=>{if(c&&y1)for(;vp(Em(t[0],t[o-1],y)):p}function CJe(t,e){const r=t[t.length-1];for(let n=1;n<=e;n++){const i=pk(0,e,n);t.push(La(r,1,i))}}function NJe(t){const e=[0];return CJe(e,t.length-1),e}function IJe(t,e){return t.map(r=>r*e)}function PJe(t,e){return t.map(()=>e||vbe).splice(0,t.length-1)}function fA({duration:t=300,keyframes:e,times:r,ease:n="easeInOut"}){const i=zQe(n)?n.map(une):une(n),o={done:!1,value:e[0]},c=IJe(r&&r.length===e.length?r:NJe(e),t),a=kJe(c,e,{ease:Array.isArray(i)?i:PJe(e,i)});return{calculatedDuration:t,next:f=>(o.value=a(f),o.done=f>=t,o)}}const RJe=t=>t!==null;function sF(t,{repeat:e,repeatType:r="loop"},n,i=1){const o=t.filter(RJe),a=i<0||e&&r!=="loop"&&e%2===1?0:o.length-1;return!a||n===void 0?o[a]:n}const LJe={decay:n8,inertia:n8,tween:fA,keyframes:fA,spring:cM};function Pbe(t){typeof t.type=="string"&&(t.type=LJe[t.type])}class NH{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 DJe=t=>t/100;class uM extends NH{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!==Xc.now()&&this.tick(Xc.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;Pbe(e);const{type:r=fA,repeat:n=0,repeatDelay:i=0,repeatType:o,velocity:c=0}=e;let{keyframes:a}=e;const f=r||fA;f!==fA&&typeof a[0]!="number"&&(this.mixKeyframes=YC(DJe,Cbe(a[0],a[1])),a=[0,100]);const p=f({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=f({...e,keyframes:[...a].reverse(),velocity:-c})),p.calculatedDuration===null&&(p.calculatedDuration=CH(p));const{calculatedDuration:y}=p;this.calculatedDuration=y,this.resolvedDuration=y+i,this.totalDuration=this.resolvedDuration*(n+1)-i,this.generator=p}updateTime(e){const r=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=r}tick(e,r=!1){const{generator:n,totalDuration:i,mixKeyframes:o,mirroredGenerator:c,resolvedDuration:a,calculatedDuration:f}=this;if(this.startTime===null)return n.next(0);const{delay:p=0,keyframes:y,repeat:v,repeatType:T,repeatDelay:E,type:k,onUpdate:P,finalKeyframe:R}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-i/this.speed,this.startTime)),r?this.currentTime=e:this.updateTime(e);const D=this.currentTime-p*(this.playbackSpeed>=0?1:-1),M=this.playbackSpeed>=0?D<0:D>i;this.currentTime=Math.max(D,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=i);let B=this.currentTime,V=n;if(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)&&(T==="reverse"?(ee=1-ee,E&&(ee-=E/a)):T==="mirror"&&(V=c)),B=Em(0,1,ee)*a}let G;M?(this.delayState.value=y[0],G=this.delayState):G=V.next(B),o&&!M&&(G.value=o(G.value));let{done:W}=G;!M&&f!==null&&(W=this.playbackSpeed>=0?this.currentTime>=i:this.currentTime<=0);const Y=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&W);return Y&&k!==n8&&(G.value=sF(y,this.options,R,this.speed)),P&&P(G.value),Y&&this.finish(),G}then(e,r){return this.finished.then(e,r)}get duration(){return ih(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+ih(e)}get time(){return ih(this.currentTime)}set time(e){e=Ou(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 Ibe(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(Xc.now()),this.playbackSpeed=e,r&&this.driver&&(this.time=ih(this.currentTime))}play(){var i,o;if(this.isStopped)return;const{driver:e=xJe,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(Xc.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 MJe(t){for(let e=1;et*180/Math.PI,i8=t=>{const e=Av(Math.atan2(t[1],t[0]));return s8(e)},OJe={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:i8,rotateZ:i8,skewX:t=>Av(Math.atan(t[1])),skewY:t=>Av(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},s8=t=>(t=t%360,t<0&&(t+=360),t),xne=i8,vne=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),_ne=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),FJe={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:vne,scaleY:_ne,scale:t=>(vne(t)+_ne(t))/2,rotateX:t=>s8(Av(Math.atan2(t[6],t[5]))),rotateY:t=>s8(Av(Math.atan2(-t[2],t[0]))),rotateZ:xne,rotate:xne,skewX:t=>Av(Math.atan(t[4])),skewY:t=>Av(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function a8(t){return t.includes("scale")?1:0}function o8(t,e){if(!t||t==="none")return a8(e);const r=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,i;if(r)n=FJe,i=r;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=OJe,i=a}if(!i)return a8(e);const o=n[e],c=i[1].split(",").map($Je);return typeof o=="function"?o(c):c[o]}const BJe=(t,e)=>{const{transform:r="none"}=getComputedStyle(t);return o8(r,e)};function $Je(t){return parseFloat(t.trim())}const xT=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],vT=new Set(xT),bne=t=>t===yT||t===Pn,zJe=new Set(["x","y","z"]),UJe=xT.filter(t=>!zJe.has(t));function VJe(t){const e=[];return UJe.forEach(r=>{const n=t.getValue(r);n!==void 0&&(e.push([r,n.get()]),n.set(r.startsWith("scale")?1:0))}),e}const Gy={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})=>o8(e,"x"),y:(t,{transform:e})=>o8(e,"y")};Gy.translateX=Gy.x;Gy.translateY=Gy.y;const Gv=new Set;let l8=!1,c8=!1,u8=!1;function Rbe(){if(c8){const t=Array.from(Gv).filter(n=>n.needsMeasurement),e=new Set(t.map(n=>n.element)),r=new Map;e.forEach(n=>{const i=VJe(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)})}c8=!1,l8=!1,Gv.forEach(t=>t.complete(u8)),Gv.clear()}function Lbe(){Gv.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(c8=!0)})}function qJe(){u8=!0,Lbe(),Rbe(),u8=!1}class IH{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?(Gv.add(this),l8||(l8=!0,ia.read(Lbe),ia.resolveKeyframes(Rbe))):(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])}MJe(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Gv.delete(this)}cancel(){this.state==="scheduled"&&(Gv.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const GJe=t=>t.startsWith("--");function Dbe(t,e,r){GJe(e)?t.style.setProperty(e,r):t.style[e]=r}const HJe={};function Mbe(t,e){const r=cbe(t);return()=>HJe[e]??r()}const WJe=Mbe(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),Obe=Mbe(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),q2=([t,e,r,n])=>`cubic-bezier(${t}, ${e}, ${r}, ${n})`,wne={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:q2([0,.65,.55,1]),circOut:q2([.55,0,1,.45]),backIn:q2([.31,.01,.66,-.59]),backOut:q2([.33,1.53,.69,.99])};function Fbe(t,e){if(t)return typeof t=="function"?Obe()?Nbe(t,e):"ease-out":_be(t)?q2(t):Array.isArray(t)?t.map(r=>Fbe(r,e)||wne.easeOut):wne[t]}function KJe(t,e,r,{delay:n=0,duration:i=300,repeat:o=0,repeatType:c="loop",ease:a="easeOut",times:f}={},p=void 0){const y={[e]:r};f&&(y.offset=f);const v=Fbe(a,i);Array.isArray(v)&&(y.easing=v);const T={delay:n,duration:i,easing:Array.isArray(v)?"linear":v,fill:"both",iterations:o+1,direction:c==="reverse"?"alternate":"normal"};return p&&(T.pseudoElement=p),t.animate(y,T)}function Bbe(t){return typeof t=="function"&&"applyToOptions"in t}function YJe({type:t,...e}){return Bbe(t)&&Obe()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class $be extends NH{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,fS(typeof e.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const p=YJe(e);this.animation=KJe(r,n,i,p,o),p.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const y=sF(i,this.options,a,this.speed);this.updateMotionValue&&this.updateMotionValue(y),Dbe(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 ih(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+ih(e)}get time(){return ih(Number(this.animation.currentTime)||0)}set time(e){const r=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Ou(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&&WJe()?(this.animation.timeline=e,r&&(this.animation.rangeStart=r),n&&(this.animation.rangeEnd=n),ch):i(this)}}const zbe={anticipate:gbe,backInOut:pbe,circInOut:xbe};function ZJe(t){return t in zbe}function XJe(t){typeof t.ease=="string"&&ZJe(t.ease)&&(t.ease=zbe[t.ease])}const lz=10;class QJe extends $be{constructor(e){XJe(e),Pbe(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 uM({...c,autoplay:!1}),f=Math.max(lz,Xc.now()-this.startTime),p=Em(0,lz,f-lz),y=a.sample(f).value,{name:v}=this.options;o&&v&&Dbe(o,v,y),r.setWithVelocity(a.sample(Math.max(0,f-p)).value,y,p),a.stop()}}const Sne=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(ff.test(t)||t==="0")&&!t.startsWith("url("));function JJe(t){const e=t[0];if(t.length===1)return!0;for(let r=0;rObject.hasOwnProperty.call(Element.prototype,"animate"));function set(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:p,transformTemplate:y}=e.owner.getProps();return iet()&&r&&(Ube.has(r)||net.has(r)&&ret(a))&&(r!=="transform"||!y)&&!p&&!n&&i!=="mirror"&&o!==0&&c!=="inertia"}const aet=40;class oet extends NH{constructor({autoplay:e=!0,delay:r=0,type:n="keyframes",repeat:i=0,repeatDelay:o=0,repeatType:c="loop",keyframes:a,name:f,motionValue:p,element:y,...v}){var k;super(),this.stop=()=>{var P,R;this._animation&&(this._animation.stop(),(P=this.stopTimeline)==null||P.call(this)),(R=this.keyframeResolver)==null||R.cancel()},this.createdAt=Xc.now();const T={autoplay:e,delay:r,type:n,repeat:i,repeatDelay:o,repeatType:c,name:f,motionValue:p,element:y,...v},E=(y==null?void 0:y.KeyframeResolver)||IH;this.keyframeResolver=new E(a,(P,R,D)=>this.onKeyframesResolved(P,R,T,!D),f,p,y),(k=this.keyframeResolver)==null||k.scheduleResolve()}onKeyframesResolved(e,r,n,i){var D,M;this.keyframeResolver=void 0;const{name:o,type:c,velocity:a,delay:f,isHandoff:p,onUpdate:y}=n;this.resolvedAt=Xc.now();let v=!0;eet(e,o,c,a)||(v=!1,(_x.instantAnimations||!f)&&(y==null||y(sF(e,n,r))),e[0]=e[e.length-1],d8(n),n.repeat=0);const E={startTime:i?this.resolvedAt?this.resolvedAt-this.createdAt>aet?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:r,...n,keyframes:e},k=v&&!p&&set(E),P=(M=(D=E.motionValue)==null?void 0:D.owner)==null?void 0:M.current;let R;if(k)try{R=new QJe({...E,element:P})}catch{R=new uM(E)}else R=new uM(E);R.finished.then(()=>{this.notifyFinished()}).catch(ch),this.pendingTimeline&&(this.stopTimeline=R.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=R}get finished(){return this._animation?this.animation.finished:this._finished}then(e,r){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),qJe()),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 Vbe(t,e,r,n=0,i=1){const o=Array.from(t).sort((p,y)=>p.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 cet=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function uet(t){const e=cet.exec(t);if(!e)return[,];const[,r,n,i]=e;return[`--${r??n}`,i]}const det=4;function qbe(t,e,r=1){fS(r<=det,`Max CSS variable fallback depth detected in property "${t}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[n,i]=uet(t);if(!n)return;const o=window.getComputedStyle(e).getPropertyValue(n);if(o){const c=o.trim();return abe(c)?parseFloat(c):c}return EH(i)?qbe(i,e,r+1):i}const het={type:"spring",stiffness:500,damping:25,restSpeed:10},fet=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),met={type:"keyframes",duration:.8},pet={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},get=(t,{keyframes:e})=>e.length>2?met:vT.has(t)?t.startsWith("scale")?fet(e[1]):het:pet;function Gbe(t,e){if(t!=null&&t.inherit&&e){const{inherit:r,...n}=t;return{...e,...n}}return t}function PH(t,e){const r=(t==null?void 0:t[e])??(t==null?void 0:t.default)??t;return r!==t?Gbe(r,t):r}const yet=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function xet(t){for(const e in t)if(!yet.has(e))return!0;return!1}const RH=(t,e,r,n={},i,o)=>c=>{const a=PH(n,t)||{},f=a.delay||n.delay||0;let{elapsed:p=0}=n;p=p-Ou(f);const y={keyframes:Array.isArray(r)?r:[null,r],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-p,onUpdate:T=>{e.set(T),a.onUpdate&&a.onUpdate(T)},onComplete:()=>{c(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:i};xet(a)||Object.assign(y,get(t,y)),y.duration&&(y.duration=Ou(y.duration)),y.repeatDelay&&(y.repeatDelay=Ou(y.repeatDelay)),y.from!==void 0&&(y.keyframes[0]=y.from);let v=!1;if((y.type===!1||y.duration===0&&!y.repeatDelay)&&(d8(y),y.delay===0&&(v=!0)),(_x.instantAnimations||_x.skipAnimations||i!=null&&i.shouldSkipAnimations)&&(v=!0,d8(y),y.delay=0),y.allowFlatten=!a.type&&!a.ease,v&&!o&&e.get()!==void 0){const T=sF(y.keyframes,a);if(T!==void 0){ia.update(()=>{y.onUpdate(T),y.onComplete()});return}}return a.isSync?new uM(y):new oet(y)};function Tne(t){const e=[{},{}];return t==null||t.values.forEach((r,n)=>{e[0][n]=r.get(),e[1][n]=r.getVelocity()}),e}function LH(t,e,r,n){if(typeof e=="function"){const[i,o]=Tne(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]=Tne(n);e=e(r!==void 0?r:t.custom,i,o)}return e}function Hv(t,e,r){const n=t.getProps();return LH(n,e,r!==void 0?r:n.custom,t)}const Hbe=new Set(["width","height","top","left","right","bottom",...xT]),Ene=30,vet=t=>!isNaN(parseFloat(t));class _et{constructor(e,r={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=n=>{var o;const i=Xc.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=Xc.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=vet(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 wH);const n=this.events[e].add(r);return e==="change"?()=>{n(),ia.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=Xc.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Ene)return 0;const r=Math.min(this.updatedAt-this.prevUpdatedAt,Ene);return ube(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 pS(t,e){return new _et(t,e)}const h8=t=>Array.isArray(t);function bet(t,e,r){t.hasValue(e)?t.getValue(e).set(r):t.addValue(e,pS(r))}function wet(t){return h8(t)?t[t.length-1]||0:t}function Tet(t,e){const r=Hv(t,e);let{transitionEnd:n={},transition:i={},...o}=r||{};o={...o,...n};for(const c in o){const a=wet(o[c]);bet(t,c,a)}}const nc=t=>!!(t&&t.getVelocity);function Eet(t){return!!(nc(t)&&t.add)}function f8(t,e){const r=t.getValue("willChange");if(Eet(r))return r.add(e);if(!r&&_x.WillChange){const n=new _x.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function DH(t){return t.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}const jet="framerAppearId",Wbe="data-"+DH(jet);function Kbe(t){return t.props[Wbe]}function Aet({protectedKeys:t,needsAnimating:e},r){const n=t.hasOwnProperty(r)&&e[r]!==!0;return e[r]=!1,n}function Ybe(t,e,{delay:r=0,transitionOverride:n,type:i}={}){let{transition:o,transitionEnd:c,...a}=e;const f=t.getDefaultTransition();o=o?Gbe(o,f):f;const p=o==null?void 0:o.reduceMotion;n&&(o=n);const y=[],v=i&&t.animationState&&t.animationState.getState()[i];for(const T in a){const E=t.getValue(T,t.latestValues[T]??null),k=a[T];if(k===void 0||v&&Aet(v,T))continue;const P={delay:r,...PH(o||{},T)},R=E.get();if(R!==void 0&&!E.isAnimating()&&!Array.isArray(k)&&k===R&&!P.velocity){ia.update(()=>E.set(k));continue}let D=!1;if(window.MotionHandoffAnimation){const V=Kbe(t);if(V){const G=window.MotionHandoffAnimation(V,T,ia);G!==null&&(P.startTime=G,D=!0)}}f8(t,T);const M=p??t.shouldReduceMotion;E.start(RH(T,E,k,M&&Hbe.has(T)?{type:!1}:P,t,D));const B=E.animation;B&&y.push(B)}if(c){const T=()=>ia.update(()=>{c&&Tet(t,c)});y.length?Promise.all(y).then(T):T()}return y}function m8(t,e,r={}){var f;const n=Hv(t,e,r.type==="exit"?(f=t.presenceContext)==null?void 0:f.custom:void 0);let{transition:i=t.getDefaultTransition()||{}}=n||{};r.transitionOverride&&(i=r.transitionOverride);const o=n?()=>Promise.all(Ybe(t,n,r)):()=>Promise.resolve(),c=t.variantChildren&&t.variantChildren.size?(p=0)=>{const{delayChildren:y=0,staggerChildren:v,staggerDirection:T}=i;return ket(t,e,p,y,v,T,r)}:()=>Promise.resolve(),{when:a}=i;if(a){const[p,y]=a==="beforeChildren"?[o,c]:[c,o];return p().then(()=>y())}else return Promise.all([o(),c(r.delay)])}function ket(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(m8(f,e,{...c,delay:r+(typeof n=="function"?0:n)+Vbe(t.variantChildren,f,n,i,o)}).then(()=>f.notify("AnimationComplete",e)));return Promise.all(a)}function Cet(t,e,r={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const i=e.map(o=>m8(t,o,r));n=Promise.all(i)}else if(typeof e=="string")n=m8(t,e,r);else{const i=typeof e=="function"?Hv(t,e,r.custom):e;n=Promise.all(Ybe(t,i,r))}return n.then(()=>{t.notify("AnimationComplete",e)})}const Net={test:t=>t==="auto",parse:t=>t},Zbe=t=>e=>e.test(t),Xbe=[yT,Pn,ym,xy,JQe,QQe,Net],jne=t=>Xbe.find(Zbe(t));function Iet(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||lbe(t):!0}const Pet=new Set(["brightness","contrast","saturate","opacity"]);function Ret(t){const[e,r]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=r.match(jH)||[];if(!n)return t;const i=r.replace(n,"");let o=Pet.has(e)?1:0;return n!==r&&(o*=100),e+"("+o+i+")"}const Let=/\b([a-z-]*)\(.*?\)/gu,p8={...ff,getAnimatableNone:t=>{const e=t.match(Let);return e?e.map(Ret).join(" "):t}},g8={...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))}},Ane={...yT,transform:Math.round},Det={rotate:xy,rotateX:xy,rotateY:xy,rotateZ:xy,scale:_R,scaleX:_R,scaleY:_R,scaleZ:_R,skew:xy,skewX:xy,skewY:xy,distance:Pn,translateX:Pn,translateY:Pn,translateZ:Pn,x:Pn,y:Pn,z:Pn,perspective:Pn,transformPerspective:Pn,opacity:gk,originX:fne,originY:fne,originZ:Pn},MH={borderWidth:Pn,borderTopWidth:Pn,borderRightWidth:Pn,borderBottomWidth:Pn,borderLeftWidth:Pn,borderRadius:Pn,borderTopLeftRadius:Pn,borderTopRightRadius:Pn,borderBottomRightRadius:Pn,borderBottomLeftRadius:Pn,width:Pn,maxWidth:Pn,height:Pn,maxHeight:Pn,top:Pn,right:Pn,bottom:Pn,left:Pn,inset:Pn,insetBlock:Pn,insetBlockStart:Pn,insetBlockEnd:Pn,insetInline:Pn,insetInlineStart:Pn,insetInlineEnd:Pn,padding:Pn,paddingTop:Pn,paddingRight:Pn,paddingBottom:Pn,paddingLeft:Pn,paddingBlock:Pn,paddingBlockStart:Pn,paddingBlockEnd:Pn,paddingInline:Pn,paddingInlineStart:Pn,paddingInlineEnd:Pn,margin:Pn,marginTop:Pn,marginRight:Pn,marginBottom:Pn,marginLeft:Pn,marginBlock:Pn,marginBlockStart:Pn,marginBlockEnd:Pn,marginInline:Pn,marginInlineStart:Pn,marginInlineEnd:Pn,fontSize:Pn,backgroundPositionX:Pn,backgroundPositionY:Pn,...Det,zIndex:Ane,fillOpacity:gk,strokeOpacity:gk,numOctaves:Ane},Met={...MH,color:Ho,backgroundColor:Ho,outlineColor:Ho,fill:Ho,stroke:Ho,borderColor:Ho,borderTopColor:Ho,borderRightColor:Ho,borderBottomColor:Ho,borderLeftColor:Ho,filter:p8,WebkitFilter:p8,mask:g8,WebkitMask:g8},Qbe=t=>Met[t],Oet=new Set([p8,g8]);function Jbe(t,e){let r=Qbe(t);return Oet.has(r)||(r=ff),r.getAnimatableNone?r.getAnimatableNone(e):void 0}const Fet=new Set(["auto","none","0"]);function Bet(t,e,r){let n=0,i;for(;n{e.getValue(f).set(p)}),this.resolveNoneKeyframes()}}function ewe(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 twe=(t,e)=>e&&typeof t=="number"?e.transform(t):t;function LL(t){return obe(t)&&"offsetHeight"in t&&!("ownerSVGElement"in t)}const{schedule:OH,cancel:R9t}=bbe(queueMicrotask,!1),Gh={x:!1,y:!1};function rwe(){return Gh.x||Gh.y}function zet(t){return t==="x"||t==="y"?Gh[t]?null:(Gh[t]=!0,()=>{Gh[t]=!1}):Gh.x||Gh.y?null:(Gh.x=Gh.y=!0,()=>{Gh.x=Gh.y=!1})}function nwe(t,e){const r=ewe(t),n=new AbortController,i={passive:!0,...e,signal:n.signal};return[r,i,()=>n.abort()]}function Uet(t){return!(t.pointerType==="touch"||rwe())}function Vet(t,e,r={}){const[n,i,o]=nwe(t,r);return n.forEach(c=>{let a=!1,f=!1,p;const y=()=>{c.removeEventListener("pointerleave",k)},v=R=>{p&&(p(R),p=void 0),y()},T=R=>{a=!1,window.removeEventListener("pointerup",T),window.removeEventListener("pointercancel",T),f&&(f=!1,v(R))},E=()=>{a=!0,window.addEventListener("pointerup",T,i),window.addEventListener("pointercancel",T,i)},k=R=>{if(R.pointerType!=="touch"){if(a){f=!0;return}v(R)}},P=R=>{if(!Uet(R))return;f=!1;const D=e(c,R);typeof D=="function"&&(p=D,c.addEventListener("pointerleave",k,i))};c.addEventListener("pointerenter",P,i),c.addEventListener("pointerdown",E,i)}),o}const iwe=(t,e)=>e?t===e?!0:iwe(t,e.parentElement):!1,FH=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,qet=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Get(t){return qet.has(t.tagName)||t.isContentEditable===!0}const Het=new Set(["INPUT","SELECT","TEXTAREA"]);function Wet(t){return Het.has(t.tagName)||t.isContentEditable===!0}const DL=new WeakSet;function kne(t){return e=>{e.key==="Enter"&&t(e)}}function cz(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Ket=(t,e)=>{const r=t.currentTarget;if(!r)return;const n=kne(()=>{if(DL.has(r))return;cz(r,"down");const i=kne(()=>{cz(r,"up")}),o=()=>cz(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 Cne(t){return FH(t)&&!rwe()}const Nne=new WeakSet;function Yet(t,e,r={}){const[n,i,o]=nwe(t,r),c=a=>{const f=a.currentTarget;if(!Cne(a)||Nne.has(a))return;DL.add(f),r.stopPropagation&&Nne.add(a);const p=e(f,a),y=(E,k)=>{window.removeEventListener("pointerup",v),window.removeEventListener("pointercancel",T),DL.has(f)&&DL.delete(f),Cne(E)&&typeof p=="function"&&p(E,{success:k})},v=E=>{y(E,f===window||f===document||r.useGlobalTarget||iwe(f,E.target))},T=E=>{y(E,!1)};window.addEventListener("pointerup",v,i),window.addEventListener("pointercancel",T,i)};return n.forEach(a=>{(r.useGlobalTarget?window:a).addEventListener("pointerdown",c,i),LL(a)&&(a.addEventListener("focus",p=>Ket(p,i)),!Get(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function BH(t){return obe(t)&&"ownerSVGElement"in t}const ML=new WeakMap;let vy;const swe=(t,e,r)=>(n,i)=>i&&i[0]?i[0][t+"Size"]:BH(n)&&"getBBox"in n?n.getBBox()[e]:n[r],Zet=swe("inline","width","offsetWidth"),Xet=swe("block","height","offsetHeight");function Qet({target:t,borderBoxSize:e}){var r;(r=ML.get(t))==null||r.forEach(n=>{n(t,{get width(){return Zet(t,e)},get height(){return Xet(t,e)}})})}function Jet(t){t.forEach(Qet)}function ett(){typeof ResizeObserver>"u"||(vy=new ResizeObserver(Jet))}function ttt(t,e){vy||ett();const r=ewe(t);return r.forEach(n=>{let i=ML.get(n);i||(i=new Set,ML.set(n,i)),i.add(e),vy==null||vy.observe(n)}),()=>{r.forEach(n=>{const i=ML.get(n);i==null||i.delete(e),i!=null&&i.size||vy==null||vy.unobserve(n)})}}const OL=new Set;let Jw;function rtt(){Jw=()=>{const t={get width(){return window.innerWidth},get height(){return window.innerHeight}};OL.forEach(e=>e(t))},window.addEventListener("resize",Jw)}function ntt(t){return OL.add(t),Jw||rtt(),()=>{OL.delete(t),!OL.size&&typeof Jw=="function"&&(window.removeEventListener("resize",Jw),Jw=void 0)}}function Ine(t,e){return typeof t=="function"?ntt(t):ttt(t,e)}function itt(t){return BH(t)&&t.tagName==="svg"}const stt=[...Xbe,Ho,ff],att=t=>stt.find(Zbe(t)),Pne=()=>({translate:0,scale:1,origin:0,originPoint:0}),e1=()=>({x:Pne(),y:Pne()}),Rne=()=>({min:0,max:0}),ol=()=>({x:Rne(),y:Rne()}),ott=new WeakMap;function aF(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function yk(t){return typeof t=="string"||Array.isArray(t)}const $H=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],zH=["initial",...$H];function oF(t){return aF(t.animate)||zH.some(e=>yk(t[e]))}function awe(t){return!!(oF(t)||t.variants)}function ltt(t,e,r){for(const n in e){const i=e[n],o=r[n];if(nc(i))t.addValue(n,i);else if(nc(o))t.addValue(n,pS(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,pS(c!==void 0?c:i,{owner:t}))}}for(const n in r)e[n]===void 0&&t.removeValue(n);return e}const y8={current:null},owe={current:!1},ctt=typeof window<"u";function utt(){if(owe.current=!0,!!ctt)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>y8.current=t.matches;t.addEventListener("change",e),e()}else y8.current=!1}const Lne=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let dM={};function lwe(t){dM=t}function dtt(){return dM}class htt{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=IH,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const E=Xc.now();this.renderScheduledAtthis.bindToMotionValue(o,i)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(owe.current||utt(),this.shouldReduceMotion=y8.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(),bx(this.notifyUpdate),bx(this.render),this.valueSubscriptions.forEach(r=>r()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(e=this.parent)==null||e.removeChild(this);for(const r in this.events)this.events[r].clear();for(const r in this.features){const n=this.features[r];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,r){if(this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)(),r.accelerate&&Ube.has(e)&&this.current instanceof HTMLElement){const{factory:c,keyframes:a,times:f,ease:p,duration:y}=r.accelerate,v=new $be({element:this.current,name:e,keyframes:a,times:f,ease:p,duration:Ou(y)}),T=c(v);this.valueSubscriptions.set(e,()=>{T(),v.cancel()});return}const n=vT.has(e);n&&this.onBindTransform&&this.onBindTransform();const i=r.on("change",c=>{this.latestValues[e]=c,this.props.onUpdate&&ia.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 dM){const r=dM[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):ol()}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=pS(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"&&(abe(n)||lbe(n))?n=parseFloat(n):!att(n)&&ff.test(r)&&(n=Jbe(e,r)),this.setBaseTarget(e,nc(n)?n.get():n)),nc(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=LH(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&&!nc(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 wH),this.events[e].add(r)}notify(e,...r){this.events[e]&&this.events[e].notify(...r)}scheduleRenderMicrotask(){OH.render(this.render)}}class cwe extends htt{constructor(){super(...arguments),this.KeyframeResolver=$et}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;nc(e)&&(this.childSubscription=e.on("change",r=>{this.current&&(this.current.textContent=`${r}`)}))}}class Bx{constructor(e){this.isMounted=!1,this.node=e}update(){}}function uwe({top:t,left:e,right:r,bottom:n}){return{x:{min:e,max:r},y:{min:t,max:n}}}function ftt({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function mtt(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 uz(t){return t===void 0||t===1}function x8({scale:t,scaleX:e,scaleY:r}){return!uz(t)||!uz(e)||!uz(r)}function pv(t){return x8(t)||dwe(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function dwe(t){return Dne(t.x)||Dne(t.y)}function Dne(t){return t&&t!=="0%"}function hM(t,e,r){const n=t-r,i=e*n;return r+i}function Mne(t,e,r,n,i){return i!==void 0&&(t=hM(t,i,n)),hM(t,r,n)+e}function v8(t,e=0,r=1,n,i){t.min=Mne(t.min,e,r,n,i),t.max=Mne(t.max,e,r,n,i)}function hwe(t,{x:e,y:r}){v8(t.x,e.translate,e.scale,e.originPoint),v8(t.y,r.translate,r.scale,r.originPoint)}const One=.999999999999,Fne=1.0000000000001;function ptt(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;fOne&&(e.x=1),e.yOne&&(e.y=1)}function rm(t,e){t.min+=e,t.max+=e}function Bne(t,e,r,n,i=.5){const o=La(t.min,t.max,i);v8(t,e,r,o,n)}function $ne(t,e){return typeof t=="string"?parseFloat(t)/100*(e.max-e.min):t}function FL(t,e,r){const n=r??t;Bne(t.x,$ne(e.x,n.x),e.scaleX,e.scale,e.originX),Bne(t.y,$ne(e.y,n.y),e.scaleY,e.scale,e.originY)}function fwe(t,e){return uwe(mtt(t.getBoundingClientRect(),e))}function gtt(t,e,r){const n=fwe(t,r),{scroll:i}=e;return i&&(rm(n.x,i.offset.x),rm(n.y,i.offset.y)),n}const ytt={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},xtt=xT.length;function vtt(t,e,r){let n="",i=!0;for(let o=0;o{if(!e.target)return t;if(typeof t=="string")if(Pn.test(t))t=parseFloat(t);else return t;const r=zne(t,e.target.x),n=zne(t,e.target.y);return`${r}% ${n}%`}},_tt={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 p=La(a,f,.5);return typeof i[2+c]=="number"&&(i[2+c]/=p),typeof i[3+c]=="number"&&(i[3+c]/=p),o(i)}},_8={borderRadius:{...h2,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:h2,borderTopRightRadius:h2,borderBottomLeftRadius:h2,borderBottomRightRadius:h2,boxShadow:_tt};function pwe(t,{layout:e,layoutId:r}){return vT.has(t)||t.startsWith("origin")||(e||r!==void 0)&&(!!_8[t]||t==="opacity")}function VH(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)(nc(n[a])||i&&nc(i[a])||pwe(a,t)||((c=r==null?void 0:r.getValue(a))==null?void 0:c.liveStyle)!==void 0)&&(o[a]=n[a]);return o}function btt(t){return window.getComputedStyle(t)}class wtt extends cwe{constructor(){super(...arguments),this.type="html",this.renderInstance=mwe}readValueFromInstance(e,r){var n;if(vT.has(r))return(n=this.projection)!=null&&n.isProjecting?a8(r):BJe(e,r);{const i=btt(e),o=(Sbe(r)?i.getPropertyValue(r):i[r])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:r}){return fwe(e,r)}build(e,r,n){UH(e,r,n.transformTemplate)}scrapeMotionValuesFromProps(e,r,n){return VH(e,r,n)}}const Stt={offset:"stroke-dashoffset",array:"stroke-dasharray"},Ttt={offset:"strokeDashoffset",array:"strokeDasharray"};function Ett(t,e,r=1,n=0,i=!0){t.pathLength=1;const o=i?Stt:Ttt;t[o.offset]=`${-n}`,t[o.array]=`${e} ${r}`}const jtt=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function gwe(t,{attrX:e,attrY:r,attrScale:n,pathLength:i,pathSpacing:o=1,pathOffset:c=0,...a},f,p,y){if(UH(t,a,p),f){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:v,style:T}=t;v.transform&&(T.transform=v.transform,delete v.transform),(T.transform||v.transformOrigin)&&(T.transformOrigin=v.transformOrigin??"50% 50%",delete v.transformOrigin),T.transform&&(T.transformBox=(y==null?void 0:y.transformBox)??"fill-box",delete v.transformBox);for(const E of jtt)v[E]!==void 0&&(T[E]=v[E],delete v[E]);e!==void 0&&(v.x=e),r!==void 0&&(v.y=r),n!==void 0&&(v.scale=n),i!==void 0&&Ett(v,i,o,c,!1)}const ywe=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"]),xwe=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Att(t,e,r,n){mwe(t,e,void 0,n);for(const i in e.attrs)t.setAttribute(ywe.has(i)?i:DH(i),e.attrs[i])}function vwe(t,e,r){const n=VH(t,e,r);for(const i in t)if(nc(t[i])||nc(e[i])){const o=xT.indexOf(i)!==-1?"attr"+i.charAt(0).toUpperCase()+i.substring(1):i;n[o]=t[i]}return n}class ktt extends cwe{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ol}getBaseTargetFromProps(e,r){return e[r]}readValueFromInstance(e,r){if(vT.has(r)){const n=Qbe(r);return n&&n.default||0}return r=ywe.has(r)?r:DH(r),e.getAttribute(r)}scrapeMotionValuesFromProps(e,r,n){return vwe(e,r,n)}build(e,r,n){gwe(e,r,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,r,n,i){Att(e,r,n,i)}mount(e){this.isSVGTag=xwe(e.tagName),super.mount(e)}}const Ctt=zH.length;function _we(t){if(!t)return;if(!t.isControllingVariants){const r=t.parent?_we(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})=>Cet(t,r,n)))}function Rtt(t){let e=Ptt(t),r=Une(),n=!0,i=!1;const o=p=>(y,v)=>{var E;const T=Hv(t,v,p==="exit"?(E=t.presenceContext)==null?void 0:E.custom:void 0);if(T){const{transition:k,transitionEnd:P,...R}=T;y={...y,...R,...P}}return y};function c(p){e=p(t)}function a(p){const{props:y}=t,v=_we(t.parent)||{},T=[],E=new Set;let k={},P=1/0;for(let D=0;DP&&G,ee=!1;const le=Array.isArray(V)?V:[V];let pe=le.reduce(o(M),{});W===!1&&(pe={});const{prevResolvedValues:Se={}}=B,je={...Se,...pe},Le=me=>{Q=!0,E.has(me)&&(ee=!0,E.delete(me)),B.needsAnimating[me]=!0;const Te=t.getValue(me);Te&&(Te.liveStyle=!1)};for(const me in je){const Te=pe[me],Ne=Se[me];if(k.hasOwnProperty(me))continue;let Ee=!1;h8(Te)&&h8(Ne)?Ee=!bwe(Te,Ne):Ee=Te!==Ne,Ee?Te!=null?Le(me):E.add(me):Te!==void 0&&E.has(me)?Le(me):B.protectedKeys[me]=!0}B.prevProp=V,B.prevResolvedValues=pe,B.isActive&&(k={...k,...pe}),(n||i)&&t.blockInitialAnimation&&(Q=!1);const Ae=Y&&J;Q&&(!Ae||ee)&&T.push(...le.map(me=>{const Te={type:M};if(typeof me=="string"&&(n||i)&&!Ae&&t.manuallyAnimateOnMount&&t.parent){const{parent:Ne}=t,Ee=Hv(Ne,me);if(Ne.enteringChildren&&Ee){const{delayChildren:we}=Ee.transition||{};Te.delay=Vbe(Ne.enteringChildren,t,we)}}return{animation:me,options:Te}}))}if(E.size){const D={};if(typeof y.initial!="boolean"){const M=Hv(t,Array.isArray(y.initial)?y.initial[0]:y.initial);M&&M.transition&&(D.transition=M.transition)}E.forEach(M=>{const B=t.getBaseTarget(M),V=t.getValue(M);V&&(V.liveStyle=!0),D[M]=B??null}),T.push({animation:D})}let R=!!T.length;return n&&(y.initial===!1||y.initial===y.animate)&&!t.manuallyAnimateOnMount&&(R=!1),n=!1,i=!1,R?e(T):Promise.resolve()}function f(p,y){var T;if(r[p].isActive===y)return Promise.resolve();(T=t.variantChildren)==null||T.forEach(E=>{var k;return(k=E.animationState)==null?void 0:k.setActive(p,y)}),r[p].isActive=y;const v=a(p);for(const E in r)r[E].protectedKeys={};return v}return{animateChanges:a,setActive:f,setAnimateFunction:c,getState:()=>r,reset:()=>{r=Une(),i=!0}}}function Ltt(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!bwe(e,t):!1}function iv(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Une(){return{animate:iv(!0),whileInView:iv(),whileHover:iv(),whileTap:iv(),whileDrag:iv(),whileFocus:iv(),exit:iv()}}function b8(t,e){t.min=e.min,t.max=e.max}function $h(t,e){b8(t.x,e.x),b8(t.y,e.y)}function Vne(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}const wwe=1e-4,Dtt=1-wwe,Mtt=1+wwe,Swe=.01,Ott=0-Swe,Ftt=0+Swe;function Qc(t){return t.max-t.min}function Btt(t,e,r){return Math.abs(t-e)<=r}function qne(t,e,r,n=.5){t.origin=n,t.originPoint=La(e.min,e.max,t.origin),t.scale=Qc(r)/Qc(e),t.translate=La(r.min,r.max,t.origin)-t.originPoint,(t.scale>=Dtt&&t.scale<=Mtt||isNaN(t.scale))&&(t.scale=1),(t.translate>=Ott&&t.translate<=Ftt||isNaN(t.translate))&&(t.translate=0)}function mA(t,e,r,n){qne(t.x,e.x,r.x,n?n.originX:void 0),qne(t.y,e.y,r.y,n?n.originY:void 0)}function Gne(t,e,r,n=0){const i=n?La(r.min,r.max,n):r.min;t.min=i+e.min,t.max=t.min+Qc(e)}function $tt(t,e,r,n){Gne(t.x,e.x,r.x,n==null?void 0:n.x),Gne(t.y,e.y,r.y,n==null?void 0:n.y)}function Hne(t,e,r,n=0){const i=n?La(r.min,r.max,n):r.min;t.min=e.min-i,t.max=t.min+Qc(e)}function fM(t,e,r,n){Hne(t.x,e.x,r.x,n==null?void 0:n.x),Hne(t.y,e.y,r.y,n==null?void 0:n.y)}function Wne(t,e,r,n,i){return t-=e,t=hM(t,1/r,n),i!==void 0&&(t=hM(t,1/i,n)),t}function ztt(t,e=0,r=1,n=.5,i,o=t,c=t){if(ym.test(e)&&(e=parseFloat(e),e=La(c.min,c.max,e/100)-c.min),typeof e!="number")return;let a=La(o.min,o.max,n);t===o&&(a-=e),t.min=Wne(t.min,e,r,a,i),t.max=Wne(t.max,e,r,a,i)}function Kne(t,e,[r,n,i],o,c){ztt(t,e[r],e[n],e[i],e.scale,o,c)}const Utt=["x","scaleX","originX"],Vtt=["y","scaleY","originY"];function Yne(t,e,r,n){Kne(t.x,e,Utt,r?r.x:void 0,n?n.x:void 0),Kne(t.y,e,Vtt,r?r.y:void 0,n?n.y:void 0)}function Zne(t){return t.translate===0&&t.scale===1}function Twe(t){return Zne(t.x)&&Zne(t.y)}function Xne(t,e){return t.min===e.min&&t.max===e.max}function qtt(t,e){return Xne(t.x,e.x)&&Xne(t.y,e.y)}function Qne(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Ewe(t,e){return Qne(t.x,e.x)&&Qne(t.y,e.y)}function Jne(t){return Qc(t.x)/Qc(t.y)}function eie(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}function Xf(t){return[t("x"),t("y")]}function Gtt(t,e,r){let n="";const i=t.x.translate/e.x,o=t.y.translate/e.y,c=(r==null?void 0:r.z)||0;if((i||o||c)&&(n=`translate3d(${i}px, ${o}px, ${c}px) `),(e.x!==1||e.y!==1)&&(n+=`scale(${1/e.x}, ${1/e.y}) `),r){const{transformPerspective:p,rotate:y,rotateX:v,rotateY:T,skewX:E,skewY:k}=r;p&&(n=`perspective(${p}px) ${n}`),y&&(n+=`rotate(${y}deg) `),v&&(n+=`rotateX(${v}deg) `),T&&(n+=`rotateY(${T}deg) `),E&&(n+=`skewX(${E}deg) `),k&&(n+=`skewY(${k}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 jwe=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],Htt=jwe.length,tie=t=>typeof t=="string"?parseFloat(t):t,rie=t=>typeof t=="number"||Pn.test(t);function Wtt(t,e,r,n,i,o){i?(t.opacity=La(0,r.opacity??1,Ktt(n)),t.opacityExit=La(e.opacity??1,0,Ytt(n))):o&&(t.opacity=La(e.opacity??1,r.opacity??1,n));for(let c=0;cne?1:r(pk(t,e,n))}function Ztt(t,e,r){const n=nc(t)?t:pS(t);return n.start(RH("",n,e,r)),n.animation}function xk(t,e,r,n={passive:!0}){return t.addEventListener(e,r,n),()=>t.removeEventListener(e,r)}const Xtt=(t,e)=>t.depth-e.depth;class Qtt{constructor(){this.children=[],this.isDirty=!1}add(e){bH(this.children,e),this.isDirty=!0}remove(e){aM(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(Xtt),this.isDirty=!1,this.children.forEach(e)}}function Jtt(t,e){const r=Xc.now(),n=({timestamp:i})=>{const o=i-r;o>=e&&(bx(n),t(o-e))};return ia.setup(n,!0),()=>bx(n)}function BL(t){return nc(t)?t.get():t}class ert{constructor(){this.members=[]}add(e){bH(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&&(aM(this.members,n),n.unmount())}e.scheduleRender()}remove(e){if(aM(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const r=this.members[this.members.length-1];r&&this.promote(r)}}relegate(e){var r;for(let n=this.members.indexOf(e)-1;n>=0;n--){const i=this.members[n];if(i.isPresent!==!1&&((r=i.instance)==null?void 0:r.isConnected)!==!1)return this.promote(i),!0}return!1}promote(e,r){var i;const n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.updateSnapshot(),e.scheduleRender();const{layoutDependency:o}=n.options,{layoutDependency:c}=e.options;(o===void 0||o!==c)&&(e.resumeFrom=n,r&&(n.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),(i=e.root)!=null&&i.isUpdating&&(e.isLayoutDirty=!0)),e.options.crossfade===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{var r,n,i,o,c;(n=(r=e.options).onExitComplete)==null||n.call(r),(c=(i=e.resumingFrom)==null?void 0:(o=i.options).onExitComplete)==null||c.call(o)})}scheduleRender(){this.members.forEach(e=>e.instance&&e.scheduleRender(!1))}removeLeadSnapshot(){var e;(e=this.lead)!=null&&e.snapshot&&(this.lead.snapshot=void 0)}}const $L={hasAnimatedSinceResize:!0,hasEverUpdated:!1},dz=["","X","Y","Z"],trt=1e3;let rrt=0;function hz(t,e,r,n){const{latestValues:i}=e;i[t]&&(r[t]=i[t],e.setStaticValue(t,0),n&&(n[t]=0))}function kwe(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const r=Kbe(e);if(window.MotionHasOptimisedAnimation(r,"transform")){const{layout:i,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(r,"transform",ia,!(i||o))}const{parent:n}=t;n&&!n.hasCheckedOptimisedAppear&&kwe(n)}function Cwe({attachResizeListener:t,defaultParent:e,measureScroll:r,checkIsScrollRoot:n,resetTransform:i}){return class{constructor(c={},a=e==null?void 0:e()){this.id=rrt++,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(srt),this.nodes.forEach(drt),this.nodes.forEach(hrt),this.nodes.forEach(art)},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;ia.read(()=>{v=window.innerWidth}),t(c,()=>{const E=window.innerWidth;E!==v&&(v=E,this.root.updateBlockedByResize=!0,y&&y(),y=Jtt(T,250),$L.hasAnimatedSinceResize&&($L.hasAnimatedSinceResize=!1,this.nodes.forEach(aie)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&p&&(a||f)&&this.addEventListener("didUpdate",({delta:y,hasLayoutChanged:v,hasRelativeLayoutChanged:T,layout:E})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const k=this.options.transition||p.getDefaultTransition()||yrt,{onLayoutAnimationStart:P,onLayoutAnimationComplete:R}=p.getProps(),D=!this.targetLayout||!Ewe(this.targetLayout,E),M=!v&&T;if(this.options.layoutRoot||this.resumeFrom||M||v&&(D||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const B={...PH(k,"layout"),onPlay:P,onComplete:R};(p.shouldReduceMotion||this.options.layoutRoot)&&(B.delay=0,B.type=!1),this.startAnimation(B),this.setAnimationOrigin(y,M)}else v||aie(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=E})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const c=this.getStack();c&&c.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),bx(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(frt),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&&kwe(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&&!Qc(this.snapshot.measuredBox.x)&&!Qc(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let f=0;f{const G=V/1e3;oie(v.x,c.x,G),oie(v.y,c.y,G),this.setTargetDelta(v),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(fM(T,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),prt(this.relativeTarget,this.relativeTargetOrigin,T,G),B&&qtt(this.relativeTarget,B)&&(this.isProjectionDirty=!1),B||(B=ol()),$h(B,this.relativeTarget)),P&&(this.animationValues=y,Wtt(y,p,this.latestValues,G,M,D)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=G},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(c){var a,f,p;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(p=(f=this.resumingFrom)==null?void 0:f.currentAnimation)==null||p.stop(),this.pendingAnimation&&(bx(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ia.update(()=>{$L.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=pS(0)),this.motionValue.jump(0,!1),this.currentAnimation=Ztt(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(trt),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const c=this.getLead();let{targetWithTransforms:a,target:f,layout:p,latestValues:y}=c;if(!(!a||!f||!p)){if(this!==c&&this.layout&&p&&Nwe(this.options.animationType,this.layout.layoutBox,p.layoutBox)){f=this.target||ol();const v=Qc(this.layout.layoutBox.x);f.x.min=c.target.x.min,f.x.max=f.x.min+v;const T=Qc(this.layout.layoutBox.y);f.y.min=c.target.y.min,f.y.max=f.y.min+T}$h(a,f),FL(a,y),mA(this.projectionDeltaWithTransform,this.layoutCorrected,a,y)}}registerSharedNode(c,a){this.sharedNodes.has(c)||this.sharedNodes.set(c,new ert),this.sharedNodes.get(c).add(a);const p=a.options.initialPromotionConfig;a.promote({transition:p?p.transition:void 0,preserveFollowOpacity:p&&p.shouldPreserveFollowOpacity?p.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 p=this.getStack();p&&p.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 p={};f.z&&hz("z",c,p,this.animationValues);for(let y=0;y{var a;return(a=c.currentAnimation)==null?void 0:a.stop()}),this.root.nodes.forEach(iie),this.root.sharedNodes.clear()}}}function nrt(t){t.updateLayout()}function irt(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")Xf(v=>{const T=c?e.measuredBox[v]:e.layoutBox[v],E=Qc(T);T.min=n[v].min,T.max=T.min+E});else if(o==="x"||o==="y"){const v=o==="x"?"y":"x";b8(c?e.measuredBox[v]:e.layoutBox[v],n[v])}else Nwe(o,e.layoutBox,n)&&Xf(v=>{const T=c?e.measuredBox[v]:e.layoutBox[v],E=Qc(n[v]);T.max=T.min+E,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[v].max=t.relativeTarget[v].min+E)});const a=e1();mA(a,n,e.layoutBox);const f=e1();c?mA(f,t.applyTransform(i,!0),e.measuredBox):mA(f,n,e.layoutBox);const p=!Twe(a);let y=!1;if(!t.resumeFrom){const v=t.getClosestProjectingParent();if(v&&!v.resumeFrom){const{snapshot:T,layout:E}=v;if(T&&E){const k=t.options.layoutAnchor||void 0,P=ol();fM(P,e.layoutBox,T.layoutBox,k);const R=ol();fM(R,n,E.layoutBox,k),Ewe(P,R)||(y=!0),v.options.layoutRoot&&(t.relativeTarget=R,t.relativeTargetOrigin=P,t.relativeParent=v)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:f,layoutDelta:a,hasLayoutChanged:p,hasRelativeLayoutChanged:y})}else if(t.isLead()){const{onExitComplete:n}=t.options;n&&n()}t.options.transition=void 0}function srt(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 art(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function ort(t){t.clearSnapshot()}function iie(t){t.clearMeasurements()}function lrt(t){t.isLayoutDirty=!0,t.updateLayout()}function sie(t){t.isLayoutDirty=!1}function crt(t){t.isAnimationBlocked&&t.layout&&!t.isLayoutDirty&&(t.snapshot=t.layout,t.isLayoutDirty=!0)}function urt(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function aie(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function drt(t){t.resolveTargetDelta()}function hrt(t){t.calcProjection()}function frt(t){t.resetSkewAndRotation()}function mrt(t){t.removeLeadSnapshot()}function oie(t,e,r){t.translate=La(e.translate,0,r),t.scale=La(e.scale,1,r),t.origin=e.origin,t.originPoint=e.originPoint}function lie(t,e,r,n){t.min=La(e.min,r.min,n),t.max=La(e.max,r.max,n)}function prt(t,e,r,n){lie(t.x,e.x,r.x,n),lie(t.y,e.y,r.y,n)}function grt(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const yrt={duration:.45,ease:[.4,0,.1,1]},cie=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),uie=cie("applewebkit/")&&!cie("chrome/")?Math.round:ch;function die(t){t.min=uie(t.min),t.max=uie(t.max)}function xrt(t){die(t.x),die(t.y)}function Nwe(t,e,r){return t==="position"||t==="preserve-aspect"&&!Btt(Jne(e),Jne(r),.2)}function vrt(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const _rt=Cwe({attachResizeListener:(t,e)=>xk(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}),fz={current:void 0},Iwe=Cwe({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!fz.current){const t=new _rt({});t.mount(window),t.setOptions({layoutScroll:!0}),fz.current=t}return fz.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),qH=C.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function hie(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function brt(...t){return e=>{let r=!1;const n=t.map(i=>{const o=hie(i,e);return!r&&typeof o=="function"&&(r=!0),o});if(r)return()=>{for(let i=0;i{const{width:E,height:k,top:P,left:R,right:D,bottom:M}=f.current;if(e||o===!1||!a.current||!E||!k)return;const B=r==="left"?`left: ${R}`:`right: ${D}`,V=n==="bottom"?`bottom: ${M}`:`top: ${P}`;a.current.dataset.motionPopId=c;const G=document.createElement("style");p&&(G.nonce=p);const W=i??document.head;return W.appendChild(G),G.sheet&&G.sheet.insertRule(` [data-motion-pop-id="${c}"] { position: absolute !important; width: ${E}px !important; height: ${k}px !important; ${B}px !important; ${V}px !important; } `),()=>{var Y;(Y=a.current)==null||Y.removeAttribute("data-motion-pop-id"),W.contains(G)&&W.removeChild(G)}},[e]),s.jsx(Srt,{isPresent:e,childRef:a,sizeRef:f,pop:o,children:o===!1?t:C.cloneElement(t,{ref:v})})}const Ert=({children:t,initial:e,isPresent:r,onExitComplete:n,custom:i,presenceAffectsLayout:o,mode:c,anchorX:a,anchorY:f,root:p})=>{const y=_H(jrt),v=C.useId();let T=!0,E=C.useMemo(()=>(T=!1,{id:v,initial:e,isPresent:r,custom:i,onExitComplete:k=>{y.set(k,!0);for(const P of y.values())if(!P)return;n&&n()},register:k=>(y.set(k,!1),()=>y.delete(k))}),[r,y,n]);return o&&T&&(E={...E}),C.useMemo(()=>{y.forEach((k,P)=>y.set(P,!1))},[r]),C.useEffect(()=>{!r&&!y.size&&n&&n()},[r]),t=s.jsx(Trt,{pop:c==="popLayout",isPresent:r,anchorX:a,anchorY:f,root:p,children:t}),s.jsx(nF.Provider,{value:E,children:t})};function jrt(){return new Map}function Pwe(t=!0){const e=C.useContext(nF);if(e===null)return[!0,null];const{isPresent:r,onExitComplete:n,register:i}=e,o=C.useId();C.useEffect(()=>{if(t)return i(o)},[t]);const c=C.useCallback(()=>t&&n&&n(o),[o,n,t]);return!r&&n?[!1,c]:[!0]}const bR=t=>t.key||"";function fie(t){const e=[];return C.Children.forEach(t,r=>{C.isValidElement(r)&&e.push(r)}),e}const Rwe=({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:p})=>{const[y,v]=Pwe(c),T=C.useMemo(()=>fie(t),[t]),E=c&&!y?[]:T.map(bR),k=C.useRef(!0),P=C.useRef(T),R=_H(()=>new Map),D=C.useRef(new Set),[M,B]=C.useState(T),[V,G]=C.useState(T);sbe(()=>{k.current=!1,P.current=T;for(let J=0;J{const Q=bR(J),ee=c&&!y?!1:T===V||E.includes(Q),le=()=>{if(D.current.has(Q))return;if(R.has(Q))D.current.add(Q),R.set(Q,!0);else return;let pe=!0;R.forEach(Se=>{Se||(pe=!1)}),pe&&(Y==null||Y(),G(P.current),c&&(v==null||v()),n&&n())};return s.jsx(Ert,{isPresent:ee,initial:!k.current||r?void 0:!1,custom:e,presenceAffectsLayout:i,mode:o,root:p,onExitComplete:ee?void 0:le,anchorX:a,anchorY:f,children:J},Q)})})},Lwe=C.createContext({strict:!1}),mie={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 pie=!1;function Art(){if(pie)return;const t={};for(const e in mie)t[e]={isEnabled:r=>mie[e].some(n=>!!r[n])};lwe(t),pie=!0}function Dwe(){return Art(),dtt()}function krt(t){const e=Dwe();for(const r in t)e[r]={...e[r],...t[r]};lwe(e)}const Crt=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 mM(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Crt.has(t)}let Mwe=t=>!mM(t);function Nrt(t){typeof t=="function"&&(Mwe=e=>e.startsWith("on")?!mM(e):t(e))}try{Nrt(require("@emotion/is-prop-valid").default)}catch{}function Irt(t,e,r){const n={};for(const i in t)i==="values"&&typeof t.values=="object"||nc(t[i])||(Mwe(i)||r===!0&&mM(i)||!e&&!mM(i)||t.draggable&&i.startsWith("onDrag"))&&(n[i]=t[i]);return n}const lF=C.createContext({});function Prt(t,e){if(oF(t)){const{initial:r,animate:n}=t;return{initial:r===!1||yk(r)?r:void 0,animate:yk(n)?n:void 0}}return t.inherit!==!1?e:{}}function Rrt(t){const{initial:e,animate:r}=Prt(t,C.useContext(lF));return C.useMemo(()=>({initial:e,animate:r}),[gie(e),gie(r)])}function gie(t){return Array.isArray(t)?t.join(" "):t}const GH=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Owe(t,e,r){for(const n in e)!nc(e[n])&&!pwe(n,r)&&(t[n]=e[n])}function Lrt({transformTemplate:t},e){return C.useMemo(()=>{const r=GH();return UH(r,e,t),Object.assign({},r.vars,r.style)},[e])}function Drt(t,e){const r=t.style||{},n={};return Owe(n,r,t),Object.assign(n,Lrt(t,e)),n}function Mrt(t,e){const r={},n=Drt(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 Fwe=()=>({...GH(),attrs:{}});function Ort(t,e,r,n){const i=C.useMemo(()=>{const o=Fwe();return gwe(o,e,xwe(n),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Owe(o,t.style,t),i.style={...o,...i.style}}return i}const Frt=["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 HH(t){return typeof t!="string"||t.includes("-")?!1:!!(Frt.indexOf(t)>-1||/[A-Z]/u.test(t))}function Brt(t,e,r,{latestValues:n},i,o=!1,c){const f=(c??HH(t)?Ort:Mrt)(e,n,i,t),p=Irt(e,typeof t=="string",o),y=t!==C.Fragment?{...p,...f,ref:r}:{},{children:v}=e,T=C.useMemo(()=>nc(v)?v.get():v,[v]);return C.createElement(t,{...y,children:T})}function $rt({scrapeMotionValuesFromProps:t,createRenderState:e},r,n,i){return{latestValues:zrt(r,n,i,t),renderState:e()}}function zrt(t,e,r,n){const i={},o=n(t,{});for(const T in o)i[T]=BL(o[T]);let{initial:c,animate:a}=t;const f=oF(t),p=awe(t);e&&p&&!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"&&!aF(v)){const T=Array.isArray(v)?v:[v];for(let E=0;E(e,r)=>{const n=C.useContext(lF),i=C.useContext(nF),o=()=>$rt(t,e,n,i);return r?o():_H(o)},Urt=Bwe({scrapeMotionValuesFromProps:VH,createRenderState:GH}),Vrt=Bwe({scrapeMotionValuesFromProps:vwe,createRenderState:Fwe}),qrt=Symbol.for("motionComponentSymbol");function Grt(t,e,r){const n=C.useRef(r);C.useInsertionEffect(()=>{n.current=r});const i=C.useRef(null);return C.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 $we=C.createContext({});function Dw(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Hrt(t,e,r,n,i,o){var B,V;const{visualElement:c}=C.useContext(lF),a=C.useContext(Lwe),f=C.useContext(nF),p=C.useContext(qH),y=p.reducedMotion,v=p.skipAnimations,T=C.useRef(null),E=C.useRef(!1);n=n||a.renderer,!T.current&&n&&(T.current=n(t,{visualState:e,parent:c,props:r,presenceContext:f,blockInitialAnimation:f?f.initial===!1:!1,reducedMotionConfig:y,skipAnimations:v,isSVG:o}),E.current&&T.current&&(T.current.manuallyAnimateOnMount=!0));const k=T.current,P=C.useContext($we);k&&!k.projection&&i&&(k.type==="html"||k.type==="svg")&&Wrt(T.current,r,i,P);const R=C.useRef(!1);C.useInsertionEffect(()=>{k&&R.current&&k.update(r,f)});const D=r[Wbe],M=C.useRef(!!D&&typeof window<"u"&&!((B=window.MotionHandoffIsComplete)!=null&&B.call(window,D))&&((V=window.MotionHasOptimisedAnimation)==null?void 0:V.call(window,D)));return sbe(()=>{E.current=!0,k&&(R.current=!0,window.MotionIsMounted=!0,k.updateFeatures(),k.scheduleRenderMicrotask(),M.current&&k.animationState&&k.animationState.animateChanges())}),C.useEffect(()=>{k&&(!M.current&&k.animationState&&k.animationState.animateChanges(),M.current&&(queueMicrotask(()=>{var G;(G=window.MotionHandoffMarkAsComplete)==null||G.call(window,D)}),M.current=!1),k.enteringChildren=void 0)}),k}function Wrt(t,e,r,n){const{layoutId:i,layout:o,drag:c,dragConstraints:a,layoutScroll:f,layoutRoot:p,layoutAnchor:y,layoutCrossfade:v}=e;t.projection=new r(t.latestValues,e["data-framer-portal-id"]?void 0:zwe(t.parent)),t.projection.setOptions({layoutId:i,layout:o,alwaysMeasureLayout:!!c||a&&Dw(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:n,crossfade:v,layoutScroll:f,layoutRoot:p,layoutAnchor:y})}function zwe(t){if(t)return t.options.allowProjection!==!1?t.projection:zwe(t.parent)}function mz(t,{forwardMotionProps:e=!1,type:r}={},n,i){n&&krt(n);const o=r?r==="svg":HH(t),c=o?Vrt:Urt;function a(p,y){let v;const T={...C.useContext(qH),...p,layoutId:Krt(p)},{isStatic:E}=T,k=Rrt(p),P=c(p,E);if(!E&&typeof window<"u"){Yrt();const R=Zrt(T);v=R.MeasureLayout,k.visualElement=Hrt(t,P,T,i,R.ProjectionNode,o)}return s.jsxs(lF.Provider,{value:k,children:[v&&k.visualElement?s.jsx(v,{visualElement:k.visualElement,...T}):null,Brt(t,p,Grt(P,k.visualElement,y),P,E,e,o)]})}a.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const f=C.forwardRef(a);return f[qrt]=t,f}function Krt({layoutId:t}){const e=C.useContext(vH).id;return e&&t!==void 0?e+"-"+t:t}function Yrt(t,e){C.useContext(Lwe).strict}function Zrt(t){const e=Dwe(),{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 Xrt(t,e){if(typeof Proxy>"u")return mz;const r=new Map,n=(o,c)=>mz(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,mz(c,void 0,t,e)),r.get(c))})}const Qrt=(t,e)=>e.isSVG??HH(t)?new ktt(e):new wtt(e,{allowProjection:t!==C.Fragment});class Jrt extends Bx{constructor(e){super(e),e.animationState||(e.animationState=Rtt(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();aF(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 ent=0;class tnt extends Bx{constructor(){super(...arguments),this.id=ent++,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=Hv(this.node,c,a);if(f){const{transition:p,transitionEnd:y,...v}=f;for(const T in v)(o=this.node.getValue(T))==null||o.jump(v[T])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const i=this.node.animationState.setActive("exit",!e);r&&!e&&i.then(()=>{this.isExitComplete=!0,r(this.id)})}mount(){const{register:e,onExitComplete:r}=this.node.presenceContext||{};r&&r(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const rnt={animation:{Feature:Jrt},exit:{Feature:tnt}};function QC(t){return{point:{x:t.pageX,y:t.pageY}}}const nnt=t=>e=>FH(e)&&t(e,QC(e));function pA(t,e,r,n){return xk(t,e,nnt(r),n)}const Uwe=({current:t})=>t?t.ownerDocument.defaultView:null,yie=(t,e)=>Math.abs(t-e);function int(t,e){const r=yie(t.x,e.x),n=yie(t.y,e.y);return Math.sqrt(r**2+n**2)}const xie=new Set(["auto","scroll"]);class Vwe{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=E=>{this.handleScroll(E.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=wR(this.lastRawMoveEventInfo,this.transformPagePoint));const E=pz(this.lastMoveEventInfo,this.history),k=this.startEvent!==null,P=int(E.offset,{x:0,y:0})>=this.distanceThreshold;if(!k&&!P)return;const{point:R}=E,{timestamp:D}=Wl;this.history.push({...R,timestamp:D});const{onStart:M,onMove:B}=this.handlers;k||(M&&M(this.lastMoveEvent,E),this.startEvent=this.lastMoveEvent),B&&B(this.lastMoveEvent,E)},this.handlePointerMove=(E,k)=>{this.lastMoveEvent=E,this.lastRawMoveEventInfo=k,this.lastMoveEventInfo=wR(k,this.transformPagePoint),ia.update(this.updatePoint,!0)},this.handlePointerUp=(E,k)=>{this.end();const{onEnd:P,onSessionEnd:R,resumeAnimation:D}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&D&&D(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const M=pz(E.type==="pointercancel"?this.lastMoveEventInfo:wR(k,this.transformPagePoint),this.history);this.startEvent&&P&&P(E,M),R&&R(E,M)},!FH(e))return;this.dragSnapToOrigin=o,this.handlers=r,this.transformPagePoint=n,this.distanceThreshold=c,this.contextWindow=i||window;const f=QC(e),p=wR(f,this.transformPagePoint),{point:y}=p,{timestamp:v}=Wl;this.history=[{...y,timestamp:v}];const{onSessionStart:T}=r;T&&T(e,pz(p,this.history)),this.removeListeners=YC(pA(this.contextWindow,"pointermove",this.handlePointerMove),pA(this.contextWindow,"pointerup",this.handlePointerUp),pA(this.contextWindow,"pointercancel",this.handlePointerUp)),a&&this.startScrollTracking(a)}startScrollTracking(e){let r=e.parentElement;for(;r;){const n=getComputedStyle(r);(xie.has(n.overflowX)||xie.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),ia.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),bx(this.updatePoint)}}function wR(t,e){return e?{point:e(t.point)}:t}function vie(t,e){return{x:t.x-e.x,y:t.y-e.y}}function pz({point:t},e){return{point:t,delta:vie(t,qwe(e)),offset:vie(t,snt(e)),velocity:ant(e,.1)}}function snt(t){return t[0]}function qwe(t){return t[t.length-1]}function ant(t,e){if(t.length<2)return{x:0,y:0};let r=t.length-1,n=null;const i=qwe(t);for(;r>=0&&(n=t[r],!(i.timestamp-n.timestamp>Ou(e)));)r--;if(!n)return{x:0,y:0};n===t[0]&&t.length>2&&i.timestamp-n.timestamp>Ou(e)*2&&(n=t[1]);const o=ih(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 ont(t,{min:e,max:r},n){return e!==void 0&&tr&&(t=n?La(r,t,n.max):Math.min(t,r)),t}function _ie(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 lnt(t,{top:e,left:r,bottom:n,right:i}){return{x:_ie(t.x,r,i),y:_ie(t.y,e,n)}}function bie(t,e){let r=e.min-t.min,n=e.max-t.max;return e.max-e.minn?r=pk(e.min,e.max-n,t.min):n>i&&(r=pk(t.min,t.max-i,e.min)),Em(0,1,r)}function dnt(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 w8=.35;function hnt(t=w8){return t===!1?t=0:t===!0&&(t=w8),{x:wie(t,"left","right"),y:wie(t,"top","bottom")}}function wie(t,e,r){return{min:Sie(t,e),max:Sie(t,r)}}function Sie(t,e){return typeof t=="number"?t:t[e]||0}const fnt=new WeakMap;class mnt{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=ol(),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(QC(v).point),this.stopAnimation()},c=(v,T)=>{const{drag:E,dragPropagation:k,onDragStart:P}=this.getProps();if(E&&!k&&(this.openDragLock&&this.openDragLock(),this.openDragLock=zet(E),!this.openDragLock))return;this.latestPointerEvent=v,this.latestPanInfo=T,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Xf(D=>{let M=this.getAxisMotionValue(D).get()||0;if(ym.test(M)){const{projection:B}=this.visualElement;if(B&&B.layout){const V=B.layout.layoutBox[D];V&&(M=Qc(V)*(parseFloat(M)/100))}}this.originPoint[D]=M}),P&&ia.update(()=>P(v,T),!1,!0),f8(this.visualElement,"transform");const{animationState:R}=this.visualElement;R&&R.setActive("whileDrag",!0)},a=(v,T)=>{this.latestPointerEvent=v,this.latestPanInfo=T;const{dragPropagation:E,dragDirectionLock:k,onDirectionLock:P,onDrag:R}=this.getProps();if(!E&&!this.openDragLock)return;const{offset:D}=T;if(k&&this.currentDirection===null){this.currentDirection=gnt(D),this.currentDirection!==null&&P&&P(this.currentDirection);return}this.updateAxis("x",T.point,D),this.updateAxis("y",T.point,D),this.visualElement.render(),R&&ia.update(()=>R(v,T),!1,!0)},f=(v,T)=>{this.latestPointerEvent=v,this.latestPanInfo=T,this.stop(v,T),this.latestPointerEvent=null,this.latestPanInfo=null},p=()=>{const{dragSnapToOrigin:v}=this.getProps();(v||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:y}=this.getProps();this.panSession=new Vwe(e,{onSessionStart:o,onStart:c,onMove:a,onSessionEnd:f,resumeAnimation:p},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:y,distanceThreshold:n,contextWindow:Uwe(this.visualElement),element:this.visualElement.current})}stop(e,r){const n=e||this.latestPointerEvent,i=r||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!i||!n)return;const{velocity:c}=i;this.startAnimation(c);const{onDragEnd:a}=this.getProps();a&&ia.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||!SR(e,i,this.currentDirection))return;const o=this.getAxisMotionValue(e);let c=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(c=ont(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&&Dw(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=lnt(n.layoutBox,e):this.constraints=!1,this.elastic=hnt(r),i!==this.constraints&&!Dw(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&Xf(c=>{this.constraints!==!1&&this.getAxisMotionValue(c)&&(this.constraints[c]=dnt(n.layoutBox[c],this.constraints[c]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:r}=this.getProps();if(!e||!Dw(e))return!1;const n=e.current;fS(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=gtt(n,i.root,this.visualElement.getTransformPagePoint());let c=cnt(i.layout.layoutBox,o);if(r){const a=r(ftt(c));this.hasMutatedConstraints=!!a,a&&(c=uwe(a))}return c}startAnimation(e){const{drag:r,dragMomentum:n,dragElastic:i,dragTransition:o,dragSnapToOrigin:c,onDragTransitionEnd:a}=this.getProps(),f=this.constraints||{},p=Xf(y=>{if(!SR(y,r,this.currentDirection))return;let v=f&&f[y]||{};(c===!0||c===y)&&(v={min:0,max:0});const T=i?200:1e6,E=i?40:1e7,k={type:"inertia",velocity:n?e[y]:0,bounceStiffness:T,bounceDamping:E,timeConstant:750,restDelta:1,restSpeed:10,...o,...v};return this.startAxisValueAnimation(y,k)});return Promise.all(p).then(a)}startAxisValueAnimation(e,r){const n=this.getAxisMotionValue(e);return f8(this.visualElement,e),n.start(RH(e,n,0,r,this.visualElement,!1))}stopAnimation(){Xf(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){Xf(r=>{const{drag:n}=this.getProps();if(!SR(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]-La(c,a,.5)+f)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:r}=this.getProps(),{projection:n}=this.visualElement;if(!Dw(r)||!n||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};Xf(c=>{const a=this.getAxisMotionValue(c);if(a&&this.constraints!==!1){const f=a.get();i[c]=unt({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(),Xf(c=>{if(!SR(c,e,null))return;const a=this.getAxisMotionValue(c),{min:f,max:p}=this.constraints[c];a.set(La(f,p,i[c]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;fnt.set(this.visualElement,this);const e=this.visualElement.current,r=pA(e,"pointerdown",p=>{const{drag:y,dragListener:v=!0}=this.getProps(),T=p.target,E=T!==e&&Wet(T);y&&v&&!E&&this.start(p)});let n;const i=()=>{const{dragConstraints:p}=this.getProps();Dw(p)&&p.current&&(this.constraints=this.resolveRefConstraints(),n||(n=pnt(e,p.current,()=>this.scalePositionWithinConstraints())))},{projection:o}=this.visualElement,c=o.addEventListener("measure",i);o&&!o.layout&&(o.root&&o.root.updateScroll(),o.updateLayout()),ia.read(i);const a=xk(window,"resize",()=>this.scalePositionWithinConstraints()),f=o.addEventListener("didUpdate",({delta:p,hasLayoutChanged:y})=>{this.isDragging&&y&&(Xf(v=>{const T=this.getAxisMotionValue(v);T&&(this.originPoint[v]+=p[v].translate,T.set(T.get()+p[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=w8,dragMomentum:a=!0}=e;return{...e,drag:r,dragDirectionLock:n,dragPropagation:i,dragConstraints:o,dragElastic:c,dragMomentum:a}}}function Tie(t){let e=!0;return()=>{if(e){e=!1;return}t()}}function pnt(t,e,r){const n=Ine(t,Tie(r)),i=Ine(e,Tie(r));return()=>{n(),i()}}function SR(t,e,r){return(e===!0||e===t)&&(r===null||r===t)}function gnt(t,e=10){let r=null;return Math.abs(t.y)>e?r="y":Math.abs(t.x)>e&&(r="x"),r}class ynt extends Bx{constructor(e){super(e),this.removeGroupControls=ch,this.removeListeners=ch,this.controls=new mnt(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ch}update(){const{dragControls:e}=this.node.getProps(),{dragControls:r}=this.node.prevProps||{};e!==r&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const gz=t=>(e,r)=>{t&&ia.update(()=>t(e,r),!1,!0)};class xnt extends Bx{constructor(){super(...arguments),this.removePointerDownListener=ch}onPointerDown(e){this.session=new Vwe(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Uwe(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:r,onPan:n,onPanEnd:i}=this.node.getProps();return{onSessionStart:gz(e),onStart:gz(r),onMove:gz(n),onEnd:(o,c)=>{delete this.session,i&&ia.postRender(()=>i(o,c))}}}mount(){this.removePointerDownListener=pA(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 yz=!1;class vnt extends C.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),yz&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),$L.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:r,visualElement:n,drag:i,isPresent:o}=this.props,{projection:c}=n;return c&&(c.isPresent=o,e.layoutDependency!==r&&c.setOptions({...c.options,layoutDependency:r}),yz=!0,i||e.layoutDependency!==r||r===void 0||e.isPresent!==o?c.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?c.promote():c.relegate()||ia.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(),OH.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:r,switchLayoutGroup:n}=this.props,{projection:i}=e;yz=!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 Gwe(t){const[e,r]=Pwe(),n=C.useContext(vH);return s.jsx(vnt,{...t,layoutGroup:n,switchLayoutGroup:C.useContext($we),isPresent:e,safeToRemove:r})}const _nt={pan:{Feature:xnt},drag:{Feature:ynt,ProjectionNode:Iwe,MeasureLayout:Gwe}};function Eie(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&&ia.postRender(()=>o(e,QC(e)))}class bnt extends Bx{mount(){const{current:e}=this.node;e&&(this.unmount=Vet(e,(r,n)=>(Eie(this.node,n,"Start"),i=>Eie(this.node,i,"End"))))}unmount(){}}class wnt extends Bx{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=YC(xk(this.node.current,"focus",()=>this.onFocus()),xk(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function jie(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&&ia.postRender(()=>o(e,QC(e)))}class Snt extends Bx{mount(){const{current:e}=this.node;if(!e)return;const{globalTapTarget:r,propagate:n}=this.node.props;this.unmount=Yet(e,(i,o)=>(jie(this.node,o,"Start"),(c,{success:a})=>jie(this.node,c,a?"End":"Cancel")),{useGlobalTarget:r,stopPropagation:(n==null?void 0:n.tap)===!1})}unmount(){}}const S8=new WeakMap,xz=new WeakMap,Tnt=t=>{const e=S8.get(t.target);e&&e(t)},Ent=t=>{t.forEach(Tnt)};function jnt({root:t,...e}){const r=t||document;xz.has(r)||xz.set(r,{});const n=xz.get(r),i=JSON.stringify(e);return n[i]||(n[i]=new IntersectionObserver(Ent,{root:t,...e})),n[i]}function Ant(t,e,r){const n=jnt(e);return S8.set(t,r),n.observe(t),()=>{S8.delete(t),n.unobserve(t)}}const knt={some:0,all:1};class Cnt extends Bx{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:knt[i]},a=p=>{const{isIntersecting:y}=p;if(this.isInView===y||(this.isInView=y,o&&!y&&this.hasEnteredView))return;y&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",y);const{onViewportEnter:v,onViewportLeave:T}=this.node.getProps(),E=y?v:T;E&&E(p)};this.stopObserver=Ant(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(Nnt(e,r))&&this.startObserver()}unmount(){var e;(e=this.stopObserver)==null||e.call(this),this.hasEnteredView=!1,this.isInView=!1}}function Nnt({viewport:t={}},{viewport:e={}}={}){return r=>t[r]!==e[r]}const Int={inView:{Feature:Cnt},tap:{Feature:Snt},focus:{Feature:wnt},hover:{Feature:bnt}},Pnt={layout:{ProjectionNode:Iwe,MeasureLayout:Gwe}},Rnt={...rnt,...Int,..._nt,...Pnt},fr=Xrt(Rnt,Qrt);function Lnt(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 Aie(t){return t.visitor_intent==="buying"&&!t.has_agent}function Dnt({token:t}={}){var E;const e=Pm(),r=t||e.token,{data:n,isLoading:i,isError:o}=RQe(r);Ar();const c=(E=n==null?void 0:n.open_houses)==null?void 0:E.id,{data:a}=mr({queryKey:["cohost-visitors",r,c],queryFn:async()=>{const{data:k,error:P}=await Re.rpc("get_cohost_visitors",{_token:r});if(P)throw P;return k||[]},enabled:!!r&&!!c,refetchInterval:15e3});if(i)return 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,p=(a==null?void 0:a.length)||0,y=(a==null?void 0:a.filter(k=>k.visitor_intent==="buying").length)||0,v=(a==null?void 0:a.filter(Aie).length)||0,T=k=>{if(!k)return"";const[P,R]=k.split(":"),D=parseInt(P);return`${D>12?D-12:D||12}:${R} ${D>=12?"PM":"AM"}`};return 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(fl,{className:"h-4 w-4"}),s.jsx("span",{className:"font-bold text-white",children:p})]}),s.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[s.jsx(fme,{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(va,{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:Ri(new Date(f.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),f.start_time&&s.jsxs("span",{children:[T(f.start_time),f.end_time?` – ${T(f.end_time)}`:""]})]}),s.jsx(Lm,{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(Rwe,{children:a.map((k,P)=>{var M;const R=Lnt(k.visitor_intent),D=Aie(k);return s.jsxs(fr.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:P*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${D?"bg-orange-500/10 border-orange-500/30":"bg-white/5 border-white/10"}`,children:[s.jsx("div",{className:`w-11 h-11 rounded-full flex items-center justify-center text-lg font-bold shrink-0 ${D?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(M=k.first_name[0])==null?void 0:M.toUpperCase()}),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:[k.first_name," ",k.last_name||""]}),D&&s.jsx(ss,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),k.has_agent&&s.jsx(ss,{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(ss,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${R.color}`,children:[R.emoji," ",R.label]}),s.jsx("span",{className:"text-white/30 text-xs",children:Ri(new Date(k.created_at),"h:mm a")})]})]})]},k.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(vme,{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 Mnt(){const e=ki().pathname.slice(1);if(C.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(Dnt,{token:r})}if(e.startsWith("rsvp/")){const r=e.slice(5);if(r)return s.jsx(ibe,{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(nbe,{slug:e})}const kie=[{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 Cie(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 Nie({value:t,className:e}){return s.jsx("span",{className:qt("tabular-nums",e),children:Kf(t)})}function Ont({data:t,agent:e,interactive:r=!0,compact:n=!1}){var Y,J;const i=r&&t.allow_client_edits!==!1,[o,c]=C.useState(()=>t.scenarios.map(Q=>({...Q}))),[a,f]=C.useState(()=>({...t.inputs})),[p,y]=C.useState(()=>Math.min(1,Math.max(0,t.scenarios.length-1))),[v,T]=C.useState(!1),E=C.useMemo(()=>o.map(Q=>wYe(a,Q,t.close_date)),[o,a,t.close_date]),k=E[p]??E[0],P=E[Math.min(1,E.length-1)],R=[t.property_address,[t.city,t.state].filter(Boolean).join(", "),t.zip].filter(Boolean).join(" · "),D=t.mode==="offers",M=E.reduce((Q,ee,le)=>{var pe;return ee.net>(((pe=E[Q])==null?void 0:pe.net)??-1/0)?le:Q},0),B=(Q,ee)=>c(le=>le.map((pe,Se)=>Se===Q?{...pe,...ee}:pe)),V=()=>{c(t.scenarios.map(Q=>({...Q}))),f({...t.inputs})};if(!k)return null;const G=Math.max(k.price,1),W=[{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:E.every(Q=>!Q.concessions)},{label:"Repair credits",get:Q=>-Q.repairs,sub:!0,hide:E.every(Q=>!Q.repairs)},{label:"Other costs",get:Q=>-Q.otherTotal,sub:!0,hide:!((Y=E[0])!=null&&Y.otherTotal)}];return s.jsxs("div",{className:qt("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(Bt,{asChild:!0,variant:"outline",size:"sm",children:s.jsxs("a",{href:`tel:${e.phone}`,children:[s.jsx(ri,{className:"mr-1.5 h-4 w-4"}),"Call"]})}),s.jsx(Bt,{asChild:!0,variant:"outline",size:"sm",children:s.jsxs("a",{href:`sms:${e.phone}`,children:[s.jsx(fh,{className:"mr-1.5 h-4 w-4"}),"Text"]})})]}),(e==null?void 0:e.email)&&s.jsx(Bt,{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(mi,{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"}),R&&s.jsxs("p",{className:"flex items-center gap-2 text-sm opacity-90",children:[s.jsx(Es,{className:"h-4 w-4"}),R]}),s.jsxs("div",{children:[s.jsxs("p",{className:"text-sm opacity-80",children:["Estimated walk-away · ",(J=o[p])==null?void 0:J.label]}),s.jsx("p",{className:"font-serif text-5xl font-semibold tracking-tight tabular-nums sm:text-6xl",children:Kf(k.net)})]}),s.jsxs("p",{className:"text-sm opacity-80",children:[Math.round(k.netPct*100),"% of the ",Kf(k.price)," sale price",Cie(t.close_date)&&s.jsxs(s.Fragment,{children:[" · ",s.jsx(oo,{className:"inline h-3.5 w-3.5 -mt-0.5"})," closing ",Cie(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,k.net/G*100)}%`}}),kie.map(Q=>{const ee=Q.key==="concessions"?k.concessions+k.repairs:k[Q.key];return ee>0?s.jsx("div",{className:qt("h-full transition-all duration-500",Q.cls),style:{width:`${ee/G*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 ",Kf(k.net)]}),kie.map(Q=>{const ee=Q.key==="concessions"?k.concessions+k.repairs:k[Q.key];return ee>0?s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx("i",{className:qt("h-2.5 w-2.5 rounded-full",Q.cls)}),Q.label," ",Kf(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:qt("grid gap-4",o.length===3?"md:grid-cols-3":o.length===2?"md:grid-cols-2":""),children:o.map((Q,ee)=>{var Se,je;const le=E[ee],pe=le.net-P.net;return s.jsxs("div",{role:"button",tabIndex:0,onClick:()=>y(ee),onKeyDown:Le=>Le.key==="Enter"&&y(ee),className:qt("relative cursor-pointer rounded-3xl border bg-card p-5 text-left transition-all",ee===p?"border-primary ring-2 ring-primary/30 shadow-md":"hover:border-primary/40"),children:[D&&ee===M&&E.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(Nie,{value:le.price,className:"font-medium text-foreground"})]}),s.jsx("p",{className:"mt-3 text-3xl font-semibold tracking-tight text-foreground",children:s.jsx(Nie,{value:le.net})}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"estimated net"}),ee!==Math.min(1,E.length-1)&&E.length>1&&s.jsxs("p",{className:qt("mt-2 inline-flex items-center gap-1 text-xs font-medium",pe>=0?"text-primary":"text-destructive"),children:[s.jsx(Nx,{className:qt("h-3.5 w-3.5",pe<0&&"rotate-180")}),pe>=0?"+":"−",Kf(Math.abs(pe))," 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===p&&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(w1,{min:Math.round((((Se=t.scenarios[ee])==null?void 0:Se.price)||le.price)*.8/1e3)*1e3,max:Math.round((((je=t.scenarios[ee])==null?void 0:je.price)||le.price)*1.2/1e3)*1e3||1e5,step:1e3,value:[Q.price],onValueChange:([Le])=>B(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(Br,{inputMode:"numeric",value:Q.price||"",onChange:Le=>B(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(Br,{inputMode:"numeric",value:Q.concessions||"",placeholder:"0",onChange:Le=>B(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(Br,{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(Br,{inputMode:"decimal",value:a.listingCommissionPct+a.buyerCommissionPct,onChange:Q=>{const ee=Number(Q.target.value)||0,le=a.listingCommissionPct+a.buyerCommissionPct||1;f({...a,listingCommissionPct:+(ee*a.listingCommissionPct/le).toFixed(3),buyerCommissionPct:+(ee*a.buyerCommissionPct/le).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(Bt,{variant:"ghost",size:"sm",onClick:V,children:[s.jsx(iMe,{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(Bt,{variant:"outline",size:"sm",className:"print:hidden",onClick:()=>window.print(),children:[s.jsx(eMe,{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:qt("px-5 py-3 text-right font-medium",ee===p&&"text-primary"),children:Q.label},Q.id))]})}),s.jsxs("tbody",{children:[W.filter(Q=>!Q.hide).map(Q=>s.jsxs("tr",{className:"border-t",children:[s.jsx("td",{className:qt("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:()=>T(ee=>!ee),children:[Q.label,s.jsx(yl,{className:qt("h-3.5 w-3.5 transition-transform",v&&"rotate-180")})]}):Q.label}),E.map((ee,le)=>s.jsx("td",{className:qt("px-5 py-2.5 text-right tabular-nums",Q.sub?"text-muted-foreground":"font-medium text-foreground"),children:Q.get(ee)<0?`−${Kf(-Q.get(ee),!0)}`:Kf(Q.get(ee),!0)},le))]},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}),E.map((le,pe)=>s.jsxs("td",{className:"px-5 py-1.5 text-right tabular-nums text-muted-foreground",children:["−",Kf(ee.amount,!0)]},pe))]},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"}),E.map((Q,ee)=>s.jsx("td",{className:"px-5 py-4 text-right text-lg font-semibold tabular-nums text-primary",children:Kf(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 Fnt({dealId:t}){const{data:e}=mr({queryKey:["portal-net-sheet",t],queryFn:async()=>{const{data:n,error:i}=await Re.rpc("get_portal_net_sheet",{_deal_id:t});if(i)throw i;return n??null}}),{data:r}=TYe(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(Ont,{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 Bnt({dealData:t,agentProfile:e,welcomeMessage:r,isWon:n,branding:i}){var p;const o=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,c=(i==null?void 0:i.logo_url)||null,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(fr.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(fr.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:((p=e.name)==null?void 0:p.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(fr.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(va,{className:"w-3 h-3"}),(t==null?void 0:t.deal_type)==="listing"?"Sale":(t==null?void 0:t.deal_type)==="buy-side"?"Purchase":"Transaction",n&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"opacity-50",children:"·"}),"Complete"]})]}),s.jsx("h1",{className:"portal-serif text-[2.5rem] leading-[1.05] mb-3",style:{color:"var(--portal-hero-ink)"},children:(t==null?void 0:t.deal_name)||"Your Transaction"}),s.jsx("div",{className:"portal-hairline w-24 mx-auto mb-4"}),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(Es,{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(ri,{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(mi,{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(J1,{className:"w-4 h-4"}),s.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function Hwe({targetCloseDate:t,actualCloseDate:e,clientName:r}){if(e||!t)return null;const n=t.split(/[-/T]/),i=new Date(Number(n[0]),Number(n[1])-1,Number(n[2])),c=vHe(i,new Date);if(dS(i)&&!lh(i))return null;const a=lh(i),f=a?"0":String(Math.max(0,c)),p=Math.max(4,Math.min(100,(60-Math.min(60,c))/60*100));return s.jsxs("div",{className:"portal-tile p-8 text-center",children:[s.jsx("p",{className:"portal-eyebrow mb-4",children:a?"The Moment Has Arrived":"Countdown to Closing"}),a?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(fr.span,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6},className:"portal-serif tabular-nums leading-none",style:{fontSize:"5.5rem",color:"hsl(var(--portal-gold))",textShadow:"0 0 40px hsl(var(--portal-gold) / 0.4)"},children:f}),s.jsx("span",{className:"portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink-muted))"},children:c===1?"day":"days"})]}),s.jsx("div",{className:"portal-hairline w-16 mx-auto my-4"}),s.jsx("p",{className:"text-xs tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-muted))"},children:"Until you hold the keys"}),s.jsx("div",{className:"mt-6 mx-auto max-w-[260px]",children:s.jsx("div",{className:"h-[2px] rounded-full overflow-hidden",style:{background:"hsl(var(--portal-gold) / 0.15)"},children:s.jsx(fr.div,{initial:{width:0},animate:{width:`${p}%`},transition:{duration:1.2,ease:"easeOut"},className:"h-full rounded-full",style:{background:"var(--portal-gradient-gold)",boxShadow:"0 0 12px hsl(var(--portal-gold) / 0.6)"}})})})]})]})}function D9t(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 $nt(t,e){return te.has(r.id))}function O9t(t){return t.reduce((e,r)=>e+r.file_size,0)>25*1024*1024?"Choose documents totaling no more than 25 MB.":null}const znt={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 Wwe({journeyStages:t,currentIndex:e}){const[r,n]=C.useState(e);return C.useEffect(()=>n(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:"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((i,o)=>{const c=$nt(o,e),a=r===o,f=znt[i.key];return s.jsxs("li",{className:"portal-roadmap-step","data-status":c,children:[s.jsxs(Bt,{variant:"ghost",className:"portal-roadmap-trigger h-auto w-full justify-start gap-3 whitespace-normal py-3 text-left","aria-expanded":a,"aria-current":c==="current"?"step":void 0,onClick:()=>n(a?null:o),children:[s.jsx("span",{className:"portal-roadmap-marker flex h-8 w-8 shrink-0 items-center justify-center rounded-full",children:c==="completed"?s.jsx(no,{className:"h-4 w-4"}):o+1}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"portal-serif block text-lg",children:i.label}),s.jsx("span",{className:"block text-xs font-normal",children:c==="current"?"You are here":c==="completed"?"Completed":"Ahead of you"})]}),a?s.jsx(ume,{className:"h-4 w-4 shrink-0"}):s.jsx(yl,{className:"h-4 w-4 shrink-0"})]}),a&&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:i.description}),f&&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:f.expect})]}),s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow mb-1",children:"Your next move"}),s.jsx("p",{children:f.action})]})]})]})]},i.key)})})]}):null}function Kwe({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 gS(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 F9t(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 Unt(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})).sort((e,r)=>e.date.localeCompare(r.date)):[]}function Vnt(t){return Unt(t).filter(e=>e.show_in_portal)}function B9t(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 qnt=[{key:"contract_date",label:"Contract Accepted",icon:DU},{key:"earnest_money_due_date",label:"Earnest Money",icon:$p},{key:"inspection_date",label:"Inspection",icon:xd},{key:"inspection_contingency_date",label:"Inspection Deadline",icon:_m},{key:"appraisal_date",label:"Appraisal",icon:va},{key:"loan_approval_date",label:"Loan Approval",icon:YO},{key:"title_docs_due_date",label:"Title & Disclosures",icon:_m},{key:"final_walkthrough_date",label:"Final Walkthrough",icon:ODe},{key:"target_close_date",label:"Target Close",icon:oo}];function Gnt(t,e){const r=Ri(e,"yyyyMMdd");return`https://calendar.google.com/calendar/render?${new URLSearchParams({action:"TEMPLATE",text:t,dates:`${r}/${r}`,details:"Added from your Client Portal"}).toString()}`}function Hnt(t,e){const r=Ri(e,"yyyyMMdd");return`data:text/calendar;charset=utf-8,${encodeURIComponent(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:${r} DTEND;VALUE=DATE:${r} SUMMARY:${t} DESCRIPTION:Added from your Client Portal END:VEVENT END:VCALENDAR`)}`}function Ywe({deal:t,portal:e,targetCloseDate:r,contractDate:n,inspectionDate:i,appraisalDate:o,actualCloseDate:c}){const a={...t||{},contract_date:(t==null?void 0:t.contract_date)??n??null,inspection_date:(t==null?void 0:t.inspection_date)??(e==null?void 0:e.inspection_date)??i??null,appraisal_date:(t==null?void 0:t.appraisal_date)??(e==null?void 0:e.appraisal_date)??o??null,target_close_date:(t==null?void 0:t.target_close_date)??r??null},f=(t==null?void 0:t.actual_close_date)??c??null,p=Array.isArray(t==null?void 0:t.completed_key_dates)?t.completed_key_dates:[],y=qnt.map(P=>P.key==="target_close_date"&&f?{...P,label:"Closed",date:f,done:!0}:{...P,date:a[P.key],done:p.includes(P.key)}).filter(P=>!!P.date),v=y.findIndex(P=>P.key==="target_close_date"),T=Vnt(t==null?void 0:t.custom_key_dates).map(P=>({key:`custom-${P.id}`,label:P.label,icon:RDe,date:P.date,done:!!P.done}));if(T.length){const P=v>=0?y.splice(v,1):[];y.push(...T),y.sort((R,D)=>(R.date||"").localeCompare(D.date||"")),y.push(...P)}if(y.length===0)return null;const E=(P,R,D)=>{const M=gS(R);if(D==="google")window.open(Gnt(P,M),"_blank");else{const B=Hnt(P,M),V=document.createElement("a");V.href=B,V.download=`${P.replace(/\s+/g,"-").toLowerCase()}.ics`,V.click()}},k=y.filter(P=>P.done).length;return s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"Milestones"}),s.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-5 flex-wrap",children:[s.jsx("h2",{className:"portal-serif text-2xl",style:{color:"hsl(var(--portal-ink))"},children:"Key dates"}),s.jsxs("span",{className:"text-[11px] tracking-[0.18em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[k," of ",y.length," complete"]})]}),s.jsxs("div",{className:"space-y-4 relative",children:[s.jsx("div",{className:"absolute left-[10px] top-2 bottom-2 w-[1px]",style:{background:"hsl(var(--portal-gold) / 0.18)"}}),y.map(({label:P,date:R,done:D,icon:M})=>{const B=gS(R),V=dS(B)&&!lh(B),G=lh(B),W=!V&&!G,Y=D?"Completed":G?"Today":V?"In progress":"Upcoming";return s.jsxs("div",{className:"flex items-start gap-3 relative",children:[s.jsx("div",{className:"w-[21px] h-[21px] rounded-full mt-0.5 flex-shrink-0 relative z-10 flex items-center justify-center",style:{background:D?"hsl(var(--portal-gold))":G?"hsl(var(--portal-gold) / 0.25)":"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.7)",boxShadow:G?"0 0 12px hsl(var(--portal-gold) / 0.5)":"none"},children:D?s.jsx(no,{className:"w-3 h-3",style:{color:"hsl(var(--portal-surface))"}}):s.jsx(M,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:P}),s.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.15rem",color:D?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:Ri(B,"MMM d, yyyy")}),s.jsx("span",{className:"inline-block mt-1 text-[9px] tracking-[0.2em] uppercase px-2 py-0.5 rounded-full",style:{color:D||G?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-dim))",border:`1px solid hsl(var(--portal-gold) / ${D||G?.5:.18})`},children:Y})]}),W&&s.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[s.jsx("button",{onClick:()=>E(P,R,"google"),className:"p-1.5 rounded transition-colors",style:{color:"hsl(var(--portal-ink-dim))"},onMouseEnter:J=>{J.currentTarget.style.color="hsl(var(--portal-gold))"},onMouseLeave:J=>{J.currentTarget.style.color="hsl(var(--portal-ink-dim))"},title:"Add to Google Calendar",children:s.jsx(cme,{className:"w-3.5 h-3.5"})}),s.jsx("button",{onClick:()=>E(P,R,"apple"),className:"text-[9px] tracking-widest px-1.5 py-1 rounded",style:{color:"hsl(var(--portal-ink-dim))"},title:"Download .ics",children:".ICS"})]})]},P)})]})]})}function Zwe({documents:t}){const e=n=>n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`,r=async n=>{const{data:i}=await Re.storage.from("deal-files").createSignedUrl(n.storage_path,300);i!=null&&i.signedUrl&&window.open(i.signedUrl,"_blank")};return s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"Paperwork"}),s.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents"}),s.jsx("div",{className:"space-y-2",children:t.map(n=>s.jsxs("button",{onClick:()=>r(n),className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left group",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},onMouseEnter:i=>{i.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.35)"},onMouseLeave:i=>{i.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.08)"},children:[s.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:s.jsx(_m,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:n.file_name}),s.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:e(n.file_size)})]}),s.jsx(sc,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},n.id))})]})}function Xwe({slug:t,wrapper:e}){const r=Hs(),[n,i]=C.useState(null),{data:o=[]}=mr({queryKey:["portal-signature-requests",t],enabled:!!t,queryFn:async()=>{const{data:y,error:v}=await Re.functions.invoke("forms-portal-public",{body:{action:"list",slug:t}});return v?[]:(y==null?void 0:y.envelopes)||[]}}),c=o.filter(y=>y.my_turn),a=o.filter(y=>!y.my_turn&&y.status!=="completed");if(!c.length&&!a.length)return null;const f=async y=>{i(y);try{const{data:v,error:T}=await Re.functions.invoke("forms-portal-public",{body:{action:"sign_link",slug:t,envelope_id:y}});if(T||v!=null&&v.error)throw new Error((v==null?void 0:v.error)||"Could not open the document");r(v.path)}catch(v){Vt.error((v==null?void 0:v.message)||"Could not open the document")}finally{i(null)}},p=s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"Needs you"}),s.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents to sign"}),s.jsxs("div",{className:"space-y-2",children:[c.map(y=>s.jsxs("button",{onClick:()=>f(y.id),disabled:n===y.id,className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left",style:{background:"hsl(var(--portal-gold) / 0.1)",border:"1px solid hsl(var(--portal-gold) / 0.4)"},children:[s.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.14)",border:"1px solid hsl(var(--portal-gold) / 0.3)"},children:n===y.id?s.jsx(su,{className:"w-4 h-4 animate-spin",style:{color:"hsl(var(--portal-gold))"}}):s.jsx(KDe,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:y.title}),s.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-gold))"},children:"Tap to review & sign"})]})]},y.id)),a.map(y=>s.jsxs("div",{className:"w-full flex items-center gap-3 p-3 rounded-xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},children:[s.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.06)"},children:y.my_status==="signed"?s.jsx(oc,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}}):s.jsx(Dl,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink-muted))",fontSize:"1rem"},children:y.title}),s.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:y.my_status==="signed"?"You signed — waiting on others":"Waiting on another signer"})]})]},y.id))]})]});return e?e(p):p}function Qwe({updates:t}){const e=r=>{var n,i;if(r.includes("youtube.com/watch")){const o=new URL(r).searchParams.get("v");return o?`https://www.youtube.com/embed/${o}`:null}if(r.includes("youtu.be/")){const o=(n=r.split("youtu.be/")[1])==null?void 0:n.split("?")[0];return o?`https://www.youtube.com/embed/${o}`:null}if(r.includes("loom.com/share/")){const o=(i=r.split("loom.com/share/")[1])==null?void 0:i.split("?")[0];return o?`https://www.loom.com/embed/${o}`:null}return r};return s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"Dispatch"}),s.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Updates from your agent"}),s.jsx("div",{className:"space-y-6",children:t.map((r,n)=>s.jsx("div",{className:n>0?"pt-6":"",style:n>0?{borderTop:"1px solid hsl(var(--portal-gold) / 0.1)"}:void 0,children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5",style:{background:r.is_stage_change?"hsl(var(--portal-gold) / 0.15)":"hsl(var(--portal-surface-3))",border:"1px solid hsl(var(--portal-gold) / 0.25)"},children:r.is_stage_change?s.jsx(SDe,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):s.jsx(bC,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[s.jsx("h3",{className:"portal-serif",style:{fontSize:n===0?"1.4rem":"1.15rem",color:"hsl(var(--portal-ink))"},children:r.title}),s.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase flex-shrink-0",style:{color:"hsl(var(--portal-ink-dim))"},children:Ri(new Date(r.created_at),"MMM d")})]}),r.content&&s.jsx("p",{className:`text-sm mt-2 leading-relaxed ${n===0?"italic portal-serif":""}`,style:{color:"hsl(var(--portal-ink-muted))",fontSize:n===0?"1rem":"0.875rem"},children:n===0?`“${r.content}”`:r.content}),r.video_url&&s.jsx("div",{className:"mt-3 rounded-xl overflow-hidden aspect-video",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:s.jsx("iframe",{src:e(r.video_url)||r.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:r.title})})]})]})},r.id))})]})}const Wnt=[{value:"lender",label:"Lender"},{value:"inspector",label:"Inspector"},{value:"title_escrow",label:"Title / Escrow"},{value:"insurance",label:"Insurance"},{value:"home_warranty",label:"Home Warranty"},{value:"movers",label:"Movers"},{value:"cleaners",label:"Cleaners"},{value:"handyman",label:"Handyman"},{value:"painter",label:"Painter"},{value:"landscaper",label:"Landscaper"},{value:"photographer",label:"Photographer"},{value:"stager",label:"Stager"},{value:"contractor",label:"Contractor"},{value:"electrician",label:"Electrician"},{value:"plumber",label:"Plumber"},{value:"hvac",label:"HVAC"},{value:"roofer",label:"Roofer"},{value:"pest_control",label:"Pest Control"},{value:"attorney",label:"Attorney"},{value:"accountant",label:"Accountant"},{value:"other",label:"Other"}];function Iie(t){var r,n;const e=(r=t.custom_category)==null?void 0:r.trim();return e||((n=Wnt.find(i=>i.value===t.category))==null?void 0:n.label)||t.category}function Pie(t){var r;const e=(r=t.custom_category)==null?void 0:r.trim();return e?`custom:${e.toLowerCase()}`:t.category}const $9t=[{value:"book",label:"Book Now (link)"},{value:"quote",label:"Request Quote (email)"},{value:"call",label:"Call"},{value:"email",label:"Email"},{value:"website",label:"Visit Website"}];function z9t(t){return mr({queryKey:["vendors","brokerage",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Re.from("vendors").select("*").eq("owner_type","brokerage").eq("owner_brokerage_id",t).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(r)throw r;return e||[]},enabled:!!t})}function U9t(){const t=Li(),{brokerageId:e}=Hn();return mr({queryKey:["vendors","library",t,e],queryFn:async()=>{if(!t)return{vendors:[],selections:[]};let r=Re.from("vendors").select("*");e?r=r.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${e})`):r=r.eq("owner_type","agent").eq("owner_user_id",t);const[{data:n,error:i},{data:o,error:c}]=await Promise.all([r.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),Re.from("agent_vendor_selections").select("*").eq("agent_user_id",t)]);if(i)throw i;if(c)throw c;return{vendors:n||[],selections:o||[]}},enabled:!!t})}function V9t(){const t=Ar();return Sr({mutationFn:async e=>{if(e.id){const{id:r,created_at:n,...i}=e,{data:o,error:c}=await Re.from("vendors").update(i).eq("id",r).select().single();if(c)throw c;return o}else{const{data:r,error:n}=await Re.from("vendors").insert(e).select().single();if(n)throw n;return r}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function q9t(){const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("vendors").delete().eq("id",e);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function G9t(){const t=Li(),e=Ar();return Sr({mutationFn:async({vendorId:r,isVisible:n})=>{if(!t)throw new Error("No user");const{data:i}=await Re.from("agent_vendor_selections").select("id").eq("agent_user_id",t).eq("vendor_id",r).maybeSingle();if(i){const{error:o}=await Re.from("agent_vendor_selections").update({is_visible:n}).eq("id",i.id);if(o)throw o}else{const{error:o}=await Re.from("agent_vendor_selections").insert({agent_user_id:t,vendor_id:r,is_visible:n});if(o)throw o}},onSuccess:()=>e.invalidateQueries({queryKey:["vendors"]})})}function Jwe(t){return mr({queryKey:["portal-vendors",t==null?void 0:t.id,t==null?void 0:t.owner_user_id],queryFn:async()=>{if(!(t!=null&&t.id)||!(t!=null&&t.owner_user_id))return[];const e=t.owner_user_id,{data:r}=await Re.from("profiles").select("brokerage_id").eq("id",e).maybeSingle(),n=r==null?void 0:r.brokerage_id,i=Re.from("vendors").select("*").eq("is_active",!0),o=n?i.or(`and(owner_type.eq.agent,owner_user_id.eq.${e}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${n})`):i.eq("owner_type","agent").eq("owner_user_id",e),[{data:c,error:a},{data:f},{data:p}]=await Promise.all([o.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),Re.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",e),Re.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",t.id)]);if(a)throw a;const y=new Map;(f||[]).forEach(E=>y.set(E.vendor_id,{display_order:E.display_order,is_visible:E.is_visible}));const v=new Map;return(p||[]).forEach(E=>v.set(E.vendor_id,E.is_visible)),(c||[]).filter(E=>{if(v.get(E.id)===!1)return!1;const k=y.get(E.id);return!(k&&k.is_visible===!1&&!E.is_required)}).map(E=>{var k;return{...E,display_order:((k=y.get(E.id))==null?void 0:k.display_order)??E.sort_order??0}}).sort((E,k)=>(E.display_order||0)-(k.display_order||0))},enabled:!!(t!=null&&t.id)&&!!(t!=null&&t.owner_user_id)})}async function Rie(t){try{await Re.from("vendor_clicks").insert({vendor_id:t.vendorId,portal_id:t.portalId||null,agent_user_id:t.agentUserId||null,action_taken:t.actionTaken||null,user_agent:typeof navigator<"u"?navigator.userAgent.slice(0,500):null})}catch(e){console.warn("vendor click track failed",e)}}function H9t(t,e){return mr({queryKey:["vendor-clicks",t,e],queryFn:async()=>{if(!e)return{};const{data:r}=await Re.from("vendors").select("id").eq(t==="agent"?"owner_user_id":"owner_brokerage_id",e).eq("owner_type",t),n=(r||[]).map(c=>c.id);if(n.length===0)return{};const{data:i}=await Re.from("vendor_clicks").select("vendor_id").in("vendor_id",n),o={};return(i||[]).forEach(c=>{o[c.vendor_id]=(o[c.vendor_id]||0)+1}),o},enabled:!!e})}function e1e({portalId:t,ownerUserId:e,currentStage:r,brandingColor:n,layout:i="list"}){const{data:o=[],isLoading:c}=Jwe({id:t,owner_user_id:e});if(c||o.length===0)return null;const a=o.filter(D=>!D.stage_filter||D.stage_filter.length===0||!r?!0:D.stage_filter.includes(r));if(a.length===0)return null;const f=n||"#406E71",p=(D,M)=>{switch(M){case"book":return D.booking_url;case"website":return D.website;case"call":return D.phone?`tel:${D.phone.replace(/[^\d+]/g,"")}`:null;case"email":case"quote":return D.email?`mailto:${D.email}`:null}},y=D=>{const M=p(D,D.action_type);Rie({vendorId:D.id,portalId:t,agentUserId:e,actionTaken:D.action_type}),M&&window.open(M,D.action_type==="call"||D.action_type==="email"||D.action_type==="quote"?"_self":"_blank")},v=D=>{const M=p(D,D.action_type);return[{action:"website",label:"Website",icon:s.jsx(qv,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:s.jsx(mi,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:s.jsx(ri,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:s.jsx(oo,{className:"w-3.5 h-3.5"})}].filter(V=>V.action!==D.action_type).map(V=>{const G=p(D,V.action);return!G||G===M?null:s.jsxs("button",{onClick:()=>{Rie({vendorId:D.id,portalId:t,agentUserId:e,actionTaken:V.action}),window.open(G,V.action==="call"||V.action==="email"?"_self":"_blank")},className:"inline-flex items-center gap-1 text-slate-500 hover:text-slate-700 hover:underline",title:V.label,children:[V.icon,s.jsx("span",{className:"text-xs",children:V.label})]},V.action)}).filter(Boolean)},T=D=>{switch(D.action_type){case"book":return"Book Now";case"quote":return"Request Quote";case"call":return"Call";case"email":return"Email";case"website":return"Visit Site"}},E=D=>{switch(D.action_type){case"book":return s.jsx(oo,{className:"w-3.5 h-3.5"});case"call":return s.jsx(ri,{className:"w-3.5 h-3.5"});case"email":case"quote":return s.jsx(mi,{className:"w-3.5 h-3.5"});case"website":return s.jsx(qv,{className:"w-3.5 h-3.5"})}},k=s.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[s.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center",style:{backgroundColor:`${f}15`,color:f},children:s.jsx(xs,{className:"w-4 h-4"})}),s.jsxs("div",{children:[s.jsx("h2",{className:"font-semibold text-slate-800",children:"Trusted Partners"}),s.jsx("p",{className:"text-xs text-slate-500",children:"My personally-vetted recommendations for you"})]})]}),P=a.some(D=>D.disclosure_text)&&s.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:a.filter(D=>D.disclosure_text).map(D=>s.jsxs("p",{className:"text-[10px] text-slate-400",children:[s.jsxs("span",{className:"font-medium",children:[D.company||D.name,":"]})," ",D.disclosure_text]},D.id))});if(i==="grid")return s.jsxs($n,{className:"p-5 sm:p-6 rounded-2xl border-slate-200/80 shadow-sm bg-white/70 backdrop-blur",children:[k,s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:a.map(D=>s.jsxs("div",{className:"group flex flex-col p-4 rounded-xl border border-slate-200/70 bg-white hover:shadow-md hover:-translate-y-0.5 transition-all",children:[s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"w-12 h-12 rounded-lg bg-slate-50 border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:D.logo_url?s.jsx("img",{src:D.logo_url,alt:D.name,className:"w-full h-full object-cover"}):s.jsx("span",{className:"text-base font-semibold text-slate-500",children:(D.company||D.name).charAt(0)})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"font-semibold text-sm text-slate-800 truncate",children:D.company||D.name}),D.company&&D.name&&s.jsx("p",{className:"text-xs text-slate-500 truncate",children:D.name}),s.jsx("span",{className:"inline-block mt-1 text-[10px] font-medium px-1.5 py-0.5 rounded",style:{backgroundColor:`${f}12`,color:f},children:Iie(D)})]})]}),D.description&&s.jsx("p",{className:"text-xs text-slate-500 mt-3 line-clamp-2",children:D.description}),s.jsxs("div",{className:"mt-auto pt-4 flex flex-col gap-2",children:[s.jsxs(Bt,{size:"sm",onClick:()=>y(D),style:{backgroundColor:f},className:"text-white hover:opacity-90 w-full",children:[E(D),s.jsx("span",{className:"ml-1.5 text-xs",children:T(D)})]}),v(D).length>0&&s.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:v(D)})]})]},D.id))}),P]});const R=a.reduce((D,M)=>((D[Pie(M)]=D[Pie(M)]||[]).push(M),D),{});return s.jsxs($n,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[k,s.jsx("div",{className:"space-y-4",children:Object.entries(R).map(([D,M])=>s.jsxs("div",{children:[s.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:Iie(M[0])}),s.jsx("div",{className:"space-y-2",children:M.map(B=>s.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-slate-50 hover:bg-slate-100 transition-colors",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-white border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:B.logo_url?s.jsx("img",{src:B.logo_url,alt:B.name,className:"w-full h-full object-cover"}):s.jsx("span",{className:"text-sm font-semibold text-slate-500",children:B.name.charAt(0)})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"font-medium text-sm text-slate-800 truncate",children:B.company||B.name}),B.company&&B.name&&s.jsx("p",{className:"text-xs text-slate-500 truncate",children:B.name}),B.description&&s.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:B.description})]}),s.jsxs(Bt,{size:"sm",onClick:()=>y(B),style:{backgroundColor:f},className:"text-white hover:opacity-90 shrink-0",children:[E(B),s.jsx("span",{className:"ml-1.5 text-xs",children:T(B)})]})]},B.id))})]},D))}),P]})}function Knt(t){const e=window.location.hostname;return e==="localhost"||e.includes("lovable.app")?`${window.location.origin}/portal/${t}/refer`:`https://clients.relevelup.com/${t}/refer`}function Ynt(t){if(!t)return null;const e=t.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([\w-]+)/);if(e)return`https://www.youtube.com/embed/${e[1]}`;const r=t.match(/loom\.com\/share\/([\w-]+)/);return r?`https://www.loom.com/embed/${r[1]}`:(t.match(/\.(mp4|webm|mov)(\?|$)/i),t)}function t1e({portalId:t,portalSlug:e,ownerUserId:r,rewardText:n,ctaHeadline:i,agentName:o,clientName:c,reviewUrl:a,hubVideoUrl:f}){const[p,y]=C.useState(!1),v=C.useRef(!1),T=Knt(e);C.useEffect(()=>{v.current||(v.current=!0,Re.from("portal_referral_clicks").insert({portal_id:t,owner_user_id:r,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[t,r]);const E=async W=>{await Re.from("portal_referral_clicks").insert({portal_id:t,owner_user_id:r,click_type:W,user_agent:navigator.userAgent.slice(0,500)})},k=()=>`${c?`Hey, it's ${c}!`:"Hey!"} I just had an amazing experience working with ${o||"my real estate agent"} on my home. If you or someone you know is thinking about buying or selling, here's their referral link: ${T}`,P=async()=>{await navigator.clipboard.writeText(T),y(!0),E("copy_link"),setTimeout(()=>y(!1),2e3)},R=()=>{E("share_sms");const W=encodeURIComponent(k());window.location.href=`sms:?&body=${W}`},D=()=>{E("share_email");const W=encodeURIComponent("A referral you'll thank me for"),Y=encodeURIComponent(k());window.location.href=`mailto:?subject=${W}&body=${Y}`},M=()=>{E("open_form"),window.open(T,"_blank")},B=i||"Know someone buying or selling?",V=f?Ynt(f):null,G=V==null?void 0:V.match(/\.(mp4|webm|mov)(\?|$)/i);return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"bg-gradient-to-br from-emerald-50 via-teal-50 to-cyan-50 rounded-2xl p-6 border border-emerald-100 text-center",children:[s.jsx("div",{className:"text-5xl mb-2",children:"🎉"}),s.jsxs("h3",{className:"text-xl font-bold text-emerald-900 mb-1 font-serif",children:["Welcome Home",c?`, ${c.split(" ")[0]}`:"","!"]}),s.jsx("p",{className:"text-sm text-emerald-700/80",children:"Your transaction is complete. We're so proud to have been part of your journey."})]}),V&&s.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden",children:[s.jsx("div",{className:"px-4 pt-4 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(xs,{className:"w-4 h-4 text-[#406E71]"}),s.jsxs("p",{className:"text-sm font-medium text-slate-700",children:["A message from ",o||"your agent"]})]})}),s.jsx("div",{className:"aspect-video bg-slate-900",children:G?s.jsx("video",{src:V,controls:!0,className:"w-full h-full",playsInline:!0}):s.jsx("iframe",{src:V,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}),s.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white shadow-xl",children:[s.jsx("div",{className:"absolute inset-0 opacity-[0.07]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"20px 20px"}}),s.jsxs("div",{className:"relative p-6",children:[s.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/15 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium mb-3",children:[s.jsx(hf,{className:"w-3 h-3"}),"Referral Program"]}),s.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:B}),n&&s.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[s.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",n]}),s.jsxs("p",{className:"text-sm text-white/70 mb-5 leading-relaxed",children:["The biggest compliment you can give ",o||"us"," is sending a friend or family member."]}),s.jsxs("button",{onClick:M,className:"w-full bg-white text-[#2a4c64] font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 shadow-md hover:bg-white/95 active:scale-[0.99] transition-all",children:["Refer a Friend",s.jsx(Ds,{className:"w-4 h-4"})]}),s.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[s.jsxs("button",{onClick:R,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[s.jsx(J1,{className:"w-3.5 h-3.5"}),"Text"]}),s.jsxs("button",{onClick:D,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[s.jsx(mi,{className:"w-3.5 h-3.5"}),"Email"]}),s.jsxs("button",{onClick:P,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[p?s.jsx(no,{className:"w-3.5 h-3.5"}):s.jsx(MU,{className:"w-3.5 h-3.5"}),p?"Copied":"Copy"]})]})]})]}),a&&s.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",onClick:()=>E("review_click"),className:"block bg-white border border-slate-200 hover:border-amber-300 hover:bg-amber-50/30 rounded-2xl p-4 transition-colors",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"text-2xl",children:"⭐"}),s.jsxs("div",{className:"flex-1",children:[s.jsx("p",{className:"text-sm font-semibold text-slate-800",children:"Loved working together?"}),s.jsx("p",{className:"text-xs text-slate-500",children:"Leave a quick review — it means the world."})]}),s.jsx(Ds,{className:"w-4 h-4 text-slate-400"})]})})]})}function Znt(t){return mr({queryKey:["portal-messages",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("portal_messages").select("*").eq("portal_id",t).order("created_at",{ascending:!0});if(r)throw r;return e||[]},enabled:!!t,refetchInterval:3e4})}function Xnt(){const t=Ar();return Sr({mutationFn:async({portalId:e,senderType:r,senderName:n,body:i,deviceFingerprint:o,portalUrl:c})=>{const{data:a,error:f}=await Re.from("portal_messages").insert({portal_id:e,sender_type:r,sender_name:n||null,body:i.trim(),device_fingerprint:o||null,...r==="agent"?{read_at:new Date().toISOString()}:{}}).select().single();if(f)throw f;try{await Re.functions.invoke("portal-message-notify",{body:{message_id:a.id,portal_url:c}})}catch(p){console.error("portal-message-notify failed",p)}return a},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["portal-messages",r.portalId]}),t.invalidateQueries({queryKey:["portal-unread-messages"]}),t.invalidateQueries({queryKey:["portal-conversations"]})}})}function W9t(){const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("portal_messages").update({read_at:new Date().toISOString()}).eq("portal_id",e).eq("sender_type","client").is("read_at",null);if(r)throw r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["portal-messages",r]}),t.invalidateQueries({queryKey:["portal-unread-messages"]}),t.invalidateQueries({queryKey:["portal-conversations"]})}})}function K9t(){const t=Li();return mr({queryKey:["portal-conversations",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("client_portals").select("id, slug, client_name, client_email, archived_at").eq("owner_user_id",t).is("archived_at",null);if(r)throw r;if(!e||e.length===0)return[];const n=e.map(f=>f.id),i=[],o=100,c=1e3;for(let f=0;f{const p=a.get(f.id)||[];return{portalId:f.id,slug:f.slug,clientName:f.client_name,clientEmail:f.client_email,lastMessage:p.length?p[p.length-1]:null,unreadCount:p.filter(y=>y.sender_type==="client"&&!y.read_at).length,messageCount:p.length}}).sort((f,p)=>{var T,E;const y=((T=f.lastMessage)==null?void 0:T.created_at)||"",v=((E=p.lastMessage)==null?void 0:E.created_at)||"";return y===v?(f.clientName||"").localeCompare(p.clientName||""):v.localeCompare(y)})},enabled:!!t,refetchInterval:3e4})}function r1e({portalId:t,clientName:e,agentName:r,agentAvatar:n,deviceFingerprint:i}){const{data:o,isLoading:c}=Znt(t),a=Xnt(),[f,p]=C.useState(""),y=`portal_msg_name_${t}`,[v,T]=C.useState(()=>localStorage.getItem(y)||e||""),E=C.useRef(null);C.useEffect(()=>{var R;(R=E.current)==null||R.scrollIntoView({block:"nearest"})},[o==null?void 0:o.length]);const k=async()=>{const R=f.trim();if(!R)return;const D=(v||e||"").trim();if(!D){Vt.error("Please add your name first");return}try{localStorage.setItem(y,D),await a.mutateAsync({portalId:t,senderType:"client",senderName:D,body:R,deviceFingerprint:i,portalUrl:window.location.href}),p(""),Vt.success("Message sent")}catch(M){Vt.error((M==null?void 0:M.message)||"Could not send your message")}},P="hsl(var(--portal-gold))";return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[s.jsx(fh,{className:"w-4 h-4",style:{color:P}}),s.jsx("h2",{className:"portal-serif",style:{fontSize:"1.35rem",color:"hsl(var(--portal-ink))"},children:"Messages"})]}),s.jsx("div",{className:"portal-hairline mb-4"}),s.jsxs("div",{className:"space-y-3 max-h-[340px] overflow-y-auto pr-1",children:[c&&s.jsx("div",{className:"flex justify-center py-6",children:s.jsx(su,{className:"w-4 h-4 animate-spin",style:{color:P}})}),!c&&(!o||o.length===0)&&s.jsxs("p",{className:"text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:["Have a question for ",r||"your agent","? Send a message below — they'll be notified right away."]}),o==null?void 0:o.map(R=>{const D=R.sender_type==="agent";return s.jsx("div",{className:`flex ${D?"justify-start":"justify-end"}`,children:s.jsxs("div",{className:"max-w-[85%] rounded-2xl px-4 py-3",style:{background:D?"hsl(var(--portal-surface-2))":"hsl(var(--portal-gold) / 0.12)",border:`1px solid ${D?"hsl(var(--portal-gold) / 0.12)":"hsl(var(--portal-gold) / 0.28)"}`},children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[D&&n&&s.jsx("img",{src:n,alt:r||"Agent",className:"w-5 h-5 rounded-full object-cover"}),s.jsxs("span",{className:"text-[11px] uppercase tracking-[0.14em]",style:{color:"hsl(var(--portal-ink-dim))"},children:[D?r||"Your agent":R.sender_name||"You"," ·"," ",Ri(new Date(R.created_at),"MMM d, h:mm a")]})]}),s.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:R.body})]})},R.id)}),s.jsx("div",{ref:E})]}),s.jsxs("div",{className:"mt-4 space-y-2",children:[!e&&s.jsx("input",{value:v,onChange:R=>T(R.target.value),placeholder:"Your name",className:"w-full rounded-xl px-3 py-2 text-sm outline-none",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.18)",color:"hsl(var(--portal-ink))"}}),s.jsx("textarea",{value:f,onChange:R=>p(R.target.value),rows:3,placeholder:`Write a message to ${r||"your agent"}...`,className:"w-full rounded-xl px-3 py-2 text-sm outline-none resize-none",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.18)",color:"hsl(var(--portal-ink))"}}),s.jsxs("button",{onClick:k,disabled:a.isPending||!f.trim(),className:"w-full flex items-center justify-center gap-2 rounded-xl py-2.5 text-sm font-medium transition-opacity disabled:opacity-50",style:{background:"hsl(var(--portal-gold) / 0.16)",border:"1px solid hsl(var(--portal-gold) / 0.35)",color:P},children:[a.isPending?s.jsx(su,{className:"w-4 h-4 animate-spin"}):s.jsx(kD,{className:"w-4 h-4"}),"Send message"]})]})]})}function Qnt(t){return t==="buy-side"||t==="buyer"?"Home Search in Progress":t==="listing"||t==="seller"||t==="dual"?"Your Home Is On The Market":"Active Phase"}function Jnt(t){return t==="buy-side"||t==="buyer"?"We're actively searching for homes that match your criteria.":t==="listing"||t==="seller"||t==="dual"?"Your property is now being marketed to potential buyers.":"Your transaction is actively moving forward."}const eit={Lead:{label:"Getting Started",description:"We're beginning your home journey and preparing the next steps."},Consultation:{label:"Planning Your Move",description:"We're discussing your goals and building a plan for buying or selling."},"Agreement Signed":{label:"Officially Working Together",description:"We've signed the agreement and are moving forward together."},"Under Contract":{label:"Under Contract",description:"Your offer has been accepted and we are now moving through inspections and due diligence."},Closing:{label:"Final Steps to Closing",description:"We're finalizing documents and preparing for closing day."},"Closed Won":{label:"Closing Day",description:"Congratulations! Your transaction is complete. 🎉"}},n1e=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function i1e(t){return n1e.map(e=>{if(e==="Active")return{key:"Active",label:Qnt(t),description:Jnt(t)};const r=eit[e];return{key:e,label:r.label,description:r.description}})}function pM(t){if(!t)return 0;const e=n1e.indexOf(t);return e>=0?e:0}function tit({portal:t,linkedPortal:e,activePortal:r,activeTab:n,onTabChange:i,agentProfile:o,branding:c,updates:a,documents:f}){var Le,Ae,be;const p=(c==null?void 0:c.cover_photo_url)||null,y=(c==null?void 0:c.logo_url)||null,v=(c==null?void 0:c.tagline)||"Your Real Estate Concierge",T=r==null?void 0:r.deal_pipeline,E=T==null?void 0:T.deal_pipeline_stages,k=E==null?void 0:E.is_won_stage,P=T==null?void 0:T.deal_type,R=r==null?void 0:r.stage_mapping;let D=i1e(P);R&&R.length>0&&(D=R.map((me,Te)=>{var Ne,Ee;return{key:`custom-${Te}`,label:me.label||((Ne=D[Te])==null?void 0:Ne.label)||`Stage ${Te+1}`,description:me.description||((Ee=D[Te])==null?void 0:Ee.description)||"",video_url:me.video_url||void 0}}));const M=R&&R.length>0?Math.min(pM(E==null?void 0:E.name),D.length-1):pM(E==null?void 0:E.name),B=D[M],V=B==null?void 0:B.video_url,G=k&&r.show_post_close_tips!==!1&&r.referral_enabled!==!1,W=T!=null&&T.property_address?`${T.property_address}, ${T.city||""}, ${T.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,Y=!!e,J=(Le=t==null?void 0:t.deal_pipeline)==null?void 0:Le.deal_type,Q=(Ae=e==null?void 0:e.deal_pipeline)==null?void 0:Ae.deal_type,ee=me=>me==="listing"?"Your Sale":me==="buy-side"?"Your Purchase":"Transaction",le=D.length>1?Math.round((M+1)/D.length*100):0,{data:pe=[]}=Jwe({id:r==null?void 0:r.id,owner_user_id:r==null?void 0:r.owner_user_id}),Se=pe.some(me=>!me.stage_filter||me.stage_filter.length===0||!(E!=null&&E.name)?!0:me.stage_filter.includes(E.name)),je=()=>{var me;(me=document.getElementById("trusted-vendors"))==null||me.scrollIntoView({behavior:"smooth",block:"start"})};return s.jsxs("div",{className:"min-h-screen relative",style:{background:"var(--portal-gradient-noir)"},children:[s.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[600px] opacity-70",style:{background:"radial-gradient(ellipse 70% 100% at 50% 0%, hsl(var(--portal-gold) / 0.08), transparent 60%)"}}),s.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-8",children:[s.jsxs(fr.div,{initial:{opacity:0,y:-6},animate:{opacity:1,y:0},transition:{duration:.4},className:"flex items-center justify-between mb-8",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[y?s.jsx("div",{className:"rounded-lg px-3 py-1.5",style:{background:"hsl(0 0% 100% / 0.04)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:s.jsx("img",{src:y,alt:"Brand",className:"h-8 max-w-[140px] object-contain"})}):s.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center portal-serif text-xl",style:{background:"var(--portal-gradient-gold)",color:"hsl(var(--portal-bg))"},children:"✦"}),s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow",children:"Private Client Portal"}),s.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.1rem",color:"hsl(var(--portal-ink))"},children:r!=null&&r.client_name?`Welcome, ${r.client_name.split(" ")[0]}`:"Your transaction"})]})]}),s.jsxs("div",{className:"flex items-center gap-2 text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[s.jsx(KA,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),s.jsxs(fr.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.6,ease:"easeOut"},className:"relative overflow-hidden rounded-3xl mb-8",style:{minHeight:380,border:"1px solid hsl(var(--portal-gold) / 0.25)",boxShadow:"var(--portal-shadow-luxe)"},children:[p?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${p})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter)"}}),s.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-scrim)"}})]}):s.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-fallback)"}}),s.jsx("div",{className:"absolute top-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.6), transparent)"}}),s.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-12",children:[s.jsxs("div",{className:"col-span-2 flex flex-col justify-end",children:[s.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.22em] uppercase mb-6 self-start",style:{background:"hsl(0 0% 0% / 0.28)",backdropFilter:"blur(6px)",border:"1px solid var(--portal-hero-accent)",color:"var(--portal-hero-accent)"},children:[s.jsx(va,{className:"w-3 h-3"}),P==="listing"?"Sale":P==="buy-side"?"Purchase":"Transaction",k&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"opacity-50 mx-1",children:"·"}),"Complete"]})]}),s.jsx("h1",{className:"portal-serif leading-[0.95] mb-4",style:{fontSize:"4.5rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:(T==null?void 0:T.deal_name)||"Your Transaction"}),s.jsx("div",{className:"portal-hairline w-32 mb-5"}),W&&s.jsxs("div",{className:"flex items-center gap-2",style:{color:"var(--portal-hero-ink-muted)",textShadow:"var(--portal-hero-text-shadow)"},children:[s.jsx(Es,{className:"w-4 h-4",style:{color:"var(--portal-hero-accent)"}}),s.jsx("span",{className:"text-base",children:W})]}),(r==null?void 0:r.welcome_message)&&s.jsxs("p",{className:"mt-6 portal-serif italic leading-relaxed max-w-2xl",style:{color:"var(--portal-hero-ink-muted)",fontSize:"1.15rem",textShadow:"var(--portal-hero-text-shadow)"},children:["“",r.welcome_message,"”"]})]}),s.jsxs("div",{className:"flex flex-col items-center justify-center",children:[s.jsx(rit,{pct:le}),s.jsx("p",{className:"portal-eyebrow mt-4",style:{color:"var(--portal-hero-accent)"},children:"Journey Progress"}),s.jsxs("p",{className:"portal-serif mt-1",style:{fontSize:"1.1rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:["Stage ",M+1," of ",D.length]})]})]}),s.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.4), transparent)"}})]}),Y&&s.jsx("div",{className:"inline-flex gap-1 rounded-xl p-1 mb-8",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(me=>{const Te=me==="primary"?J:Q,Ne=n===me;return s.jsx("button",{onClick:()=>i(me),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:Ne?"hsl(var(--portal-surface-3))":"transparent",color:Ne?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:Ne?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:ee(Te)},me)})}),s.jsxs(fr.div,{initial:"hidden",animate:"show",variants:{hidden:{},show:{transition:{staggerChildren:.06}}},className:"grid grid-cols-12 gap-5",children:[s.jsx("aside",{className:"col-span-3 space-y-5",children:s.jsxs("div",{className:"sticky top-6 space-y-5",children:[s.jsxs(Vf,{children:[s.jsxs("div",{className:"text-center pt-2 pb-1",children:[o!=null&&o.avatar_url?s.jsx("div",{className:"w-24 h-24 mx-auto relative",children:s.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:s.jsx("img",{src:o.avatar_url,alt:o.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):s.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.4)",color:"hsl(var(--portal-gold))"},children:((be=o==null?void 0:o.name)==null?void 0:be.charAt(0))||"?"}),s.jsx("h3",{className:"mt-4 portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink))"},children:o==null?void 0:o.name}),s.jsx("div",{className:"portal-hairline w-12 mx-auto my-2"}),s.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:v})]}),s.jsxs("div",{className:"mt-5 space-y-2",children:[(o==null?void 0:o.phone)&&s.jsx(vz,{href:`tel:${o.phone}`,icon:ri,label:"Call",sub:o.phone}),(o==null?void 0:o.phone)&&s.jsx(vz,{href:`sms:${o.phone}`,icon:J1,label:"Text message"}),(o==null?void 0:o.email)&&s.jsx(vz,{href:`mailto:${o.email}`,icon:mi,label:"Email",sub:o.email})]})]}),s.jsxs(Vf,{children:[s.jsx("p",{className:"portal-eyebrow mb-4",children:"At a Glance"}),s.jsxs("div",{className:"space-y-4",children:[(T==null?void 0:T.target_close_date)&&s.jsx(_z,{icon:oo,label:"Target close",value:Lie(T.target_close_date)}),(T==null?void 0:T.contract_date)&&s.jsx(_z,{icon:Dl,label:"Under contract",value:Lie(T.contract_date)}),s.jsx(_z,{icon:yl,label:"Progress",value:`${le}%`})]})]})]})}),s.jsxs("main",{className:"col-span-6 space-y-5",children:[G&&s.jsx(t1e,{portalId:r.id,portalSlug:r.slug,ownerUserId:r.owner_user_id,rewardText:r.referral_reward_text,ctaHeadline:r.referral_cta_headline,agentName:o==null?void 0:o.name,clientName:r.client_name,reviewUrl:r.review_url,hubVideoUrl:r.homeowner_hub_video_url}),s.jsx(Hwe,{targetCloseDate:T==null?void 0:T.target_close_date,actualCloseDate:T==null?void 0:T.actual_close_date,clientName:r.client_name}),B&&s.jsx(Vf,{children:s.jsx(Kwe,{currentStage:B,nextStepText:r.next_step_text,nextStepVideoUrl:V||r.next_step_video_url})}),s.jsx(Vf,{children:s.jsx(Wwe,{journeyStages:D,currentIndex:M})}),a&&a.length>0&&s.jsx(Vf,{children:s.jsx(Qwe,{updates:a})}),(r==null?void 0:r.id)&&s.jsx(Vf,{children:s.jsx(r1e,{portalId:r.id,clientName:r.client_name,agentName:o==null?void 0:o.name,agentAvatar:o==null?void 0:o.avatar_url})})]}),s.jsxs("aside",{className:"col-span-3 space-y-5",children:[s.jsx(Vf,{children:s.jsx(Ywe,{deal:T,portal:r})}),(r==null?void 0:r.slug)&&s.jsx(Xwe,{slug:r.slug,wrapper:me=>s.jsx(Vf,{children:me})}),f&&f.length>0&&s.jsx(Vf,{children:s.jsx(Zwe,{documents:f})}),Se&&s.jsx(Vf,{children:s.jsxs("button",{onClick:je,className:"w-full flex items-center gap-3 rounded-xl px-3 py-3 transition-all text-left group",style:{background:"hsl(var(--portal-gold) / 0.06)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},onMouseEnter:me=>{me.currentTarget.style.background="hsl(var(--portal-gold) / 0.12)"},onMouseLeave:me=>{me.currentTarget.style.background="hsl(var(--portal-gold) / 0.06)"},children:[s.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.15)",color:"hsl(var(--portal-gold))"},children:s.jsx(N9,{className:"w-4 h-4"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"portal-serif",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:"Trusted Vendors"}),s.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:"My hand-picked network"})]}),s.jsx(yl,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})]})}),s.jsxs("div",{className:"text-center pt-2 space-y-2",children:[s.jsx("div",{className:"portal-hairline w-12 mx-auto"}),s.jsx("p",{className:"text-[10px] tracking-[0.25em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:"Powered by ReLevelUp"})]})]})]}),(r==null?void 0:r.id)&&(r==null?void 0:r.owner_user_id)&&s.jsx("div",{id:"trusted-vendors",className:"mt-8 scroll-mt-10",children:s.jsx(e1e,{portalId:r.id,ownerUserId:r.owner_user_id,currentStage:E==null?void 0:E.name,brandingColor:"hsl(var(--portal-gold))",layout:"grid"})})]})]})}function Vf({children:t}){return s.jsx(fr.div,{variants:{hidden:{opacity:0,y:10},show:{opacity:1,y:0,transition:{duration:.45,ease:"easeOut"}}},className:"portal-tile p-6",children:t})}function vz({href:t,icon:e,label:r,sub:n}){return s.jsxs("a",{href:t,className:"flex items-center gap-3 rounded-xl px-3 py-2.5 transition-all",style:{background:"hsl(var(--portal-gold) / 0.05)",border:"1px solid hsl(var(--portal-gold) / 0.12)"},onMouseEnter:i=>{i.currentTarget.style.background="hsl(var(--portal-gold) / 0.1)",i.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.3)"},onMouseLeave:i=>{i.currentTarget.style.background="hsl(var(--portal-gold) / 0.05)",i.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.12)"},children:[s.jsx("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.15)",color:"hsl(var(--portal-gold))"},children:s.jsx(e,{className:"w-4 h-4"})}),s.jsxs("div",{className:"min-w-0 text-left",children:[s.jsx("p",{className:"text-sm portal-serif",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:r}),n&&s.jsx("p",{className:"text-[10px] tracking-[0.15em] uppercase truncate mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:n})]})]})}function _z({icon:t,label:e,value:r}){return s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.1)",color:"hsl(var(--portal-gold))"},children:s.jsx(t,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:e}),s.jsx("p",{className:"portal-serif truncate",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:r})]})]})}function rit({pct:t}){const i=2*Math.PI*78,o=i-t/100*i;return s.jsxs("div",{className:"relative",style:{width:170,height:170},children:[s.jsxs("svg",{width:170,height:170,className:"-rotate-90",children:[s.jsx("defs",{children:s.jsxs("linearGradient",{id:"portal-progress-gold",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[s.jsx("stop",{offset:"0%",stopColor:"var(--portal-hero-accent)"}),s.jsx("stop",{offset:"100%",stopColor:"var(--portal-hero-ink)"})]})}),s.jsx("circle",{cx:170/2,cy:170/2,r:78,stroke:"hsl(0 0% 100% / 0.22)",strokeWidth:2,fill:"none"}),s.jsx(fr.circle,{cx:170/2,cy:170/2,r:78,stroke:"url(#portal-progress-gold)",strokeWidth:3,strokeLinecap:"round",fill:"none",initial:{strokeDashoffset:i},animate:{strokeDashoffset:o},transition:{duration:1.4,ease:"easeOut"},strokeDasharray:i,style:{filter:"drop-shadow(0 0 6px hsl(0 0% 0% / 0.45))"}})]}),s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[s.jsx("span",{className:"portal-serif tabular-nums leading-none",style:{fontSize:"3rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:t}),s.jsx("span",{className:"text-[10px] tracking-[0.25em] uppercase mt-1",style:{color:"var(--portal-hero-ink-dim)",textShadow:"var(--portal-hero-text-shadow)"},children:"percent"})]})]})}function Lie(t){const e=t.split(/[-/T]/),r=new Date(Number(e[0]),Number(e[1])-1,Number(e[2]));return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(r)}var WH="Progress",KH=100,[nit,Y9t]=Qo(WH),[iit,sit]=nit(WH),s1e=C.forwardRef((t,e)=>{const{__scopeProgress:r,value:n=null,max:i,getValueLabel:o=ait,...c}=t;(i||i===0)&&!Die(i)&&console.error(oit(`${i}`,"Progress"));const a=Die(i)?i:KH;n!==null&&!Mie(n,a)&&console.error(lit(`${n}`,"Progress"));const f=Mie(n,a)?n:null,p=gM(f)?o(f,a):void 0;return s.jsx(iit,{scope:r,value:f,max:a,children:s.jsx(nn.div,{"aria-valuemax":a,"aria-valuemin":0,"aria-valuenow":gM(f)?f:void 0,"aria-valuetext":p,role:"progressbar","data-state":l1e(f,a),"data-value":f??void 0,"data-max":a,...c,ref:e})})});s1e.displayName=WH;var a1e="ProgressIndicator",o1e=C.forwardRef((t,e)=>{const{__scopeProgress:r,...n}=t,i=sit(a1e,r);return s.jsx(nn.div,{"data-state":l1e(i.value,i.max),"data-value":i.value??void 0,"data-max":i.max,...n,ref:e})});o1e.displayName=a1e;function ait(t,e){return`${Math.round(t/e*100)}%`}function l1e(t,e){return t==null?"indeterminate":t===e?"complete":"loading"}function gM(t){return typeof t=="number"}function Die(t){return gM(t)&&!isNaN(t)&&t>0}function Mie(t,e){return gM(t)&&!isNaN(t)&&t<=e&&t>=0}function oit(t,e){return`Invalid prop \`max\` of value \`${t}\` supplied to \`${e}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${KH}\`.`}function lit(t,e){return`Invalid prop \`value\` of value \`${t}\` supplied to \`${e}\`. The \`value\` prop must be: - a positive number - less than the value passed to \`max\` (or ${KH} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var c1e=s1e,cit=o1e;const gA=C.forwardRef(({className:t,value:e,...r},n)=>s.jsx(c1e,{ref:n,className:qt("relative h-4 w-full overflow-hidden rounded-full bg-secondary",t),...r,children:s.jsx(cit,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(e||0)}%)`}})}));gA.displayName=c1e.displayName;const G2=[{key:"application",label:"Application completed",short:"Application"},{key:"disclosures",label:"Disclosures & docs collected",short:"Docs"},{key:"appraisal_ordered",label:"Appraisal ordered",short:"Appraisal ordered"},{key:"appraisal_value",label:"Appraisal in at value",short:"Appraised"},{key:"conditional_approval",label:"Conditional approval",short:"Approved"},{key:"clear_to_close",label:"Clear to close",short:"Clear to close"}],uit={appraisal_value:"appraisal_date",clear_to_close:"loan_approval_date"};function dit(t){const e=G2.filter(n=>{var i;return!!((i=t==null?void 0:t[n.key])!=null&&i.done_at)}).length,r=G2.find(n=>{var i;return!((i=t==null?void 0:t[n.key])!=null&&i.done_at)})??null;return{done:e,total:G2.length,pct:Math.round(e/G2.length*100),next:r}}function Z9t(t,e,r,n,i="agent"){return{...t||{},[e]:r?{done_at:n,by:i}:null}}function X9t(t,e,r){const n=uit[e];return!n||!r||t.includes(n)?t:[...t,n]}const Q9t=["Conventional","FHA","VA","USDA","Jumbo","Cash","Other"],J9t={sent:"Sent",contacted:"Contacted",application:"Application in",preapproved:"Pre-approved",nurture:"Nurture",closed:"Closed",declined:"Declined",accepted:"Accepted"};function e7t(t,e=typeof window<"u"?window.location.origin:""){return`${e}/lender/${t}`}function hit({portalId:t}){const{data:e}=mr({queryKey:["portal-lender",t],queryFn:async()=>{const{data:n,error:i}=await Re.rpc("get_portal_lender",{_portal_id:t});if(i)throw i;return n}});if(!e)return null;const r=dit(e.milestones);return s.jsxs("section",{className:"rounded-2xl border bg-card p-5 space-y-4",children:[s.jsxs("div",{className:"flex items-start gap-3",children:[e.photo_url?s.jsx("img",{src:e.photo_url,alt:e.name,className:"h-12 w-12 rounded-full object-cover"}):s.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-primary/10 text-primary",children:s.jsx(YO,{className:"h-5 w-5"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Your financing partner"}),s.jsx("p",{className:"font-semibold",children:e.name}),s.jsx("p",{className:"text-xs text-muted-foreground",children:[e.company,e.nmls&&`NMLS ${e.nmls}`,e.loan_type].filter(Boolean).join(" · ")})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex justify-between text-xs",children:[s.jsx("span",{children:"Loan progress"}),s.jsx("span",{children:r.next?`Next: ${r.next.short}`:"Clear to close! 🎉"})]}),s.jsx(gA,{value:r.pct,className:"h-2"}),s.jsx("div",{className:"grid gap-1 sm:grid-cols-2",children:G2.map(n=>{var o,c;const i=!!((c=(o=e.milestones)==null?void 0:o[n.key])!=null&&c.done_at);return s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i?s.jsx(oc,{className:"h-4 w-4 text-primary"}):s.jsx(t_,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:i?"":"text-muted-foreground",children:n.label})]},n.key)})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.phone&&s.jsx(Bt,{asChild:!0,size:"sm",variant:"outline",children:s.jsxs("a",{href:`tel:${e.phone}`,children:[s.jsx(ri,{className:"mr-1.5 h-3.5 w-3.5"}),"Call"]})}),e.email&&s.jsx(Bt,{asChild:!0,size:"sm",variant:"outline",children:s.jsxs("a",{href:`mailto:${e.email}`,children:[s.jsx(mi,{className:"mr-1.5 h-3.5 w-3.5"}),"Email"]})}),e.apply_url&&s.jsx(Bt,{asChild:!0,size:"sm",children:s.jsxs("a",{href:e.apply_url,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(b_,{className:"mr-1.5 h-3.5 w-3.5"}),"Loan application"]})})]})]})}function fit({portal:t,dealData:e,agentProfile:r,customQuestions:n,deviceFingerprint:i,onComplete:o}){var R,D;const[c,a]=C.useState({first_name:((R=t.client_name)==null?void 0:R.split(" ")[0])||"",last_name:((D=t.client_name)==null?void 0:D.split(" ").slice(1).join(" "))||"",email:t.client_email||"",phone:t.client_phone||"",preferred_contact_method:"email",client_role:"buyer",notes:"",spouse_first_name:"",spouse_last_name:"",spouse_email:"",spouse_phone:""}),[f,p]=C.useState({}),[y,v]=C.useState(!1),T=Sr({mutationFn:async()=>{const{error:M}=await Re.from("portal_onboarding_submissions").insert({portal_id:t.id,first_name:c.first_name,last_name:c.last_name||null,email:c.email||null,phone:c.phone||null,preferred_contact_method:c.preferred_contact_method,client_role:c.client_role,notes:c.notes||null,device_fingerprint:i,custom_answers:Object.keys(f).length>0?f:null,spouse_first_name:y&&c.spouse_first_name||null,spouse_last_name:y&&c.spouse_last_name||null,spouse_email:y&&c.spouse_email||null,spouse_phone:y&&c.spouse_phone||null});if(M)throw M},onSuccess:o,onError:M=>{console.error("[PortalOnboarding] Submit failed:",M),Vt.error("Something went wrong. Please try again.")}}),E=e!=null&&e.property_address?`${e.property_address}, ${e.city||""}, ${e.state||""}`:null,k="mt-1 rounded-xl bg-white text-slate-900 placeholder:text-slate-400 border-slate-200 focus-visible:ring-slate-400",P="mt-1 w-full rounded-xl border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400";return s.jsx("div",{className:"max-w-md mx-auto px-4 py-10",children:s.jsxs("div",{className:"bg-white rounded-2xl shadow-xl ring-1 ring-slate-200 p-6 sm:p-8",children:[s.jsxs("div",{className:"text-center mb-8",children:[(r==null?void 0:r.avatar_url)&&s.jsx("img",{src:r.avatar_url,alt:r.name,className:"w-16 h-16 rounded-full border-2 border-slate-200 mx-auto mb-3 object-cover"}),s.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Welcome to Your Portal"}),E&&s.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[s.jsx(Es,{className:"w-3.5 h-3.5"}),s.jsx("span",{children:E.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),s.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Please fill in your details to access your transaction portal."})]}),s.jsxs("form",{onSubmit:M=>{M.preventDefault(),T.mutate()},className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),s.jsx(Br,{required:!0,value:c.first_name,onChange:M=>a(B=>({...B,first_name:M.target.value})),className:k,placeholder:"John"})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),s.jsx(Br,{value:c.last_name,onChange:M=>a(B=>({...B,last_name:M.target.value})),className:k,placeholder:"Doe"})]})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Email"}),s.jsx(Br,{type:"email",value:c.email,onChange:M=>a(B=>({...B,email:M.target.value})),className:k,placeholder:"john@example.com"})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Phone"}),s.jsx(Br,{type:"tel",value:c.phone,onChange:M=>a(B=>({...B,phone:M.target.value})),className:k,placeholder:"(555) 123-4567"})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Preferred Contact Method"}),s.jsx("div",{className:"flex gap-2 mt-1.5",children:[{value:"email",label:"Email"},{value:"call",label:"Phone"},{value:"text",label:"Text"}].map(M=>s.jsx("button",{type:"button",onClick:()=>a(B=>({...B,preferred_contact_method:M.value})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c.preferred_contact_method===M.value?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:M.label},M.value))})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Your Role"}),s.jsx("div",{className:"flex gap-2 mt-1.5",children:["buyer","seller","both"].map(M=>s.jsx("button",{type:"button",onClick:()=>a(B=>({...B,client_role:M})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c.client_role===M?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:M.charAt(0).toUpperCase()+M.slice(1)},M))})]}),n.map(M=>s.jsxs("div",{children:[s.jsxs(Mr,{className:"text-xs font-medium text-slate-700",children:[M.question_text," ",M.is_required&&"*"]}),M.field_type==="text"&&s.jsx(Br,{required:M.is_required,value:f[M.id]||"",onChange:B=>p(V=>({...V,[M.id]:B.target.value})),className:k}),M.field_type==="textarea"&&s.jsx("textarea",{required:M.is_required,value:f[M.id]||"",onChange:B=>p(V=>({...V,[M.id]:B.target.value})),className:`${P} min-h-[80px]`}),M.field_type==="dropdown"&&s.jsxs("select",{required:M.is_required,value:f[M.id]||"",onChange:B=>p(V=>({...V,[M.id]:B.target.value})),className:`${P} h-10`,children:[s.jsx("option",{value:"",children:"Select..."}),(M.options||[]).map(B=>s.jsx("option",{value:B,children:B},B))]}),M.field_type==="toggle"&&s.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(B=>s.jsx("button",{type:"button",onClick:()=>p(V=>({...V,[M.id]:B})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${f[M.id]===B?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:B},B))})]},M.id)),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),s.jsx("textarea",{value:c.notes,onChange:M=>a(B=>({...B,notes:M.target.value})),className:`${P} min-h-[60px]`,placeholder:"Anything you'd like your agent to know..."})]}),t.allow_spouse&&s.jsxs("div",{children:[s.jsx("button",{type:"button",onClick:()=>v(!y),className:"text-sm text-blue-600 hover:text-blue-700 font-medium",children:y?"− Remove spouse/partner":"+ Add spouse/partner"}),y&&s.jsxs("div",{className:"mt-3 p-4 bg-slate-50 rounded-xl border border-slate-200 space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"First Name"}),s.jsx(Br,{value:c.spouse_first_name,onChange:M=>a(B=>({...B,spouse_first_name:M.target.value})),className:k})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),s.jsx(Br,{value:c.spouse_last_name,onChange:M=>a(B=>({...B,spouse_last_name:M.target.value})),className:k})]})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Email"}),s.jsx(Br,{type:"email",value:c.spouse_email,onChange:M=>a(B=>({...B,spouse_email:M.target.value})),className:k})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Phone"}),s.jsx(Br,{type:"tel",value:c.spouse_phone,onChange:M=>a(B=>({...B,spouse_phone:M.target.value})),className:k})]})]})]}),s.jsx(Bt,{type:"submit",disabled:T.isPending||!c.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:T.isPending?"Submitting...":"Access My Portal"})]})]})})}function mit(t,e){const r=(n,i)=>i!=null&&i!==""?i:n!=null&&n!==""?n:null;return{logo_url:r(t==null?void 0:t.logo_url,e==null?void 0:e.logo_url),cover_photo_url:r(t==null?void 0:t.cover_photo_url,e==null?void 0:e.cover_photo_url),brand_color:r(t==null?void 0:t.brand_color,e==null?void 0:e.brand_color),accent_color:r(t==null?void 0:t.accent_color,e==null?void 0:e.accent_color),tagline:r(t==null?void 0:t.tagline,e==null?void 0:e.tagline),welcome_message:r(t==null?void 0:t.welcome_message,e==null?void 0:e.welcome_message),portal_theme:r(t==null?void 0:t.portal_theme,e==null?void 0:e.portal_theme)||"noir"}}function t7t(){const t=Li();return mr({queryKey:["agent-portal-branding",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Re.from("agent_portal_branding").select("*").eq("user_id",t).maybeSingle();if(r)throw r;return e},enabled:!!t})}function pit(t){return mr({queryKey:["agent-portal-branding-public",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Re.from("agent_portal_branding").select("logo_url, cover_photo_url, brand_color, accent_color, tagline, welcome_message, portal_theme").eq("user_id",t).maybeSingle();if(r)throw r;return e},enabled:!!t})}function r7t(){const t=Li(),e=Ar();return Sr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Re.from("agent_portal_branding").upsert({user_id:t,...r},{onConflict:"user_id"}).select().single();if(i)throw i;return n},onSuccess:()=>{e.invalidateQueries({queryKey:["agent-portal-branding",t]}),e.invalidateQueries({queryKey:["agent-portal-branding-public",t]})}})}async function n7t(t,e,r){var a;const n=((a=e.name.split(".").pop())==null?void 0:a.toLowerCase())||"png",i=`${t}/${r}-${Date.now()}.${n}`,{error:o}=await Re.storage.from("portal-branding").upload(i,e,{upsert:!0,cacheControl:"3600"});if(o)throw o;const{data:c}=Re.storage.from("portal-branding").getPublicUrl(i);return c.publicUrl}function git(t,e){return mr({queryKey:["client-portal-public",t],queryFn:async()=>{if(!t)return null;const{data:r,error:n}=await Re.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, earnest_money_due_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, title_docs_due_date, final_walkthrough_date, completed_key_dates, custom_key_dates, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("slug",t).eq("is_enabled",!0).maybeSingle();if(n)throw n;return r},enabled:e})}function yit(t){return mr({queryKey:["client-portal-by-id",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Re.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, earnest_money_due_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, title_docs_due_date, final_walkthrough_date, completed_key_dates, custom_key_dates, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("id",t).eq("is_enabled",!0).maybeSingle();if(r)throw r;return e},enabled:!!t})}function xit({slug:t}){var me,Te,Ne,Ee,we,He;const[e,r]=C.useState(!1),[n,i]=C.useState("primary"),[o]=C.useState(()=>{const tt=`portal_fp_${t}`;let at=localStorage.getItem(tt);return at||(at=localStorage.getItem("portal_fp"),at?localStorage.setItem(tt,at):(at=crypto.randomUUID(),localStorage.setItem(tt,at),localStorage.setItem("portal_fp",at))),at});C.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:c,isLoading:a,error:f}=git(t,!0),p=c==null?void 0:c.linked_portal_id,{data:y}=yit(p),v=(me=c==null?void 0:c.deal_pipeline)==null?void 0:me.owner_user_id;mr({queryKey:["portal-stages",v],queryFn:async()=>{const{data:tt,error:at}=await Re.from("deal_pipeline_stages").select("*").eq("owner_user_id",v).order("sort_order",{ascending:!0});if(at)throw at;return tt},enabled:!!v});const{data:T}=mr({queryKey:["portal-agent",v],queryFn:async()=>{const{data:tt,error:at}=await Re.from("profiles").select("id, name, avatar_url, phone, email").eq("id",v).single();if(at)throw at;return tt},enabled:!!v}),{data:E}=pit(v),k=n==="linked"&&y?y:c,P=k==null?void 0:k.id,R=mit(E,k==null?void 0:k.branding_override),D=R.portal_theme==="azure"?"azure":"noir";C.useEffect(()=>{const tt=`portal-theme-${D}`;return document.body.classList.add(tt),()=>document.body.classList.remove(tt)},[D]);const{data:M}=mr({queryKey:["portal-updates-public",P],queryFn:async()=>{const{data:tt,error:at}=await Re.from("portal_updates").select("*").eq("portal_id",P).order("created_at",{ascending:!1});if(at)throw at;return tt},enabled:!!P}),B=(Te=k==null?void 0:k.deal_pipeline)==null?void 0:Te.id,{data:V}=mr({queryKey:["portal-documents",B],queryFn:async()=>{const{data:tt,error:at}=await Re.from("deal_files").select("*").eq("deal_id",B).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(at)throw at;return tt},enabled:!!B}),G=c==null?void 0:c.id,W=G?`portal_onboarded_${G}_${o}`:null,Y=W?localStorage.getItem(W)==="1":!1,{data:J,isLoading:Q}=mr({queryKey:["portal-onboarding-check",G,o],queryFn:async()=>{const{data:tt,error:at}=await Re.from("portal_onboarding_submissions").select("id").eq("portal_id",G).eq("device_fingerprint",o).maybeSingle();if(at)throw at;return tt&&W&&localStorage.setItem(W,"1"),tt},enabled:!!G&&!!(c!=null&&c.require_onboarding)&&!Y,staleTime:5*60*1e3}),ee=!!(c!=null&&c.require_onboarding)&&!Y&&!J&&!e,{data:le}=mr({queryKey:["portal-custom-questions-public",v],queryFn:async()=>{const{data:tt,error:at}=await Re.from("portal_custom_questions").select("*").eq("owner_user_id",v).eq("is_active",!0).order("sort_order",{ascending:!0});if(at)throw at;return tt},enabled:!!v&&ee}),pe=Y||!!J||e||!(c!=null&&c.require_onboarding);if(a||c!=null&&c.require_onboarding&&!Y&&Q)return s.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:s.jsx(su,{className:"w-6 h-6 animate-spin",style:{color:"hsl(var(--portal-gold))"}})});if(f||!c)return s.jsx("div",{className:"min-h-screen flex items-center justify-center p-6",style:{background:"var(--portal-gradient-noir)"},children:s.jsxs("div",{className:"text-center max-w-md",children:[s.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-6",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)"},children:s.jsx(KA,{className:"w-6 h-6",style:{color:"hsl(var(--portal-gold))"}})}),s.jsx("h1",{className:"portal-serif text-4xl mb-3",style:{color:"hsl(var(--portal-ink))"},children:"Portal Not Available"}),s.jsx("div",{className:"portal-hairline mx-auto w-24 mb-4"}),s.jsx("p",{className:"text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:"This portal is no longer active or doesn't exist."})]})});if(!pe){const tt=c==null?void 0:c.deal_pipeline;return s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-slate-100",children:s.jsx(fit,{portal:c,dealData:tt,agentProfile:T,customQuestions:le||[],deviceFingerprint:o,onComplete:()=>{W&&localStorage.setItem(W,"1"),r(!0)}})})}const Se=(Ne=c==null?void 0:c.deal_pipeline)==null?void 0:Ne.deal_type,je=(Ee=y==null?void 0:y.deal_pipeline)==null?void 0:Ee.deal_type,Le=!!y,Ae=tt=>tt==="listing"?"Your Sale":tt==="buy-side"?"Your Purchase":"Transaction",be=tt=>tt==="listing"?s.jsx(va,{className:"w-3.5 h-3.5"}):s.jsx(pme,{className:"w-3.5 h-3.5"});return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"hidden lg:block",children:s.jsx(tit,{portal:c,linkedPortal:y,activePortal:k,activeTab:n,onTabChange:i,agentProfile:T,branding:R,updates:M,documents:V})}),s.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[s.jsx(Bnt,{dealData:k==null?void 0:k.deal_pipeline,agentProfile:T,welcomeMessage:(k==null?void 0:k.welcome_message)||R.welcome_message,isWon:(He=(we=k==null?void 0:k.deal_pipeline)==null?void 0:we.deal_pipeline_stages)==null?void 0:He.is_won_stage,branding:R}),s.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[Le&&s.jsx("div",{className:"flex gap-1 rounded-xl p-1",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(tt=>{const at=n===tt,Et=tt==="primary"?Se:je;return s.jsxs("button",{onClick:()=>i(tt),className:"flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all portal-serif",style:{background:at?"hsl(var(--portal-surface-3))":"transparent",color:at?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",boxShadow:at?"0 1px 0 hsl(var(--portal-gold) / 0.3) inset":"none"},children:[be(Et),s.jsx("span",{style:{fontSize:"1rem"},children:Ae(Et)})]},tt)})}),s.jsx(vit,{portal:k,updates:M,documents:V,agentProfile:T}),P&&s.jsx("div",{className:"rounded-2xl p-5",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.14)"},children:s.jsx(r1e,{portalId:P,clientName:k==null?void 0:k.client_name,agentName:T==null?void 0:T.name,agentAvatar:T==null?void 0:T.avatar_url,deviceFingerprint:o})}),s.jsxs("div",{className:"text-center pt-8 pb-2 space-y-3",children:[s.jsx("div",{className:"portal-hairline w-16 mx-auto"}),s.jsxs("div",{className:"flex items-center justify-center gap-1.5",style:{color:"hsl(var(--portal-ink-dim))"},children:[s.jsx(KA,{className:"w-3 h-3"}),s.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase",children:"Secure Client Portal"})]}),T&&s.jsxs("p",{className:"text-xs",style:{color:"hsl(var(--portal-ink-muted))"},children:["Curated by ",s.jsx("span",{className:"portal-serif",style:{color:"hsl(var(--portal-gold))",fontSize:"0.95rem"},children:T.name})]})]})]})]})]})}function vit({portal:t,updates:e,documents:r,agentProfile:n}){const i=t,o=i==null?void 0:i.deal_pipeline,c=o==null?void 0:o.deal_pipeline_stages,a=c==null?void 0:c.is_won_stage,f=o==null?void 0:o.deal_type,p=t.stage_mapping;let y=i1e(f);p&&p.length>0&&(y=p.map((P,R)=>{var D,M;return{key:`custom-${R}`,label:P.label||((D=y[R])==null?void 0:D.label)||`Stage ${R+1}`,description:P.description||((M=y[R])==null?void 0:M.description)||"",video_url:P.video_url||void 0}}));const v=p&&p.length>0?Math.min(pM(c==null?void 0:c.name),y.length-1):pM(c==null?void 0:c.name),T=y[v],E=T==null?void 0:T.video_url,k=a&&t.show_post_close_tips!==!1&&t.referral_enabled!==!1;return s.jsxs(s.Fragment,{children:[k&&s.jsx(t1e,{portalId:t.id,portalSlug:t.slug,ownerUserId:t.owner_user_id,rewardText:t.referral_reward_text,ctaHeadline:t.referral_cta_headline,agentName:n==null?void 0:n.name,clientName:t.client_name,reviewUrl:t.review_url,hubVideoUrl:t.homeowner_hub_video_url}),s.jsx(Hwe,{targetCloseDate:o==null?void 0:o.target_close_date,actualCloseDate:o==null?void 0:o.actual_close_date,clientName:t.client_name}),s.jsx(Wwe,{journeyStages:y,currentIndex:v}),T&&s.jsx(Kwe,{currentStage:T,nextStepText:t.next_step_text,nextStepVideoUrl:E||t.next_step_video_url}),s.jsx(Ywe,{deal:o,portal:t}),(o==null?void 0:o.id)&&(f==="seller"||f==="dual")&&s.jsx(Fnt,{dealId:o.id}),(t==null?void 0:t.id)&&s.jsx(hit,{portalId:t.id}),(t==null?void 0:t.slug)&&s.jsx(Xwe,{slug:t.slug}),r&&r.length>0&&s.jsx(Zwe,{documents:r}),(t==null?void 0:t.id)&&(t==null?void 0:t.owner_user_id)&&s.jsx(e1e,{portalId:t.id,ownerUserId:t.owner_user_id,currentStage:c==null?void 0:c.name}),e&&e.length>0&&s.jsx(Qwe,{updates:e})]})}function u1e({slug:t}){const e=Pm(),r=t||e.slug,[n,i]=C.useState(!1),[o,c]=C.useState(!1),[a,f]=C.useState(""),[p,y]=C.useState(""),[v,T]=C.useState(""),[E,k]=C.useState(""),[P,R]=C.useState(""),[D,M]=C.useState("buying"),[B,V]=C.useState("");C.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:G,isLoading:W,error:Y}=mr({queryKey:["portal-referral-target",r],queryFn:async()=>{if(!r)return null;const{data:ee,error:le}=await Re.from("client_portals").select(` id, slug, owner_user_id, client_name, referral_enabled, referral_reward_text, referral_cta_headline, is_enabled `).eq("slug",r).eq("is_enabled",!0).maybeSingle();if(le)throw le;return ee},enabled:!!r}),{data:J}=mr({queryKey:["portal-referral-agent",G==null?void 0:G.owner_user_id],queryFn:async()=>{const{data:ee}=await Re.from("profiles").select("id, name, avatar_url").eq("id",G.owner_user_id).single();return ee},enabled:!!(G!=null&&G.owner_user_id)}),Q=async ee=>{if(ee.preventDefault(),!G||!v.trim()){Vt.error("Please enter your friend's name");return}if(!E.trim()&&!P.trim()){Vt.error("Please add at least an email or phone for your friend");return}i(!0);try{const{error:le}=await Re.from("portal_referrals").insert({portal_id:G.id,owner_user_id:G.owner_user_id,referrer_name:a.trim()||G.client_name||null,referrer_email:p.trim()||null,friend_name:v.trim(),friend_email:E.trim()||null,friend_phone:P.trim()||null,friend_interest:D,friend_message:B.trim()||null});if(le)throw le;c(!0)}catch(le){Vt.error(le.message||"Could not submit referral")}finally{i(!1)}};return W?s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:s.jsx(ml,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):Y||!G||!G.referral_enabled?s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:s.jsx("span",{className:"text-2xl",children:"🔒"})}),s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Referral Page Unavailable"}),s.jsx("p",{className:"text-slate-500",children:"This referral link is no longer active."})]})}):o?s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-emerald-50 via-teal-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[s.jsx("div",{className:"w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-4",children:s.jsx(no,{className:"w-8 h-8 text-emerald-600"})}),s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2 font-serif",children:"Thank you! 🙏"}),s.jsxs("p",{className:"text-sm text-slate-600 leading-relaxed mb-6",children:["Your referral has been sent to ",(J==null?void 0:J.name)||"your agent",". They'll reach out to"," ",s.jsx("span",{className:"font-semibold text-slate-800",children:v})," personally and treat them like family."]}),s.jsxs("button",{onClick:()=>window.history.back(),className:"inline-flex items-center gap-2 text-sm text-[#406E71] hover:text-[#2a4c64] font-medium",children:[s.jsx(dx,{className:"w-4 h-4"}),"Back to your portal"]})]})}):s.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white pb-12",children:[s.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white px-4 pt-10 pb-12 overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"24px 24px"}}),s.jsxs("div",{className:"relative max-w-lg mx-auto text-center",children:[J!=null&&J.avatar_url?s.jsx("img",{src:J.avatar_url,alt:J.name||"Agent",className:"w-16 h-16 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 object-cover"}):s.jsx("div",{className:"w-16 h-16 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 bg-white/10 flex items-center justify-center",children:s.jsx(hf,{className:"w-7 h-7 text-white/70"})}),s.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/10 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium text-white/90 mb-2",children:[s.jsx(hf,{className:"w-3 h-3"})," Referral"]}),s.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:G.referral_cta_headline||"Refer a Friend"}),s.jsxs("p",{className:"text-sm text-white/70",children:["Send ",(J==null?void 0:J.name)||"your agent"," someone you trust."]}),G.referral_reward_text&&s.jsxs("p",{className:"text-xs text-white/60 mt-2",children:["You'll get: ",s.jsx("span",{className:"text-white font-medium",children:G.referral_reward_text})," when they close."]})]})]}),s.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-6 relative z-10",children:s.jsxs("form",{onSubmit:Q,className:"bg-white rounded-2xl shadow-lg border border-slate-100 p-5 space-y-5",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Tell us about your friend"}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsxs(Mr,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx(Br,{id:"friend_name",value:v,onChange:ee=>T(ee.target.value),placeholder:"Jane Smith",required:!0,className:"mt-1"})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),s.jsx(Br,{id:"friend_email",type:"email",value:E,onChange:ee=>k(ee.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),s.jsx(Br,{id:"friend_phone",type:"tel",value:P,onChange:ee=>R(ee.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),s.jsx("p",{className:"text-[11px] text-slate-400",children:"Add at least an email or phone so we can reach them."}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-sm",children:"They're interested in..."}),s.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[{v:"buying",l:"Buying"},{v:"selling",l:"Selling"},{v:"both",l:"Both"},{v:"unsure",l:"Not sure"}].map(ee=>s.jsx("button",{type:"button",onClick:()=>M(ee.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${D===ee.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:ee.l},ee.v))})]}),s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),s.jsx("textarea",{id:"friend_message",value:B,onChange:ee=>V(ee.target.value),placeholder:"They're moving from Boston in the spring...",rows:3,className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]})]})]}),s.jsxs("div",{className:"border-t pt-4",children:[s.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Your info"}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),s.jsx(Br,{id:"referrer_name",value:a,onChange:ee=>f(ee.target.value),placeholder:G.client_name||"Your name",className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx(Mr,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),s.jsx(Br,{id:"referrer_email",type:"email",value:p,onChange:ee=>y(ee.target.value),placeholder:"So we can thank you!",className:"mt-1"})]})]})]}),s.jsxs("button",{type:"submit",disabled:n,className:"w-full bg-[#406E71] hover:bg-[#345e7a] disabled:opacity-60 text-white font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 transition-colors",children:[n?s.jsx(su,{className:"w-4 h-4 animate-spin"}):s.jsx(hf,{className:"w-4 h-4"}),n?"Sending...":"Send Referral"]}),s.jsx("p",{className:"text-[11px] text-center text-slate-400",children:"By submitting, you confirm your friend has agreed to be contacted."})]})})]})}const _it=Object.freeze(Object.defineProperty({__proto__:null,default:u1e},Symbol.toStringTag,{value:"Module"}));function bit(){const e=ki().pathname.slice(1).replace(/\/$/,"");if(C.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>{document.body.classList.remove("client-portal-page")}),[]),!e)return s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Client Portal"}),s.jsx("p",{className:"text-slate-500",children:"Visit your personalized portal link to view your transaction details."})]})});const r=e.match(/^([^/]+)\/refer$/);return r?s.jsx(u1e,{slug:r[1]}):e.includes("/")?s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Page Not Found"}),s.jsx("p",{className:"text-slate-500",children:"This portal link doesn't look right."})]})}):s.jsx(xit,{slug:e})}function wit(t){const e=[],r=n=>{n&&!e.includes(n)&&e.push(n)};for(const n of t.filter(Boolean)){r(n);try{const i=new URL(n),o=i.searchParams.get("u");o&&/\/functions\/v1\/trestle-media/i.test(i.pathname)&&r(o)}catch{}}return e}function T8({photos:t,alt:e="",className:r="w-full h-full",imgClassName:n="w-full h-full object-cover",iconClassName:i="w-8 h-8"}){const o=C.useMemo(()=>wit(Array.isArray(t)?t:[]),[t]),[c,a]=C.useState(0);return C.useEffect(()=>{a(0)},[o.join("|")]),!o.length||c>=o.length?s.jsx("div",{className:`${r} bg-muted flex items-center justify-center text-muted-foreground`,children:s.jsx(va,{className:`${i} opacity-40`})}):s.jsx("div",{className:`${r} overflow-hidden bg-muted`,children:s.jsx("img",{src:o[c],alt:e,className:n,onError:()=>a(f=>f+1)})})}function Sit({comp:t,open:e,onClose:r}){var p;const[n,i]=C.useState(0);if(!t)return null;const o=Array.isArray(t.photos)?t.photos.filter(Boolean):[],c=t.soldPrice||t.price,a=t.sqft&&c?Math.round(c/t.sqft):null,f=y=>{if(!y)return null;const[v,T,E]=y.split(/[-/T]/);return v?`${T}/${E}/${v}`:null};return s.jsx(lo,{open:e,onOpenChange:y=>{y||r()},children:s.jsxs(qa,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[s.jsxs(xl,{className:"px-6 pt-6 pb-2",children:[s.jsx(Xo,{className:"text-xl",children:t.address}),s.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[s.jsx(Es,{className:"w-3.5 h-3.5"}),t.city,", ",t.state," ",t.zip]})]}),o.length>0?s.jsxs("div",{className:"px-6",children:[s.jsx(T8,{photos:o.slice(n),className:"rounded-lg aspect-[16/10]"}),o.length>1&&s.jsx("div",{className:"flex gap-2 mt-2 overflow-x-auto pb-2",children:o.slice(0,24).map((y,v)=>s.jsx("button",{onClick:()=>i(v),className:`flex-none w-20 h-16 rounded overflow-hidden border-2 transition ${v===n?"border-primary":"border-transparent opacity-70 hover:opacity-100"}`,children:s.jsx(T8,{photos:[y],iconClassName:"w-5 h-5"})},v))})]}):s.jsx("div",{className:"px-6",children:s.jsx("div",{className:"rounded-lg bg-muted aspect-[16/10] flex items-center justify-center text-muted-foreground",children:s.jsx(va,{className:"w-12 h-12 opacity-40"})})}),s.jsxs("div",{className:"px-6 pt-4 flex items-center justify-between flex-wrap gap-2",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-3xl font-bold flex items-center gap-1",children:[s.jsx($p,{className:"w-6 h-6 text-muted-foreground"}),(c||0).toLocaleString()]}),a&&s.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",a,"/sqft"]})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1",children:[s.jsx(ss,{variant:"outline",children:t.status}),t.daysOnMarket!=null&&s.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.daysOnMarket," DOM"]})]})]}),(t.listDate||t.statusChangeDate||t.soldDate)&&s.jsxs("div",{className:"px-6 pt-4",children:[s.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Timeline"}),s.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[s.jsx(bz,{label:"Active",date:f(t.listDate),active:!0}),s.jsx(bz,{label:"Pending",date:/Pending|Contingent|Under Contract|Backup/i.test(String(t.status||""))?f(t.statusChangeDate):null,active:/Pending|Contingent|Under Contract|Backup/i.test(String(t.status||""))}),s.jsx(bz,{label:"Closed",date:f(t.soldDate)||(/Closed|Sold/i.test(String(t.status||""))?f(t.statusChangeDate):null),active:/Closed|Sold/i.test(String(t.status||""))})]})]}),s.jsxs("div",{className:"px-6 pt-4 grid grid-cols-2 md:grid-cols-4 gap-3",children:[s.jsx(TR,{icon:s.jsx(XS,{className:"w-4 h-4"}),label:"Beds",value:t.bedrooms??"—"}),s.jsx(TR,{icon:s.jsx(__,{className:"w-4 h-4"}),label:"Baths",value:t.bathrooms??"—"}),s.jsx(TR,{icon:s.jsx(QO,{className:"w-4 h-4"}),label:"SqFt",value:((p=t.sqft)==null?void 0:p.toLocaleString())??"—"}),s.jsx(TR,{icon:s.jsx(oo,{className:"w-4 h-4"}),label:"Year Built",value:t.yearBuilt??"—"})]}),s.jsxs("div",{className:"px-6 pt-4 grid sm:grid-cols-2 gap-x-6 gap-y-2 text-sm",children:[s.jsx(Uc,{label:"MLS #",value:t.mlsNumber}),s.jsx(Uc,{label:"Property Type",value:t.propertySubType||t.propertyType}),s.jsx(Uc,{label:"Lot Size",value:t.lotSize}),s.jsx(Uc,{label:"Garage",value:t.garageSpaces}),s.jsx(Uc,{label:"Stories",value:t.stories}),s.jsx(Uc,{label:"HOA",value:t.hoaFee?`$${t.hoaFee}/${(t.hoaFrequency||"mo").toLowerCase()}`:null}),s.jsx(Uc,{label:"Tax (annual)",value:t.taxAmount?`$${t.taxAmount.toLocaleString()}`:null}),s.jsx(Uc,{label:"Heating",value:t.heating}),s.jsx(Uc,{label:"Cooling",value:t.cooling}),s.jsx(Uc,{label:"Parking",value:t.parking}),s.jsx(Uc,{label:"Elementary",value:t.elementarySchool}),s.jsx(Uc,{label:"Middle",value:t.middleSchool}),s.jsx(Uc,{label:"High",value:t.highSchool}),s.jsx(Uc,{label:"Listed By",value:t.listAgentFullName}),s.jsx(Uc,{label:"Office",value:t.listOfficeName})]}),t.description&&s.jsxs("div",{className:"px-6 pt-4",children:[s.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1",children:"Description"}),s.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap",children:t.description})]}),s.jsx("div",{className:"px-6 py-4"})]})})}function TR({icon:t,label:e,value:r}){return s.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[t,e]}),s.jsx("div",{className:"text-lg font-semibold mt-0.5",children:r})]})}function Uc({label:t,value:e}){return e==null||e===""||e===0?null:s.jsxs("div",{className:"flex justify-between border-b border-dashed py-1",children:[s.jsx("span",{className:"text-muted-foreground",children:t}),s.jsx("span",{className:"font-medium text-right ml-3 truncate",children:String(e)})]})}function bz({label:t,date:e,active:r}){return s.jsxs("div",{className:`rounded-lg border p-2 text-center ${r?"bg-primary/5 border-primary/30":"bg-muted/30"}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:t}),s.jsx("div",{className:`text-sm font-medium mt-0.5 ${e?"":"text-muted-foreground/60"}`,children:e||"—"})]})}function ER({to:t,durationMs:e=1400,prefix:r="",suffix:n="",className:i,delayMs:o=0}){const[c,a]=C.useState(0),f=C.useRef(null);return C.useEffect(()=>{if(!Number.isFinite(t))return;let p=0;const y=0,v=E=>1-Math.pow(1-E,3),T=setTimeout(()=>{const E=k=>{p||(p=k);const P=k-p,R=Math.min(1,P/e);a(Math.round(y+(t-y)*v(R))),R<1&&(f.current=requestAnimationFrame(E))};f.current=requestAnimationFrame(E)},o);return()=>{clearTimeout(T),f.current&&cancelAnimationFrame(f.current)}},[t,e,o]),s.jsxs("span",{className:i,children:[r,c.toLocaleString(),n]})}function Tit({low:t,likely:e,high:r,defaultMortgage:n=0,defaultCommissionPct:i=6,defaultClosingPct:o=1}){const[c,a]=C.useState(e),[f,p]=C.useState(n),[y,v]=C.useState(i),[T,E]=C.useState(o),{commission:k,closing:P,net:R}=C.useMemo(()=>{const B=Math.round(c*y/100),V=Math.round(c*T/100);return{commission:B,closing:V,net:Math.max(0,c-B-V-(f||0))}},[c,y,T,f]),D=B=>`$${B.toLocaleString()}`,M=r>t?(c-t)/(r-t)*100:50;return s.jsxs($n,{className:"overflow-hidden border-primary/20",children:[s.jsxs("div",{className:"bg-gradient-to-br from-primary/5 to-primary/10 px-6 pt-6 pb-4 border-b border-primary/10",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(Nx,{className:"w-4 h-4 text-primary"}),s.jsx("span",{className:"text-xs uppercase tracking-widest font-semibold text-primary",children:"Your Price Story"})]}),s.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"What if you priced it at…"}),s.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Drag the price. Watch your estimated walk-away update in real-time."})]}),s.jsxs(Kn,{className:"p-6 space-y-6",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-end justify-between mb-3",children:[s.jsx("span",{className:"text-xs text-muted-foreground",children:"List price"}),s.jsx("span",{className:"text-3xl font-bold tabular-nums",children:D(c)})]}),s.jsxs("div",{className:"relative",children:[s.jsx(w1,{value:[c],min:t,max:r,step:1e3,onValueChange:([B])=>a(B)}),s.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-2",children:[s.jsx("span",{children:D(t)}),s.jsxs("span",{children:["Suggested ",D(e)]}),s.jsx("span",{children:D(r)})]})]}),s.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-muted overflow-hidden",children:s.jsx("div",{className:"h-full bg-gradient-to-r from-emerald-500 via-primary to-amber-500 transition-all",style:{width:`${Math.min(100,Math.max(0,M))}%`}})})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs",children:"Mortgage payoff"}),s.jsx(Br,{type:"number",inputMode:"numeric",value:f||"",placeholder:"$0",onChange:B=>p(Number(B.target.value)||0)})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs",children:"Commission %"}),s.jsx(Br,{type:"number",step:"0.25",value:y,onChange:B=>v(Number(B.target.value)||0)})]}),s.jsxs("div",{children:[s.jsx(Mr,{className:"text-xs",children:"Closing costs %"}),s.jsx(Br,{type:"number",step:"0.25",value:T,onChange:B=>E(Number(B.target.value)||0)})]})]}),s.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[s.jsxs("div",{className:"px-5 py-4 grid grid-cols-2 gap-y-2 text-sm",children:[s.jsx("span",{className:"text-muted-foreground",children:"Sale price"}),s.jsx("span",{className:"text-right tabular-nums font-medium",children:D(c)}),s.jsxs("span",{className:"text-muted-foreground",children:["Commission (",y,"%)"]}),s.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",D(k)]}),s.jsxs("span",{className:"text-muted-foreground",children:["Closing (",T,"%)"]}),s.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",D(P)]}),f>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-muted-foreground",children:"Mortgage payoff"}),s.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",D(f)]})]})]}),s.jsxs("div",{className:"bg-gradient-to-r from-emerald-500/10 to-primary/10 px-5 py-4 border-t flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(I9,{className:"w-5 h-5 text-emerald-600"}),s.jsx("span",{className:"font-semibold",children:"Your estimated walk-away"})]}),s.jsx("span",{className:"text-2xl font-bold tabular-nums text-emerald-700",children:D(R)})]})]}),s.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:"This is a rough estimate to help you think through pricing. Actual proceeds depend on title fees, prorations, repairs, and other items your agent will walk through in detail."})]})]})}const Eit={quick:eS,target:TC,stretch:Nx},jit=t=>`$${Math.round(t).toLocaleString()}`;function Ait({ai:t,agentFirstName:e}){var i,o;const r=((i=t.tiers)==null?void 0:i.length)===3?t.tiers:[],n=(t.summary||"").split(/\n{2,}/).filter(Boolean);return s.jsxs("section",{className:"space-y-6",children:[s.jsxs("div",{className:"max-w-3xl",children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"Your pricing strategy"}),s.jsx("h2",{className:"text-2xl md:text-4xl font-bold leading-tight tracking-tight",children:t.headline||"Where your home fits in today’s market"})]}),r.length>0&&s.jsx("div",{className:"grid md:grid-cols-3 gap-4 items-stretch",children:r.map((c,a)=>{const f=Eit[c.key]||TC,p=c.key==="target";return s.jsxs($n,{className:qt("relative overflow-hidden animate-fade-in transition-transform",p?"border-primary shadow-xl md:-translate-y-2 bg-gradient-to-b from-primary/10 to-card":"shadow-sm"),style:{animationDelay:`${a*120}ms`},children:[p&&s.jsx("div",{className:"absolute inset-x-0 top-0 h-1 bg-primary"}),s.jsxs(Kn,{className:"p-6 flex flex-col h-full",children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsx("div",{className:qt("w-10 h-10 rounded-xl flex items-center justify-center",p?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"),children:s.jsx(f,{className:"w-5 h-5"})}),p&&s.jsxs(ss,{className:"gap-1",children:[s.jsx(lc,{className:"w-3 h-3",fill:"currentColor"}),e?`${e}’s pick`:"Recommended"]})]}),s.jsx("p",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:c.label}),s.jsx("div",{className:qt("font-bold tabular-nums mt-1",p?"text-4xl text-primary":"text-3xl"),children:jit(c.price)}),s.jsx("p",{className:"text-sm text-muted-foreground mt-3 leading-relaxed",children:c.note})]})]},c.key)})}),n.length>0&&s.jsx($n,{className:"border-primary/20",children:s.jsxs(Kn,{className:"p-6 md:p-10 grid md:grid-cols-[auto,1fr] gap-6",children:[s.jsx("div",{className:"hidden md:block w-1 rounded-full bg-gradient-to-b from-primary to-primary/10"}),s.jsx("div",{className:"space-y-4 text-base md:text-lg leading-relaxed text-foreground/90",children:n.map((c,a)=>s.jsx("p",{children:c},a))})]})}),!!((o=t.marketStats)!=null&&o.length)&&s.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:t.marketStats.map((c,a)=>s.jsxs("div",{className:"rounded-2xl border bg-card p-4 md:p-5 text-center",children:[s.jsx("div",{className:"text-xl md:text-2xl font-bold tabular-nums",children:c.value}),s.jsx("div",{className:"text-[11px] uppercase tracking-wider text-muted-foreground mt-1",children:c.label})]},a))}),(t.adjustmentsExplainer||t.competingInventory)&&s.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[t.adjustmentsExplainer&&s.jsx($n,{children:s.jsxs(Kn,{className:"p-6",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2 text-primary",children:[s.jsx(sMe,{className:"w-4 h-4"}),s.jsx("p",{className:"text-xs uppercase tracking-widest font-semibold",children:"How the comps were adjusted"})]}),s.jsx("p",{className:"text-sm md:text-base text-muted-foreground leading-relaxed",children:t.adjustmentsExplainer})]})}),t.competingInventory&&s.jsx($n,{children:s.jsxs(Kn,{className:"p-6",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2 text-primary",children:[s.jsx(N9,{className:"w-4 h-4"}),s.jsx("p",{className:"text-xs uppercase tracking-widest font-semibold",children:"Your competition"})]}),s.jsx("p",{className:"text-sm md:text-base text-muted-foreground leading-relaxed",children:t.competingInventory})]})})]})]})}function d1e({tokenOverride:t}={}){var Pt,tr,_t,cr,Tr,sn,ur,xr,rr,vn,ct,jt,er,Pr;const e=Pm(),r=t??e.token,[n,i]=C.useState(null),[o,c]=C.useState(null),[a,f]=C.useState([]),[p,y]=C.useState(!0),[v,T]=C.useState(""),[E,k]=C.useState(""),[P,R]=C.useState(""),[D,M]=C.useState(!1),[B,V]=C.useState(!1),[G,W]=C.useState(null),[Y,J]=C.useState(null),[Q,ee]=C.useState(!1),{toast:le}=Rfe();C.useEffect(()=>{r&&(async()=>{const{data:dr}=await Re.from("cmas").select("*").eq("share_token",r).eq("status","shared").maybeSingle();if(!dr){y(!1);return}i(dr);const[{data:ar},{data:Nt}]=await Promise.all([Re.from("cma_comps").select("*").eq("cma_id",dr.id).order("position"),Re.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",dr.agent_id).maybeSingle()]);f((ar||[]).filter(En=>En.selected)),c(Nt);const gr=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",gr),await Re.from("cma_views").insert({cma_id:dr.id,visitor_token:gr,user_agent:navigator.userAgent}),y(!1)})()},[r]);const pe=async dr=>{if(!n)return;const ar=localStorage.getItem("cma_visitor_token")||"";await Re.from("cma_views").insert({cma_id:n.id,visitor_token:ar,reactions:{[dr]:!0}}),Re.functions.invoke("cma-reply-notify",{body:{shareToken:r,reaction:dr,visitorToken:ar}}).catch(()=>{}),le({title:"Thanks — your agent just got notified ✨"})},Se=!(n!=null&&n.contact_id),je=async()=>{if(!n||!v.trim())return;if(Se&&(!E.trim()||!P.trim())){le({title:"Please add your name and email",variant:"destructive"});return}M(!0);const dr=localStorage.getItem("cma_visitor_token")||"",{data:ar,error:Nt}=await Re.functions.invoke("cma-reply-notify",{body:{shareToken:r,message:v,visitorToken:dr,viewerName:E.trim()||void 0,viewerEmail:P.trim()||void 0}});if(M(!1),Nt||!(ar!=null&&ar.success)){le({title:"Could not send",description:(Nt==null?void 0:Nt.message)||(ar==null?void 0:ar.error),variant:"destructive"});return}T(""),V(!0),le({title:"Message sent to your agent"})},Le=C.useMemo(()=>{const dr=a.map(ar=>{const Nt=ar.snapshot,gr=(Nt==null?void 0:Nt.soldPrice)||(Nt==null?void 0:Nt.price);return gr&&(Nt!=null&&Nt.sqft)?gr/Nt.sqft:null}).filter(ar=>!!ar).sort((ar,Nt)=>ar-Nt);return dr.length?Math.round(dr[Math.floor(dr.length/2)]):null},[a]);if(p)return s.jsx("div",{className:"min-h-screen flex items-center justify-center",children:s.jsx(su,{className:"w-8 h-8 animate-spin"})});if(!n)return s.jsx("div",{className:"min-h-screen flex items-center justify-center text-center p-6",children:s.jsxs("div",{children:[s.jsx(va,{className:"w-12 h-12 mx-auto text-muted-foreground mb-4"}),s.jsx("h1",{className:"text-xl font-semibold",children:"CMA not found"}),s.jsx("p",{className:"text-muted-foreground",children:"This report may have been removed or unpublished."})]})});const Ae=n.subject||{},be=(Pt=n.settings)==null?void 0:Pt.personalVideo,me=(tr=Ae.photos)==null?void 0:tr[0],Te=n.contact_first_name?n.contact_first_name:null,Ne=((o==null?void 0:o.name)||"A").split(" ").map(dr=>dr[0]).slice(0,2).join("").toUpperCase(),Ee=o!=null&&o.phone?`tel:${String(o.phone).replace(/[^\d+]/g,"")}`:null,we=o!=null&&o.email?`mailto:${o.email}`:null,He=o!=null&&o.phone?`sms:${String(o.phone).replace(/[^\d+]/g,"")}`:null,tt=n.price_low??null,at=n.price_likely??null,Et=n.price_high??null,vt=tt&&at&&Et,Gt=at&&Ae.sqft?Math.round(at/Ae.sqft):null,pt=Gt&&Le?Math.round((Gt-Le)/Le*100):null;return s.jsxs("div",{className:"min-h-screen bg-background pb-28 md:pb-0",children:[o&&s.jsx("div",{className:"border-b bg-card sticky top-0 z-40 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:s.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-6 py-3 flex items-center gap-3",children:[o.avatar_url?s.jsx("img",{src:o.avatar_url,alt:o.name,className:"w-10 h-10 rounded-full object-cover ring-2 ring-primary/20"}):s.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center font-semibold text-primary text-sm",children:Ne}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"font-semibold leading-tight truncate text-sm",children:o.name}),(o.title||o.brokerage_name)&&s.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center gap-1 truncate",children:[o.brokerage_name&&s.jsx(_o,{className:"w-3 h-3 shrink-0"}),s.jsx("span",{className:"truncate",children:[o.title,o.brokerage_name].filter(Boolean).join(" · ")})]})]}),s.jsxs("div",{className:"hidden md:flex items-center gap-2",children:[Ee&&s.jsx(Bt,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:Ee,children:[s.jsx(ri,{className:"w-4 h-4 mr-1"}),"Call"]})}),we&&s.jsx(Bt,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:we,children:[s.jsx(mi,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),s.jsxs("div",{className:"relative overflow-hidden",children:[me?s.jsxs("div",{className:"absolute inset-0",children:[s.jsx("img",{src:me,alt:Ae.address,className:"w-full h-full object-cover scale-110 animate-[kenburns_18s_ease-out_infinite_alternate]",style:{animation:"kenburns 22s ease-in-out infinite alternate"}}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-950/85 via-slate-900/75 to-primary/60"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-background via-background/20 to-transparent"})]}):s.jsxs("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-950 via-slate-900 to-primary",children:[s.jsx("div",{className:"absolute inset-0 opacity-30 [background:radial-gradient(circle_at_80%_20%,hsl(var(--primary)/0.6),transparent_55%)]"}),s.jsx("div",{className:"absolute inset-x-0 bottom-0 h-24 bg-gradient-to-t from-background to-transparent"})]}),s.jsx("style",{children:` @keyframes kenburns { 0% { transform: scale(1.08) translate(0, 0); } 100% { transform: scale(1.18) translate(-1.5%, -1%); } } `}),s.jsx("div",{className:"relative container mx-auto max-w-6xl px-4 md:px-8 pt-12 md:pt-20 pb-16 md:pb-24",children:s.jsxs("div",{className:"grid md:grid-cols-5 gap-8 items-center",children:[s.jsxs("div",{className:`${be!=null&&be.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[s.jsxs(ss,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[s.jsx(xs,{className:"w-3 h-3 mr-1"}),Te?`Prepared for ${Te}`:n.buyer_mode?"Your Buyer Analysis":"Your Market Analysis"]}),s.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold leading-[1.05] tracking-tight",children:Ae.address}),s.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[s.jsx(Es,{className:"w-4 h-4"}),Ae.city,", ",Ae.state," ",Ae.zip]}),vt&&s.jsxs("div",{className:"mt-8 md:mt-10",children:[s.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-white/60 mb-2",children:"Estimated Value"}),s.jsx("div",{className:"flex items-baseline gap-4 flex-wrap",children:s.jsx("div",{className:"text-5xl md:text-7xl font-bold tabular-nums",children:s.jsx(ER,{to:at,prefix:"$",durationMs:1600,delayMs:250})})}),s.jsxs("div",{className:"mt-4 flex items-center gap-3 md:gap-6 text-sm text-white/80",children:[s.jsxs("div",{children:[s.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Low"}),s.jsx("span",{className:"tabular-nums font-medium",children:s.jsx(ER,{to:tt,prefix:"$",delayMs:500})})]}),s.jsx("div",{className:"h-8 w-px bg-white/20"}),s.jsxs("div",{children:[s.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Likely"}),s.jsx("span",{className:"tabular-nums font-medium",children:s.jsx(ER,{to:at,prefix:"$",delayMs:650})})]}),s.jsx("div",{className:"h-8 w-px bg-white/20"}),s.jsxs("div",{children:[s.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"High"}),s.jsx("span",{className:"tabular-nums font-medium",children:s.jsx(ER,{to:Et,prefix:"$",delayMs:800})})]})]})]})]}),(be==null?void 0:be.url)&&s.jsx("div",{className:"md:col-span-2 animate-scale-in",children:s.jsxs("button",{onClick:()=>ee(!0),className:"group relative w-full aspect-[4/5] md:aspect-[4/5] rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/20 bg-black",children:[be.thumb?s.jsx("img",{src:be.thumb,alt:"",className:"w-full h-full object-cover"}):s.jsx("video",{src:be.url,className:"w-full h-full object-cover",muted:!0,playsInline:!0,preload:"metadata"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 to-black/10 group-hover:from-black/40 transition-colors"}),s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-white",children:[s.jsx("div",{className:"w-16 h-16 md:w-20 md:h-20 rounded-full bg-white/95 text-primary flex items-center justify-center shadow-2xl group-hover:scale-110 transition-transform",children:s.jsx(QDe,{className:"w-7 h-7 md:w-8 md:h-8 ml-1",fill:"currentColor"})}),s.jsxs("p",{className:"mt-4 text-sm font-medium tracking-wide",children:["A message from ",((_t=o==null?void 0:o.name)==null?void 0:_t.split(" ")[0])||"your agent"]})]})]})})]})})]}),Q&&(be==null?void 0:be.url)&&s.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>ee(!1),children:s.jsxs("div",{className:"relative w-full max-w-4xl",onClick:dr=>dr.stopPropagation(),children:[s.jsx("video",{src:be.url,controls:!0,autoPlay:!0,className:"w-full rounded-xl"}),s.jsx(Bt,{variant:"ghost",className:"absolute -top-12 right-0 text-white hover:bg-white/10",onClick:()=>ee(!1),children:"Close"})]})}),s.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-8 py-10 md:py-16 space-y-10 md:space-y-14",children:[s.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 -mt-20 md:-mt-24 relative z-10",children:[{label:"Beds",value:Ae.bedrooms??"—"},{label:"Baths",value:Ae.bathrooms??"—"},{label:"Sq Ft",value:((cr=Ae.sqft)==null?void 0:cr.toLocaleString())??"—"},{label:"Year Built",value:Ae.yearBuilt??"—"}].map((dr,ar)=>s.jsx($n,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${ar*80}ms`},children:s.jsxs(Kn,{className:"p-4 md:p-6 text-center",children:[s.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:dr.value}),s.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:dr.label})]})},ar))}),((sn=(Tr=n.settings)==null?void 0:Tr.priceOverride)==null?void 0:sn.enabled)&&((xr=(ur=n.settings)==null?void 0:ur.priceOverride)==null?void 0:xr.note)&&s.jsx($n,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:s.jsxs(Kn,{className:"p-6 md:p-8",children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"A note from your agent"}),s.jsx("p",{className:"text-base md:text-lg leading-relaxed whitespace-pre-wrap text-foreground/90",children:n.settings.priceOverride.note})]})}),((rr=n.settings)==null?void 0:rr.ai)&&s.jsx(Ait,{ai:n.settings.ai,agentFirstName:(vn=o==null?void 0:o.name)==null?void 0:vn.split(" ")[0]}),vt&&s.jsx(Tit,{low:tt,likely:at,high:Et}),Le&&Gt&&s.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[s.jsx($n,{className:"md:col-span-2",children:s.jsxs(Kn,{className:"p-6 md:p-8",children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"Why this price"}),s.jsx("h2",{className:"text-2xl md:text-3xl font-bold mb-3",children:"The market is talking."}),s.jsxs("p",{className:"text-muted-foreground leading-relaxed",children:["Based on ",s.jsxs("strong",{className:"text-foreground",children:[a.length," comparable ",a.length===1?"home":"homes"]})," in ",Ae.city,", the median sale rate is ",s.jsxs("strong",{className:"text-foreground",children:["$",Le,"/sqft"]}),". Applied to your home's ",(ct=Ae.sqft)==null?void 0:ct.toLocaleString()," sqft, the comps support a value near ",s.jsxs("strong",{className:"text-foreground",children:["$",(Le*(Ae.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),s.jsx($n,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:s.jsxs(Kn,{className:"p-6 md:p-8 h-full flex flex-col justify-center",children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground mb-1",children:"Your home"}),s.jsxs("div",{className:"text-3xl font-bold tabular-nums",children:["$",Gt,s.jsx("span",{className:"text-base font-normal text-muted-foreground",children:"/sqft"})]}),s.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Neighborhood avg: ",s.jsxs("span",{className:"font-medium text-foreground",children:["$",Le,"/sqft"]})]}),pt!==null&&pt!==0&&s.jsxs("p",{className:`text-sm font-medium mt-1 ${pt>0?"text-emerald-600":"text-rose-600"}`,children:[pt>0?"▲":"▼"," ",Math.abs(pt),"% ",pt>0?"above":"below"," the median"]})]})})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-baseline justify-between mb-4",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold",children:"Homes like yours"}),s.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"The Comparables"})]}),s.jsxs(ss,{variant:"outline",className:"text-xs",children:[a.length," comps"]})]}),s.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-4",children:a.map((dr,ar)=>{var En,ni;const Nt=dr.snapshot,gr=Nt.soldPrice||Nt.price;return s.jsxs($n,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${Y===ar?"ring-2 ring-primary":""}`,style:{animationDelay:`${ar*60}ms`},onClick:()=>W(ar),onMouseEnter:()=>J(ar),onMouseLeave:()=>J(null),children:[s.jsxs("div",{className:"relative",children:[s.jsx(T8,{photos:Nt.photos,className:`w-full ${(En=Nt.photos)!=null&&En.length?"h-44":"h-20"}`}),s.jsxs(ss,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",ar+1]}),s.jsx(ss,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:Nt.status})]}),s.jsxs(Kn,{className:"p-4",children:[s.jsx("div",{className:"font-semibold leading-tight truncate",children:Nt.address}),s.jsxs("div",{className:"text-xs text-muted-foreground",children:[Nt.city,", ",Nt.state]}),s.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:s.jsxs("span",{className:"text-muted-foreground",children:[Nt.bedrooms??"?","bd · ",Nt.bathrooms??"?","ba · ",((ni=Nt.sqft)==null?void 0:ni.toLocaleString())??"?"," sqft"]})}),s.jsxs("div",{className:"flex justify-between items-center mt-3 pt-3 border-t",children:[s.jsxs("span",{className:"text-xl font-bold tabular-nums",children:["$",gr==null?void 0:gr.toLocaleString()]}),Nt.sqft&&gr?s.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(gr/Nt.sqft),"/sqft"]}):null]}),Nt.ai&&typeof Nt.adjustedPrice=="number"&&s.jsxs("div",{className:"mt-3 rounded-lg bg-primary/5 px-3 py-2 text-xs",children:[s.jsxs("div",{className:"flex justify-between gap-2",children:[s.jsx("span",{className:"text-muted-foreground",children:"Adjusted to your home"}),s.jsxs("span",{className:"font-semibold tabular-nums text-foreground",children:["$",Nt.adjustedPrice.toLocaleString()]})]}),Nt.adjustmentNotes&&s.jsx("p",{className:"text-muted-foreground mt-1 leading-snug line-clamp-2",children:Nt.adjustmentNotes})]})]})]},ar)})})]}),s.jsx(Sit,{comp:G!==null?(jt=a[G])==null?void 0:jt.snapshot:null,open:G!==null,onClose:()=>W(null)}),s.jsx($n,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:s.jsxs(Kn,{className:"p-6 md:p-8 space-y-5",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-1",children:"Your turn"}),s.jsxs("h2",{className:"text-2xl md:text-3xl font-bold",children:["What do you think",Te?`, ${Te}`:"","?"]}),s.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((er=o==null?void 0:o.name)==null?void 0:er.split(" ")[0])||"Your agent"," hears you instantly."]})]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:bm,label:"I love this price"},{kind:"fair",icon:hMe,label:"Seems fair"},{kind:"lower",icon:wme,label:"I'd price lower"},{kind:"higher",icon:Nx,label:"I'd price higher"},{kind:"ready_to_list",icon:OU,label:"Ready to list"},{kind:"want_walkthrough",icon:KO,label:"Want a walkthrough"},{kind:"need_time",icon:oo,label:"Need more time"},{kind:"have_questions",icon:ADe,label:"I have questions"}].map(({kind:dr,icon:ar,label:Nt})=>s.jsxs(Bt,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>pe(dr),children:[s.jsx(ar,{className:"w-4 h-4 mr-2"}),Nt]},dr))}),s.jsxs("div",{className:"pt-4 border-t",children:[s.jsxs("p",{className:"text-sm font-medium mb-2 flex items-center gap-1",children:[s.jsx(J1,{className:"w-4 h-4"}),"Ask your agent a question"]}),B?s.jsxs("div",{className:"rounded-md bg-emerald-50 border border-emerald-200 p-4 text-sm text-emerald-800 animate-fade-in",children:["✓ Sent! ",((Pr=o==null?void 0:o.name)==null?void 0:Pr.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):s.jsxs(s.Fragment,{children:[Se&&s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:[s.jsx("input",{className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your name",value:E,onChange:dr=>k(dr.target.value)}),s.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:P,onChange:dr=>R(dr.target.value)})]}),s.jsx("textarea",{className:"w-full border rounded-md p-3 text-sm min-h-[100px] bg-background",placeholder:"What questions do you have about this analysis?",value:v,onChange:dr=>T(dr.target.value)}),s.jsx(Bt,{onClick:je,disabled:!v.trim()||D,className:"mt-2",children:D?"Sending…":"Send to agent"})]})]})]})}),o&&s.jsx($n,{className:"overflow-hidden border-primary/20",children:s.jsx("div",{className:"bg-gradient-to-br from-primary/10 to-primary/5 p-6 md:p-10",children:s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 items-start",children:[o.avatar_url?s.jsx("img",{src:o.avatar_url,alt:o.name,className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl object-cover ring-4 ring-background shadow-lg"}):s.jsx("div",{className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl bg-primary/20 flex items-center justify-center text-3xl font-bold text-primary ring-4 ring-background shadow-lg",children:Ne}),s.jsxs("div",{className:"flex-1",children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground",children:"Prepared by"}),s.jsx("h2",{className:"text-2xl md:text-3xl font-bold mt-1",children:o.name}),(o.title||o.brokerage_name)&&s.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:[o.title,o.brokerage_name].filter(Boolean).join(" · ")}),o.bio&&s.jsx("p",{className:"text-sm text-muted-foreground mt-3 leading-relaxed",children:o.bio}),s.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[Ee&&s.jsx(Bt,{asChild:!0,children:s.jsxs("a",{href:Ee,children:[s.jsx(ri,{className:"w-4 h-4 mr-2"}),o.phone]})}),we&&s.jsx(Bt,{variant:"outline",asChild:!0,children:s.jsxs("a",{href:we,children:[s.jsx(mi,{className:"w-4 h-4 mr-2"}),"Email"]})}),o.website_url&&s.jsx(Bt,{variant:"outline",asChild:!0,children:s.jsxs("a",{href:o.website_url,target:"_blank",rel:"noreferrer",children:[s.jsx(qv,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),o&&(Ee||He||we)&&s.jsxs("div",{className:"md:hidden fixed bottom-0 left-0 right-0 bg-card/95 backdrop-blur border-t shadow-2xl z-50 px-3 py-3 flex gap-2",style:{paddingBottom:"calc(0.75rem + env(safe-area-inset-bottom))"},children:[Ee&&s.jsx(Bt,{className:"flex-1",asChild:!0,children:s.jsxs("a",{href:Ee,children:[s.jsx(ri,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),He&&s.jsx(Bt,{variant:"outline",className:"flex-1",asChild:!0,children:s.jsxs("a",{href:He,children:[s.jsx(J1,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),we&&s.jsx(Bt,{variant:"outline",className:"flex-1",asChild:!0,children:s.jsxs("a",{href:we,children:[s.jsx(mi,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}const kit=Object.freeze(Object.defineProperty({__proto__:null,default:d1e},Symbol.toStringTag,{value:"Module"}));function Cit(){const e=ki().pathname.slice(1).replace(/\/$/,"");return!e||e.includes("/")?s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"CMA Portal"}),s.jsx("p",{className:"text-slate-500",children:"Open your CMA link to view your personalized market analysis."})]})}):s.jsx(d1e,{tokenOverride:e})}const E8="levelup_affiliate_ref",Nit=30,Iit=()=>{const[t]=Px();C.useEffect(()=>{const e=t.get("ref");if(e){const r={code:e.toUpperCase(),timestamp:Date.now()};localStorage.setItem(E8,JSON.stringify(r)),console.log("[Affiliate] Stored referral code:",e)}},[t])},Pit=()=>{try{const t=localStorage.getItem(E8);if(!t)return null;const e=JSON.parse(t),r=Nit*24*60*60*1e3;return Date.now()-e.timestamp>r?(localStorage.removeItem(E8),console.log("[Affiliate] Referral code expired"),null):e.code}catch{return null}},Oie="/assets/levelup-logo-header-_ZX7DvlA.png",Rit="/assets/scale-your-team-ku4MPatU.png";function Lit({open:t,onOpenChange:e}){return s.jsx(lo,{open:t,onOpenChange:e,children:s.jsxs(qa,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[s.jsx(xl,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-[#4a6b6d]/10 rounded-lg",children:s.jsx(_o,{className:"h-5 w-5 text-[#4a6b6d]"})}),s.jsxs("div",{children:[s.jsx(Xo,{children:"Schedule a Brokerage Interest Meeting"}),s.jsx(wd,{children:"Learn how LevelUp can empower your entire team"})]})]})}),t&&s.jsx("iframe",{src:"https://booking.relevelup.com/jeremy-collins",className:"w-full border-0 rounded-lg",style:{height:"600px",minHeight:"500px"},title:"Schedule Brokerage Interest Meeting"})]})})}const h1e="/assets/mission_control-BJ-Kz8rX.png",Dit="/assets/crm-CsLftmB2.png",Mit="/assets/deal_pipeline-XYgypvwv.png",Oit="/assets/staging_studio-5iLDjnv0.png",Fit="/assets/coaching-CSQEA81I.png",Bit="/assets/marketing_studio-Brx1ZOnN.png";function f1e(){return s.jsxs("nav",{"aria-label":"LevelUp policies",className:"flex flex-wrap items-center justify-center gap-x-5 gap-y-3 rounded-md bg-background px-4 py-3 text-sm text-foreground",children:[s.jsx("a",{href:"/sms-consent",className:"text-primary underline underline-offset-4",children:"SMS Consent"}),s.jsx("a",{href:"/terms-of-service",className:"text-primary underline underline-offset-4",children:"Terms of Service"}),s.jsx("a",{href:"/privacy-policy",className:"text-primary underline underline-offset-4",children:"Privacy Policy"}),s.jsx("a",{href:"/terms-of-service#sms-terms",className:"text-primary underline underline-offset-4",children:"SMS Terms"})]})}const $it=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:h1e},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:Dit},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:Mit},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:Oit},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:Fit},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:Bit}];function zit({slot:t}){return s.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/10 bg-white/5 backdrop-blur-sm shadow-2xl",children:[s.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-white/10",children:[s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),s.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),t.src?s.jsx("img",{src:t.src,alt:`LevelUp ${t.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):s.jsxs("div",{className:"w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 bg-white/5",children:[s.jsx(xs,{className:"h-8 w-8 text-white/40"}),s.jsx("p",{className:"text-sm font-medium text-white/60",children:t.label}),s.jsx("p",{className:"text-xs px-6 text-center text-white/40",children:"Screenshot placeholder"})]}),s.jsxs("figcaption",{className:"px-4 py-3 text-sm text-white/80",children:[s.jsx("span",{className:"font-semibold text-white",children:t.label})," — ",t.caption]})]})}const qd={individual_agent:{name:"Individual Agent",price:"$39",period:"/month",description:"Perfect for independent agents ready to level up",features:["Full dashboard access","300+ professional templates","Academy training library","Community & networking","Live events & workshops","Social media content","Newsletter resources","Email support"],trial:"7-day free trial",popular:!1},brokerage_over_25:{name:"Brokerage",subtitle:"Unlimited Agents",price:"$499",period:"/month",description:"Scale your brokerage without limits",features:["Everything in Individual, plus:","Unlimited agents","Brokerage manager dashboard","Exclusive brokerage resources","Team performance analytics","Agent onboarding tools","Resource sharing","Priority support"],popular:!1}},Uit=[{icon:E9,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:XO,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:oo,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:J1,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:_m,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:hf,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],Vit=[{category:"Marketing Studio",icon:wC,items:["Weekly Reels scripts","Social Post Generator","300+ Canva templates","Marketing Calendar","Postcard Direct Mail","Listing Music Videos","Social Swag drops"]},{category:"Lead Generation",icon:TC,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:UDe,items:["Agent OS CRM","Deal pipeline","Forms & e-signatures","Client portal","Smart follow-up queue","Lead ponds for teams","Google Business reviews"]},{category:"AI & Media",icon:pMe,items:["AI Staging Studio","Video library & sharing","Screen recording","Virtual backgrounds","AI blog writer","YouTube → Blog","Ask AI assistant"]},{category:"Growth & Coaching",icon:WA,items:["Academy courses","Live weekly coaching","Coaching programs","1:1 coaching booking","Private community","Live events & workshops"]},{category:"Brokerage Tools",icon:_o,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],qit=[{icon:fl,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:xs,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:ri,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:jDe,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Es,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:HA,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:bm,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:eS,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],Git=[{name:"Sarah M.",role:"Top Producer, RE/MAX",quote:"LevelUp completely transformed how I run my business. The templates alone save me hours every week."},{name:"Mike T.",role:"Brokerage Owner",quote:"Onboarding new agents used to take weeks. Now they're productive from day one with all the training resources."},{name:"Jessica L.",role:"Team Lead",quote:"The community is incredible. I've learned more from other agents here than any conference I've attended."}],Hit=()=>{const{user:t,loading:e}=Hn(),r=Hs(),[n]=Px();C.useEffect(()=>{const Y=window.location.host==="listings.relevelup.com",J=window.location.pathname==="/";if(Y&&J){r("/public/listings",{replace:!0});return}},[r]);const[i,o]=C.useState(null),[c,a]=C.useState(null),[f,p]=C.useState(!1),[y,v]=C.useState(""),[T,E]=C.useState(""),[k,P]=C.useState(""),[R,D]=C.useState(!1),[M,B]=C.useState(!1),V=(Y,J=!1)=>{a({tier:Y,skipTrial:J}),p(!0)};Iit(),C.useEffect(()=>{const Y=window.location.host==="listings.relevelup.com",J=location.pathname.startsWith("/public/");!e&&t&&!Y&&!J&&r("/dashboard")},[t,e,r,location.pathname]),C.useEffect(()=>{n.get("canceled")==="true"&&Vt.error("Checkout was canceled. Feel free to try again when you're ready!")},[n]);const G=async(Y,J=!1)=>{if(!y){Vt.error("Please enter your email address");return}if(!T.trim()){Vt.error("Please enter your full name");return}D(!0),o(Y+(J?"_direct":""));const Q=Pit();try{const{data:ee,error:le}=await Re.functions.invoke("create-checkout",{body:{tier:Y,email:y,name:T.trim(),couponCode:k.trim()||void 0,skipTrial:J,referralCode:Q}});if(le)throw le;if(ee!=null&&ee.url)window.open(ee.url,"_blank","noopener,noreferrer"),Vt.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(ee){console.error("Checkout error:",ee),Vt.error(ee.message||"Failed to start checkout. Please try again.")}finally{D(!1),o(null),p(!1),a(null)}},W=()=>{c&&G(c.tier,c.skipTrial)};return e?s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#4a6b6d]",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-white border-t-transparent"})}):s.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[s.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:s.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[s.jsx("div",{className:"flex items-center",children:s.jsx("img",{src:Oie,alt:"LevelUp",className:"h-8 md:h-10"})}),s.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[s.jsx(Bt,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var Y;return(Y=document.getElementById("features"))==null?void 0:Y.scrollIntoView({behavior:"smooth"})},children:"Features"}),s.jsx(Bt,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var Y;return(Y=document.getElementById("pricing"))==null?void 0:Y.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),s.jsx(Bt,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>r("/brokerage-solutions"),children:"For Brokerages"}),s.jsx(Bt,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>r("/blog"),children:"Blog"}),s.jsx(Bt,{onClick:()=>r("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),s.jsxs("section",{className:"relative overflow-hidden bg-[#0f2530]",children:[s.jsx("style",{children:` @keyframes hero-float { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-12px); } } @keyframes hero-float-slow { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-8px); } } @keyframes hero-glow { 0%,100% { opacity: 0.55; } 50% { opacity: 0.9; } } `}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-[#122c3a] via-[#16384a] to-[#0f2530]"}),s.jsx("div",{className:"absolute -top-40 left-1/2 -translate-x-1/2 h-[560px] w-[900px] rounded-full bg-[#4aa8a0]/25 blur-[140px] animate-[hero-glow_7s_ease-in-out_infinite]"}),s.jsx("div",{className:"absolute top-1/3 -left-40 h-[420px] w-[420px] rounded-full bg-[#2a6f8a]/20 blur-[120px]"}),s.jsx("div",{className:"absolute top-1/4 -right-40 h-[420px] w-[420px] rounded-full bg-[#c9a84c]/10 blur-[120px]"}),s.jsx("div",{className:"absolute inset-0 opacity-[0.12] bg-[linear-gradient(to_right,rgba(255,255,255,0.5)_1px,transparent_1px),linear-gradient(to_bottom,rgba(255,255,255,0.5)_1px,transparent_1px)] bg-[size:56px_56px] [mask-image:radial-gradient(ellipse_75%_65%_at_50%_35%,black,transparent)]"}),s.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-[#0f2530] to-transparent"}),s.jsxs("div",{className:"container mx-auto px-4 relative",children:[s.jsxs("div",{className:"max-w-5xl mx-auto text-center pt-20 md:pt-28 pb-10 space-y-8",children:[s.jsx("div",{className:"flex justify-center animate-fade-in",children:s.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/5 backdrop-blur-sm px-4 py-1.5 text-xs md:text-sm font-semibold tracking-wide text-white/85 shadow-lg",children:[s.jsx(xs,{className:"h-3.5 w-3.5 text-[#7fd4cc]"}),"The Agent Operating System — coaching, CRM & marketing in one"]})}),s.jsxs("h1",{className:"text-4xl sm:text-5xl md:text-7xl font-sans font-bold tracking-tight text-white leading-[1.05] animate-fade-in",children:["The tools you need",s.jsx("br",{className:"hidden sm:block"})," to get it done.",s.jsx("span",{className:"block mt-3 bg-gradient-to-r from-[#8fe0d6] via-[#5cc0b6] to-[#e6c878] bg-clip-text text-transparent",children:"The platform to keep it going."})]}),s.jsx("p",{className:"text-base md:text-xl text-white/65 max-w-2xl mx-auto leading-relaxed animate-fade-in",children:"Weekly coaching, a smart CRM, done-for-you marketing and AI tools — everything a modern agent runs on, in one login."}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-2 animate-fade-in",children:[s.jsxs(Bt,{size:"lg",onClick:()=>{var Y;return(Y=document.getElementById("free-trial"))==null?void 0:Y.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold bg-white text-[#122c3a] hover:bg-white/90 shadow-[0_0_40px_-8px_rgba(140,220,210,0.6)] transition-all hover:scale-105 group rounded-full",children:["Start Your Free Trial",s.jsx(Ds,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),s.jsx(Bt,{size:"lg",variant:"outline",onClick:()=>{var Y;return(Y=document.getElementById("features"))==null?void 0:Y.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold border-2 border-white/40 text-white bg-white/5 backdrop-blur-sm hover:bg-white hover:text-[#122c3a] rounded-full",children:"See What's Included"})]}),s.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-8 gap-y-3 pt-2 text-sm text-white/55 animate-fade-in",children:[s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx(lc,{className:"h-4 w-4 text-[#e6c878] fill-[#e6c878]"})," Built with agents' direct input"]}),s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx(eS,{className:"h-4 w-4 text-[#7fd4cc]"})," New tools added every month"]}),s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx(KA,{className:"h-4 w-4 text-white/60"})," Cancel anytime"]})]})]}),s.jsxs("div",{className:"relative max-w-5xl mx-auto pb-20 md:pb-28 px-2",children:[s.jsx("div",{className:"absolute inset-x-8 top-10 bottom-0 rounded-[40px] bg-gradient-to-b from-[#4aa8a0]/30 to-transparent blur-2xl","aria-hidden":!0}),s.jsxs("div",{className:"relative animate-[hero-float-slow_8s_ease-in-out_infinite]",children:[s.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/15 bg-[#0d1f29]/80 backdrop-blur-md shadow-[0_40px_80px_-20px_rgba(0,0,0,0.7)]",children:[s.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2.5 border-b border-white/10 bg-white/5",children:[s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),s.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),s.jsx("img",{src:h1e,alt:"LevelUp Agent Command Center dashboard",className:"w-full h-auto block"})]}),s.jsxs("div",{className:"hidden md:flex absolute -left-10 top-24 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_6s_ease-in-out_infinite]",children:[s.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[#4aa8a0]/20",children:s.jsx(Nx,{className:"h-5 w-5 text-[#7fd4cc]"})}),s.jsxs("span",{children:[s.jsx("span",{className:"block text-sm font-semibold text-white",children:"Smart Queue ready"}),s.jsx("span",{className:"block text-xs text-white/55",children:"5 follow-ups due today"})]})]}),s.jsxs("div",{className:"hidden md:flex absolute -right-10 top-1/2 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_7s_ease-in-out_infinite_1s]",children:[s.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[#e6c878]/15",children:s.jsx(E9,{className:"h-5 w-5 text-[#e6c878]"})}),s.jsxs("span",{children:[s.jsx("span",{className:"block text-sm font-semibold text-white",children:"Weekly Reels delivered"}),s.jsx("span",{className:"block text-xs text-white/55",children:"Fresh scripts every Monday"})]})]}),s.jsxs("div",{className:"hidden md:flex absolute left-8 -bottom-6 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_6.5s_ease-in-out_infinite_0.5s]",children:[s.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-white/10",children:s.jsx(oo,{className:"h-5 w-5 text-white/80"})}),s.jsxs("span",{children:[s.jsx("span",{className:"block text-sm font-semibold text-white",children:"Coaching booked"}),s.jsx("span",{className:"block text-xs text-white/55",children:"Meet link added automatically"})]})]})]})]})]})]}),s.jsx("section",{className:"py-20 bg-background",children:s.jsx("div",{className:"container mx-auto px-4",children:s.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[s.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),s.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[s.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),s.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),s.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."}),s.jsx("p",{className:"text-lg text-muted-foreground",children:"Learn how we support agents and empower brokerages to grow—together."}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center pt-4",children:[s.jsxs(Bt,{size:"lg",variant:"outline",onClick:()=>{var Y;return(Y=document.getElementById("brokerage"))==null?void 0:Y.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[s.jsx(_o,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),s.jsxs(Bt,{size:"lg",onClick:()=>{var Y;return(Y=document.getElementById("pricing"))==null?void 0:Y.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[s.jsx(Ml,{className:"mr-2 h-5 w-5"}),"Individual Membership"]})]})]})})}),s.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:s.jsxs("div",{className:"container mx-auto px-4",children:[s.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[s.jsxs("span",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-semibold mb-5",children:[s.jsx(FDe,{className:"w-4 h-4"}),"40+ tools & counting"]}),s.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),s.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:Uit.map((Y,J)=>s.jsxs($n,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[s.jsxs(ud,{children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:s.jsx(Y.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),s.jsx(dd,{className:"text-xl font-sans",children:Y.title})]}),s.jsx(Kn,{children:s.jsx("p",{className:"text-muted-foreground leading-relaxed",children:Y.description})})]},J))}),s.jsxs("div",{className:"mt-14 max-w-6xl mx-auto rounded-3xl bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] p-8 md:p-12 relative overflow-hidden shadow-2xl",children:[s.jsx("div",{className:"absolute inset-0 opacity-10",children:s.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),s.jsxs("div",{className:"relative",children:[s.jsxs("div",{className:"text-center mb-10",children:[s.jsx("h3",{className:"text-2xl md:text-3xl font-bold text-white font-sans",children:"...and that's just the beginning"}),s.jsx("p",{className:"text-white/60 mt-2",children:"Dozens of purpose-built tools, all included with membership."})]}),s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-10 gap-y-8",children:Vit.map(Y=>s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2.5 mb-4",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-white/10",children:s.jsx(Y.icon,{className:"h-4 w-4 text-white"})}),s.jsx("span",{className:"text-sm font-bold uppercase tracking-wider text-white/90",children:Y.category})]}),s.jsx("ul",{className:"space-y-2.5",children:Y.items.map(J=>s.jsxs("li",{className:"flex items-center gap-2.5 text-white/70 text-sm",children:[s.jsx(no,{className:"h-3.5 w-3.5 text-emerald-300 shrink-0"}),J]},J))})]},Y.category))}),s.jsxs("p",{className:"text-center text-white/50 text-sm mt-10 flex items-center justify-center gap-2",children:[s.jsx(xs,{className:"h-4 w-4"}),"New tools added every month — membership keeps getting more valuable."]})]})]})]})}),s.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 opacity-10",children:s.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),s.jsxs("div",{className:"container mx-auto px-4 relative",children:[s.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-14",children:[s.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-white/70",children:"See it in action"}),s.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight font-sans",children:"A real platform, not another course"}),s.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto text-lg",children:"This is what members open every morning."})]}),s.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10 max-w-6xl mx-auto",children:$it.map(Y=>s.jsx(zit,{slot:Y},Y.key))})]})]}),s.jsxs("section",{id:"agent-os",className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 opacity-10",children:s.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),s.jsxs("div",{className:"container mx-auto px-4 relative",children:[s.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[s.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[s.jsx(xs,{className:"w-4 h-4"}),"Included with Membership"]}),s.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",s.jsx("span",{className:"italic",children:"Agent OS"})]}),s.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:qit.map((Y,J)=>s.jsxs($n,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[s.jsxs(ud,{className:"pb-3",children:[s.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:s.jsx(Y.icon,{className:"w-6 h-6 text-white"})}),s.jsx(dd,{className:"text-lg font-semibold text-white",children:Y.title})]}),s.jsx(Kn,{children:s.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:Y.description})})]},J))}),s.jsx("div",{className:"text-center mt-12",children:s.jsxs(Bt,{size:"lg",onClick:()=>{var Y;return(Y=document.getElementById("pricing"))==null?void 0:Y.scrollIntoView({behavior:"smooth"})},className:"bg-white text-[#4a6b6d] hover:bg-white/90 shadow-xl transition-all hover:scale-105",children:["Get Agent OS with Your Membership",s.jsx(Ds,{className:"ml-2 w-5 h-5"})]})})]})]}),s.jsx("section",{id:"brokerage",className:"py-20 bg-[#4a6b6d]/5",children:s.jsx("div",{className:"container mx-auto px-4",children:s.jsx("div",{className:"max-w-6xl mx-auto",children:s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-12 items-center",children:[s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium",children:[s.jsx(_o,{className:"w-4 h-4"}),"For Brokerages"]}),s.jsxs("h2",{className:"text-3xl font-sans font-bold md:text-6xl",children:["Empower Your"," ",s.jsx("span",{className:"italic text-[#4a6b6d]",children:"Entire Team"})]}),s.jsx("p",{className:"text-lg text-muted-foreground",children:"Give every agent on your team access to world-class training and resources. Track performance, streamline onboarding, and watch your brokerage thrive."}),s.jsx("ul",{className:"space-y-4",children:["Dedicated brokerage manager dashboard","Invite and manage agents with one click","Exclusive brokerage-only resources","Team analytics and performance tracking","Simplified agent onboarding","Share resources across your team"].map((Y,J)=>s.jsxs("li",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center flex-shrink-0",children:s.jsx(no,{className:"w-4 h-4 text-[#4a6b6d]"})}),s.jsx("span",{className:"text-foreground",children:Y})]},J))}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[s.jsxs(Bt,{size:"lg",onClick:()=>{var Y;return(Y=document.getElementById("pricing"))==null?void 0:Y.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",s.jsx(jd,{className:"ml-2 w-5 h-5"})]}),s.jsxs(Bt,{size:"lg",variant:"outline",onClick:()=>B(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[s.jsx(oo,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),s.jsx("div",{className:"relative hidden md:block",children:s.jsx("img",{src:Rit,alt:"Scale Your Team from 5 to 500 Agents",className:"w-full rounded-3xl shadow-lg"})})]})})})}),s.jsx("section",{className:"py-20 bg-background",children:s.jsxs("div",{className:"container mx-auto px-4",children:[s.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[s.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Agents Love ",s.jsx("span",{className:"italic text-[#4a6b6d]",children:"LevelUp"})]}),s.jsx("p",{className:"text-lg text-muted-foreground",children:"See what top producers are saying about the platform."})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-8 max-w-6xl mx-auto",children:Git.map((Y,J)=>s.jsx($n,{className:"bg-muted/30 border-0",children:s.jsxs(Kn,{className:"pt-8",children:[s.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(Q=>s.jsx(lc,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},Q))}),s.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',Y.quote,'"']}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold",children:Y.name}),s.jsx("p",{className:"text-sm text-muted-foreground",children:Y.role})]})]})},J))})]})}),s.jsxs("section",{id:"free-trial",className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 opacity-10",children:s.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),s.jsx("div",{className:"container mx-auto px-4 relative",children:s.jsxs("div",{className:"max-w-3xl mx-auto text-center space-y-8",children:[s.jsxs("h2",{className:"text-3xl md:text-5xl font-bold text-white",children:["Start Your Free Trial ",s.jsx("span",{className:"italic",children:"Today"})]}),s.jsx("p",{className:"text-lg md:text-xl text-white/80 leading-relaxed",children:"Get instant access to 7 days of trainings, templates, and tools — designed to give you quick wins now and resources you'll keep forever."}),s.jsx("div",{className:"pt-4",children:s.jsxs(Bt,{size:"lg",className:"px-12 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group rounded-full",onClick:()=>V("individual_agent"),children:["Start Free Trial",s.jsx(Ds,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]})})]}),s.jsx("section",{id:"pricing",className:"py-20 bg-muted/30",children:s.jsxs("div",{className:"container mx-auto px-4",children:[s.jsxs("div",{className:"text-center mb-16",children:[s.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Simple, Transparent ",s.jsx("span",{className:"italic text-[#4a6b6d]",children:"Pricing"})]}),s.jsx("p",{className:"text-lg text-muted-foreground max-w-2xl mx-auto",children:"Choose the plan that fits your needs. All plans include everything you need to succeed."})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8 max-w-4xl mx-auto",children:[s.jsxs($n,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[s.jsxs(ud,{className:"pb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/10 flex items-center justify-center",children:s.jsx(Ml,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsx(dd,{className:"text-xl font-sans",children:qd.individual_agent.name})]}),s.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[s.jsx("span",{className:"text-5xl font-bold",children:qd.individual_agent.price}),s.jsx("span",{className:"text-muted-foreground text-lg",children:qd.individual_agent.period})]}),s.jsx(ak,{className:"text-base mt-2",children:qd.individual_agent.description}),s.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-green-500/10 text-green-600 text-sm font-medium mt-4",children:[s.jsx(Dl,{className:"w-4 h-4"}),qd.individual_agent.trial]})]}),s.jsx(Kn,{className:"flex-1 pt-0",children:s.jsx("ul",{className:"space-y-3",children:qd.individual_agent.features.map((Y,J)=>s.jsxs("li",{className:"flex items-center gap-3",children:[s.jsx(no,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),s.jsx("span",{children:Y})]},J))})}),s.jsxs(NV,{className:"flex flex-col gap-3 pt-4",children:[s.jsx(Bt,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>V("individual_agent"),children:"Start Free Trial"}),s.jsx(Bt,{variant:"outline",className:"w-full rounded-full border-2 border-[#4a6b6d] text-[#4a6b6d] bg-white hover:bg-[#4a6b6d]/5 uppercase text-sm font-medium tracking-wide",onClick:()=>V("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),s.jsxs($n,{className:"relative flex flex-col border-2 border-[#4a6b6d] shadow-2xl bg-background",children:[s.jsx("div",{className:"absolute -top-4 left-1/2 -translate-x-1/2 px-6 py-2 bg-[#4a6b6d] text-white text-sm font-semibold rounded-full shadow-lg",children:"Most Popular"}),s.jsxs(ud,{className:"pb-4 pt-8",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/20 flex items-center justify-center",children:s.jsx(_o,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsxs("div",{children:[s.jsx(dd,{className:"text-xl font-sans",children:qd.brokerage_over_25.name}),s.jsx("span",{className:"text-sm text-muted-foreground",children:qd.brokerage_over_25.subtitle})]})]}),s.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[s.jsx("span",{className:"text-5xl font-bold",children:qd.brokerage_over_25.price}),s.jsx("span",{className:"text-muted-foreground text-lg",children:qd.brokerage_over_25.period})]}),s.jsx(ak,{className:"text-base mt-2",children:qd.brokerage_over_25.description})]}),s.jsx(Kn,{className:"flex-1 pt-0",children:s.jsx("ul",{className:"space-y-3",children:qd.brokerage_over_25.features.map((Y,J)=>s.jsxs("li",{className:"flex items-center gap-3",children:[s.jsx(no,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),s.jsx("span",{children:Y})]},J))})}),s.jsxs(NV,{className:"pt-4 flex flex-col gap-3",children:[s.jsx(Bt,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>V("brokerage_over_25"),children:"Get Started"}),s.jsxs(Bt,{variant:"link",className:"text-[#4a6b6d]",onClick:()=>r("/brokerage-solutions"),children:["Explore all brokerage management tools ",s.jsx(Ds,{className:"ml-1 w-4 h-4"})]})]})]})]})]})}),s.jsx("section",{id:"neutrality",className:"py-20 bg-background",children:s.jsx("div",{className:"container mx-auto px-4",children:s.jsxs("div",{className:"max-w-4xl mx-auto",children:[s.jsxs("div",{className:"text-center mb-12",children:[s.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium mb-4",children:[s.jsx(KA,{className:"w-4 h-4"}),"Our Commitment"]}),s.jsxs("h2",{className:"text-3xl md:text-4xl font-sans font-bold",children:["LevelUp Brokerage ",s.jsx("span",{className:"italic text-[#4a6b6d]",children:"Neutrality Policy"})]}),s.jsx("p",{className:"text-lg text-muted-foreground mt-4 max-w-2xl mx-auto",children:"We are committed to being a trusted, independent partner for every agent and brokerage."})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[s.jsx($n,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:s.jsxs(Kn,{className:"p-6 flex items-start gap-4",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:s.jsx(_o,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),s.jsx($n,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:s.jsxs(Kn,{className:"p-6 flex items-start gap-4",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:s.jsx(hx,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not share member information with any brokerage."})]})}),s.jsx($n,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:s.jsxs(Kn,{className:"p-6 flex items-start gap-4",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:s.jsx(zU,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not recruit brokerage partners' agents."})]})}),s.jsx($n,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:s.jsxs(Kn,{className:"p-6 flex items-start gap-4",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:s.jsx(_m,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not use LevelUp events, trainings, webinars, CRM data, or member lists for recruiting purposes."})]})})]})]})})}),s.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 opacity-10",children:s.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),s.jsx("div",{className:"container mx-auto px-4 relative",children:s.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[s.jsx("h2",{className:"text-3xl text-white font-sans md:text-5xl",children:"Ready to Level Up?"}),s.jsx("p",{className:"text-lg text-white/80 max-w-2xl mx-auto",children:"Join thousands of agents who are closing more deals, saving time, and growing their business with LevelUp."}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[s.jsxs(Bt,{size:"lg",onClick:()=>{var Y;return(Y=document.getElementById("pricing"))==null?void 0:Y.scrollIntoView({behavior:"smooth"})},className:"px-10 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105",children:["Start Your Free Trial",s.jsx(Ds,{className:"ml-2 w-5 h-5"})]}),s.jsx(Bt,{size:"lg",onClick:()=>r("/auth"),className:"px-10 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#4a6b6d]",children:"Sign In"})]})]})})]}),s.jsx("footer",{className:"py-12 bg-[#3d5a5c] text-white/80",children:s.jsxs("div",{className:"container mx-auto px-4",children:[s.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[s.jsx("img",{src:Oie,alt:"LevelUp",className:"h-8"}),s.jsxs("p",{className:"text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),s.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-6",children:[s.jsx("a",{href:"/brokerage-solutions",className:"text-white/60 hover:text-white transition-colors text-sm",children:"For Brokerages"}),s.jsx("a",{href:"/blog",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Blog"}),s.jsx("a",{href:"/privacy-policy",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Privacy Policy"}),s.jsx("a",{href:"mailto:support@relevelup.com",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Contact Support"})]})]}),s.jsx("div",{className:"mt-6",children:s.jsx(f1e,{})})]})}),s.jsx(Lit,{open:M,onOpenChange:B}),s.jsx(lo,{open:f,onOpenChange:p,children:s.jsxs(qa,{className:"sm:max-w-md",children:[s.jsxs(xl,{children:[s.jsx(Xo,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),s.jsx(wd,{children:(c==null?void 0:c.tier)==="individual_agent"&&!(c!=null&&c.skipTrial)?"Start your 7-day free trial":(c==null?void 0:c.tier)==="individual_agent"?"Subscribe to Individual Agent":"Subscribe to Brokerage"})]}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{children:[s.jsxs(Mr,{htmlFor:"dialog-name",children:["Full Name ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx(Br,{id:"dialog-name",type:"text",placeholder:"John Smith",value:T,onChange:Y=>E(Y.target.value),className:"mt-1",required:!0})]}),s.jsxs("div",{children:[s.jsxs(Mr,{htmlFor:"dialog-email",children:["Email Address ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx(Br,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:y,onChange:Y=>v(Y.target.value),className:"mt-1",required:!0})]}),s.jsxs("div",{children:[s.jsxs(Mr,{htmlFor:"dialog-coupon",children:["Discount Code ",s.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),s.jsx(Br,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:k,onChange:Y=>P(Y.target.value),className:"mt-1"})]})]}),s.jsx(Bt,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:W,disabled:R,children:R?"Loading...":"Continue to Checkout"})]})})]})},Wit="/__l5e/assets-v1/68014836-514e-4076-834c-9b66112cd2a0/levelup-logo-horizontal.png",Kit=mg({email:Ai().email("Invalid email address"),password:Ai().min(6,"Password must be at least 6 characters")}),m1e="https://dashboard.relevelup.com",jR="/oauth-connect",Yit=`${m1e}/profile?reset=true`,zL="levelupOAuthRouteHistory";function Fie(t){return t.startsWith("/")&&!t.startsWith("//")&&!t.includes("://")}function Zit(t){const e=Date.now(),r=15e3;try{const o=[...JSON.parse(sessionStorage.getItem(zL)??"[]").filter(a=>e-a.ata.route));return o.length>=6&&c.has("auth")&&c.has("consent")}catch{return sessionStorage.setItem(zL,JSON.stringify([{route:t,at:e}])),!1}}function Xit(){sessionStorage.removeItem(zL)}const Bie=()=>{const{signIn:t,user:e,loading:r}=Hn(),n=(e==null?void 0:e.id)??null,i=Hs(),[o]=Px(),c=o.get("authorization_id")??"",a=o.get("next")??"",[f,p]=C.useState(!1),[y,v]=C.useState({}),[T,E]=C.useState(""),[k,P]=C.useState(!1),[R,D]=C.useState(!1),[M,B]=C.useState(null),[V,G]=C.useState(null),[W,Y]=C.useState(!1),[J,Q]=C.useState(!1),[ee,le]=C.useState(()=>{if(o.get("paused")!=="1")return null;let Ae="";try{Ae=sessionStorage.getItem("accountPausedReason")||""}catch{}return Ae?`Your account is paused. ${Ae}`:"Your account is paused. Please contact LevelUp support to reactivate it."}),pe=C.useRef(!1);C.useEffect(()=>{if(c&&/(\.lovable\.app|\.lovableproject\.com)$/.test(window.location.hostname)){const Ae=new URL("/auth",m1e);Ae.searchParams.set("next",`${jR}?authorization_id=${encodeURIComponent(c)}`),window.location.replace(Ae.toString());return}if(c){const Ae=`${jR}?authorization_id=${encodeURIComponent(c)}`;sessionStorage.setItem("redirectAfterLogin",Ae);return}a&&Fie(a)&&sessionStorage.setItem("redirectAfterLogin",a)},[c,a]),C.useEffect(()=>{if(r||!n||pe.current)return;const Ae=c?`${jR}?authorization_id=${encodeURIComponent(c)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!Fie(Ae)){sessionStorage.removeItem("redirectAfterLogin"),pe.current=!0,i("/dashboard",{replace:!0});return}const be=Ae.startsWith(jR)||Ae.startsWith("/oauth/consent")||Ae.startsWith("/.lovable/oauth/consent");if(be&&Zit("auth")){B("We couldn't complete the OAuth sign-in handoff because the browser kept bouncing between sign-in and consent. Please refresh this page and try Connect again.");return}pe.current=!0,be||(Xit(),sessionStorage.removeItem("redirectAfterLogin")),i(Ae,{replace:!0})},[c,r,i,n]);const Se=async Ae=>{Ae.preventDefault(),v({}),le(null),G(null),Y(!1),p(!0);const be=new FormData(Ae.currentTarget),me=be.get("email"),Te=be.get("password");try{Kit.parse({email:me,password:Te}),await t(me,Te)}catch(Ne){if(Ne instanceof _9e){const Ee={};Ne.issues.forEach(we=>{we.path[0]&&(Ee[we.path[0]]=we.message)}),v(Ee)}else if(Ne instanceof Error&&Ne.name==="AccountPaused")le(Ne.message);else if(me)try{const{data:Ee}=await Re.functions.invoke("account-activation-status",{body:{email:me}});Ee!=null&&Ee.needsActivation&&G(me)}catch{}}finally{p(!1)}},je=async()=>{if(V){Q(!0);try{const{data:Ae,error:be}=await Re.functions.invoke("send-password-reset",{body:{email:V,variant:"activation"}});if(be)throw be;if((Ae==null?void 0:Ae.sent)===!1)throw new Error("We couldn't send the activation email. Please try again in a moment or contact support.");Y(!0),Vt.success("Activation email sent! Check your inbox.")}catch(Ae){Vt.error(Ae instanceof Error?Ae.message:"Failed to send activation email")}finally{Q(!1)}}},Le=async()=>{if(!T){Vt.error("Please enter your email address");return}P(!0);try{const{data:Ae,error:be}=await Re.functions.invoke("send-password-reset",{body:{email:T.trim().toLowerCase(),redirectTo:Yit}});if(be)throw be;if((Ae==null?void 0:Ae.sent)===!1){Vt.error("We couldn't find a LevelUp account for that email. Double-check the address, or email hello@relevelup.com and we'll help.");return}Vt.success("Password reset email sent! Check your inbox."),D(!1),E("")}catch(Ae){Vt.error(Ae instanceof Error?Ae.message:"Failed to send reset email")}finally{P(!1)}};return s.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]",children:s.jsxs("div",{className:"absolute inset-0 opacity-30",children:[s.jsx("div",{className:"absolute top-0 left-0 w-96 h-96 bg-white/10 rounded-full blur-3xl animate-pulse"}),s.jsx("div",{className:"absolute bottom-0 right-0 w-96 h-96 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),s.jsx("div",{className:"absolute top-1/2 left-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"2s"}})]})}),s.jsxs("div",{className:"relative z-10 flex flex-col min-h-screen",children:[s.jsx("header",{className:"p-6",children:s.jsxs(Wr,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[s.jsx(dx,{className:"h-4 w-4"}),"Back to Home"]})}),s.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:s.jsxs("div",{className:"w-full max-w-md",children:[s.jsx("div",{className:"flex justify-center mb-8",children:s.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:s.jsx("img",{src:Wit,alt:"LevelUp",className:"h-12 w-auto"})})}),s.jsxs($n,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[s.jsxs(ud,{className:"space-y-1 text-center pb-4",children:[s.jsx(dd,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),s.jsx(ak,{className:"text-gray-600",children:M||"Sign in to access your dashboard"})]}),s.jsxs(Kn,{children:[ee&&s.jsxs("div",{className:"mb-4 rounded-lg border border-amber-300 bg-amber-50 p-4 text-left",children:[s.jsx("p",{className:"text-sm font-semibold text-amber-900",children:"Account paused"}),s.jsx("p",{className:"mt-1 text-sm text-amber-800",children:ee}),s.jsx("a",{href:"mailto:support@relevelup.com",className:"mt-2 inline-block text-sm font-medium text-amber-900 underline",children:"Contact support"})]}),V&&s.jsxs("div",{className:"mb-4 rounded-lg border border-[#4a6b6d]/30 bg-[#f2f7f7] p-4 text-left",children:[s.jsx("p",{className:"text-sm font-semibold text-[#2a4347]",children:"You haven't set a password yet"}),s.jsx("p",{className:"mt-1 text-sm text-gray-700",children:W?`We just emailed ${V} a link to set your password and sign in. Check your inbox (and spam folder).`:`Your LevelUp account for ${V} is ready — it just needs a password. We'll email you a link to set one.`}),!W&&s.jsx(Bt,{type:"button",onClick:je,disabled:J,className:"mt-3 bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",children:J?"Sending...":"Email me a set-password link"})]}),s.jsxs("form",{onSubmit:Se,className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Mr,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),s.jsx(Br,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),y.email&&s.jsx("p",{className:"text-sm text-red-600",children:y.email})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Mr,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),s.jsx(Br,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),y.password&&s.jsx("p",{className:"text-sm text-red-600",children:y.password})]}),s.jsx(Bt,{type:"submit",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg transition-all duration-200 shadow-lg hover:shadow-xl",disabled:f,children:f?"Signing in...":"Sign In"}),s.jsxs(lo,{open:R,onOpenChange:D,children:[s.jsx(yxe,{asChild:!0,children:s.jsx(Bt,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),s.jsxs(qa,{className:"bg-white",children:[s.jsxs(xl,{children:[s.jsx(Xo,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),s.jsx(wd,{className:"text-gray-600",children:"Enter your email address and we'll send you a link to reset your password."})]}),s.jsxs("div",{className:"space-y-4 pt-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(Mr,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),s.jsx(Br,{id:"reset-email",type:"email",placeholder:"your@email.com",value:T,onChange:Ae=>E(Ae.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),s.jsx(Bt,{onClick:Le,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:k,children:k?"Sending...":"Send Reset Link"})]})]})]})]})]})]}),s.jsxs("p",{className:"text-center text-white/70 text-sm mt-6",children:["Don't have an account?"," ",s.jsx(Wr,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})}),s.jsx("footer",{className:"px-4 py-6",children:s.jsx(f1e,{})})]})]})},YH=()=>mr({queryKey:["lead-sources"],queryFn:async()=>{const{data:t,error:e}=await Re.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(e)throw e;return t}}),Qit=()=>{const t=Ar(),{user:e}=Hn();return Sr({mutationFn:async r=>{const{data:n}=await Re.from("lead_sources").select("id, name").eq("is_active",!0).ilike("name",r.trim()),i=(n||[]).find(a=>a.name.toLowerCase()===r.trim().toLowerCase()&&!0);if(i)throw new Error(`Lead source "${i.name}" already exists`);const{data:o,error:c}=await Re.from("lead_sources").insert({name:r,owner_user_id:e==null?void 0:e.id,sort_order:100}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["lead-sources"]}),Vt.success("Lead source added")},onError:r=>{Vt.error("Failed to add lead source"),console.error(r)}})},i7t=()=>{const t=Ar();return Sr({mutationFn:async({id:e,name:r})=>{const{error:n}=await Re.from("lead_sources").update({name:r}).eq("id",e);if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["lead-sources"]}),Vt.success("Lead source updated")},onError:e=>{Vt.error(e.message||"Failed to update lead source")}})},s7t=()=>{const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("lead_sources").update({is_active:!1}).eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["lead-sources"]}),Vt.success("Lead source removed")},onError:e=>{Vt.error(e.message||"Failed to remove lead source")}})},p1e=(t,e)=>{const{user:r,isAdmin:n}=Hn(),i=n&&e?e:r==null?void 0:r.id;return mr({queryKey:["scorecard-transactions",t,i],queryFn:async()=>{let o=Re.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",i).order("close_date",{ascending:!1});t&&(o=o.gte("close_date",`${t}-01-01`).lte("close_date",`${t}-12-31`));const{data:c,error:a}=await o;if(a)throw a;return c},enabled:!!i})},Jit=t=>{const{user:e,isAdmin:r}=Hn(),n=r&&t?t:e==null?void 0:e.id;return mr({queryKey:["scorecard-transactions-all",n],queryFn:async()=>{const{data:i,error:o}=await Re.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",n).order("close_date",{ascending:!1});if(o)throw o;return i},enabled:!!n})},ZH=()=>{const t=Ar(),{user:e}=Hn();return Sr({mutationFn:async r=>{const{data:n,error:i}=await Re.from("scorecard_transactions").insert({...r,owner_user_id:e.id}).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["scorecard-transactions"]}),t.invalidateQueries({queryKey:["scorecard-transactions-all"]}),Vt.success("Transaction added")},onError:r=>{Vt.error("Failed to add transaction"),console.error(r)}})},est=()=>{const t=Ar();return Sr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Re.from("scorecard_transactions").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["scorecard-transactions"]}),t.invalidateQueries({queryKey:["scorecard-transactions-all"]}),Vt.success("Transaction updated")},onError:e=>{Vt.error("Failed to update transaction"),console.error(e)}})},tst=()=>{const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("scorecard_transactions").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["scorecard-transactions"]}),t.invalidateQueries({queryKey:["scorecard-transactions-all"]}),Vt.success("Transaction deleted")},onError:e=>{Vt.error("Failed to delete transaction"),console.error(e)}})},rst=(t,e)=>{const{user:r,isAdmin:n}=Hn(),i=n&&e?e:r==null?void 0:r.id;return mr({queryKey:["scorecard-goals",t,i],queryFn:async()=>{const{data:o,error:c}=await Re.from("scorecard_goals").select("*").eq("owner_user_id",i).eq("year",t).maybeSingle();if(c)throw c;return o},enabled:!!i})},nst=()=>{const t=Ar(),{user:e}=Hn();return Sr({mutationFn:async r=>{const{data:n,error:i}=await Re.from("scorecard_goals").upsert({...r,owner_user_id:e.id},{onConflict:"owner_user_id,year"}).select().single();if(i)throw i;return n},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["scorecard-goals",n.year]}),Vt.success("Goals saved")},onError:r=>{Vt.error("Failed to save goals"),console.error(r)}})},cF=()=>{const{user:t}=Hn();return mr({queryKey:["scorecard-settings",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await Re.from("scorecard_settings").select("*").eq("user_id",t.id).maybeSingle();if(r)throw r;return e},enabled:!!(t!=null&&t.id)})},ist=()=>{const t=Ar(),{user:e}=Hn();return Sr({mutationFn:async r=>{const{data:n,error:i}=await Re.from("scorecard_settings").upsert({...r,user_id:e.id},{onConflict:"user_id"}).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["scorecard-settings"]}),Vt.success("Settings saved")},onError:r=>{Vt.error("Failed to save settings"),console.error(r)}})},sst=(t,e)=>{const{data:r,isLoading:n}=p1e(t,e),{data:i,isLoading:o}=Jit(e),{data:c}=cF(),a=(c==null?void 0:c.show_commission)??!0,f=p=>{if(!p||p.length===0)return{totalTransactions:0,buyerCount:0,sellerCount:0,totalVolume:0,averagePrice:0,totalCommission:0,totalNetToAgent:0,topLeadSource:null,transactionsByMonth:[],leadSourceBreakdown:[]};const y=p.filter(G=>G.transaction_type==="buyer").length,v=p.filter(G=>G.transaction_type==="seller").length,T=p.reduce((G,W)=>G+Number(W.sale_price),0),E=p.reduce((G,W)=>G+(Number(W.commission_amount)||0),0),k=p.reduce((G,W)=>{const Y=Number(W.commission_amount)||0;if(!Y)return G;let J=Y;return W.brokerage_split_pct&&(J-=Y*(W.brokerage_split_pct/100)),W.team_split_pct&&(J-=Y*(W.team_split_pct/100)),W.franchise_fee_pct&&(J-=Y*(W.franchise_fee_pct/100)),W.referral_fee_pct&&(J-=Y*(W.referral_fee_pct/100)),W.transaction_fee&&(J-=W.transaction_fee),G+Math.max(0,J)},0),P={};p.forEach(G=>{var Y;const W=((Y=G.lead_source)==null?void 0:Y.name)||"Unknown";P[W]=(P[W]||0)+1});const R=Object.entries(P).map(([G,W])=>({name:G,count:W})).sort((G,W)=>W.count-G.count),D=R[0]||null,M={};p.forEach(G=>{const W=gS(G.close_date).toLocaleString("default",{month:"short"});M[W]=(M[W]||0)+1});const V=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(G=>({month:G,count:M[G]||0}));return{totalTransactions:p.length,buyerCount:y,sellerCount:v,totalVolume:T,averagePrice:p.length>0?T/p.length:0,totalCommission:a?E:0,totalNetToAgent:a?k:0,topLeadSource:D,transactionsByMonth:V,leadSourceBreakdown:R}};return{yearStats:f(r),lifetimeStats:f(i),isLoading:n||o,showCommission:a}},a7t=()=>{const{isAdmin:t}=Hn();return mr({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:e,error:r}=await Re.from("scorecard_transactions").select("owner_user_id").order("owner_user_id");if(r)throw r;const n=[...new Set(e.map(c=>c.owner_user_id))],{data:i,error:o}=await Re.from("profiles").select("id, name, email").in("id",n);if(o)throw o;return i},enabled:t})},XH=C.forwardRef(({className:t,...e},r)=>s.jsx("div",{className:"relative w-full overflow-auto",children:s.jsx("table",{ref:r,className:qt("w-full caption-bottom text-sm",t),...e})}));XH.displayName="Table";const QH=C.forwardRef(({className:t,...e},r)=>s.jsx("thead",{ref:r,className:qt("[&_tr]:border-b",t),...e}));QH.displayName="TableHeader";const JH=C.forwardRef(({className:t,...e},r)=>s.jsx("tbody",{ref:r,className:qt("[&_tr:last-child]:border-0",t),...e}));JH.displayName="TableBody";const ast=C.forwardRef(({className:t,...e},r)=>s.jsx("tfoot",{ref:r,className:qt("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...e}));ast.displayName="TableFooter";const vk=C.forwardRef(({className:t,...e},r)=>s.jsx("tr",{ref:r,className:qt("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",t),...e}));vk.displayName="TableRow";const Yl=C.forwardRef(({className:t,...e},r)=>s.jsx("th",{ref:r,className:qt("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",t),...e}));Yl.displayName="TableHead";const Zl=C.forwardRef(({className:t,...e},r)=>s.jsx("td",{ref:r,className:qt("p-4 align-middle [&:has([role=checkbox])]:pr-0",t),...e}));Zl.displayName="TableCell";const ost=C.forwardRef(({className:t,...e},r)=>s.jsx("caption",{ref:r,className:qt("mt-4 text-sm text-muted-foreground",t),...e}));ost.displayName="TableCaption";const j8="boost";function $x(t,e){typeof window>"u"||window.dispatchEvent(new CustomEvent(j8,{detail:{type:t,requestId:e}}))}function o7t(t){const e=r=>{const n=r.detail;t(typeof n=="string"?{type:n}:n)};return window.addEventListener(j8,e),()=>window.removeEventListener(j8,e)}const l7t=["Idle","Thinking","Listening","Working","Success","Alert","Celebration","Pointing","Wave","Sleeping"],c7t=new Set(["Idle","Thinking","Listening","Working","Sleeping"]),u7t={contact_created:{clip:"Celebration",priority:4},task_completed:{clip:"Celebration",priority:4},lead_received:{clip:"Alert",priority:3},gift_claimed:{clip:"Celebration",priority:5},task_created:{clip:"Success",priority:2},request_success:{clip:"Success",priority:2}},$ie={hidden:!1,paused:!1,reduceMotion:!1,muteAnnouncements:!1},g1e=new Map,y1e=t=>`boost:prefs:${t}`;function d7t(t){try{const e=window.localStorage.getItem(y1e(t));if(e)return{...$ie,...JSON.parse(e)}}catch{}return g1e.get(t)??$ie}function h7t(t,e){g1e.set(t,e);try{window.localStorage.setItem(y1e(t),JSON.stringify(e))}catch{}}let f2=null;function f7t(){var t;if(f2!==null)return f2;try{const e=document.createElement("canvas"),r=e.getContext("webgl2")||e.getContext("webgl");f2=!!r,(t=r==null?void 0:r.getExtension("WEBGL_lose_context"))==null||t.loseContext()}catch{f2=!1}return f2}const eW=()=>mr({queryKey:["relationship-types"],queryFn:async()=>{const{data:t,error:e}=await Re.from("relationship_types").select("*").order("sort_order");if(e)throw e;return t}}),m7t=()=>{const t=Li(),e=1e3;return mr({queryKey:["innercircle-contacts-lite",t],queryFn:async()=>{const r=[];let n=0;for(;;){const{data:i,error:o}=await Re.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code, birthday, home_anniversary, wedding_anniversary, created_at").eq("owner_user_id",t).order("created_at",{ascending:!1}).range(n,n+e-1);if(o)throw o;const c=i??[];if(r.push(...c),c.length{const e=Li(),r=1e3,n=async i=>{const o=[];let c=0;for(;;){const{data:a,error:f}=await i.range(c,c+r-1);if(f)throw f;const p=a??[];if(o.push(...p),p.length{let i=Re.from("innercircle_contacts").select("*").eq("owner_user_id",e).order("created_at",{ascending:!1}).order("first_name");const o=await n(i);if(o.length===0)return o;const c=o.map(E=>E.id),a=Array.from(new Set(o.map(E=>E.lead_source_id).filter(E=>!!E))),f=(E,k=250)=>{const P=[];for(let R=0;R{const{data:k,error:P}=await Re.from("innercircle_contact_tags").select("id, contact_id, relationship_type_id, relationship_type:relationship_types(*)").in("contact_id",E);if(P)throw P;return k??[]})),Promise.all(f(a).map(async E=>{const{data:k,error:P}=await Re.from("lead_sources").select("id, name").in("id",E);if(P)throw P;return k??[]}))]),v=new Map;p.flat().forEach(E=>{const k=v.get(E.contact_id)??[];k.push(E),v.set(E.contact_id,k)});const T=new Map(y.flat().map(E=>[E.id,E]));return o.map(E=>({...E,lead_source_ref:E.lead_source_id?T.get(E.lead_source_id)??null:null,tags:v.get(E.id)??[]}))},enabled:!!e,staleTime:10*60*1e3})},p7t=t=>mr({queryKey:["innercircle-contact",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("id",t).maybeSingle();if(r)throw r;return e},enabled:!!t}),g7t=()=>{const t=Li();return mr({queryKey:["innercircle-contact-counts",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(r)throw r;const n={};return e==null||e.forEach(i=>{var o;(o=i.tags)==null||o.forEach(c=>{n[c.relationship_type_id]=(n[c.relationship_type_id]||0)+1})}),n},enabled:!!t})},lst=()=>{const t=Ar(),e=Li();return Sr({mutationFn:async r=>{const{tagIds:n,...i}=r,o={...i,birthday:i.birthday||null,home_anniversary:i.home_anniversary||null,spouse_birthday:i.spouse_birthday||null,owner_user_id:e},{data:c,error:a}=await Re.from("innercircle_contacts").insert(o).select().single();if(a)throw a;if(n&&n.length>0){const{error:f}=await Re.from("innercircle_contact_tags").insert(n.map(p=>({contact_id:c.id,relationship_type_id:p})));if(f)throw f}return c},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),$x("contact_created"),Ts({title:"Contact created successfully"})},onError:r=>{Ts({title:"Error creating contact",description:r.message,variant:"destructive"})}})},y7t=()=>{const t=Ar();return Sr({mutationFn:async({id:e,...r})=>{const{tagIds:n,tags:i,...o}=r,c=["birthday","home_anniversary","spouse_birthday","wedding_anniversary","last_contacted_at","next_touch_date"],a={...o};for(const y of Object.keys(a)){const v=a[y];(v===""||typeof v=="string"&&c.includes(y)&&v.trim()==="")&&(a[y]=null)}const{data:f,error:p}=await Re.from("innercircle_contacts").update(a).eq("id",e).select().single();if(p)throw p;if(n!==void 0&&(await Re.from("innercircle_contact_tags").delete().eq("contact_id",e),n.length>0)){const{error:y}=await Re.from("innercircle_contact_tags").insert(n.map(v=>({contact_id:e,relationship_type_id:v})));if(y)throw y}return f},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),$x("contact_created"),Ts({title:"Contact updated successfully"})},onError:e=>{Ts({title:"Error updating contact",description:e.message,variant:"destructive"})}})},x7t=()=>{const t=Ar();return Sr({mutationFn:async({contactId:e,spouseContactId:r})=>{if(r){const{error:n}=await Re.from("innercircle_contacts").update({spouse_contact_id:r}).eq("id",e);if(n)throw n;const{error:i}=await Re.from("innercircle_contacts").update({spouse_contact_id:e}).eq("id",r);if(i)throw i}else{const{data:n}=await Re.from("innercircle_contacts").select("spouse_contact_id").eq("id",e).single(),i=n==null?void 0:n.spouse_contact_id,{error:o}=await Re.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",e);if(o)throw o;if(i){const{error:c}=await Re.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",i);if(c)throw c}}},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact"]}),t.invalidateQueries({queryKey:["innercircle-contact-spouse"]}),Ts({title:"Spouse link updated"})},onError:e=>{Ts({title:"Error linking spouse",description:e.message,variant:"destructive"})}})},v7t=()=>{const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("innercircle_contacts").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Ts({title:"Contact deleted successfully"})},onError:e=>{Ts({title:"Error deleting contact",description:e.message,variant:"destructive"})}})},_7t=()=>{const t=Ar();return Sr({mutationFn:async({ids:e,onProgress:r})=>{let i=0;for(let o=0;o{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),t.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})},cst=()=>mr({queryKey:["action-types"],queryFn:async()=>{const{data:t,error:e}=await Re.from("action_types").select("*").order("sort_order");if(e)throw e;return t}}),b7t=t=>mr({queryKey:["action-scripts",t],queryFn:async()=>{let e=Re.from("action_scripts").select("*, action_type:action_types(*)");const{data:r,error:n}=await e;if(n)throw n;return r}}),w7t=()=>mr({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:t,error:e}=await Re.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(e)throw e;return t}}),S7t=()=>{const t=Ar(),e=Li();return Sr({mutationFn:async({name:r,description:n})=>{const{data:i,error:o}=await Re.from("touchpoint_plans").insert({name:r,description:n,owner_user_id:e,active:!0,is_template:!1}).select().single();if(o)throw o;return i},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),Ts({title:"Plan created successfully"})},onError:r=>{Ts({title:"Error creating plan",description:r.message,variant:"destructive"})}})},T7t=()=>{const t=Ar(),e=Li();return Sr({mutationFn:async({sourcePlanId:r,newName:n})=>{const{data:i,error:o}=await Re.from("touchpoint_plans").select(` *, items:touchpoint_plan_items(*) `).eq("id",r).single();if(o)throw o;if(!i)throw new Error("Source plan not found");const{data:c,error:a}=await Re.from("touchpoint_plans").insert({name:n,description:i.description,owner_user_id:e,active:!0,is_template:!1}).select().single();if(a)throw a;if(i.items&&i.items.length>0){const f=i.items.map(y=>({plan_id:c.id,month_number:y.month_number,action_type_id:y.action_type_id,default_script_id:y.default_script_id,notes:y.notes})),{error:p}=await Re.from("touchpoint_plan_items").insert(f);if(p)throw p}return c},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),Ts({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:r=>{Ts({title:"Error duplicating plan",description:r.message,variant:"destructive"})}})},E7t=()=>{const t=Ar();return Sr({mutationFn:async({id:e,name:r,description:n})=>{const{data:i,error:o}=await Re.from("touchpoint_plans").update({name:r,description:n}).eq("id",e).select().single();if(o)throw o;return i},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),Ts({title:"Plan updated successfully"})}})},j7t=()=>{const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("touchpoint_plans").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),Ts({title:"Plan deleted successfully"})}})},A7t=()=>{const t=Ar();return Sr({mutationFn:async({planId:e,items:r})=>{if(await Re.from("touchpoint_plan_items").delete().eq("plan_id",e),r.length>0){const{error:n}=await Re.from("touchpoint_plan_items").insert(r.map(i=>({plan_id:e,month_number:i.month_number,action_type_id:i.action_type_id,default_script_id:i.default_script_id||null,notes:i.notes})));if(n)throw n}},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),Ts({title:"Plan schedule updated"})}})},k7t=()=>{const t=Ar();return Sr({mutationFn:async({actionTypeId:e,title:r,scriptBody:n,emailSubject:i,tone:o})=>{const{data:{user:c}}=await Re.auth.getUser(),{data:a,error:f}=await Re.from("action_scripts").insert({action_type_id:e,title:r,script_body:n,email_subject:i||null,tone:o||null,active:!0,user_id:c==null?void 0:c.id}).select().single();if(f)throw f;return a},onSuccess:()=>{t.invalidateQueries({queryKey:["action-scripts"]}),Ts({title:"Script created successfully"})},onError:e=>{Ts({title:"Error creating script",description:e.message,variant:"destructive"})}})},C7t=()=>{const t=Li();return mr({queryKey:["user-plan-enrollments",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(r)throw r;return e},enabled:!!t})},N7t=()=>{const t=Ar(),e=Li();return Sr({mutationFn:async({planId:r,relationshipTypeId:n,active:i})=>{const{data:o}=await Re.from("user_plan_enrollments").select("id").eq("plan_id",r).eq("relationship_type_id",n).maybeSingle();if(o){const{error:c}=await Re.from("user_plan_enrollments").update({active:i}).eq("id",o.id);if(c)throw c}else if(i){const{error:c}=await Re.from("user_plan_enrollments").insert({owner_user_id:e,plan_id:r,relationship_type_id:n,active:!0,start_date:new Date().toISOString().split("T")[0]});if(c)throw c}},onSuccess:()=>{t.invalidateQueries({queryKey:["user-plan-enrollments"]}),Ts({title:"Plan enrollment updated"})}})},v1e=(t=7)=>{const e=Li();return mr({queryKey:["contact-touch-logs",e,t],queryFn:async()=>{const r=new Date;r.setDate(r.getDate()-t);const{data:n,error:i}=await Re.from("contact_touch_logs").select(` *, contact:innercircle_contacts(*), action_type:action_types(*) `).eq("owner_user_id",e).gte("completed_at",r.toISOString()).order("completed_at",{ascending:!1});if(i)throw i;return n},enabled:!!e})},ust=()=>{const t=Li();return mr({queryKey:["contacts-last-touch",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("contact_touch_logs").select("contact_id, completed_at").eq("owner_user_id",t).order("completed_at",{ascending:!1});if(r)throw r;const n={};return e==null||e.forEach(i=>{n[i.contact_id]||(n[i.contact_id]=i.completed_at)}),n},enabled:!!t})},I7t=(t=90)=>{const{data:e}=x1e(),{data:r}=ust();if(!e||!r)return{contacts:[],count:0};const n=new Date;n.setDate(n.getDate()-t);const i=e.filter(o=>{const c=r[o.id];return c?new Date(c){const t=Ar(),e=Li();return Sr({mutationFn:async({contactId:r,actionTypeId:n,scriptUsedId:i,notes:o,completedAt:c})=>{const{data:a,error:f}=await Re.from("contact_touch_logs").insert({owner_user_id:e,contact_id:r,action_type_id:n,script_used_id:i,notes:o,completed_at:c||new Date().toISOString()}).select().single();if(f)throw f;return a},onSuccess:async(r,n)=>{var i,o;t.invalidateQueries({queryKey:["contact-touch-logs"]}),t.invalidateQueries({queryKey:["contacts-last-touch"]}),t.invalidateQueries({queryKey:["today-actions"]}),t.invalidateQueries({queryKey:["popby-logs"]}),$x("task_completed"),Ts({title:"Action completed!"});try{const[c,a]=await Promise.all([Re.from("innercircle_contacts").select("email").eq("id",n.contactId).single(),Re.from("action_types").select("name").eq("id",n.actionTypeId).single()]),f=(i=c.data)==null?void 0:i.email,p=((o=a.data)==null?void 0:o.name)||"Touch";/pop[\s-]?by/i.test(p)&&Re.from("popby_logs").insert({owner_user_id:e,contact_id:n.contactId,notes:n.notes??null,completed_at:n.completedAt||r.completed_at}).then(()=>{t.invalidateQueries({queryKey:["popby-logs"]})}),f&&Re.functions.invoke("boldtrail-sync",{body:{action:"push_touch",contact_email:f,touch_type:p,touch_notes:n.notes||null,touch_date:n.completedAt||r.completed_at}}).catch(()=>{})}catch{}}})},_1e="agentos_weekly_touch_goal",zie=20,hst=()=>{if(typeof window>"u")return zie;const t=localStorage.getItem(_1e);if(t){const e=parseInt(t,10);if(!isNaN(e)&&e>0)return e}return zie},P7t=t=>{localStorage.setItem(_1e,t.toString())},R7t=()=>{const{data:t}=v1e(7),e=new Date;e.setHours(0,0,0,0);const r=new Date(e);r.setDate(e.getDate()-e.getDay());const n=(t==null?void 0:t.filter(c=>new Date(c.completed_at)>=r).length)||0;let i=0;if(t&&t.length>0){const c=new Set(t.map(f=>new Date(f.completed_at).toDateString()));let a=new Date(e);for(;c.has(a.toDateString());)i++,a.setDate(a.getDate()-1)}const o=hst();return{actionsThisWeek:n,weeklyGoal:o,streak:i,progress:Math.min(n/o*100,100)}},fst=()=>{const t=Li();return mr({queryKey:["contact-plan-cycles",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("contact_plan_cycles").select(` *, contact:innercircle_contacts(*), plan:touchpoint_plans( *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) ) `);if(r)throw r;return e},enabled:!!t})},L7t=()=>{const t=Ar();return Li(),Sr({mutationFn:async()=>{var f;const{data:e}=await Re.from("user_plan_enrollments").select("*").eq("active",!0);if(!e||e.length===0)return;const{data:r}=await Re.auth.getUser(),n=(f=r==null?void 0:r.user)==null?void 0:f.id;if(!n)return;const{data:i}=await Re.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",n);if(!i)return;const{data:o}=await Re.from("contact_plan_cycles").select("contact_id, plan_id"),c=new Set((o==null?void 0:o.map(p=>`${p.contact_id}-${p.plan_id}`))||[]),a=[];for(const p of i)for(const y of p.tags||[]){const v=e.find(T=>T.relationship_type_id===y.relationship_type_id);v&&!c.has(`${p.id}-${v.plan_id}`)&&a.push({contact_id:p.id,plan_id:v.plan_id,relationship_type_id:y.relationship_type_id})}if(a.length>0){const{error:p}=await Re.from("contact_plan_cycles").insert(a);if(p)throw p}return a.length},onSuccess:e=>{t.invalidateQueries({queryKey:["contact-plan-cycles"]}),e&&e>0&&Ts({title:`${e} contact(s) enrolled in plans`})}})},D7t=()=>{const t=Li(),{data:e}=fst(),{data:r}=v1e(30);return mr({queryKey:["today-actions",t,e==null?void 0:e.length,r==null?void 0:r.length],queryFn:async()=>{var k;if(!e||e.length===0)return[];const{data:n}=await Re.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),i=new Set((n==null?void 0:n.map(P=>P.contact_id))||[]),o=new Date,c=[],a=new Date(o.getFullYear(),o.getMonth(),1),f=new Set((r==null?void 0:r.filter(P=>new Date(P.completed_at)>=a).map(P=>`${P.contact_id}-${P.action_type_id}`))||[]);for(const P of e){if(!((k=P.plan)!=null&&k.items)||P.plan.items.length===0||!P.contact||i.has(P.contact_id))continue;const R=new Date(P.cycle_start_date),M=Math.floor((o.getTime()-R.getTime())/(30.44*24*60*60*1e3))%12+1,B=P.plan.items.find(V=>V.month_number===M);if(B&&B.action_type){const V=`${P.contact_id}-${B.action_type_id}`;if(!f.has(V)){const{data:G}=await Re.from("relationship_types").select("name").eq("id",P.relationship_type_id).single();c.push({contact:P.contact,actionType:B.action_type,script:B.default_script||void 0,planName:P.plan.name,relationshipTypeName:(G==null?void 0:G.name)||"",monthNumber:M})}}}const p=5,y=o.getDate(),v=c.sort((P,R)=>P.contact.first_name.localeCompare(R.contact.first_name)),T=(y-1)%Math.max(1,v.length);return[...v.slice(T),...v.slice(0,T)].slice(0,p)},enabled:!!t&&!!e})};var uF="Popover",[b1e,M7t]=Qo(uF,[Ix]),JC=Ix(),[mst,zx]=b1e(uF),w1e=t=>{const{__scopePopover:e,children:r,open:n,defaultOpen:i,onOpenChange:o,modal:c=!1}=t,a=JC(e),f=C.useRef(null),[p,y]=C.useState(!1),[v,T]=yd({prop:n,defaultProp:i??!1,onChange:o,caller:uF});return s.jsx(c3,{...a,children:s.jsx(mst,{scope:e,contentId:Fl(),triggerRef:f,open:v,onOpenChange:T,onOpenToggle:C.useCallback(()=>T(E=>!E),[T]),hasCustomAnchor:p,onCustomAnchorAdd:C.useCallback(()=>y(!0),[]),onCustomAnchorRemove:C.useCallback(()=>y(!1),[]),modal:c,children:r})})};w1e.displayName=uF;var S1e="PopoverAnchor",pst=C.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=zx(S1e,r),o=JC(r),{onCustomAnchorAdd:c,onCustomAnchorRemove:a}=i;return C.useEffect(()=>(c(),()=>a()),[c,a]),s.jsx(PC,{...o,...n,ref:e})});pst.displayName=S1e;var T1e="PopoverTrigger",E1e=C.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=zx(T1e,r),o=JC(r),c=Yn(e,i.triggerRef),a=s.jsx(nn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":N1e(i.open),...n,ref:c,onClick:Or(t.onClick,i.onOpenToggle)});return i.hasCustomAnchor?a:s.jsx(PC,{asChild:!0,...o,children:a})});E1e.displayName=T1e;var tW="PopoverPortal",[gst,yst]=b1e(tW,{forceMount:void 0}),j1e=t=>{const{__scopePopover:e,forceMount:r,children:n,container:i}=t,o=zx(tW,e);return s.jsx(gst,{scope:e,forceMount:r,children:s.jsx(vl,{present:r||o.open,children:s.jsx(YS,{asChild:!0,container:i,children:n})})})};j1e.displayName=tW;var yS="PopoverContent",A1e=C.forwardRef((t,e)=>{const r=yst(yS,t.__scopePopover),{forceMount:n=r.forceMount,...i}=t,o=zx(yS,t.__scopePopover);return s.jsx(vl,{present:n||o.open,children:o.modal?s.jsx(vst,{...i,ref:e}):s.jsx(_st,{...i,ref:e})})});A1e.displayName=yS;var xst=ux("PopoverContent.RemoveScroll"),vst=C.forwardRef((t,e)=>{const r=zx(yS,t.__scopePopover),n=C.useRef(null),i=Yn(e,n),o=C.useRef(!1);return C.useEffect(()=>{const c=n.current;if(c)return r3(c)},[]),s.jsx(jC,{as:xst,allowPinchZoom:!0,children:s.jsx(k1e,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Or(t.onCloseAutoFocus,c=>{var a;c.preventDefault(),o.current||(a=r.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Or(t.onPointerDownOutside,c=>{const a=c.detail.originalEvent,f=a.button===0&&a.ctrlKey===!0,p=a.button===2||f;o.current=p},{checkForDefaultPrevented:!1}),onFocusOutside:Or(t.onFocusOutside,c=>c.preventDefault(),{checkForDefaultPrevented:!1})})})}),_st=C.forwardRef((t,e)=>{const r=zx(yS,t.__scopePopover),n=C.useRef(!1),i=C.useRef(!1);return s.jsx(k1e,{...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,p;(f=t.onInteractOutside)==null||f.call(t,o),o.defaultPrevented||(n.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const c=o.target;((p=r.triggerRef.current)==null?void 0:p.contains(c))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})}),k1e=C.forwardRef((t,e)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:c,onEscapeKeyDown:a,onPointerDownOutside:f,onFocusOutside:p,onInteractOutside:y,...v}=t,T=zx(yS,r),E=JC(r);return e3(),s.jsx(EC,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:o,children:s.jsx(v_,{asChild:!0,disableOutsidePointerEvents:c,onInteractOutside:y,onEscapeKeyDown:a,onPointerDownOutside:f,onFocusOutside:p,onDismiss:()=>T.onOpenChange(!1),children:s.jsx(u3,{"data-state":N1e(T.open),role:"dialog",id:T.contentId,...E,...v,ref:e,style:{...v.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),C1e="PopoverClose",bst=C.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=zx(C1e,r);return s.jsx(nn.button,{type:"button",...n,ref:e,onClick:Or(t.onClick,()=>i.onOpenChange(!1))})});bst.displayName=C1e;var wst="PopoverArrow",Sst=C.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=JC(r);return s.jsx(d3,{...i,...n,ref:e})});Sst.displayName=wst;function N1e(t){return t?"open":"closed"}var Tst=w1e,Est=E1e,jst=j1e,I1e=A1e;const UL=Tst,VL=Est,yA=C.forwardRef(({className:t,align:e="center",sideOffset:r=4,...n},i)=>s.jsx(jst,{children:s.jsx(I1e,{ref:i,align:e,sideOffset:r,className:qt("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...n})}));yA.displayName=I1e.displayName;const Ast=mg({property_address:Ai().min(1,"Property address is required"),city:Ai().optional(),state:Ai().optional(),zip:Ai().optional(),transaction_type:cS(["buyer","seller"]),close_date:Ai().min(1,"Close date is required"),sale_price:dA().min(0,"Sale price must be positive"),commission_amount:dA().optional(),lead_source_id:Ai().optional(),client_type_id:Ai().optional(),contact_id:Ai().optional(),notes:Ai().optional(),is_win:J9e()});function P1e({open:t,onOpenChange:e,transaction:r}){const[n,i]=C.useState(!1),[o,c]=C.useState(""),[a,f]=C.useState(!1),[p,y]=C.useState(""),v=ZH(),T=est(),{data:E}=YH(),{data:k}=eW(),{data:P}=x1e(),R=lst(),D=Qit(),{data:M}=cF(),B=(M==null?void 0:M.show_commission)??!0,V=M7({resolver:O7(Ast),defaultValues:{property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1}});C.useEffect(()=>{r?V.reset({property_address:r.property_address,city:r.city||"",state:r.state||"",zip:r.zip||"",transaction_type:r.transaction_type,close_date:r.close_date,sale_price:Number(r.sale_price),commission_amount:r.commission_amount?Number(r.commission_amount):void 0,lead_source_id:r.lead_source_id||void 0,client_type_id:r.client_type_id||void 0,contact_id:r.contact_id||void 0,notes:r.notes||"",is_win:r.is_win}):V.reset({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1})},[r,V]);const G=async Q=>{const ee={property_address:Q.property_address,transaction_type:Q.transaction_type,close_date:Q.close_date,sale_price:Q.sale_price,is_win:Q.is_win,commission_amount:Q.commission_amount||null,lead_source_id:Q.lead_source_id||null,client_type_id:Q.client_type_id||null,contact_id:Q.contact_id||null,city:Q.city||null,state:Q.state||null,zip:Q.zip||null,notes:Q.notes||null};r?await T.mutateAsync({id:r.id,...ee}):await v.mutateAsync(ee),e(!1)},W=async()=>{if(!o.trim())return;const[Q,...ee]=o.trim().split(" "),le=ee.join(" ")||null,pe=await R.mutateAsync({first_name:Q,last_name:le,tagIds:[]});pe&&(V.setValue("contact_id",pe.id),c(""),f(!1),i(!1))},Y=async()=>{if(!p.trim())return;const Q=await D.mutateAsync(p.trim());Q&&(V.setValue("lead_source_id",Q.id),y(""))},J=P==null?void 0:P.find(Q=>Q.id===V.watch("contact_id"));return s.jsx(lo,{open:t,onOpenChange:e,children:s.jsxs(qa,{className:"max-w-lg max-h-[90vh]",children:[s.jsx(xl,{children:s.jsx(Xo,{children:r?"Edit Transaction":"Add Transaction"})}),s.jsx(Lm,{className:"max-h-[70vh] pr-4",children:s.jsx(H7,{...V,children:s.jsxs("form",{onSubmit:V.handleSubmit(G),className:"space-y-4",children:[s.jsx(ll,{control:V.control,name:"property_address",render:({field:Q})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"Property Address *"}),s.jsx(Go,{children:s.jsx(Br,{placeholder:"123 Main St",...Q})}),s.jsx(lf,{})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[s.jsx(ll,{control:V.control,name:"city",render:({field:Q})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"City"}),s.jsx(Go,{children:s.jsx(Br,{placeholder:"City",...Q})})]})}),s.jsx(ll,{control:V.control,name:"state",render:({field:Q})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"State"}),s.jsx(Go,{children:s.jsx(Br,{placeholder:"TX",...Q})})]})}),s.jsx(ll,{control:V.control,name:"zip",render:({field:Q})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"Zip"}),s.jsx(Go,{children:s.jsx(Br,{placeholder:"75001",...Q})})]})})]}),s.jsx(ll,{control:V.control,name:"transaction_type",render:({field:Q})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"Transaction Type *"}),s.jsxs(ba,{onValueChange:Q.onChange,value:Q.value,children:[s.jsx(Go,{children:s.jsx(oa,{children:s.jsx(wa,{placeholder:"Select type"})})}),s.jsxs(la,{children:[s.jsx(mn,{value:"buyer",children:"Buyer"}),s.jsx(mn,{value:"seller",children:"Seller"})]})]}),s.jsx(lf,{})]})}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsx(ll,{control:V.control,name:"close_date",render:({field:Q})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"Close Date *"}),s.jsx(Go,{children:s.jsx(Br,{type:"date",...Q})}),s.jsx(lf,{})]})}),s.jsx(ll,{control:V.control,name:"sale_price",render:({field:Q})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"Sale Price *"}),s.jsx(Go,{children:s.jsx(Br,{type:"number",placeholder:"0",...Q,onChange:ee=>Q.onChange(Number(ee.target.value))})}),s.jsx(lf,{})]})})]}),B&&s.jsx(ll,{control:V.control,name:"commission_amount",render:({field:Q})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"Commission"}),s.jsx(Go,{children:s.jsx(Br,{type:"number",placeholder:"0",...Q,value:Q.value??"",onChange:ee=>Q.onChange(ee.target.value?Number(ee.target.value):void 0)})})]})}),s.jsx(ll,{control:V.control,name:"lead_source_id",render:({field:Q})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"Lead Source"}),s.jsxs(ba,{onValueChange:Q.onChange,value:Q.value||"",children:[s.jsx(Go,{children:s.jsx(oa,{children:s.jsx(wa,{placeholder:"Select source"})})}),s.jsx(la,{children:E==null?void 0:E.map(ee=>s.jsx(mn,{value:ee.id,children:ee.name},ee.id))})]})]})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Br,{placeholder:"Add custom source...",value:p,onChange:Q=>y(Q.target.value),className:"flex-1"}),s.jsx(Bt,{type:"button",variant:"outline",size:"icon",onClick:Y,disabled:!p.trim(),children:s.jsx(gm,{className:"h-4 w-4"})})]}),s.jsx(ll,{control:V.control,name:"client_type_id",render:({field:Q})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"Client Type"}),s.jsxs(ba,{onValueChange:Q.onChange,value:Q.value||"",children:[s.jsx(Go,{children:s.jsx(oa,{children:s.jsx(wa,{placeholder:"Select client type"})})}),s.jsx(la,{children:k==null?void 0:k.map(ee=>s.jsx(mn,{value:ee.id,children:ee.name},ee.id))})]})]})}),s.jsx(ll,{control:V.control,name:"contact_id",render:({field:Q})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"Client Contact"}),s.jsxs(UL,{open:n,onOpenChange:i,children:[s.jsx(VL,{asChild:!0,children:s.jsx(Go,{children:s.jsxs(Bt,{variant:"outline",role:"combobox",className:qt("w-full justify-between",!Q.value&&"text-muted-foreground"),children:[J?`${J.first_name} ${J.last_name||""}`.trim():"Select contact",s.jsx(LU,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),s.jsxs(yA,{className:"w-full p-0",align:"start",children:[s.jsxs(uk,{children:[s.jsx(dk,{placeholder:"Search contacts..."}),s.jsxs(hk,{children:[s.jsx(fk,{children:s.jsxs("div",{className:"p-2 space-y-2",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"No contact found."}),!a&&s.jsxs(Bt,{variant:"outline",size:"sm",className:"w-full",onClick:()=>f(!0),children:[s.jsx(gm,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),s.jsx(Rp,{children:P==null?void 0:P.map(ee=>s.jsxs(nf,{value:`${ee.first_name} ${ee.last_name||""}`,onSelect:()=>{Q.onChange(ee.id),i(!1)},children:[s.jsx(no,{className:qt("mr-2 h-4 w-4",ee.id===Q.value?"opacity-100":"opacity-0")}),ee.first_name," ",ee.last_name||""]},ee.id))})]})]}),a&&s.jsxs("div",{className:"p-2 border-t space-y-2",children:[s.jsx(Br,{placeholder:"Enter contact name...",value:o,onChange:ee=>c(ee.target.value)}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Bt,{size:"sm",onClick:W,disabled:!o.trim()||R.isPending,children:"Add Contact"}),s.jsx(Bt,{size:"sm",variant:"outline",onClick:()=>{f(!1),c("")},children:"Cancel"})]})]})]})]})]})}),s.jsx(ll,{control:V.control,name:"notes",render:({field:Q})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"Notes"}),s.jsx(Go,{children:s.jsx(Ad,{placeholder:"Any notes about this transaction...",...Q})})]})}),s.jsx(ll,{control:V.control,name:"is_win",render:({field:Q})=>s.jsxs(Vo,{className:"flex items-center justify-between rounded-lg border p-3",children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsx(qo,{children:"Mark as Win 🏆"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),s.jsx(Go,{children:s.jsx(gT,{checked:Q.value,onCheckedChange:Q.onChange})})]})}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(Bt,{type:"button",variant:"outline",onClick:()=>e(!1),children:"Cancel"}),s.jsxs(Bt,{type:"submit",disabled:v.isPending||T.isPending,children:[r?"Update":"Add"," Transaction"]})]})]})})})]})})}const wz=768;function kst(){const[t,e]=C.useState(void 0);return C.useEffect(()=>{const r=window.matchMedia(`(max-width: ${wz-1}px)`),n=()=>{e(window.innerWidthr.removeEventListener("change",n)},[]),!!t}function R1e({transactions:t,showCommission:e,isLoading:r,agentNameMap:n,readOnly:i}){const[o,c]=C.useState(null),[a,f]=C.useState(null),[p,y]=C.useState(""),[v,T]=C.useState("all"),[E,k]=C.useState("all"),[P,R]=C.useState("all"),[D,M]=C.useState(!1),B=tst(),V=ZH(),{data:G}=YH();eW();const W=kst(),Y=ee=>{const{id:le,created_at:pe,updated_at:Se,lead_source:je,client_type:Le,contact:Ae,...be}=ee;V.mutate(be)},J=()=>{a&&(B.mutate(a),f(null))},Q=t.filter(ee=>{var Ae,be,me,Te;const le=p===""||ee.property_address.toLowerCase().includes(p.toLowerCase())||((be=(Ae=ee.contact)==null?void 0:Ae.first_name)==null?void 0:be.toLowerCase().includes(p.toLowerCase()))||((Te=(me=ee.contact)==null?void 0:me.last_name)==null?void 0:Te.toLowerCase().includes(p.toLowerCase())),pe=v==="all"||ee.transaction_type===v,Se=E==="all"||ee.lead_source_id===E,je=P==="all"||ee.client_type_id===P,Le=!D||ee.is_win;return le&&pe&&Se&&je&&Le});return r?s.jsx($n,{children:s.jsx(Kn,{className:"p-6 space-y-4",children:[1,2,3].map(ee=>s.jsx(ml,{className:"h-16 w-full"},ee))})}):s.jsxs(s.Fragment,{children:[s.jsxs($n,{children:[s.jsx(ud,{className:"pb-3",children:s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[s.jsxs(dd,{children:["Transactions (",Q.length,")"]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("div",{className:"relative",children:[s.jsx(xd,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),s.jsx(Br,{placeholder:"Search...",value:p,onChange:ee=>y(ee.target.value),className:"pl-8 w-[150px]"})]}),s.jsxs(ba,{value:v,onValueChange:T,children:[s.jsx(oa,{className:"w-[100px]",children:s.jsx(wa,{placeholder:"Type"})}),s.jsxs(la,{children:[s.jsx(mn,{value:"all",children:"All Types"}),s.jsx(mn,{value:"buyer",children:"Buyer"}),s.jsx(mn,{value:"seller",children:"Seller"})]})]}),s.jsxs(ba,{value:E,onValueChange:k,children:[s.jsx(oa,{className:"w-[130px]",children:s.jsx(wa,{placeholder:"Lead Source"})}),s.jsxs(la,{children:[s.jsx(mn,{value:"all",children:"All Sources"}),G==null?void 0:G.map(ee=>s.jsx(mn,{value:ee.id,children:ee.name},ee.id))]})]}),s.jsxs(Bt,{variant:D?"default":"outline",size:"sm",onClick:()=>M(!D),children:[s.jsx(f1,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),s.jsx(Kn,{children:Q.length===0?s.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):W?s.jsx("div",{className:"space-y-3",children:Q.map(ee=>s.jsxs($n,{className:"p-4",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"font-medium truncate",children:ee.property_address}),ee.is_win&&s.jsx(f1,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[ee.city,ee.state?`, ${ee.state}`:""]})]}),s.jsx(ss,{variant:ee.transaction_type==="buyer"?"default":"secondary",children:ee.transaction_type})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3 text-sm",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Close Date: "}),Gee(ee.close_date)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Price: "}),$a(ee.sale_price)]}),e&&ee.commission_amount&&s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),$a(ee.commission_amount)]}),ee.lead_source&&s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Source: "}),ee.lead_source.name]}),ee.contact&&s.jsxs("div",{className:"col-span-2",children:[s.jsx("span",{className:"text-muted-foreground",children:"Client: "}),ee.contact.first_name," ",ee.contact.last_name]}),n&&s.jsxs("div",{className:"col-span-2",children:[s.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),n[ee.owner_user_id]||"Unknown"]})]}),!i&&s.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[s.jsx(Bt,{variant:"ghost",size:"sm",onClick:()=>c(ee),children:s.jsx(BU,{className:"h-4 w-4"})}),s.jsx(Bt,{variant:"ghost",size:"sm",onClick:()=>Y(ee),children:s.jsx(MU,{className:"h-4 w-4"})}),s.jsx(Bt,{variant:"ghost",size:"sm",onClick:()=>f(ee.id),children:s.jsx(CD,{className:"h-4 w-4 text-destructive"})})]})]},ee.id))}):s.jsx("div",{className:"overflow-x-auto",children:s.jsxs(XH,{children:[s.jsx(QH,{children:s.jsxs(vk,{children:[n&&s.jsx(Yl,{children:"Agent"}),s.jsx(Yl,{children:"Property"}),s.jsx(Yl,{children:"Type"}),s.jsx(Yl,{children:"Close Date"}),s.jsx(Yl,{children:"Sale Price"}),e&&s.jsx(Yl,{children:"Commission"}),s.jsx(Yl,{children:"Lead Source"}),s.jsx(Yl,{children:"Client"}),!i&&s.jsx(Yl,{className:"w-[50px]"})]})}),s.jsx(JH,{children:Q.map(ee=>{var le;return s.jsxs(vk,{children:[n&&s.jsx(Zl,{className:"font-medium text-sm",children:n[ee.owner_user_id]||"Unknown"}),s.jsx(Zl,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[ee.is_win&&s.jsx(f1,{className:"h-4 w-4 text-yellow-500"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium",children:ee.property_address}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[ee.city,ee.state?`, ${ee.state}`:""]})]})]})}),s.jsx(Zl,{children:s.jsx(ss,{variant:ee.transaction_type==="buyer"?"default":"secondary",children:ee.transaction_type})}),s.jsx(Zl,{children:Gee(ee.close_date)}),s.jsx(Zl,{children:$a(ee.sale_price)}),e&&s.jsx(Zl,{children:ee.commission_amount?$a(ee.commission_amount):"-"}),s.jsx(Zl,{children:((le=ee.lead_source)==null?void 0:le.name)||"-"}),s.jsx(Zl,{children:ee.contact?`${ee.contact.first_name} ${ee.contact.last_name||""}`.trim():"-"}),!i&&s.jsx(Zl,{children:s.jsxs(FC,{children:[s.jsx(BC,{asChild:!0,children:s.jsx(Bt,{variant:"ghost",size:"icon",children:s.jsx(kDe,{className:"h-4 w-4"})})}),s.jsxs(dT,{align:"end",children:[s.jsxs(Nu,{onClick:()=>c(ee),children:[s.jsx(BU,{className:"h-4 w-4 mr-2"}),"Edit"]}),s.jsxs(Nu,{onClick:()=>Y(ee),children:[s.jsx(MU,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),s.jsxs(Nu,{onClick:()=>f(ee.id),className:"text-destructive",children:[s.jsx(CD,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},ee.id)})})]})})})]}),s.jsx(P1e,{open:!!o,onOpenChange:ee=>!ee&&c(null),transaction:o||void 0}),s.jsx(Tpe,{open:!!a,onOpenChange:ee=>!ee&&f(null),children:s.jsxs(F9,{children:[s.jsxs(B9,{children:[s.jsx(z9,{children:"Delete Transaction?"}),s.jsx(U9,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),s.jsxs($9,{children:[s.jsx(q9,{children:"Cancel"}),s.jsx(V9,{onClick:J,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function Cst({goals:t,stats:e,year:r,showCommission:n}){const i=new Date().getMonth()+1,o=new Date().getFullYear()===r?i:12,c=12-o,a=(T,E)=>{if(!E||E===0)return null;const k=Math.min(T/E*100,100),P=Math.max(E-T,0),R=c>0?P/c:0,D=o/12*100,M=k>=D?"ahead":k>=D*.8?"on-track":"behind";return{percent:k,remaining:P,pace:R,status:M}},f=a(e.totalTransactions,t.transactions_goal),p=a(e.totalVolume,t.volume_goal),y=n?a(e.totalCommission,t.gci_goal):null,v=T=>{switch(T){case"ahead":return s.jsxs(ss,{className:"bg-green-500 text-white",children:[s.jsx(Nx,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return s.jsxs(ss,{variant:"secondary",children:[s.jsx(HDe,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return s.jsxs(ss,{variant:"destructive",children:[s.jsx(wme,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!t.transactions_goal&&!t.volume_goal&&!t.gci_goal?null:s.jsxs($n,{children:[s.jsx(ud,{className:"pb-3",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(TC,{className:"h-5 w-5 text-primary"}),s.jsxs(dd,{children:[r," Goals Progress"]})]})}),s.jsx(Kn,{children:s.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[t.transactions_goal&&f&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium",children:"Transactions"}),v(f.status)]}),s.jsx(gA,{value:f.percent,className:"h-2"}),s.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[s.jsxs("span",{children:[e.totalTransactions," of ",t.transactions_goal]}),s.jsxs("span",{children:[Math.round(f.percent),"%"]})]}),f.remaining>0&&c>0&&s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Math.ceil(f.pace),"/month to hit goal"]})]}),t.volume_goal&&p&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium",children:"Volume"}),v(p.status)]}),s.jsx(gA,{value:p.percent,className:"h-2"}),s.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[s.jsxs("span",{children:[$a(e.totalVolume,!0)," of ",$a(t.volume_goal,!0)]}),s.jsxs("span",{children:[Math.round(p.percent),"%"]})]}),p.remaining>0&&c>0&&s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",$a(p.pace,!0),"/month"]})]}),n&&t.gci_goal&&y&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium",children:"GCI"}),v(y.status)]}),s.jsx(gA,{value:y.percent,className:"h-2"}),s.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[s.jsxs("span",{children:[$a(e.totalCommission,!0)," of ",$a(t.gci_goal,!0)]}),s.jsxs("span",{children:[Math.round(y.percent),"%"]})]}),y.remaining>0&&c>0&&s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",$a(y.pace,!0),"/month"]})]})]})})]})}var Nst=Array.isArray,$u=Nst,Ist=typeof tc=="object"&&tc&&tc.Object===Object&&tc,L1e=Ist,Pst=L1e,Rst=typeof self=="object"&&self&&self.Object===Object&&self,Lst=Pst||Rst||Function("return this")(),Dm=Lst,Dst=Dm,Mst=Dst.Symbol,eN=Mst,Uie=eN,D1e=Object.prototype,Ost=D1e.hasOwnProperty,Fst=D1e.toString,m2=Uie?Uie.toStringTag:void 0;function Bst(t){var e=Ost.call(t,m2),r=t[m2];try{t[m2]=void 0;var n=!0}catch{}var i=Fst.call(t);return n&&(e?t[m2]=r:delete t[m2]),i}var $st=Bst,zst=Object.prototype,Ust=zst.toString;function Vst(t){return Ust.call(t)}var qst=Vst,Vie=eN,Gst=$st,Hst=qst,Wst="[object Null]",Kst="[object Undefined]",qie=Vie?Vie.toStringTag:void 0;function Yst(t){return t==null?t===void 0?Kst:Wst:qie&&qie in Object(t)?Gst(t):Hst(t)}var pg=Yst;function Zst(t){return t!=null&&typeof t=="object"}var gg=Zst,Xst=pg,Qst=gg,Jst="[object Symbol]";function eat(t){return typeof t=="symbol"||Qst(t)&&Xst(t)==Jst}var _T=eat,tat=$u,rat=_T,nat=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,iat=/^\w*$/;function sat(t,e){if(tat(t))return!1;var r=typeof t;return r=="number"||r=="symbol"||r=="boolean"||t==null||rat(t)?!0:iat.test(t)||!nat.test(t)||e!=null&&t in Object(e)}var rW=sat;function aat(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var Ux=aat;const bT=ds(Ux);var oat=pg,lat=Ux,cat="[object AsyncFunction]",uat="[object Function]",dat="[object GeneratorFunction]",hat="[object Proxy]";function fat(t){if(!lat(t))return!1;var e=oat(t);return e==uat||e==dat||e==cat||e==hat}var nW=fat;const _i=ds(nW);var mat=Dm,pat=mat["__core-js_shared__"],gat=pat,Sz=gat,Gie=function(){var t=/[^.]+$/.exec(Sz&&Sz.keys&&Sz.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function yat(t){return!!Gie&&Gie in t}var xat=yat,vat=Function.prototype,_at=vat.toString;function bat(t){if(t!=null){try{return _at.call(t)}catch{}try{return t+""}catch{}}return""}var M1e=bat,wat=nW,Sat=xat,Tat=Ux,Eat=M1e,jat=/[\\^$.*+?()[\]{}|]/g,Aat=/^\[object .+?Constructor\]$/,kat=Function.prototype,Cat=Object.prototype,Nat=kat.toString,Iat=Cat.hasOwnProperty,Pat=RegExp("^"+Nat.call(Iat).replace(jat,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Rat(t){if(!Tat(t)||Sat(t))return!1;var e=wat(t)?Pat:Aat;return e.test(Eat(t))}var Lat=Rat;function Dat(t,e){return t==null?void 0:t[e]}var Mat=Dat,Oat=Lat,Fat=Mat;function Bat(t,e){var r=Fat(t,e);return Oat(r)?r:void 0}var A_=Bat,$at=A_,zat=$at(Object,"create"),dF=zat,Hie=dF;function Uat(){this.__data__=Hie?Hie(null):{},this.size=0}var Vat=Uat;function qat(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var Gat=qat,Hat=dF,Wat="__lodash_hash_undefined__",Kat=Object.prototype,Yat=Kat.hasOwnProperty;function Zat(t){var e=this.__data__;if(Hat){var r=e[t];return r===Wat?void 0:r}return Yat.call(e,t)?e[t]:void 0}var Xat=Zat,Qat=dF,Jat=Object.prototype,eot=Jat.hasOwnProperty;function tot(t){var e=this.__data__;return Qat?e[t]!==void 0:eot.call(e,t)}var rot=tot,not=dF,iot="__lodash_hash_undefined__";function sot(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=not&&e===void 0?iot:e,this}var aot=sot,oot=Vat,lot=Gat,cot=Xat,uot=rot,dot=aot;function wT(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e-1}var kot=Aot,Cot=hF;function Not(t,e){var r=this.__data__,n=Cot(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}var Iot=Not,Pot=mot,Rot=wot,Lot=Eot,Dot=kot,Mot=Iot;function ST(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e0?1:-1},kv=function(e){return c_(e)&&e.indexOf("%")===e.length-1},Kr=function(e){return ict(e)&&!tN(e)},lct=function(e){return zi(e)},gl=function(e){return Kr(e)||c_(e)},cct=0,rN=function(e){var r=++cct;return"".concat(e||"").concat(r)},eu=function(e,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!Kr(e)&&!c_(e))return n;var o;if(kv(e)){var c=e.indexOf("%");o=r*parseFloat(e.slice(0,c))/100}else o=+e;return tN(o)&&(o=n),i&&o>r&&(o=r),o},Iy=function(e){if(!e)return null;var r=Object.keys(e);return r&&r.length?e[r[0]]:null},uct=function(e){if(!Array.isArray(e))return!1;for(var r=e.length,n={},i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function yct(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function k8(t){"@babel/helpers - typeof";return k8=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},k8(t)}var Jie={click:"onClick",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseover:"onMouseOver",mousemove:"onMouseMove",mouseout:"onMouseOut",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",touchcancel:"onTouchCancel",touchend:"onTouchEnd",touchmove:"onTouchMove",touchstart:"onTouchStart",contextmenu:"onContextMenu",dblclick:"onDoubleClick"},Up=function(e){return typeof e=="string"?e:e?e.displayName||e.name||"Component":""},ese=null,Ez=null,fW=function t(e){if(e===ese&&Array.isArray(Ez))return Ez;var r=[];return C.Children.forEach(e,function(n){zi(n)||(Jlt.isFragment(n)?r=r.concat(t(n.props.children)):r.push(n))}),Ez=r,ese=e,r};function uh(t,e){var r=[],n=[];return Array.isArray(e)?n=e.map(function(i){return Up(i)}):n=[Up(e)],fW(t).forEach(function(i){var o=md(i,"type.displayName")||md(i,"type.name");n.indexOf(o)!==-1&&r.push(i)}),r}function id(t,e){var r=uh(t,e);return r&&r[0]}var tse=function(e){if(!e||!e.props)return!1;var r=e.props,n=r.width,i=r.height;return!(!Kr(n)||n<=0||!Kr(i)||i<=0)},xct=["a","altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColormatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-url","foreignObject","g","glyph","glyphRef","hkern","image","line","lineGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","switch","symbol","text","textPath","title","tref","tspan","use","view","vkern"],vct=function(e){return e&&e.type&&c_(e.type)&&xct.indexOf(e.type)>=0},O7t=function(e){return e&&k8(e)==="object"&&"clipDot"in e},_ct=function(e,r,n,i){var o,c=(o=Tz==null?void 0:Tz[i])!==null&&o!==void 0?o:[];return r.startsWith("data-")||!_i(e)&&(i&&c.includes(r)||fct.includes(r))||n&&hW.includes(r)},fi=function(e,r,n){if(!e||typeof e=="function"||typeof e=="boolean")return null;var i=e;if(C.isValidElement(e)&&(i=e.props),!bT(i))return null;var o={};return Object.keys(i).forEach(function(c){var a;_ct((a=i)===null||a===void 0?void 0:a[c],c,r,n)&&(o[c]=i[c])}),o},C8=function t(e,r){if(e===r)return!0;var n=C.Children.count(e);if(n!==C.Children.count(r))return!1;if(n===0)return!0;if(n===1)return rse(Array.isArray(e)?e[0]:e,Array.isArray(r)?r[0]:r);for(var i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Ect(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function I8(t){var e=t.children,r=t.width,n=t.height,i=t.viewBox,o=t.className,c=t.style,a=t.title,f=t.desc,p=Tct(t,Sct),y=i||{width:r,height:n,x:0,y:0},v=$i("recharts-surface",o);return Xe.createElement("svg",N8({},fi(p,!0,"svg"),{className:v,width:r,height:n,style:c,viewBox:"".concat(y.x," ").concat(y.y," ").concat(y.width," ").concat(y.height)}),Xe.createElement("title",null,a),Xe.createElement("desc",null,f),e)}var jct=["children","className"];function P8(){return P8=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function kct(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var Vs=Xe.forwardRef(function(t,e){var r=t.children,n=t.className,i=Act(t,jct),o=$i("recharts-layer",n);return Xe.createElement("g",P8({className:o},fi(i,!0),{ref:e}),r)}),mf=function(e,r){for(var n=arguments.length,i=new Array(n>2?n-2:0),o=2;oi?0:i+e),r=r>i?i:r,r<0&&(r+=i),i=e>r?0:r-e>>>0,e>>>=0;for(var o=Array(i);++n=n?t:Ict(t,e,r)}var Rct=Pct,Lct="\\ud800-\\udfff",Dct="\\u0300-\\u036f",Mct="\\ufe20-\\ufe2f",Oct="\\u20d0-\\u20ff",Fct=Dct+Mct+Oct,Bct="\\ufe0e\\ufe0f",$ct="\\u200d",zct=RegExp("["+$ct+Lct+Fct+Bct+"]");function Uct(t){return zct.test(t)}var H1e=Uct;function Vct(t){return t.split("")}var qct=Vct,W1e="\\ud800-\\udfff",Gct="\\u0300-\\u036f",Hct="\\ufe20-\\ufe2f",Wct="\\u20d0-\\u20ff",Kct=Gct+Hct+Wct,Yct="\\ufe0e\\ufe0f",Zct="["+W1e+"]",R8="["+Kct+"]",L8="\\ud83c[\\udffb-\\udfff]",Xct="(?:"+R8+"|"+L8+")",K1e="[^"+W1e+"]",Y1e="(?:\\ud83c[\\udde6-\\uddff]){2}",Z1e="[\\ud800-\\udbff][\\udc00-\\udfff]",Qct="\\u200d",X1e=Xct+"?",Q1e="["+Yct+"]?",Jct="(?:"+Qct+"(?:"+[K1e,Y1e,Z1e].join("|")+")"+Q1e+X1e+")*",eut=Q1e+X1e+Jct,tut="(?:"+[K1e+R8+"?",R8,Y1e,Z1e,Zct].join("|")+")",rut=RegExp(L8+"(?="+L8+")|"+tut+eut,"g");function nut(t){return t.match(rut)||[]}var iut=nut,sut=qct,aut=H1e,out=iut;function lut(t){return aut(t)?out(t):sut(t)}var cut=lut,uut=Rct,dut=H1e,hut=cut,fut=$1e;function mut(t){return function(e){e=fut(e);var r=dut(e)?hut(e):void 0,n=r?r[0]:e.charAt(0),i=r?uut(r,1).join(""):e.slice(1);return n[t]()+i}}var put=mut,gut=put,yut=gut("toUpperCase"),xut=yut;const jF=ds(xut);function ya(t){return function(){return t}}const J1e=Math.cos,vM=Math.sin,_f=Math.sqrt,_M=Math.PI,AF=2*_M,D8=Math.PI,M8=2*D8,gv=1e-6,vut=M8-gv;function eSe(t){this._+=t[0];for(let e=1,r=t.length;e=0))throw new Error(`invalid digits: ${t}`);if(e>15)return eSe;const r=10**e;return function(n){this._+=n[0];for(let i=1,o=n.length;igv)if(!(Math.abs(v*f-p*y)>gv)||!o)this._append`L${this._x1=e},${this._y1=r}`;else{let E=n-c,k=i-a,P=f*f+p*p,R=E*E+k*k,D=Math.sqrt(P),M=Math.sqrt(T),B=o*Math.tan((D8-Math.acos((P+T-R)/(2*D*M)))/2),V=B/M,G=B/D;Math.abs(V-1)>gv&&this._append`L${e+V*y},${r+V*v}`,this._append`A${o},${o},0,0,${+(v*E>y*k)},${this._x1=e+G*f},${this._y1=r+G*p}`}}arc(e,r,n,i,o,c){if(e=+e,r=+r,n=+n,c=!!c,n<0)throw new Error(`negative radius: ${n}`);let a=n*Math.cos(i),f=n*Math.sin(i),p=e+a,y=r+f,v=1^c,T=c?i-o:o-i;this._x1===null?this._append`M${p},${y}`:(Math.abs(this._x1-p)>gv||Math.abs(this._y1-y)>gv)&&this._append`L${p},${y}`,n&&(T<0&&(T=T%M8+M8),T>vut?this._append`A${n},${n},0,1,${v},${e-a},${r-f}A${n},${n},0,1,${v},${this._x1=p},${this._y1=y}`:T>gv&&this._append`A${n},${n},0,${+(T>=D8)},${v},${this._x1=e+n*Math.cos(o)},${this._y1=r+n*Math.sin(o)}`)}rect(e,r,n,i){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+r}h${n=+n}v${+i}h${-n}Z`}toString(){return this._}}function mW(t){let e=3;return t.digits=function(r){if(!arguments.length)return e;if(r==null)e=null;else{const n=Math.floor(r);if(!(n>=0))throw new RangeError(`invalid digits: ${r}`);e=n}return t},()=>new but(e)}function pW(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function tSe(t){this._context=t}tSe.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e);break}}};function kF(t){return new tSe(t)}function rSe(t){return t[0]}function nSe(t){return t[1]}function iSe(t,e){var r=ya(!0),n=null,i=kF,o=null,c=mW(a);t=typeof t=="function"?t:t===void 0?rSe:ya(t),e=typeof e=="function"?e:e===void 0?nSe:ya(e);function a(f){var p,y=(f=pW(f)).length,v,T=!1,E;for(n==null&&(o=i(E=c())),p=0;p<=y;++p)!(p=E;--k)a.point(B[k],V[k]);a.lineEnd(),a.areaEnd()}D&&(B[T]=+t(R,T,v),V[T]=+e(R,T,v),a.point(n?+n(R,T,v):B[T],r?+r(R,T,v):V[T]))}if(M)return a=null,M+""||null}function y(){return iSe().defined(i).curve(c).context(o)}return p.x=function(v){return arguments.length?(t=typeof v=="function"?v:ya(+v),n=null,p):t},p.x0=function(v){return arguments.length?(t=typeof v=="function"?v:ya(+v),p):t},p.x1=function(v){return arguments.length?(n=v==null?null:typeof v=="function"?v:ya(+v),p):n},p.y=function(v){return arguments.length?(e=typeof v=="function"?v:ya(+v),r=null,p):e},p.y0=function(v){return arguments.length?(e=typeof v=="function"?v:ya(+v),p):e},p.y1=function(v){return arguments.length?(r=v==null?null:typeof v=="function"?v:ya(+v),p):r},p.lineX0=p.lineY0=function(){return y().x(t).y(e)},p.lineY1=function(){return y().x(t).y(r)},p.lineX1=function(){return y().x(n).y(e)},p.defined=function(v){return arguments.length?(i=typeof v=="function"?v:ya(!!v),p):i},p.curve=function(v){return arguments.length?(c=v,o!=null&&(a=c(o)),p):c},p.context=function(v){return arguments.length?(v==null?o=a=null:a=c(o=v),p):o},p}class sSe{constructor(e,r){this._context=e,this._x=r}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(e,r){switch(e=+e,r=+r,this._point){case 0:{this._point=1,this._line?this._context.lineTo(e,r):this._context.moveTo(e,r);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+e)/2,this._y0,this._x0,r,e,r):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+r)/2,e,this._y0,e,r);break}}this._x0=e,this._y0=r}}function wut(t){return new sSe(t,!0)}function Sut(t){return new sSe(t,!1)}const gW={draw(t,e){const r=_f(e/_M);t.moveTo(r,0),t.arc(0,0,r,0,AF)}},Tut={draw(t,e){const r=_f(e/5)/2;t.moveTo(-3*r,-r),t.lineTo(-r,-r),t.lineTo(-r,-3*r),t.lineTo(r,-3*r),t.lineTo(r,-r),t.lineTo(3*r,-r),t.lineTo(3*r,r),t.lineTo(r,r),t.lineTo(r,3*r),t.lineTo(-r,3*r),t.lineTo(-r,r),t.lineTo(-3*r,r),t.closePath()}},aSe=_f(1/3),Eut=aSe*2,jut={draw(t,e){const r=_f(e/Eut),n=r*aSe;t.moveTo(0,-r),t.lineTo(n,0),t.lineTo(0,r),t.lineTo(-n,0),t.closePath()}},Aut={draw(t,e){const r=_f(e),n=-r/2;t.rect(n,n,r,r)}},kut=.8908130915292852,oSe=vM(_M/10)/vM(7*_M/10),Cut=vM(AF/10)*oSe,Nut=-J1e(AF/10)*oSe,Iut={draw(t,e){const r=_f(e*kut),n=Cut*r,i=Nut*r;t.moveTo(0,-r),t.lineTo(n,i);for(let o=1;o<5;++o){const c=AF*o/5,a=J1e(c),f=vM(c);t.lineTo(f*r,-a*r),t.lineTo(a*n-f*i,f*n+a*i)}t.closePath()}},jz=_f(3),Put={draw(t,e){const r=-_f(e/(jz*3));t.moveTo(0,r*2),t.lineTo(-jz*r,-r),t.lineTo(jz*r,-r),t.closePath()}},Gd=-.5,Hd=_f(3)/2,O8=1/_f(12),Rut=(O8/2+1)*3,Lut={draw(t,e){const r=_f(e/Rut),n=r/2,i=r*O8,o=n,c=r*O8+r,a=-o,f=c;t.moveTo(n,i),t.lineTo(o,c),t.lineTo(a,f),t.lineTo(Gd*n-Hd*i,Hd*n+Gd*i),t.lineTo(Gd*o-Hd*c,Hd*o+Gd*c),t.lineTo(Gd*a-Hd*f,Hd*a+Gd*f),t.lineTo(Gd*n+Hd*i,Gd*i-Hd*n),t.lineTo(Gd*o+Hd*c,Gd*c-Hd*o),t.lineTo(Gd*a+Hd*f,Gd*f-Hd*a),t.closePath()}};function Dut(t,e){let r=null,n=mW(i);t=typeof t=="function"?t:ya(t||gW),e=typeof e=="function"?e:ya(e===void 0?64:+e);function i(){let o;if(r||(r=o=n()),t.apply(this,arguments).draw(r,+e.apply(this,arguments)),o)return r=null,o+""||null}return i.type=function(o){return arguments.length?(t=typeof o=="function"?o:ya(o),i):t},i.size=function(o){return arguments.length?(e=typeof o=="function"?o:ya(+o),i):e},i.context=function(o){return arguments.length?(r=o??null,i):r},i}function bM(){}function wM(t,e,r){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+r)/6)}function lSe(t){this._context=t}lSe.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:wM(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:wM(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function Mut(t){return new lSe(t)}function cSe(t){this._context=t}cSe.prototype={areaStart:bM,areaEnd:bM,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:wM(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function Out(t){return new cSe(t)}function uSe(t){this._context=t}uSe.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var r=(this._x0+4*this._x1+t)/6,n=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:wM(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function Fut(t){return new uSe(t)}function dSe(t){this._context=t}dSe.prototype={areaStart:bM,areaEnd:bM,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e))}};function But(t){return new dSe(t)}function ise(t){return t<0?-1:1}function sse(t,e,r){var n=t._x1-t._x0,i=e-t._x1,o=(t._y1-t._y0)/(n||i<0&&-0),c=(r-t._y1)/(i||n<0&&-0),a=(o*i+c*n)/(n+i);return(ise(o)+ise(c))*Math.min(Math.abs(o),Math.abs(c),.5*Math.abs(a))||0}function ase(t,e){var r=t._x1-t._x0;return r?(3*(t._y1-t._y0)/r-e)/2:e}function Az(t,e,r){var n=t._x0,i=t._y0,o=t._x1,c=t._y1,a=(o-n)/3;t._context.bezierCurveTo(n+a,i+a*e,o-a,c-a*r,o,c)}function SM(t){this._context=t}SM.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:Az(this,this._t0,ase(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){var r=NaN;if(t=+t,e=+e,!(t===this._x1&&e===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,Az(this,ase(this,r=sse(this,t,e)),r);break;default:Az(this,this._t0,r=sse(this,t,e));break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=r}}};function hSe(t){this._context=new fSe(t)}(hSe.prototype=Object.create(SM.prototype)).point=function(t,e){SM.prototype.point.call(this,e,t)};function fSe(t){this._context=t}fSe.prototype={moveTo:function(t,e){this._context.moveTo(e,t)},closePath:function(){this._context.closePath()},lineTo:function(t,e){this._context.lineTo(e,t)},bezierCurveTo:function(t,e,r,n,i,o){this._context.bezierCurveTo(e,t,n,r,o,i)}};function $ut(t){return new SM(t)}function zut(t){return new hSe(t)}function mSe(t){this._context=t}mSe.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,e=this._y,r=t.length;if(r)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),r===2)this._context.lineTo(t[1],e[1]);else for(var n=ose(t),i=ose(e),o=0,c=1;c=0;--e)i[e]=(c[e]-i[e+1])/o[e];for(o[r-1]=(t[r]+i[r-1])/2,e=0;e=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var r=this._x*(1-this._t)+t*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,e)}break}}this._x=t,this._y=e}};function Vut(t){return new CF(t,.5)}function qut(t){return new CF(t,0)}function Gut(t){return new CF(t,1)}function xS(t,e){if((c=t.length)>1)for(var r=1,n,i,o=t[e[0]],c,a=o.length;r=0;)r[e]=e;return r}function Hut(t,e){return t[e]}function Wut(t){const e=[];return e.key=t,e}function Kut(){var t=ya([]),e=F8,r=xS,n=Hut;function i(o){var c=Array.from(t.apply(this,arguments),Wut),a,f=c.length,p=-1,y;for(const v of o)for(a=0,++p;a0){for(var r,n,i=0,o=t[0].length,c;i0){for(var r=0,n=t[e[0]],i,o=n.length;r0)||!((o=(i=t[e[0]]).length)>0))){for(var r=0,n=1,i,o,c;n=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function ndt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var pSe={symbolCircle:gW,symbolCross:Tut,symbolDiamond:jut,symbolSquare:Aut,symbolStar:Iut,symbolTriangle:Put,symbolWye:Lut},idt=Math.PI/180,sdt=function(e){var r="symbol".concat(jF(e));return pSe[r]||gW},adt=function(e,r,n){if(r==="area")return e;switch(n){case"cross":return 5*e*e/9;case"diamond":return .5*e*e/Math.sqrt(3);case"square":return e*e;case"star":{var i=18*idt;return 1.25*e*e*(Math.tan(i)-Math.tan(i*2)*Math.pow(Math.tan(i),2))}case"triangle":return Math.sqrt(3)*e*e/4;case"wye":return(21-10*Math.sqrt(3))*e*e/8;default:return Math.PI*e*e/4}},odt=function(e,r){pSe["symbol".concat(jF(e))]=r},yW=function(e){var r=e.type,n=r===void 0?"circle":r,i=e.size,o=i===void 0?64:i,c=e.sizeType,a=c===void 0?"area":c,f=rdt(e,Qut),p=cse(cse({},f),{},{type:n,size:o,sizeType:a}),y=function(){var R=sdt(n),D=Dut().type(R).size(adt(o,a,n));return D()},v=p.className,T=p.cx,E=p.cy,k=fi(p,!0);return T===+T&&E===+E&&o===+o?Xe.createElement("path",B8({},k,{className:$i("recharts-symbols",v),transform:"translate(".concat(T,", ").concat(E,")"),d:y()})):null};yW.registerSymbol=odt;function vS(t){"@babel/helpers - typeof";return vS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},vS(t)}function $8(){return $8=Object.assign?Object.assign.bind():function(t){for(var e=1;e`);var M=E.inactive?p:E.color;return Xe.createElement("li",$8({className:R,style:v,key:"legend-item-".concat(k)},u_(n.props,E,k)),Xe.createElement(I8,{width:c,height:c,viewBox:y,style:T},n.renderIcon(E)),Xe.createElement("span",{className:"recharts-legend-item-text",style:{color:M}},P?P(D,E,k):D))})}},{key:"render",value:function(){var n=this.props,i=n.payload,o=n.layout,c=n.align;if(!i||!i.length)return null;var a={padding:0,margin:0,textAlign:o==="horizontal"?c:"left"};return Xe.createElement("ul",{className:"recharts-default-legend",style:a},this.renderItems())}}])}(C.PureComponent);bk(xW,"displayName","Legend");bk(xW,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var ydt=fF;function xdt(){this.__data__=new ydt,this.size=0}var vdt=xdt;function _dt(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}var bdt=_dt;function wdt(t){return this.__data__.get(t)}var Sdt=wdt;function Tdt(t){return this.__data__.has(t)}var Edt=Tdt,jdt=fF,Adt=sW,kdt=aW,Cdt=200;function Ndt(t,e){var r=this.__data__;if(r instanceof jdt){var n=r.__data__;if(!Adt||n.lengtha))return!1;var p=o.get(t),y=o.get(e);if(p&&y)return p==e&&y==t;var v=-1,T=!0,E=r&Qdt?new Kdt:void 0;for(o.set(t,e),o.set(e,t);++v-1&&t%1==0&&t-1&&t%1==0&&t<=rft}var wW=nft,ift=pg,sft=wW,aft=gg,oft="[object Arguments]",lft="[object Array]",cft="[object Boolean]",uft="[object Date]",dft="[object Error]",hft="[object Function]",fft="[object Map]",mft="[object Number]",pft="[object Object]",gft="[object RegExp]",yft="[object Set]",xft="[object String]",vft="[object WeakMap]",_ft="[object ArrayBuffer]",bft="[object DataView]",wft="[object Float32Array]",Sft="[object Float64Array]",Tft="[object Int8Array]",Eft="[object Int16Array]",jft="[object Int32Array]",Aft="[object Uint8Array]",kft="[object Uint8ClampedArray]",Cft="[object Uint16Array]",Nft="[object Uint32Array]",Pa={};Pa[wft]=Pa[Sft]=Pa[Tft]=Pa[Eft]=Pa[jft]=Pa[Aft]=Pa[kft]=Pa[Cft]=Pa[Nft]=!0;Pa[oft]=Pa[lft]=Pa[_ft]=Pa[cft]=Pa[bft]=Pa[uft]=Pa[dft]=Pa[hft]=Pa[fft]=Pa[mft]=Pa[pft]=Pa[gft]=Pa[yft]=Pa[xft]=Pa[vft]=!1;function Ift(t){return aft(t)&&sft(t.length)&&!!Pa[ift(t)]}var Pft=Ift;function Rft(t){return function(e){return t(e)}}var jSe=Rft,AM={exports:{}};AM.exports;(function(t,e){var r=L1e,n=e&&!e.nodeType&&e,i=n&&!0&&t&&!t.nodeType&&t,o=i&&i.exports===n,c=o&&r.process,a=function(){try{var f=i&&i.require&&i.require("util").types;return f||c&&c.binding&&c.binding("util")}catch{}}();t.exports=a})(AM,AM.exports);var Lft=AM.exports,Dft=Pft,Mft=jSe,gse=Lft,yse=gse&&gse.isTypedArray,Oft=yse?Mft(yse):Dft,ASe=Oft,Fft=zht,Bft=_W,$ft=$u,zft=ESe,Uft=bW,Vft=ASe,qft=Object.prototype,Gft=qft.hasOwnProperty;function Hft(t,e){var r=$ft(t),n=!r&&Bft(t),i=!r&&!n&&zft(t),o=!r&&!n&&!i&&Vft(t),c=r||n||i||o,a=c?Fft(t.length,String):[],f=a.length;for(var p in t)(e||Gft.call(t,p))&&!(c&&(p=="length"||i&&(p=="offset"||p=="parent")||o&&(p=="buffer"||p=="byteLength"||p=="byteOffset")||Uft(p,f)))&&a.push(p);return a}var Wft=Hft,Kft=Object.prototype;function Yft(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||Kft;return t===r}var Zft=Yft;function Xft(t,e){return function(r){return t(e(r))}}var kSe=Xft,Qft=kSe,Jft=Qft(Object.keys,Object),emt=Jft,tmt=Zft,rmt=emt,nmt=Object.prototype,imt=nmt.hasOwnProperty;function smt(t){if(!tmt(t))return rmt(t);var e=[];for(var r in Object(t))imt.call(t,r)&&r!="constructor"&&e.push(r);return e}var amt=smt,omt=nW,lmt=wW;function cmt(t){return t!=null&&lmt(t.length)&&!omt(t)}var nN=cmt,umt=Wft,dmt=amt,hmt=nN;function fmt(t){return hmt(t)?umt(t):dmt(t)}var NF=fmt,mmt=Cht,pmt=Bht,gmt=NF;function ymt(t){return mmt(t,gmt,pmt)}var xmt=ymt,xse=xmt,vmt=1,_mt=Object.prototype,bmt=_mt.hasOwnProperty;function wmt(t,e,r,n,i,o){var c=r&vmt,a=xse(t),f=a.length,p=xse(e),y=p.length;if(f!=y&&!c)return!1;for(var v=f;v--;){var T=a[v];if(!(c?T in e:bmt.call(e,T)))return!1}var E=o.get(t),k=o.get(e);if(E&&k)return E==e&&k==t;var P=!0;o.set(t,e),o.set(e,t);for(var R=c;++v-1}var _gt=vgt;function bgt(t,e,r){for(var n=-1,i=t==null?0:t.length;++n=Mgt){var p=e?null:Lgt(t);if(p)return Dgt(p);c=!1,i=Rgt,f=new Ngt}else f=e?[]:a;e:for(;++n=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Qgt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function Jgt(t){return t.value}function eyt(t,e){if(Xe.isValidElement(t))return Xe.cloneElement(t,e);if(typeof t=="function")return Xe.createElement(t,e);e.ref;var r=Xgt(e,Vgt);return Xe.createElement(xW,r)}var Lse=1,T1=function(t){function e(){var r;qgt(this,e);for(var n=arguments.length,i=new Array(n),o=0;oLse||Math.abs(i.height-this.lastBoundingBox.height)>Lse)&&(this.lastBoundingBox.width=i.width,this.lastBoundingBox.height=i.height,n&&n(i)):(this.lastBoundingBox.width!==-1||this.lastBoundingBox.height!==-1)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,n&&n(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?yp({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(n){var i=this.props,o=i.layout,c=i.align,a=i.verticalAlign,f=i.margin,p=i.chartWidth,y=i.chartHeight,v,T;if(!n||(n.left===void 0||n.left===null)&&(n.right===void 0||n.right===null))if(c==="center"&&o==="vertical"){var E=this.getBBoxSnapshot();v={left:((p||0)-E.width)/2}}else v=c==="right"?{right:f&&f.right||0}:{left:f&&f.left||0};if(!n||(n.top===void 0||n.top===null)&&(n.bottom===void 0||n.bottom===null))if(a==="middle"){var k=this.getBBoxSnapshot();T={top:((y||0)-k.height)/2}}else T=a==="bottom"?{bottom:f&&f.bottom||0}:{top:f&&f.top||0};return yp(yp({},v),T)}},{key:"render",value:function(){var n=this,i=this.props,o=i.content,c=i.width,a=i.height,f=i.wrapperStyle,p=i.payloadUniqBy,y=i.payload,v=yp(yp({position:"absolute",width:c||"auto",height:a||"auto"},this.getDefaultPosition(f)),f);return Xe.createElement("div",{className:"recharts-legend-wrapper",style:v,ref:function(E){n.wrapperNode=E}},eyt(o,yp(yp({},this.props),{},{payload:DSe(y,p,Jgt)})))}}],[{key:"getWithHeight",value:function(n,i){var o=yp(yp({},this.defaultProps),n.props),c=o.layout;return c==="vertical"&&Kr(n.props.height)?{height:n.props.height}:c==="horizontal"?{width:n.props.width||i}:null}}])}(C.PureComponent);IF(T1,"displayName","Legend");IF(T1,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var Dse=eN,tyt=_W,ryt=$u,Mse=Dse?Dse.isConcatSpreadable:void 0;function nyt(t){return ryt(t)||tyt(t)||!!(Mse&&t&&t[Mse])}var iyt=nyt,syt=SSe,ayt=iyt;function FSe(t,e,r,n,i){var o=-1,c=t.length;for(r||(r=ayt),i||(i=[]);++o0&&r(a)?e>1?FSe(a,e-1,r,n,i):syt(i,a):n||(i[i.length]=a)}return i}var BSe=FSe;function oyt(t){return function(e,r,n){for(var i=-1,o=Object(e),c=n(e),a=c.length;a--;){var f=c[t?a:++i];if(r(o[f],f,o)===!1)break}return e}}var lyt=oyt,cyt=lyt,uyt=cyt(),dyt=uyt,hyt=dyt,fyt=NF;function myt(t,e){return t&&hyt(t,e,fyt)}var $Se=myt,pyt=nN;function gyt(t,e){return function(r,n){if(r==null)return r;if(!pyt(r))return t(r,n);for(var i=r.length,o=e?i:-1,c=Object(r);(e?o--:++oe||o&&c&&f&&!a&&!p||n&&c&&f||!r&&f||!i)return 1;if(!n&&!o&&!p&&t=a)return f;var p=r[n];return f*(p=="desc"?-1:1)}}return t.index-e.index}var Nyt=Cyt,Iz=lW,Iyt=cW,Pyt=Mm,Ryt=zSe,Lyt=Eyt,Dyt=jSe,Myt=Nyt,Oyt=AT,Fyt=$u;function Byt(t,e,r){e.length?e=Iz(e,function(o){return Fyt(o)?function(c){return Iyt(c,o.length===1?o[0]:o)}:o}):e=[Oyt];var n=-1;e=Iz(e,Dyt(Pyt));var i=Ryt(t,function(o,c,a){var f=Iz(e,function(p){return p(o)});return{criteria:f,index:++n,value:o}});return Lyt(i,function(o,c){return Myt(o,c,r)})}var $yt=Byt;function zyt(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}var Uyt=zyt,Vyt=Uyt,Fse=Math.max;function qyt(t,e,r){return e=Fse(e===void 0?t.length-1:e,0),function(){for(var n=arguments,i=-1,o=Fse(n.length-e,0),c=Array(o);++i0){if(++e>=ext)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}var ixt=nxt,sxt=Jyt,axt=ixt,oxt=axt(sxt),lxt=oxt,cxt=AT,uxt=Gyt,dxt=lxt;function hxt(t,e){return dxt(uxt(t,e,cxt),t+"")}var fxt=hxt,mxt=iW,pxt=nN,gxt=bW,yxt=Ux;function xxt(t,e,r){if(!yxt(r))return!1;var n=typeof e;return(n=="number"?pxt(r)&&gxt(e,r.length):n=="string"&&e in r)?mxt(r[e],t):!1}var PF=xxt,vxt=BSe,_xt=$yt,bxt=fxt,$se=PF,wxt=bxt(function(t,e){if(t==null)return[];var r=e.length;return r>1&&$se(t,e[0],e[1])?e=[]:r>2&&$se(e[0],e[1],e[2])&&(e=[e[0]]),_xt(t,vxt(e,1),[])}),Sxt=wxt;const EW=ds(Sxt);function wk(t){"@babel/helpers - typeof";return wk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},wk(t)}function K8(){return K8=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r=e.x),"".concat(p2,"-left"),Kr(r)&&e&&Kr(e.x)&&r=e.y),"".concat(p2,"-top"),Kr(n)&&e&&Kr(e.y)&&nP?Math.max(y,f[n]):Math.max(v,f[n])}function Fxt(t){var e=t.translateX,r=t.translateY,n=t.useTranslate3d;return{transform:n?"translate3d(".concat(e,"px, ").concat(r,"px, 0)"):"translate(".concat(e,"px, ").concat(r,"px)")}}function Bxt(t){var e=t.allowEscapeViewBox,r=t.coordinate,n=t.offsetTopLeft,i=t.position,o=t.reverseDirection,c=t.tooltipBox,a=t.useTranslate3d,f=t.viewBox,p,y,v;return c.height>0&&c.width>0&&r?(y=Vse({allowEscapeViewBox:e,coordinate:r,key:"x",offsetTopLeft:n,position:i,reverseDirection:o,tooltipDimension:c.width,viewBox:f,viewBoxDimension:f.width}),v=Vse({allowEscapeViewBox:e,coordinate:r,key:"y",offsetTopLeft:n,position:i,reverseDirection:o,tooltipDimension:c.height,viewBox:f,viewBoxDimension:f.height}),p=Fxt({translateX:y,translateY:v,useTranslate3d:a})):p=Mxt,{cssProperties:p,cssClasses:Oxt({translateX:y,translateY:v,coordinate:r})}}function bS(t){"@babel/helpers - typeof";return bS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},bS(t)}function qse(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function Gse(t){for(var e=1;eHse||Math.abs(n.height-this.state.lastBoundingBox.height)>Hse)&&this.setState({lastBoundingBox:{width:n.width,height:n.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var n,i;this.props.active&&this.updateBBox(),this.state.dismissed&&(((n=this.props.coordinate)===null||n===void 0?void 0:n.x)!==this.state.dismissedAtCoordinate.x||((i=this.props.coordinate)===null||i===void 0?void 0:i.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var n=this,i=this.props,o=i.active,c=i.allowEscapeViewBox,a=i.animationDuration,f=i.animationEasing,p=i.children,y=i.coordinate,v=i.hasPayload,T=i.isAnimationActive,E=i.offset,k=i.position,P=i.reverseDirection,R=i.useTranslate3d,D=i.viewBox,M=i.wrapperStyle,B=Bxt({allowEscapeViewBox:c,coordinate:y,offsetTopLeft:E,position:k,reverseDirection:P,tooltipBox:this.state.lastBoundingBox,useTranslate3d:R,viewBox:D}),V=B.cssClasses,G=B.cssProperties,W=Gse(Gse({transition:T&&o?"transform ".concat(a,"ms ").concat(f):void 0},G),{},{pointerEvents:"none",visibility:!this.state.dismissed&&o&&v?"visible":"hidden",position:"absolute",top:0,left:0},M);return Xe.createElement("div",{tabIndex:-1,className:V,style:W,ref:function(J){n.wrapperNode=J}},p)}}])}(C.PureComponent),Yxt=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},Vp={isSsr:Yxt(),get:function(e){return Vp[e]},set:function(e,r){if(typeof e=="string")Vp[e]=r;else{var n=Object.keys(e);n&&n.length&&n.forEach(function(i){Vp[i]=e[i]})}}};function wS(t){"@babel/helpers - typeof";return wS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},wS(t)}function Wse(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function Kse(t){for(var e=1;e0;return Xe.createElement(Kxt,{allowEscapeViewBox:c,animationDuration:a,animationEasing:f,isAnimationActive:T,active:o,coordinate:y,hasPayload:W,offset:E,position:R,reverseDirection:D,useTranslate3d:M,viewBox:B,wrapperStyle:V},s0t(p,Kse(Kse({},this.props),{},{payload:G})))}}])}(C.PureComponent);jW(Qh,"displayName","Tooltip");jW(Qh,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!Vp.isSsr,itemStyle:{},labelStyle:{},offset:10,reverseDirection:{x:!1,y:!1},separator:" : ",trigger:"hover",useTranslate3d:!1,viewBox:{x:0,y:0,height:0,width:0},wrapperStyle:{}});var a0t=Dm,o0t=function(){return a0t.Date.now()},l0t=o0t,c0t=/\s/;function u0t(t){for(var e=t.length;e--&&c0t.test(t.charAt(e)););return e}var d0t=u0t,h0t=d0t,f0t=/^\s+/;function m0t(t){return t&&t.slice(0,h0t(t)+1).replace(f0t,"")}var p0t=m0t,g0t=p0t,Yse=Ux,y0t=_T,Zse=NaN,x0t=/^[-+]0x[0-9a-f]+$/i,v0t=/^0b[01]+$/i,_0t=/^0o[0-7]+$/i,b0t=parseInt;function w0t(t){if(typeof t=="number")return t;if(y0t(t))return Zse;if(Yse(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=Yse(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=g0t(t);var r=v0t.test(t);return r||_0t.test(t)?b0t(t.slice(2),r?2:8):x0t.test(t)?Zse:+t}var WSe=w0t,S0t=Ux,Rz=l0t,Xse=WSe,T0t="Expected a function",E0t=Math.max,j0t=Math.min;function A0t(t,e,r){var n,i,o,c,a,f,p=0,y=!1,v=!1,T=!0;if(typeof t!="function")throw new TypeError(T0t);e=Xse(e)||0,S0t(r)&&(y=!!r.leading,v="maxWait"in r,o=v?E0t(Xse(r.maxWait)||0,e):o,T="trailing"in r?!!r.trailing:T);function E(W){var Y=n,J=i;return n=i=void 0,p=W,c=t.apply(J,Y),c}function k(W){return p=W,a=setTimeout(D,e),y?E(W):c}function P(W){var Y=W-f,J=W-p,Q=e-Y;return v?j0t(Q,o-J):Q}function R(W){var Y=W-f,J=W-p;return f===void 0||Y>=e||Y<0||v&&J>=o}function D(){var W=Rz();if(R(W))return M(W);a=setTimeout(D,P(W))}function M(W){return a=void 0,T&&n?E(W):(n=i=void 0,c)}function B(){a!==void 0&&clearTimeout(a),p=0,n=f=i=a=void 0}function V(){return a===void 0?c:M(Rz())}function G(){var W=Rz(),Y=R(W);if(n=arguments,i=this,f=W,Y){if(a===void 0)return k(f);if(v)return clearTimeout(a),a=setTimeout(D,e),E(f)}return a===void 0&&(a=setTimeout(D,e)),c}return G.cancel=B,G.flush=V,G}var k0t=A0t,C0t=k0t,N0t=Ux,I0t="Expected a function";function P0t(t,e,r){var n=!0,i=!0;if(typeof t!="function")throw new TypeError(I0t);return N0t(r)&&(n="leading"in r?!!r.leading:n,i="trailing"in r?!!r.trailing:i),C0t(t,e,{leading:n,maxWait:e,trailing:i})}var R0t=P0t;const KSe=ds(R0t);function Tk(t){"@babel/helpers - typeof";return Tk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Tk(t)}function Qse(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function NR(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r0&&(Se=KSe(Se,P,{trailing:!0,leading:!1}));var je=new ResizeObserver(Se),Le=G.current.getBoundingClientRect(),Ae=Le.width,be=Le.height;return le(Ae,be),je.observe(G.current),function(){je.disconnect()}},[le,P]);var pe=C.useMemo(function(){var Se=Q.containerWidth,je=Q.containerHeight;if(Se<0||je<0)return null;mf(kv(c)||kv(f),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,c,f),mf(!r||r>0,"The aspect(%s) must be greater than zero.",r);var Le=kv(c)?Se:c,Ae=kv(f)?je:f;r&&r>0&&(Le?Ae=Le/r:Ae&&(Le=Ae*r),T&&Ae>T&&(Ae=T)),mf(Le>0||Ae>0,`The width(%s) and height(%s) of chart should be greater than 0, please check the style of container, or the props width(%s) and height(%s), or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the height and width.`,Le,Ae,c,f,y,v,r);var be=!Array.isArray(E)&&Up(E.type).endsWith("Chart");return Xe.Children.map(E,function(me){return Xe.isValidElement(me)?C.cloneElement(me,NR({width:Le,height:Ae},be?{style:NR({height:"100%",width:"100%",maxHeight:Ae,maxWidth:Le},me.props.style)}:{})):me})},[r,E,f,T,v,y,Q,c]);return Xe.createElement("div",{id:R?"".concat(R):void 0,className:$i("recharts-responsive-container",D),style:NR(NR({},V),{},{width:c,height:f,minWidth:y,minHeight:v,maxHeight:T}),ref:G},pe)}),RF=function(e){return null};RF.displayName="Cell";function Ek(t){"@babel/helpers - typeof";return Ek=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ek(t)}function eae(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function J8(t){for(var e=1;e1&&arguments[1]!==void 0?arguments[1]:{};if(e==null||Vp.isSsr)return{width:0,height:0};var n=W0t(r),i=JSON.stringify({text:e,copyStyle:n});if(bw.widthCache[i])return bw.widthCache[i];try{var o=document.getElementById(tae);o||(o=document.createElement("span"),o.setAttribute("id",tae),o.setAttribute("aria-hidden","true"),document.body.appendChild(o));var c=J8(J8({},H0t),n);Object.assign(o.style,c),o.textContent="".concat(e);var a=o.getBoundingClientRect(),f={width:a.width,height:a.height};return bw.widthCache[i]=f,++bw.cacheCount>G0t&&(bw.cacheCount=0,bw.widthCache={}),f}catch{return{width:0,height:0}}},K0t=function(e){return{top:e.top+window.scrollY-document.documentElement.clientTop,left:e.left+window.scrollX-document.documentElement.clientLeft}};function jk(t){"@babel/helpers - typeof";return jk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},jk(t)}function IM(t,e){return Q0t(t)||X0t(t,e)||Z0t(t,e)||Y0t()}function Y0t(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Z0t(t,e){if(t){if(typeof t=="string")return rae(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return rae(t,e)}}function rae(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function hvt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function lae(t,e){return gvt(t)||pvt(t,e)||mvt(t,e)||fvt()}function fvt(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function mvt(t,e){if(t){if(typeof t=="string")return cae(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return cae(t,e)}}function cae(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0&&arguments[0]!==void 0?arguments[0]:[];return Le.reduce(function(Ae,be){var me=be.word,Te=be.width,Ne=Ae[Ae.length-1];if(Ne&&(i==null||o||Ne.width+Te+nbe.width?Ae:be})};if(!y)return E;for(var P="…",R=function(Le){var Ae=v.slice(0,Le),be=QSe({breakAll:p,style:f,children:Ae+P}).wordsWithComputedWidth,me=T(be),Te=me.length>c||k(me).width>Number(i);return[Te,me]},D=0,M=v.length-1,B=0,V;D<=M&&B<=v.length-1;){var G=Math.floor((D+M)/2),W=G-1,Y=R(W),J=lae(Y,2),Q=J[0],ee=J[1],le=R(G),pe=lae(le,1),Se=pe[0];if(!Q&&!Se&&(D=G+1),Q&&Se&&(M=G-1),!Q&&Se){V=ee;break}B++}return V||E},uae=function(e){var r=zi(e)?[]:e.toString().split(XSe);return[{words:r}]},xvt=function(e){var r=e.width,n=e.scaleToFit,i=e.children,o=e.style,c=e.breakAll,a=e.maxLines;if((r||n)&&!Vp.isSsr){var f,p,y=QSe({breakAll:c,children:i,style:o});if(y){var v=y.wordsWithComputedWidth,T=y.spaceWidth;f=v,p=T}else return uae(i);return yvt({breakAll:c,children:i,maxLines:a,style:o},f,p,r,n)}return uae(i)},dae="#808080",d_=function(e){var r=e.x,n=r===void 0?0:r,i=e.y,o=i===void 0?0:i,c=e.lineHeight,a=c===void 0?"1em":c,f=e.capHeight,p=f===void 0?"0.71em":f,y=e.scaleToFit,v=y===void 0?!1:y,T=e.textAnchor,E=T===void 0?"start":T,k=e.verticalAnchor,P=k===void 0?"end":k,R=e.fill,D=R===void 0?dae:R,M=oae(e,uvt),B=C.useMemo(function(){return xvt({breakAll:M.breakAll,children:M.children,maxLines:M.maxLines,scaleToFit:v,style:M.style,width:M.width})},[M.breakAll,M.children,M.maxLines,v,M.style,M.width]),V=M.dx,G=M.dy,W=M.angle,Y=M.className,J=M.breakAll,Q=oae(M,dvt);if(!gl(n)||!gl(o))return null;var ee=n+(Kr(V)?V:0),le=o+(Kr(G)?G:0),pe;switch(P){case"start":pe=Lz("calc(".concat(p,")"));break;case"middle":pe=Lz("calc(".concat((B.length-1)/2," * -").concat(a," + (").concat(p," / 2))"));break;default:pe=Lz("calc(".concat(B.length-1," * -").concat(a,")"));break}var Se=[];if(v){var je=B[0].width,Le=M.width;Se.push("scale(".concat((Kr(Le)?Le/je:1)/je,")"))}return W&&Se.push("rotate(".concat(W,", ").concat(ee,", ").concat(le,")")),Se.length&&(Q.transform=Se.join(" ")),Xe.createElement("text",eq({},fi(Q,!0),{x:ee,y:le,className:$i("recharts-text",Y),textAnchor:E,fill:D.includes("url")?dae:D}),B.map(function(Ae,be){var me=Ae.words.join(J?"":" ");return Xe.createElement("tspan",{x:ee,dy:be===0?pe:a,key:"".concat(me,"-").concat(be)},me)}))};function sx(t,e){return t==null||e==null?NaN:te?1:t>=e?0:NaN}function vvt(t,e){return t==null||e==null?NaN:et?1:e>=t?0:NaN}function AW(t){let e,r,n;t.length!==2?(e=sx,r=(a,f)=>sx(t(a),f),n=(a,f)=>t(a)-f):(e=t===sx||t===vvt?t:_vt,r=t,n=t);function i(a,f,p=0,y=a.length){if(p>>1;r(a[v],f)<0?p=v+1:y=v}while(p>>1;r(a[v],f)<=0?p=v+1:y=v}while(pp&&n(a[v-1],f)>-n(a[v],f)?v-1:v}return{left:i,center:c,right:o}}function _vt(){return 0}function JSe(t){return t===null?NaN:+t}function*bvt(t,e){for(let r of t)r!=null&&(r=+r)>=r&&(yield r)}const wvt=AW(sx),iN=wvt.right;AW(JSe).center;class hae extends Map{constructor(e,r=Evt){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),e!=null)for(const[n,i]of e)this.set(n,i)}get(e){return super.get(fae(this,e))}has(e){return super.has(fae(this,e))}set(e,r){return super.set(Svt(this,e),r)}delete(e){return super.delete(Tvt(this,e))}}function fae({_intern:t,_key:e},r){const n=e(r);return t.has(n)?t.get(n):r}function Svt({_intern:t,_key:e},r){const n=e(r);return t.has(n)?t.get(n):(t.set(n,r),r)}function Tvt({_intern:t,_key:e},r){const n=e(r);return t.has(n)&&(r=t.get(n),t.delete(n)),r}function Evt(t){return t!==null&&typeof t=="object"?t.valueOf():t}function jvt(t=sx){if(t===sx)return eTe;if(typeof t!="function")throw new TypeError("compare is not a function");return(e,r)=>{const n=t(e,r);return n||n===0?n:(t(r,r)===0)-(t(e,e)===0)}}function eTe(t,e){return(t==null||!(t>=t))-(e==null||!(e>=e))||(te?1:0)}const Avt=Math.sqrt(50),kvt=Math.sqrt(10),Cvt=Math.sqrt(2);function PM(t,e,r){const n=(e-t)/Math.max(0,r),i=Math.floor(Math.log10(n)),o=n/Math.pow(10,i),c=o>=Avt?10:o>=kvt?5:o>=Cvt?2:1;let a,f,p;return i<0?(p=Math.pow(10,-i)/c,a=Math.round(t*p),f=Math.round(e*p),a/pe&&--f,p=-p):(p=Math.pow(10,i)*c,a=Math.round(t/p),f=Math.round(e/p),a*pe&&--f),f0))return[];if(t===e)return[t];const n=e=i))return[];const a=o-i+1,f=new Array(a);if(n)if(c<0)for(let p=0;p=n)&&(r=n);return r}function pae(t,e){let r;for(const n of t)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function tTe(t,e,r=0,n=1/0,i){if(e=Math.floor(e),r=Math.floor(Math.max(0,r)),n=Math.floor(Math.min(t.length-1,n)),!(r<=e&&e<=n))return t;for(i=i===void 0?eTe:jvt(i);n>r;){if(n-r>600){const f=n-r+1,p=e-r+1,y=Math.log(f),v=.5*Math.exp(2*y/3),T=.5*Math.sqrt(y*v*(f-v)/f)*(p-f/2<0?-1:1),E=Math.max(r,Math.floor(e-p*v/f+T)),k=Math.min(n,Math.floor(e+(f-p)*v/f+T));tTe(t,e,E,k,i)}const o=t[e];let c=r,a=n;for(g2(t,r,e),i(t[n],o)>0&&g2(t,r,n);c0;)--a}i(t[r],o)===0?g2(t,r,a):(++a,g2(t,a,n)),a<=e&&(r=a+1),e<=a&&(n=a-1)}return t}function g2(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function Nvt(t,e,r){if(t=Float64Array.from(bvt(t)),!(!(n=t.length)||isNaN(e=+e))){if(e<=0||n<2)return pae(t);if(e>=1)return mae(t);var n,i=(n-1)*e,o=Math.floor(i),c=mae(tTe(t,o).subarray(0,o+1)),a=pae(t.subarray(o+1));return c+(a-c)*(i-o)}}function Ivt(t,e,r=JSe){if(!(!(n=t.length)||isNaN(e=+e))){if(e<=0||n<2)return+r(t[0],0,t);if(e>=1)return+r(t[n-1],n-1,t);var n,i=(n-1)*e,o=Math.floor(i),c=+r(t[o],o,t),a=+r(t[o+1],o+1,t);return c+(a-c)*(i-o)}}function Pvt(t,e,r){t=+t,e=+e,r=(i=arguments.length)<2?(e=t,t=0,1):i<3?1:+r;for(var n=-1,i=Math.max(0,Math.ceil((e-t)/r))|0,o=new Array(i);++n>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):r===8?PR(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):r===4?PR(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|e&240,((e&15)<<4|e&15)/255):null):(e=Lvt.exec(t))?new Pu(e[1],e[2],e[3],1):(e=Dvt.exec(t))?new Pu(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=Mvt.exec(t))?PR(e[1],e[2],e[3],e[4]):(e=Ovt.exec(t))?PR(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=Fvt.exec(t))?wae(e[1],e[2]/100,e[3]/100,1):(e=Bvt.exec(t))?wae(e[1],e[2]/100,e[3]/100,e[4]):gae.hasOwnProperty(t)?vae(gae[t]):t==="transparent"?new Pu(NaN,NaN,NaN,0):null}function vae(t){return new Pu(t>>16&255,t>>8&255,t&255,1)}function PR(t,e,r,n){return n<=0&&(t=e=r=NaN),new Pu(t,e,r,n)}function Uvt(t){return t instanceof sN||(t=Nk(t)),t?(t=t.rgb(),new Pu(t.r,t.g,t.b,t.opacity)):new Pu}function sq(t,e,r,n){return arguments.length===1?Uvt(t):new Pu(t,e,r,n??1)}function Pu(t,e,r,n){this.r=+t,this.g=+e,this.b=+r,this.opacity=+n}CW(Pu,sq,nTe(sN,{brighter(t){return t=t==null?RM:Math.pow(RM,t),new Pu(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?kk:Math.pow(kk,t),new Pu(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new Pu(Wv(this.r),Wv(this.g),Wv(this.b),LM(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:_ae,formatHex:_ae,formatHex8:Vvt,formatRgb:bae,toString:bae}));function _ae(){return`#${Cv(this.r)}${Cv(this.g)}${Cv(this.b)}`}function Vvt(){return`#${Cv(this.r)}${Cv(this.g)}${Cv(this.b)}${Cv((isNaN(this.opacity)?1:this.opacity)*255)}`}function bae(){const t=LM(this.opacity);return`${t===1?"rgb(":"rgba("}${Wv(this.r)}, ${Wv(this.g)}, ${Wv(this.b)}${t===1?")":`, ${t})`}`}function LM(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Wv(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function Cv(t){return t=Wv(t),(t<16?"0":"")+t.toString(16)}function wae(t,e,r,n){return n<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new af(t,e,r,n)}function iTe(t){if(t instanceof af)return new af(t.h,t.s,t.l,t.opacity);if(t instanceof sN||(t=Nk(t)),!t)return new af;if(t instanceof af)return t;t=t.rgb();var e=t.r/255,r=t.g/255,n=t.b/255,i=Math.min(e,r,n),o=Math.max(e,r,n),c=NaN,a=o-i,f=(o+i)/2;return a?(e===o?c=(r-n)/a+(r0&&f<1?0:c,new af(c,a,f,t.opacity)}function qvt(t,e,r,n){return arguments.length===1?iTe(t):new af(t,e,r,n??1)}function af(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}CW(af,qvt,nTe(sN,{brighter(t){return t=t==null?RM:Math.pow(RM,t),new af(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?kk:Math.pow(kk,t),new af(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,e=isNaN(t)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*e,i=2*r-n;return new Pu(Dz(t>=240?t-240:t+120,i,n),Dz(t,i,n),Dz(t<120?t+240:t-120,i,n),this.opacity)},clamp(){return new af(Sae(this.h),RR(this.s),RR(this.l),LM(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=LM(this.opacity);return`${t===1?"hsl(":"hsla("}${Sae(this.h)}, ${RR(this.s)*100}%, ${RR(this.l)*100}%${t===1?")":`, ${t})`}`}}));function Sae(t){return t=(t||0)%360,t<0?t+360:t}function RR(t){return Math.max(0,Math.min(1,t||0))}function Dz(t,e,r){return(t<60?e+(r-e)*t/60:t<180?r:t<240?e+(r-e)*(240-t)/60:e)*255}const NW=t=>()=>t;function Gvt(t,e){return function(r){return t+r*e}}function Hvt(t,e,r){return t=Math.pow(t,r),e=Math.pow(e,r)-t,r=1/r,function(n){return Math.pow(t+n*e,r)}}function Wvt(t){return(t=+t)==1?sTe:function(e,r){return r-e?Hvt(e,r,t):NW(isNaN(e)?r:e)}}function sTe(t,e){var r=e-t;return r?Gvt(t,r):NW(isNaN(t)?e:t)}const Tae=function t(e){var r=Wvt(e);function n(i,o){var c=r((i=sq(i)).r,(o=sq(o)).r),a=r(i.g,o.g),f=r(i.b,o.b),p=sTe(i.opacity,o.opacity);return function(y){return i.r=c(y),i.g=a(y),i.b=f(y),i.opacity=p(y),i+""}}return n.gamma=t,n}(1);function Kvt(t,e){e||(e=[]);var r=t?Math.min(e.length,t.length):0,n=e.slice(),i;return function(o){for(i=0;ir&&(o=e.slice(r,o),a[c]?a[c]+=o:a[++c]=o),(n=n[0])===(i=i[0])?a[c]?a[c]+=i:a[++c]=i:(a[++c]=null,f.push({i:c,x:DM(n,i)})),r=Mz.lastIndex;return re&&(r=t,t=e,e=r),function(n){return Math.max(t,Math.min(e,n))}}function s_t(t,e,r){var n=t[0],i=t[1],o=e[0],c=e[1];return i2?a_t:s_t,f=p=null,v}function v(T){return T==null||isNaN(T=+T)?o:(f||(f=a(t.map(n),e,r)))(n(c(T)))}return v.invert=function(T){return c(i((p||(p=a(e,t.map(n),DM)))(T)))},v.domain=function(T){return arguments.length?(t=Array.from(T,MM),y()):t.slice()},v.range=function(T){return arguments.length?(e=Array.from(T),y()):e.slice()},v.rangeRound=function(T){return e=Array.from(T),r=IW,y()},v.clamp=function(T){return arguments.length?(c=T?!0:tu,y()):c!==tu},v.interpolate=function(T){return arguments.length?(r=T,y()):r},v.unknown=function(T){return arguments.length?(o=T,v):o},function(T,E){return n=T,i=E,y()}}function PW(){return LF()(tu,tu)}function o_t(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function OM(t,e){if((r=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var r,n=t.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+t.slice(r+1)]}function SS(t){return t=OM(Math.abs(t)),t?t[1]:NaN}function l_t(t,e){return function(r,n){for(var i=r.length,o=[],c=0,a=t[0],f=0;i>0&&a>0&&(f+a+1>n&&(a=Math.max(1,n-f)),o.push(r.substring(i-=a,i+a)),!((f+=a+1)>n));)a=t[c=(c+1)%t.length];return o.reverse().join(e)}}function c_t(t){return function(e){return e.replace(/[0-9]/g,function(r){return t[+r]})}}var u_t=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Ik(t){if(!(e=u_t.exec(t)))throw new Error("invalid format: "+t);var e;return new RW({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}Ik.prototype=RW.prototype;function RW(t){this.fill=t.fill===void 0?" ":t.fill+"",this.align=t.align===void 0?">":t.align+"",this.sign=t.sign===void 0?"-":t.sign+"",this.symbol=t.symbol===void 0?"":t.symbol+"",this.zero=!!t.zero,this.width=t.width===void 0?void 0:+t.width,this.comma=!!t.comma,this.precision=t.precision===void 0?void 0:+t.precision,this.trim=!!t.trim,this.type=t.type===void 0?"":t.type+""}RW.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function d_t(t){e:for(var e=t.length,r=1,n=-1,i;r0&&(n=0);break}return n>0?t.slice(0,n)+t.slice(i+1):t}var aTe;function h_t(t,e){var r=OM(t,e);if(!r)return t+"";var n=r[0],i=r[1],o=i-(aTe=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,c=n.length;return o===c?n:o>c?n+new Array(o-c+1).join("0"):o>0?n.slice(0,o)+"."+n.slice(o):"0."+new Array(1-o).join("0")+OM(t,Math.max(0,e+o-1))[0]}function jae(t,e){var r=OM(t,e);if(!r)return t+"";var n=r[0],i=r[1];return i<0?"0."+new Array(-i).join("0")+n:n.length>i+1?n.slice(0,i+1)+"."+n.slice(i+1):n+new Array(i-n.length+2).join("0")}const Aae={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:o_t,e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>jae(t*100,e),r:jae,s:h_t,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function kae(t){return t}var Cae=Array.prototype.map,Nae=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function f_t(t){var e=t.grouping===void 0||t.thousands===void 0?kae:l_t(Cae.call(t.grouping,Number),t.thousands+""),r=t.currency===void 0?"":t.currency[0]+"",n=t.currency===void 0?"":t.currency[1]+"",i=t.decimal===void 0?".":t.decimal+"",o=t.numerals===void 0?kae:c_t(Cae.call(t.numerals,String)),c=t.percent===void 0?"%":t.percent+"",a=t.minus===void 0?"−":t.minus+"",f=t.nan===void 0?"NaN":t.nan+"";function p(v){v=Ik(v);var T=v.fill,E=v.align,k=v.sign,P=v.symbol,R=v.zero,D=v.width,M=v.comma,B=v.precision,V=v.trim,G=v.type;G==="n"?(M=!0,G="g"):Aae[G]||(B===void 0&&(B=12),V=!0,G="g"),(R||T==="0"&&E==="=")&&(R=!0,T="0",E="=");var W=P==="$"?r:P==="#"&&/[boxX]/.test(G)?"0"+G.toLowerCase():"",Y=P==="$"?n:/[%p]/.test(G)?c:"",J=Aae[G],Q=/[defgprs%]/.test(G);B=B===void 0?6:/[gprs]/.test(G)?Math.max(1,Math.min(21,B)):Math.max(0,Math.min(20,B));function ee(le){var pe=W,Se=Y,je,Le,Ae;if(G==="c")Se=J(le)+Se,le="";else{le=+le;var be=le<0||1/le<0;if(le=isNaN(le)?f:J(Math.abs(le),B),V&&(le=d_t(le)),be&&+le==0&&k!=="+"&&(be=!1),pe=(be?k==="("?k:a:k==="-"||k==="("?"":k)+pe,Se=(G==="s"?Nae[8+aTe/3]:"")+Se+(be&&k==="("?")":""),Q){for(je=-1,Le=le.length;++jeAe||Ae>57){Se=(Ae===46?i+le.slice(je+1):le.slice(je))+Se,le=le.slice(0,je);break}}}M&&!R&&(le=e(le,1/0));var me=pe.length+le.length+Se.length,Te=me>1)+pe+le+Se+Te.slice(me);break;default:le=Te+pe+le+Se;break}return o(le)}return ee.toString=function(){return v+""},ee}function y(v,T){var E=p((v=Ik(v),v.type="f",v)),k=Math.max(-8,Math.min(8,Math.floor(SS(T)/3)))*3,P=Math.pow(10,-k),R=Nae[8+k/3];return function(D){return E(P*D)+R}}return{format:p,formatPrefix:y}}var LR,LW,oTe;m_t({thousands:",",grouping:[3],currency:["$",""]});function m_t(t){return LR=f_t(t),LW=LR.format,oTe=LR.formatPrefix,LR}function p_t(t){return Math.max(0,-SS(Math.abs(t)))}function g_t(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(SS(e)/3)))*3-SS(Math.abs(t)))}function y_t(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,SS(e)-SS(t))+1}function lTe(t,e,r,n){var i=nq(t,e,r),o;switch(n=Ik(n??",f"),n.type){case"s":{var c=Math.max(Math.abs(t),Math.abs(e));return n.precision==null&&!isNaN(o=g_t(i,c))&&(n.precision=o),oTe(n,c)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(o=y_t(i,Math.max(Math.abs(t),Math.abs(e))))&&(n.precision=o-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(o=p_t(i))&&(n.precision=o-(n.type==="%")*2);break}}return LW(n)}function Vx(t){var e=t.domain;return t.ticks=function(r){var n=e();return tq(n[0],n[n.length-1],r??10)},t.tickFormat=function(r,n){var i=e();return lTe(i[0],i[i.length-1],r??10,n)},t.nice=function(r){r==null&&(r=10);var n=e(),i=0,o=n.length-1,c=n[i],a=n[o],f,p,y=10;for(a0;){if(p=rq(c,a,r),p===f)return n[i]=c,n[o]=a,e(n);if(p>0)c=Math.floor(c/p)*p,a=Math.ceil(a/p)*p;else if(p<0)c=Math.ceil(c*p)/p,a=Math.floor(a*p)/p;else break;f=p}return t},t}function FM(){var t=PW();return t.copy=function(){return aN(t,FM())},vh.apply(t,arguments),Vx(t)}function cTe(t){var e;function r(n){return n==null||isNaN(n=+n)?e:n}return r.invert=r,r.domain=r.range=function(n){return arguments.length?(t=Array.from(n,MM),r):t.slice()},r.unknown=function(n){return arguments.length?(e=n,r):e},r.copy=function(){return cTe(t).unknown(e)},t=arguments.length?Array.from(t,MM):[0,1],Vx(r)}function uTe(t,e){t=t.slice();var r=0,n=t.length-1,i=t[r],o=t[n],c;return oMath.pow(t,e)}function w_t(t){return t===Math.E?Math.log:t===10&&Math.log10||t===2&&Math.log2||(t=Math.log(t),e=>Math.log(e)/t)}function Rae(t){return(e,r)=>-t(-e,r)}function DW(t){const e=t(Iae,Pae),r=e.domain;let n=10,i,o;function c(){return i=w_t(n),o=b_t(n),r()[0]<0?(i=Rae(i),o=Rae(o),t(x_t,v_t)):t(Iae,Pae),e}return e.base=function(a){return arguments.length?(n=+a,c()):n},e.domain=function(a){return arguments.length?(r(a),c()):r()},e.ticks=a=>{const f=r();let p=f[0],y=f[f.length-1];const v=y0){for(;T<=E;++T)for(k=1;ky)break;D.push(P)}}else for(;T<=E;++T)for(k=n-1;k>=1;--k)if(P=T>0?k/o(-T):k*o(T),!(Py)break;D.push(P)}D.length*2{if(a==null&&(a=10),f==null&&(f=n===10?"s":","),typeof f!="function"&&(!(n%1)&&(f=Ik(f)).precision==null&&(f.trim=!0),f=LW(f)),a===1/0)return f;const p=Math.max(1,n*a/e.ticks().length);return y=>{let v=y/o(Math.round(i(y)));return v*nr(uTe(r(),{floor:a=>o(Math.floor(i(a))),ceil:a=>o(Math.ceil(i(a)))})),e}function dTe(){const t=DW(LF()).domain([1,10]);return t.copy=()=>aN(t,dTe()).base(t.base()),vh.apply(t,arguments),t}function Lae(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function Dae(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function MW(t){var e=1,r=t(Lae(e),Dae(e));return r.constant=function(n){return arguments.length?t(Lae(e=+n),Dae(e)):e},Vx(r)}function hTe(){var t=MW(LF());return t.copy=function(){return aN(t,hTe()).constant(t.constant())},vh.apply(t,arguments)}function Mae(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function S_t(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function T_t(t){return t<0?-t*t:t*t}function OW(t){var e=t(tu,tu),r=1;function n(){return r===1?t(tu,tu):r===.5?t(S_t,T_t):t(Mae(r),Mae(1/r))}return e.exponent=function(i){return arguments.length?(r=+i,n()):r},Vx(e)}function FW(){var t=OW(LF());return t.copy=function(){return aN(t,FW()).exponent(t.exponent())},vh.apply(t,arguments),t}function E_t(){return FW.apply(null,arguments).exponent(.5)}function Oae(t){return Math.sign(t)*t*t}function j_t(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}function fTe(){var t=PW(),e=[0,1],r=!1,n;function i(o){var c=j_t(t(o));return isNaN(c)?n:r?Math.round(c):c}return i.invert=function(o){return t.invert(Oae(o))},i.domain=function(o){return arguments.length?(t.domain(o),i):t.domain()},i.range=function(o){return arguments.length?(t.range((e=Array.from(o,MM)).map(Oae)),i):e.slice()},i.rangeRound=function(o){return i.range(o).round(!0)},i.round=function(o){return arguments.length?(r=!!o,i):r},i.clamp=function(o){return arguments.length?(t.clamp(o),i):t.clamp()},i.unknown=function(o){return arguments.length?(n=o,i):n},i.copy=function(){return fTe(t.domain(),e).round(r).clamp(t.clamp()).unknown(n)},vh.apply(i,arguments),Vx(i)}function mTe(){var t=[],e=[],r=[],n;function i(){var c=0,a=Math.max(1,e.length);for(r=new Array(a-1);++c0?r[a-1]:t[0],a=r?[n[r-1],e]:[n[p-1],n[p]]},c.unknown=function(f){return arguments.length&&(o=f),c},c.thresholds=function(){return n.slice()},c.copy=function(){return pTe().domain([t,e]).range(i).unknown(o)},vh.apply(Vx(c),arguments)}function gTe(){var t=[.5],e=[0,1],r,n=1;function i(o){return o!=null&&o<=o?e[iN(t,o,0,n)]:r}return i.domain=function(o){return arguments.length?(t=Array.from(o),n=Math.min(t.length,e.length-1),i):t.slice()},i.range=function(o){return arguments.length?(e=Array.from(o),n=Math.min(t.length,e.length-1),i):e.slice()},i.invertExtent=function(o){var c=e.indexOf(o);return[t[c-1],t[c]]},i.unknown=function(o){return arguments.length?(r=o,i):r},i.copy=function(){return gTe().domain(t).range(e).unknown(r)},vh.apply(i,arguments)}const Oz=new Date,Fz=new Date;function _l(t,e,r,n){function i(o){return t(o=arguments.length===0?new Date:new Date(+o)),o}return i.floor=o=>(t(o=new Date(+o)),o),i.ceil=o=>(t(o=new Date(o-1)),e(o,1),t(o),o),i.round=o=>{const c=i(o),a=i.ceil(o);return o-c(e(o=new Date(+o),c==null?1:Math.floor(c)),o),i.range=(o,c,a)=>{const f=[];if(o=i.ceil(o),a=a==null?1:Math.floor(a),!(o0))return f;let p;do f.push(p=new Date(+o)),e(o,a),t(o);while(p_l(c=>{if(c>=c)for(;t(c),!o(c);)c.setTime(c-1)},(c,a)=>{if(c>=c)if(a<0)for(;++a<=0;)for(;e(c,-1),!o(c););else for(;--a>=0;)for(;e(c,1),!o(c););}),r&&(i.count=(o,c)=>(Oz.setTime(+o),Fz.setTime(+c),t(Oz),t(Fz),Math.floor(r(Oz,Fz))),i.every=o=>(o=Math.floor(o),!isFinite(o)||!(o>0)?null:o>1?i.filter(n?c=>n(c)%o===0:c=>i.count(0,c)%o===0):i)),i}const BM=_l(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);BM.every=t=>(t=Math.floor(t),!isFinite(t)||!(t>0)?null:t>1?_l(e=>{e.setTime(Math.floor(e/t)*t)},(e,r)=>{e.setTime(+e+r*t)},(e,r)=>(r-e)/t):BM);BM.range;const Mp=1e3,sh=Mp*60,Op=sh*60,ig=Op*24,BW=ig*7,Fae=ig*30,Bz=ig*365,Nv=_l(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*Mp)},(t,e)=>(e-t)/Mp,t=>t.getUTCSeconds());Nv.range;const $W=_l(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Mp)},(t,e)=>{t.setTime(+t+e*sh)},(t,e)=>(e-t)/sh,t=>t.getMinutes());$W.range;const zW=_l(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*sh)},(t,e)=>(e-t)/sh,t=>t.getUTCMinutes());zW.range;const UW=_l(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Mp-t.getMinutes()*sh)},(t,e)=>{t.setTime(+t+e*Op)},(t,e)=>(e-t)/Op,t=>t.getHours());UW.range;const VW=_l(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*Op)},(t,e)=>(e-t)/Op,t=>t.getUTCHours());VW.range;const oN=_l(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*sh)/ig,t=>t.getDate()-1);oN.range;const DF=_l(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/ig,t=>t.getUTCDate()-1);DF.range;const yTe=_l(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/ig,t=>Math.floor(t/ig));yTe.range;function k_(t){return _l(e=>{e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)},(e,r)=>{e.setDate(e.getDate()+r*7)},(e,r)=>(r-e-(r.getTimezoneOffset()-e.getTimezoneOffset())*sh)/BW)}const MF=k_(0),$M=k_(1),A_t=k_(2),k_t=k_(3),TS=k_(4),C_t=k_(5),N_t=k_(6);MF.range;$M.range;A_t.range;k_t.range;TS.range;C_t.range;N_t.range;function C_(t){return _l(e=>{e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCDate(e.getUTCDate()+r*7)},(e,r)=>(r-e)/BW)}const OF=C_(0),zM=C_(1),I_t=C_(2),P_t=C_(3),ES=C_(4),R_t=C_(5),L_t=C_(6);OF.range;zM.range;I_t.range;P_t.range;ES.range;R_t.range;L_t.range;const qW=_l(t=>{t.setDate(1),t.setHours(0,0,0,0)},(t,e)=>{t.setMonth(t.getMonth()+e)},(t,e)=>e.getMonth()-t.getMonth()+(e.getFullYear()-t.getFullYear())*12,t=>t.getMonth());qW.range;const GW=_l(t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCMonth(t.getUTCMonth()+e)},(t,e)=>e.getUTCMonth()-t.getUTCMonth()+(e.getUTCFullYear()-t.getUTCFullYear())*12,t=>t.getUTCMonth());GW.range;const sg=_l(t=>{t.setMonth(0,1),t.setHours(0,0,0,0)},(t,e)=>{t.setFullYear(t.getFullYear()+e)},(t,e)=>e.getFullYear()-t.getFullYear(),t=>t.getFullYear());sg.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:_l(e=>{e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)},(e,r)=>{e.setFullYear(e.getFullYear()+r*t)});sg.range;const ag=_l(t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCFullYear(t.getUTCFullYear()+e)},(t,e)=>e.getUTCFullYear()-t.getUTCFullYear(),t=>t.getUTCFullYear());ag.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:_l(e=>{e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCFullYear(e.getUTCFullYear()+r*t)});ag.range;function xTe(t,e,r,n,i,o){const c=[[Nv,1,Mp],[Nv,5,5*Mp],[Nv,15,15*Mp],[Nv,30,30*Mp],[o,1,sh],[o,5,5*sh],[o,15,15*sh],[o,30,30*sh],[i,1,Op],[i,3,3*Op],[i,6,6*Op],[i,12,12*Op],[n,1,ig],[n,2,2*ig],[r,1,BW],[e,1,Fae],[e,3,3*Fae],[t,1,Bz]];function a(p,y,v){const T=yR).right(c,T);if(E===c.length)return t.every(nq(p/Bz,y/Bz,v));if(E===0)return BM.every(Math.max(nq(p,y,v),1));const[k,P]=c[T/c[E-1][2]53)return null;"w"in _t||(_t.w=1),"Z"in _t?(Tr=zz(y2(_t.y,0,1)),sn=Tr.getUTCDay(),Tr=sn>4||sn===0?zM.ceil(Tr):zM(Tr),Tr=DF.offset(Tr,(_t.V-1)*7),_t.y=Tr.getUTCFullYear(),_t.m=Tr.getUTCMonth(),_t.d=Tr.getUTCDate()+(_t.w+6)%7):(Tr=$z(y2(_t.y,0,1)),sn=Tr.getDay(),Tr=sn>4||sn===0?$M.ceil(Tr):$M(Tr),Tr=oN.offset(Tr,(_t.V-1)*7),_t.y=Tr.getFullYear(),_t.m=Tr.getMonth(),_t.d=Tr.getDate()+(_t.w+6)%7)}else("W"in _t||"U"in _t)&&("w"in _t||(_t.w="u"in _t?_t.u%7:"W"in _t?1:0),sn="Z"in _t?zz(y2(_t.y,0,1)).getUTCDay():$z(y2(_t.y,0,1)).getDay(),_t.m=0,_t.d="W"in _t?(_t.w+6)%7+_t.W*7-(sn+5)%7:_t.w+_t.U*7-(sn+6)%7);return"Z"in _t?(_t.H+=_t.Z/100|0,_t.M+=_t.Z%100,zz(_t)):$z(_t)}}function J(pt,Pt,tr,_t){for(var cr=0,Tr=Pt.length,sn=tr.length,ur,xr;cr=sn)return-1;if(ur=Pt.charCodeAt(cr++),ur===37){if(ur=Pt.charAt(cr++),xr=G[ur in Bae?Pt.charAt(cr++):ur],!xr||(_t=xr(pt,tr,_t))<0)return-1}else if(ur!=tr.charCodeAt(_t++))return-1}return _t}function Q(pt,Pt,tr){var _t=p.exec(Pt.slice(tr));return _t?(pt.p=y.get(_t[0].toLowerCase()),tr+_t[0].length):-1}function ee(pt,Pt,tr){var _t=E.exec(Pt.slice(tr));return _t?(pt.w=k.get(_t[0].toLowerCase()),tr+_t[0].length):-1}function le(pt,Pt,tr){var _t=v.exec(Pt.slice(tr));return _t?(pt.w=T.get(_t[0].toLowerCase()),tr+_t[0].length):-1}function pe(pt,Pt,tr){var _t=D.exec(Pt.slice(tr));return _t?(pt.m=M.get(_t[0].toLowerCase()),tr+_t[0].length):-1}function Se(pt,Pt,tr){var _t=P.exec(Pt.slice(tr));return _t?(pt.m=R.get(_t[0].toLowerCase()),tr+_t[0].length):-1}function je(pt,Pt,tr){return J(pt,e,Pt,tr)}function Le(pt,Pt,tr){return J(pt,r,Pt,tr)}function Ae(pt,Pt,tr){return J(pt,n,Pt,tr)}function be(pt){return c[pt.getDay()]}function me(pt){return o[pt.getDay()]}function Te(pt){return f[pt.getMonth()]}function Ne(pt){return a[pt.getMonth()]}function Ee(pt){return i[+(pt.getHours()>=12)]}function we(pt){return 1+~~(pt.getMonth()/3)}function He(pt){return c[pt.getUTCDay()]}function tt(pt){return o[pt.getUTCDay()]}function at(pt){return f[pt.getUTCMonth()]}function Et(pt){return a[pt.getUTCMonth()]}function vt(pt){return i[+(pt.getUTCHours()>=12)]}function Gt(pt){return 1+~~(pt.getUTCMonth()/3)}return{format:function(pt){var Pt=W(pt+="",B);return Pt.toString=function(){return pt},Pt},parse:function(pt){var Pt=Y(pt+="",!1);return Pt.toString=function(){return pt},Pt},utcFormat:function(pt){var Pt=W(pt+="",V);return Pt.toString=function(){return pt},Pt},utcParse:function(pt){var Pt=Y(pt+="",!0);return Pt.toString=function(){return pt},Pt}}}var Bae={"-":"",_:" ",0:"0"},Bl=/^\s*\d+/,$_t=/^%/,z_t=/[\\^$*+?|[\]().{}]/g;function vs(t,e,r){var n=t<0?"-":"",i=(n?-t:t)+"",o=i.length;return n+(o[e.toLowerCase(),r]))}function V_t(t,e,r){var n=Bl.exec(e.slice(r,r+1));return n?(t.w=+n[0],r+n[0].length):-1}function q_t(t,e,r){var n=Bl.exec(e.slice(r,r+1));return n?(t.u=+n[0],r+n[0].length):-1}function G_t(t,e,r){var n=Bl.exec(e.slice(r,r+2));return n?(t.U=+n[0],r+n[0].length):-1}function H_t(t,e,r){var n=Bl.exec(e.slice(r,r+2));return n?(t.V=+n[0],r+n[0].length):-1}function W_t(t,e,r){var n=Bl.exec(e.slice(r,r+2));return n?(t.W=+n[0],r+n[0].length):-1}function $ae(t,e,r){var n=Bl.exec(e.slice(r,r+4));return n?(t.y=+n[0],r+n[0].length):-1}function zae(t,e,r){var n=Bl.exec(e.slice(r,r+2));return n?(t.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function K_t(t,e,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(r,r+6));return n?(t.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function Y_t(t,e,r){var n=Bl.exec(e.slice(r,r+1));return n?(t.q=n[0]*3-3,r+n[0].length):-1}function Z_t(t,e,r){var n=Bl.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function Uae(t,e,r){var n=Bl.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function X_t(t,e,r){var n=Bl.exec(e.slice(r,r+3));return n?(t.m=0,t.d=+n[0],r+n[0].length):-1}function Vae(t,e,r){var n=Bl.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function Q_t(t,e,r){var n=Bl.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function J_t(t,e,r){var n=Bl.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function ebt(t,e,r){var n=Bl.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function tbt(t,e,r){var n=Bl.exec(e.slice(r,r+6));return n?(t.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function rbt(t,e,r){var n=$_t.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function nbt(t,e,r){var n=Bl.exec(e.slice(r));return n?(t.Q=+n[0],r+n[0].length):-1}function ibt(t,e,r){var n=Bl.exec(e.slice(r));return n?(t.s=+n[0],r+n[0].length):-1}function qae(t,e){return vs(t.getDate(),e,2)}function sbt(t,e){return vs(t.getHours(),e,2)}function abt(t,e){return vs(t.getHours()%12||12,e,2)}function obt(t,e){return vs(1+oN.count(sg(t),t),e,3)}function vTe(t,e){return vs(t.getMilliseconds(),e,3)}function lbt(t,e){return vTe(t,e)+"000"}function cbt(t,e){return vs(t.getMonth()+1,e,2)}function ubt(t,e){return vs(t.getMinutes(),e,2)}function dbt(t,e){return vs(t.getSeconds(),e,2)}function hbt(t){var e=t.getDay();return e===0?7:e}function fbt(t,e){return vs(MF.count(sg(t)-1,t),e,2)}function _Te(t){var e=t.getDay();return e>=4||e===0?TS(t):TS.ceil(t)}function mbt(t,e){return t=_Te(t),vs(TS.count(sg(t),t)+(sg(t).getDay()===4),e,2)}function pbt(t){return t.getDay()}function gbt(t,e){return vs($M.count(sg(t)-1,t),e,2)}function ybt(t,e){return vs(t.getFullYear()%100,e,2)}function xbt(t,e){return t=_Te(t),vs(t.getFullYear()%100,e,2)}function vbt(t,e){return vs(t.getFullYear()%1e4,e,4)}function _bt(t,e){var r=t.getDay();return t=r>=4||r===0?TS(t):TS.ceil(t),vs(t.getFullYear()%1e4,e,4)}function bbt(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+vs(e/60|0,"0",2)+vs(e%60,"0",2)}function Gae(t,e){return vs(t.getUTCDate(),e,2)}function wbt(t,e){return vs(t.getUTCHours(),e,2)}function Sbt(t,e){return vs(t.getUTCHours()%12||12,e,2)}function Tbt(t,e){return vs(1+DF.count(ag(t),t),e,3)}function bTe(t,e){return vs(t.getUTCMilliseconds(),e,3)}function Ebt(t,e){return bTe(t,e)+"000"}function jbt(t,e){return vs(t.getUTCMonth()+1,e,2)}function Abt(t,e){return vs(t.getUTCMinutes(),e,2)}function kbt(t,e){return vs(t.getUTCSeconds(),e,2)}function Cbt(t){var e=t.getUTCDay();return e===0?7:e}function Nbt(t,e){return vs(OF.count(ag(t)-1,t),e,2)}function wTe(t){var e=t.getUTCDay();return e>=4||e===0?ES(t):ES.ceil(t)}function Ibt(t,e){return t=wTe(t),vs(ES.count(ag(t),t)+(ag(t).getUTCDay()===4),e,2)}function Pbt(t){return t.getUTCDay()}function Rbt(t,e){return vs(zM.count(ag(t)-1,t),e,2)}function Lbt(t,e){return vs(t.getUTCFullYear()%100,e,2)}function Dbt(t,e){return t=wTe(t),vs(t.getUTCFullYear()%100,e,2)}function Mbt(t,e){return vs(t.getUTCFullYear()%1e4,e,4)}function Obt(t,e){var r=t.getUTCDay();return t=r>=4||r===0?ES(t):ES.ceil(t),vs(t.getUTCFullYear()%1e4,e,4)}function Fbt(){return"+0000"}function Hae(){return"%"}function Wae(t){return+t}function Kae(t){return Math.floor(+t/1e3)}var ww,STe,TTe;Bbt({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function Bbt(t){return ww=B_t(t),STe=ww.format,ww.parse,TTe=ww.utcFormat,ww.utcParse,ww}function $bt(t){return new Date(t)}function zbt(t){return t instanceof Date?+t:+new Date(+t)}function HW(t,e,r,n,i,o,c,a,f,p){var y=PW(),v=y.invert,T=y.domain,E=p(".%L"),k=p(":%S"),P=p("%I:%M"),R=p("%I %p"),D=p("%a %d"),M=p("%b %d"),B=p("%B"),V=p("%Y");function G(W){return(f(W)e(i/(t.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(i,o)=>Nvt(t,o/n))},r.copy=function(){return kTe(e).domain(t)},yg.apply(r,arguments)}function BF(){var t=0,e=.5,r=1,n=1,i,o,c,a,f,p=tu,y,v=!1,T;function E(P){return isNaN(P=+P)?T:(P=.5+((P=+y(P))-o)*(n*Pe}var PTe=Kbt,Ybt=$F,Zbt=PTe,Xbt=AT;function Qbt(t){return t&&t.length?Ybt(t,Xbt,Zbt):void 0}var Jbt=Qbt;const zF=ds(Jbt);function ewt(t,e){return tt.e^o.s<0?1:-1;for(n=o.d.length,i=t.d.length,e=0,r=nt.d[e]^o.s<0?1:-1;return n===i?0:n>i^o.s<0?1:-1};kn.decimalPlaces=kn.dp=function(){var t=this,e=t.d.length-1,r=(e-t.e)*Ra;if(e=t.d[e],e)for(;e%10==0;e/=10)r--;return r<0?0:r};kn.dividedBy=kn.div=function(t){return qp(this,new this.constructor(t))};kn.dividedToIntegerBy=kn.idiv=function(t){var e=this,r=e.constructor;return sa(qp(e,new r(t),0,1),r.precision)};kn.equals=kn.eq=function(t){return!this.cmp(t)};kn.exponent=function(){return Yo(this)};kn.greaterThan=kn.gt=function(t){return this.cmp(t)>0};kn.greaterThanOrEqualTo=kn.gte=function(t){return this.cmp(t)>=0};kn.isInteger=kn.isint=function(){return this.e>this.d.length-2};kn.isNegative=kn.isneg=function(){return this.s<0};kn.isPositive=kn.ispos=function(){return this.s>0};kn.isZero=function(){return this.s===0};kn.lessThan=kn.lt=function(t){return this.cmp(t)<0};kn.lessThanOrEqualTo=kn.lte=function(t){return this.cmp(t)<1};kn.logarithm=kn.log=function(t){var e,r=this,n=r.constructor,i=n.precision,o=i+5;if(t===void 0)t=new n(10);else if(t=new n(t),t.s<1||t.eq(ld))throw Error(mh+"NaN");if(r.s<1)throw Error(mh+(r.s?"NaN":"-Infinity"));return r.eq(ld)?new n(0):(Va=!1,e=qp(Pk(r,o),Pk(t,o),o),Va=!0,sa(e,i))};kn.minus=kn.sub=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?OTe(e,t):DTe(e,(t.s=-t.s,t))};kn.modulo=kn.mod=function(t){var e,r=this,n=r.constructor,i=n.precision;if(t=new n(t),!t.s)throw Error(mh+"NaN");return r.s?(Va=!1,e=qp(r,t,0,1).times(t),Va=!0,r.minus(e)):sa(new n(r),i)};kn.naturalExponential=kn.exp=function(){return MTe(this)};kn.naturalLogarithm=kn.ln=function(){return Pk(this)};kn.negated=kn.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t};kn.plus=kn.add=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?DTe(e,t):OTe(e,(t.s=-t.s,t))};kn.precision=kn.sd=function(t){var e,r,n,i=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(Kv+t);if(e=Yo(i)+1,n=i.d.length-1,r=n*Ra+1,n=i.d[n],n){for(;n%10==0;n/=10)r--;for(n=i.d[0];n>=10;n/=10)r++}return t&&e>r?e:r};kn.squareRoot=kn.sqrt=function(){var t,e,r,n,i,o,c,a=this,f=a.constructor;if(a.s<1){if(!a.s)return new f(0);throw Error(mh+"NaN")}for(t=Yo(a),Va=!1,i=Math.sqrt(+a),i==0||i==1/0?(e=um(a.d),(e.length+t)%2==0&&(e+="0"),i=Math.sqrt(e),t=NT((t+1)/2)-(t<0||t%2),i==1/0?e="5e"+t:(e=i.toExponential(),e=e.slice(0,e.indexOf("e")+1)+t),n=new f(e)):n=new f(i.toString()),r=f.precision,i=c=r+3;;)if(o=n,n=o.plus(qp(a,o,c+2)).times(.5),um(o.d).slice(0,c)===(e=um(n.d)).slice(0,c)){if(e=e.slice(c-3,c+1),i==c&&e=="4999"){if(sa(o,r+1,0),o.times(o).eq(a)){n=o;break}}else if(e!="9999")break;c+=4}return Va=!0,sa(n,r)};kn.times=kn.mul=function(t){var e,r,n,i,o,c,a,f,p,y=this,v=y.constructor,T=y.d,E=(t=new v(t)).d;if(!y.s||!t.s)return new v(0);for(t.s*=y.s,r=y.e+t.e,f=T.length,p=E.length,f=0;){for(e=0,i=f+n;i>n;)a=o[i]+E[n]*T[i-n-1]+e,o[i--]=a%Il|0,e=a/Il|0;o[i]=(o[i]+e)%Il|0}for(;!o[--c];)o.pop();return e?++r:o.shift(),t.d=o,t.e=r,Va?sa(t,v.precision):t};kn.toDecimalPlaces=kn.todp=function(t,e){var r=this,n=r.constructor;return r=new n(r),t===void 0?r:(jm(t,0,CT),e===void 0?e=n.rounding:jm(e,0,8),sa(r,t+Yo(r)+1,e))};kn.toExponential=function(t,e){var r,n=this,i=n.constructor;return t===void 0?r=h_(n,!0):(jm(t,0,CT),e===void 0?e=i.rounding:jm(e,0,8),n=sa(new i(n),t+1,e),r=h_(n,!0,t+1)),r};kn.toFixed=function(t,e){var r,n,i=this,o=i.constructor;return t===void 0?h_(i):(jm(t,0,CT),e===void 0?e=o.rounding:jm(e,0,8),n=sa(new o(i),t+Yo(i)+1,e),r=h_(n.abs(),!1,t+Yo(n)+1),i.isneg()&&!i.isZero()?"-"+r:r)};kn.toInteger=kn.toint=function(){var t=this,e=t.constructor;return sa(new e(t),Yo(t)+1,e.rounding)};kn.toNumber=function(){return+this};kn.toPower=kn.pow=function(t){var e,r,n,i,o,c,a=this,f=a.constructor,p=12,y=+(t=new f(t));if(!t.s)return new f(ld);if(a=new f(a),!a.s){if(t.s<1)throw Error(mh+"Infinity");return a}if(a.eq(ld))return a;if(n=f.precision,t.eq(ld))return sa(a,n);if(e=t.e,r=t.d.length-1,c=e>=r,o=a.s,c){if((r=y<0?-y:y)<=LTe){for(i=new f(ld),e=Math.ceil(n/Ra+4),Va=!1;r%2&&(i=i.times(a),Xae(i.d,e)),r=NT(r/2),r!==0;)a=a.times(a),Xae(a.d,e);return Va=!0,t.s<0?new f(ld).div(i):sa(i,n)}}else if(o<0)throw Error(mh+"NaN");return o=o<0&&t.d[Math.max(e,r)]&1?-1:1,a.s=1,Va=!1,i=t.times(Pk(a,n+p)),Va=!0,i=MTe(i),i.s=o,i};kn.toPrecision=function(t,e){var r,n,i=this,o=i.constructor;return t===void 0?(r=Yo(i),n=h_(i,r<=o.toExpNeg||r>=o.toExpPos)):(jm(t,1,CT),e===void 0?e=o.rounding:jm(e,0,8),i=sa(new o(i),t,e),r=Yo(i),n=h_(i,t<=r||r<=o.toExpNeg,t)),n};kn.toSignificantDigits=kn.tosd=function(t,e){var r=this,n=r.constructor;return t===void 0?(t=n.precision,e=n.rounding):(jm(t,1,CT),e===void 0?e=n.rounding:jm(e,0,8)),sa(new n(r),t,e)};kn.toString=kn.valueOf=kn.val=kn.toJSON=kn[Symbol.for("nodejs.util.inspect.custom")]=function(){var t=this,e=Yo(t),r=t.constructor;return h_(t,e<=r.toExpNeg||e>=r.toExpPos)};function DTe(t,e){var r,n,i,o,c,a,f,p,y=t.constructor,v=y.precision;if(!t.s||!e.s)return e.s||(e=new y(t)),Va?sa(e,v):e;if(f=t.d,p=e.d,c=t.e,i=e.e,f=f.slice(),o=c-i,o){for(o<0?(n=f,o=-o,a=p.length):(n=p,i=c,a=f.length),c=Math.ceil(v/Ra),a=c>a?c+1:a+1,o>a&&(o=a,n.length=1),n.reverse();o--;)n.push(0);n.reverse()}for(a=f.length,o=p.length,a-o<0&&(o=a,n=p,p=f,f=n),r=0;o;)r=(f[--o]=f[o]+p[o]+r)/Il|0,f[o]%=Il;for(r&&(f.unshift(r),++i),a=f.length;f[--a]==0;)f.pop();return e.d=f,e.e=i,Va?sa(e,v):e}function jm(t,e,r){if(t!==~~t||tr)throw Error(Kv+t)}function um(t){var e,r,n,i=t.length-1,o="",c=t[0];if(i>0){for(o+=c,e=1;ec?1:-1;else for(a=f=0;ai[a]?1:-1;break}return f}function r(n,i,o){for(var c=0;o--;)n[o]-=c,c=n[o]1;)n.shift()}return function(n,i,o,c){var a,f,p,y,v,T,E,k,P,R,D,M,B,V,G,W,Y,J,Q=n.constructor,ee=n.s==i.s?1:-1,le=n.d,pe=i.d;if(!n.s)return new Q(n);if(!i.s)throw Error(mh+"Division by zero");for(f=n.e-i.e,Y=pe.length,G=le.length,E=new Q(ee),k=E.d=[],p=0;pe[p]==(le[p]||0);)++p;if(pe[p]>(le[p]||0)&&--f,o==null?M=o=Q.precision:c?M=o+(Yo(n)-Yo(i))+1:M=o,M<0)return new Q(0);if(M=M/Ra+2|0,p=0,Y==1)for(y=0,pe=pe[0],M++;(p1&&(pe=t(pe,y),le=t(le,y),Y=pe.length,G=le.length),V=Y,P=le.slice(0,Y),R=P.length;R=Il/2&&++W;do y=0,a=e(pe,P,Y,R),a<0?(D=P[0],Y!=R&&(D=D*Il+(P[1]||0)),y=D/W|0,y>1?(y>=Il&&(y=Il-1),v=t(pe,y),T=v.length,R=P.length,a=e(v,P,T,R),a==1&&(y--,r(v,Y16)throw Error(YW+Yo(t));if(!t.s)return new y(ld);for(e==null?(Va=!1,a=v):a=e,c=new y(.03125);t.abs().gte(.1);)t=t.times(c),p+=5;for(n=Math.log(xv(2,p))/Math.LN10*2+5|0,a+=n,r=i=o=new y(ld),y.precision=a;;){if(i=sa(i.times(t),a),r=r.times(++f),c=o.plus(qp(i,r,a)),um(c.d).slice(0,a)===um(o.d).slice(0,a)){for(;p--;)o=sa(o.times(o),a);return y.precision=v,e==null?(Va=!0,sa(o,v)):o}o=c}}function Yo(t){for(var e=t.e*Ra,r=t.d[0];r>=10;r/=10)e++;return e}function Uz(t,e,r){if(e>t.LN10.sd())throw Va=!0,r&&(t.precision=r),Error(mh+"LN10 precision limit exceeded");return sa(new t(t.LN10),e)}function Ty(t){for(var e="";t--;)e+="0";return e}function Pk(t,e){var r,n,i,o,c,a,f,p,y,v=1,T=10,E=t,k=E.d,P=E.constructor,R=P.precision;if(E.s<1)throw Error(mh+(E.s?"NaN":"-Infinity"));if(E.eq(ld))return new P(0);if(e==null?(Va=!1,p=R):p=e,E.eq(10))return e==null&&(Va=!0),Uz(P,p);if(p+=T,P.precision=p,r=um(k),n=r.charAt(0),o=Yo(E),Math.abs(o)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)E=E.times(t),r=um(E.d),n=r.charAt(0),v++;o=Yo(E),n>1?(E=new P("0."+r),o++):E=new P(n+"."+r.slice(1))}else return f=Uz(P,p+2,R).times(o+""),E=Pk(new P(n+"."+r.slice(1)),p-T).plus(f),P.precision=R,e==null?(Va=!0,sa(E,R)):E;for(a=c=E=qp(E.minus(ld),E.plus(ld),p),y=sa(E.times(E),p),i=3;;){if(c=sa(c.times(y),p),f=a.plus(qp(c,new P(i),p)),um(f.d).slice(0,p)===um(a.d).slice(0,p))return a=a.times(2),o!==0&&(a=a.plus(Uz(P,p+2,R).times(o+""))),a=qp(a,new P(v),p),P.precision=R,e==null?(Va=!0,sa(a,R)):a;a=f,i+=2}}function Zae(t,e){var r,n,i;for((r=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(r<0&&(r=n),r+=+e.slice(n+1),e=e.substring(0,n)):r<0&&(r=e.length),n=0;e.charCodeAt(n)===48;)++n;for(i=e.length;e.charCodeAt(i-1)===48;)--i;if(e=e.slice(n,i),e){if(i-=n,r=r-n-1,t.e=NT(r/Ra),t.d=[],n=(r+1)%Ra,r<0&&(n+=Ra),nUM||t.e<-UM))throw Error(YW+r)}else t.s=0,t.e=0,t.d=[0];return t}function sa(t,e,r){var n,i,o,c,a,f,p,y,v=t.d;for(c=1,o=v[0];o>=10;o/=10)c++;if(n=e-c,n<0)n+=Ra,i=e,p=v[y=0];else{if(y=Math.ceil((n+1)/Ra),o=v.length,y>=o)return t;for(p=o=v[y],c=1;o>=10;o/=10)c++;n%=Ra,i=n-Ra+c}if(r!==void 0&&(o=xv(10,c-i-1),a=p/o%10|0,f=e<0||v[y+1]!==void 0||p%o,f=r<4?(a||f)&&(r==0||r==(t.s<0?3:2)):a>5||a==5&&(r==4||f||r==6&&(n>0?i>0?p/xv(10,c-i):0:v[y-1])%10&1||r==(t.s<0?8:7))),e<1||!v[0])return f?(o=Yo(t),v.length=1,e=e-o-1,v[0]=xv(10,(Ra-e%Ra)%Ra),t.e=NT(-e/Ra)||0):(v.length=1,v[0]=t.e=t.s=0),t;if(n==0?(v.length=y,o=1,y--):(v.length=y+1,o=xv(10,Ra-n),v[y]=i>0?(p/xv(10,c-i)%xv(10,i)|0)*o:0),f)for(;;)if(y==0){(v[0]+=o)==Il&&(v[0]=1,++t.e);break}else{if(v[y]+=o,v[y]!=Il)break;v[y--]=0,o=1}for(n=v.length;v[--n]===0;)v.pop();if(Va&&(t.e>UM||t.e<-UM))throw Error(YW+Yo(t));return t}function OTe(t,e){var r,n,i,o,c,a,f,p,y,v,T=t.constructor,E=T.precision;if(!t.s||!e.s)return e.s?e.s=-e.s:e=new T(t),Va?sa(e,E):e;if(f=t.d,v=e.d,n=e.e,p=t.e,f=f.slice(),c=p-n,c){for(y=c<0,y?(r=f,c=-c,a=v.length):(r=v,n=p,a=f.length),i=Math.max(Math.ceil(E/Ra),a)+2,c>i&&(c=i,r.length=1),r.reverse(),i=c;i--;)r.push(0);r.reverse()}else{for(i=f.length,a=v.length,y=i0;--i)f[a++]=0;for(i=v.length;i>c;){if(f[--i]0?o=o.charAt(0)+"."+o.slice(1)+Ty(n):c>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(i<0?"e":"e+")+i):i<0?(o="0."+Ty(-i-1)+o,r&&(n=r-c)>0&&(o+=Ty(n))):i>=c?(o+=Ty(i+1-c),r&&(n=r-i-1)>0&&(o=o+"."+Ty(n))):((n=i+1)0&&(i+1===c&&(o+="."),o+=Ty(n))),t.s<0?"-"+o:o}function Xae(t,e){if(t.length>e)return t.length=e,!0}function FTe(t){var e,r,n;function i(o){var c=this;if(!(c instanceof i))return new i(o);if(c.constructor=i,o instanceof i){c.s=o.s,c.e=o.e,c.d=(o=o.d)?o.slice():o;return}if(typeof o=="number"){if(o*0!==0)throw Error(Kv+o);if(o>0)c.s=1;else if(o<0)o=-o,c.s=-1;else{c.s=0,c.e=0,c.d=[0];return}if(o===~~o&&o<1e7){c.e=0,c.d=[o];return}return Zae(c,o.toString())}else if(typeof o!="string")throw Error(Kv+o);if(o.charCodeAt(0)===45?(o=o.slice(1),c.s=-1):c.s=1,bwt.test(o))Zae(c,o);else throw Error(Kv+o)}if(i.prototype=kn,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=FTe,i.config=i.set=wwt,t===void 0&&(t={}),t)for(n=["precision","rounding","toExpNeg","toExpPos","LN10"],e=0;e=i[e+1]&&n<=i[e+2])this[r]=n;else throw Error(Kv+r+": "+n);if((n=t[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(Kv+r+": "+n);return this}var ZW=FTe(_wt);ld=new ZW(1);const Zs=ZW;function Swt(t){return Awt(t)||jwt(t)||Ewt(t)||Twt()}function Twt(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Ewt(t,e){if(t){if(typeof t=="string")return lq(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return lq(t,e)}}function jwt(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function Awt(t){if(Array.isArray(t))return lq(t)}function lq(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=e?r.apply(void 0,i):t(e-c,Qae(function(){for(var a=arguments.length,f=new Array(a),p=0;pt.length)&&(e=t.length);for(var r=0,n=new Array(e);r"u"||!(Symbol.iterator in Object(t)))){var r=[],n=!0,i=!1,o=void 0;try{for(var c=t[Symbol.iterator](),a;!(n=(a=c.next()).done)&&(r.push(a.value),!(e&&r.length===e));n=!0);}catch(f){i=!0,o=f}finally{try{!n&&c.return!=null&&c.return()}finally{if(i)throw o}}return r}}function Uwt(t){if(Array.isArray(t))return t}function VTe(t){var e=Rk(t,2),r=e[0],n=e[1],i=r,o=n;return r>n&&(i=n,o=r),[i,o]}function qTe(t,e,r){if(t.lte(0))return new Zs(0);var n=GF.getDigitCount(t.toNumber()),i=new Zs(10).pow(n),o=t.div(i),c=n!==1?.05:.1,a=new Zs(Math.ceil(o.div(c).toNumber())).add(r).mul(c),f=a.mul(i);return e?f:new Zs(Math.ceil(f))}function Vwt(t,e,r){var n=1,i=new Zs(t);if(!i.isint()&&r){var o=Math.abs(t);o<1?(n=new Zs(10).pow(GF.getDigitCount(t)-1),i=new Zs(Math.floor(i.div(n).toNumber())).mul(n)):o>1&&(i=new Zs(Math.floor(t)))}else t===0?i=new Zs(Math.floor((e-1)/2)):r||(i=new Zs(Math.floor(t)));var c=Math.floor((e-1)/2),a=Iwt(Nwt(function(f){return i.add(new Zs(f-c).mul(n)).toNumber()}),cq);return a(0,e)}function GTe(t,e,r,n){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((e-t)/(r-1)))return{step:new Zs(0),tickMin:new Zs(0),tickMax:new Zs(0)};var o=qTe(new Zs(e).sub(t).div(r-1),n,i),c;t<=0&&e>=0?c=new Zs(0):(c=new Zs(t).add(e).div(2),c=c.sub(new Zs(c).mod(o)));var a=Math.ceil(c.sub(t).div(o).toNumber()),f=Math.ceil(new Zs(e).sub(c).div(o).toNumber()),p=a+f+1;return p>r?GTe(t,e,r,n,i+1):(p0?f+(r-p):f,a=e>0?a:a+(r-p)),{step:o,tickMin:c.sub(new Zs(a).mul(o)),tickMax:c.add(new Zs(f).mul(o))})}function qwt(t){var e=Rk(t,2),r=e[0],n=e[1],i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,c=Math.max(i,2),a=VTe([r,n]),f=Rk(a,2),p=f[0],y=f[1];if(p===-1/0||y===1/0){var v=y===1/0?[p].concat(dq(cq(0,i-1).map(function(){return 1/0}))):[].concat(dq(cq(0,i-1).map(function(){return-1/0})),[y]);return r>n?uq(v):v}if(p===y)return Vwt(p,i,o);var T=GTe(p,y,c,o),E=T.step,k=T.tickMin,P=T.tickMax,R=GF.rangeStep(k,P.add(new Zs(.1).mul(E)),E);return r>n?uq(R):R}function Gwt(t,e){var r=Rk(t,2),n=r[0],i=r[1],o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,c=VTe([n,i]),a=Rk(c,2),f=a[0],p=a[1];if(f===-1/0||p===1/0)return[n,i];if(f===p)return[f];var y=Math.max(e,2),v=qTe(new Zs(p).sub(f).div(y-1),o,0),T=[].concat(dq(GF.rangeStep(new Zs(f),new Zs(p).sub(new Zs(.99).mul(v)),v)),[p]);return n>i?uq(T):T}var Hwt=zTe(qwt),Wwt=zTe(Gwt),Kwt="Invariant failed";function f_(t,e){throw new Error(Kwt)}var Ywt=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function jS(t){"@babel/helpers - typeof";return jS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},jS(t)}function VM(){return VM=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function r1t(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function n1t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i1t(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);r1&&arguments[1]!==void 0?arguments[1]:[],i=arguments.length>2?arguments[2]:void 0,o=arguments.length>3?arguments[3]:void 0,c=-1,a=(r=n==null?void 0:n.length)!==null&&r!==void 0?r:0;if(a<=1)return 0;if(o&&o.axisType==="angleAxis"&&Math.abs(Math.abs(o.range[1]-o.range[0])-360)<=1e-6)for(var f=o.range,p=0;p0?i[p-1].coordinate:i[a-1].coordinate,v=i[p].coordinate,T=p>=a-1?i[0].coordinate:i[p+1].coordinate,E=void 0;if(Jc(v-y)!==Jc(T-v)){var k=[];if(Jc(T-v)===Jc(f[1]-f[0])){E=T;var P=v+f[1]-f[0];k[0]=Math.min(P,(P+y)/2),k[1]=Math.max(P,(P+y)/2)}else{E=y;var R=T+f[1]-f[0];k[0]=Math.min(v,(R+v)/2),k[1]=Math.max(v,(R+v)/2)}var D=[Math.min(v,(E+v)/2),Math.max(v,(E+v)/2)];if(e>D[0]&&e<=D[1]||e>=k[0]&&e<=k[1]){c=i[p].index;break}}else{var M=Math.min(y,T),B=Math.max(y,T);if(e>(M+v)/2&&e<=(B+v)/2){c=i[p].index;break}}}else for(var V=0;V0&&V(n[V].coordinate+n[V-1].coordinate)/2&&e<=(n[V].coordinate+n[V+1].coordinate)/2||V===a-1&&e>(n[V].coordinate+n[V-1].coordinate)/2){c=n[V].index;break}return c},XW=function(e){var r,n=e,i=n.type.displayName,o=(r=e.type)!==null&&r!==void 0&&r.defaultProps?xo(xo({},e.type.defaultProps),e.props):e.props,c=o.stroke,a=o.fill,f;switch(i){case"Line":f=c;break;case"Area":case"Radar":f=c&&c!=="none"?c:a;break;default:f=a;break}return f},b1t=function(e){var r=e.barSize,n=e.totalSize,i=e.stackGroups,o=i===void 0?{}:i;if(!o)return{};for(var c={},a=Object.keys(o),f=0,p=a.length;f=0});if(D&&D.length){var M=D[0].type.defaultProps,B=M!==void 0?xo(xo({},M),D[0].props):D[0].props,V=B.barSize,G=B[R];c[G]||(c[G]=[]);var W=zi(V)?r:V;c[G].push({item:D[0],stackList:D.slice(1),barSize:zi(W)?void 0:eu(W,n,0)})}}return c},w1t=function(e){var r=e.barGap,n=e.barCategoryGap,i=e.bandSize,o=e.sizeList,c=o===void 0?[]:o,a=e.maxBarSize,f=c.length;if(f<1)return null;var p=eu(r,i,0,!0),y,v=[];if(c[0].barSize===+c[0].barSize){var T=!1,E=i/f,k=c.reduce(function(V,G){return V+G.barSize||0},0);k+=(f-1)*p,k>=i&&(k-=(f-1)*p,p=0),k>=i&&E>0&&(T=!0,E*=.9,k=f*E);var P=(i-k)/2>>0,R={offset:P-p,size:0};y=c.reduce(function(V,G){var W={item:G.item,position:{offset:R.offset+R.size+p,size:T?E:G.barSize}},Y=[].concat(toe(V),[W]);return R=Y[Y.length-1].position,G.stackList&&G.stackList.length&&G.stackList.forEach(function(J){Y.push({item:J,position:R})}),Y},v)}else{var D=eu(n,i,0,!0);i-2*D-(f-1)*p<=0&&(p=0);var M=(i-2*D-(f-1)*p)/f;M>1&&(M>>=0);var B=a===+a?Math.min(M,a):M;y=c.reduce(function(V,G,W){var Y=[].concat(toe(V),[{item:G.item,position:{offset:D+(M+p)*W+(M-B)/2,size:B}}]);return G.stackList&&G.stackList.length&&G.stackList.forEach(function(J){Y.push({item:J,position:Y[Y.length-1].position})}),Y},v)}return y},S1t=function(e,r,n,i){var o=n.children,c=n.width,a=n.margin,f=c-(a.left||0)-(a.right||0),p=YTe({children:o,legendWidth:f});if(p){var y=i||{},v=y.width,T=y.height,E=p.align,k=p.verticalAlign,P=p.layout;if((P==="vertical"||P==="horizontal"&&k==="middle")&&E!=="center"&&Kr(e[E]))return xo(xo({},e),{},j1({},E,e[E]+(v||0)));if((P==="horizontal"||P==="vertical"&&E==="center")&&k!=="middle"&&Kr(e[k]))return xo(xo({},e),{},j1({},k,e[k]+(T||0)))}return e},T1t=function(e,r,n){return zi(r)?!0:e==="horizontal"?r==="yAxis":e==="vertical"||n==="x"?r==="xAxis":n==="y"?r==="yAxis":!0},ZTe=function(e,r,n,i,o){var c=r.props.children,a=uh(c,HF).filter(function(p){return T1t(i,o,p.props.direction)});if(a&&a.length){var f=a.map(function(p){return p.props.dataKey});return e.reduce(function(p,y){var v=ec(y,n);if(zi(v))return p;var T=Array.isArray(v)?[UF(v),zF(v)]:[v,v],E=f.reduce(function(k,P){var R=ec(y,P,0),D=T[0]-Math.abs(Array.isArray(R)?R[0]:R),M=T[1]+Math.abs(Array.isArray(R)?R[1]:R);return[Math.min(D,k[0]),Math.max(M,k[1])]},[1/0,-1/0]);return[Math.min(E[0],p[0]),Math.max(E[1],p[1])]},[1/0,-1/0])}return null},E1t=function(e,r,n,i,o){var c=r.map(function(a){return ZTe(e,a,n,o,i)}).filter(function(a){return!zi(a)});return c&&c.length?c.reduce(function(a,f){return[Math.min(a[0],f[0]),Math.max(a[1],f[1])]},[1/0,-1/0]):null},XTe=function(e,r,n,i,o){var c=r.map(function(f){var p=f.props.dataKey;return n==="number"&&p&&ZTe(e,f,p,i)||_A(e,p,n,o)});if(n==="number")return c.reduce(function(f,p){return[Math.min(f[0],p[0]),Math.max(f[1],p[1])]},[1/0,-1/0]);var a={};return c.reduce(function(f,p){for(var y=0,v=p.length;y=2?Jc(a[0]-a[1])*2*p:p,r&&(e.ticks||e.niceTicks)){var y=(e.ticks||e.niceTicks).map(function(v){var T=o?o.indexOf(v):v;return{coordinate:i(T)+p,value:v,offset:p}});return y.filter(function(v){return!tN(v.coordinate)})}return e.isCategorical&&e.categoricalDomain?e.categoricalDomain.map(function(v,T){return{coordinate:i(v)+p,value:v,index:T,offset:p}}):i.ticks&&!n?i.ticks(e.tickCount).map(function(v){return{coordinate:i(v)+p,value:v,offset:p}}):i.domain().map(function(v,T){return{coordinate:i(v)+p,value:o?o[v]:v,index:T,offset:p}})},Vz=new WeakMap,DR=function(e,r){if(typeof r!="function")return e;Vz.has(e)||Vz.set(e,new WeakMap);var n=Vz.get(e);if(n.has(r))return n.get(r);var i=function(){e.apply(void 0,arguments),r.apply(void 0,arguments)};return n.set(r,i),i},eEe=function(e,r,n){var i=e.scale,o=e.type,c=e.layout,a=e.axisType;if(i==="auto")return c==="radial"&&a==="radiusAxis"?{scale:Ak(),realScaleType:"band"}:c==="radial"&&a==="angleAxis"?{scale:FM(),realScaleType:"linear"}:o==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?{scale:vA(),realScaleType:"point"}:o==="category"?{scale:Ak(),realScaleType:"band"}:{scale:FM(),realScaleType:"linear"};if(c_(i)){var f="scale".concat(jF(i));return{scale:(Yae[f]||vA)(),realScaleType:Yae[f]?f:"point"}}return _i(i)?{scale:i}:{scale:vA(),realScaleType:"point"}},noe=1e-4,tEe=function(e){var r=e.domain();if(!(!r||r.length<=2)){var n=r.length,i=e.range(),o=Math.min(i[0],i[1])-noe,c=Math.max(i[0],i[1])+noe,a=e(r[0]),f=e(r[n-1]);(ac||fc)&&e.domain([r[0],r[n-1]])}},j1t=function(e,r){if(!e)return null;for(var n=0,i=e.length;ni)&&(o[1]=i),o[0]>i&&(o[0]=i),o[1]=0?(e[a][n][0]=o,e[a][n][1]=o+f,o=e[a][n][1]):(e[a][n][0]=c,e[a][n][1]=c+f,c=e[a][n][1])}},C1t=function(e){var r=e.length;if(!(r<=0))for(var n=0,i=e[0].length;n=0?(e[c][n][0]=o,e[c][n][1]=o+a,o=e[c][n][1]):(e[c][n][0]=0,e[c][n][1]=0)}},N1t={sign:k1t,expand:Yut,none:xS,silhouette:Zut,wiggle:Xut,positive:C1t},I1t=function(e,r,n){var i=r.map(function(a){return a.props.dataKey}),o=N1t[n],c=Kut().keys(i).value(function(a,f){return+ec(a,f,0)}).order(F8).offset(o);return c(e)},P1t=function(e,r,n,i,o,c){if(!e)return null;var a=c?r.reverse():r,f={},p=a.reduce(function(v,T){var E,k=(E=T.type)!==null&&E!==void 0&&E.defaultProps?xo(xo({},T.type.defaultProps),T.props):T.props,P=k.stackId,R=k.hide;if(R)return v;var D=k[n],M=v[D]||{hasStack:!1,stackGroups:{}};if(gl(P)){var B=M.stackGroups[P]||{numericAxisId:n,cateAxisId:i,items:[]};B.items.push(T),M.hasStack=!0,M.stackGroups[P]=B}else M.stackGroups[rN("_stackId_")]={numericAxisId:n,cateAxisId:i,items:[T]};return xo(xo({},v),{},j1({},D,M))},f),y={};return Object.keys(p).reduce(function(v,T){var E=p[T];if(E.hasStack){var k={};E.stackGroups=Object.keys(E.stackGroups).reduce(function(P,R){var D=E.stackGroups[R];return xo(xo({},P),{},j1({},R,{numericAxisId:n,cateAxisId:i,items:D.items,stackedData:I1t(e,D.items,o)}))},k)}return xo(xo({},v),{},j1({},T,E))},y)},rEe=function(e,r){var n=r.realScaleType,i=r.type,o=r.tickCount,c=r.originalDomain,a=r.allowDecimals,f=n||r.scale;if(f!=="auto"&&f!=="linear")return null;if(o&&i==="number"&&c&&(c[0]==="auto"||c[1]==="auto")){var p=e.domain();if(!p.length)return null;var y=Hwt(p,o,a);return e.domain([UF(y),zF(y)]),{niceTicks:y}}if(o&&i==="number"){var v=e.domain(),T=Wwt(v,o,a);return{niceTicks:T}}return null};function F7t(t){var e=t.axis,r=t.ticks,n=t.bandSize,i=t.entry,o=t.index,c=t.dataKey;if(e.type==="category"){if(!e.allowDuplicatedCategory&&e.dataKey&&!zi(i[e.dataKey])){var a=yM(r,"value",i[e.dataKey]);if(a)return a.coordinate+n/2}return r[o]?r[o].coordinate+n/2:null}var f=ec(i,zi(c)?e.dataKey:c);return zi(f)?null:e.scale(f)}var ioe=function(e){var r=e.axis,n=e.ticks,i=e.offset,o=e.bandSize,c=e.entry,a=e.index;if(r.type==="category")return n[a]?n[a].coordinate+i:null;var f=ec(c,r.dataKey,r.domain[a]);return zi(f)?null:r.scale(f)-o/2+i},R1t=function(e){var r=e.numericAxis,n=r.scale.domain();if(r.type==="number"){var i=Math.min(n[0],n[1]),o=Math.max(n[0],n[1]);return i<=0&&o>=0?0:o<0?o:i}return n[0]},L1t=function(e,r){var n,i=(n=e.type)!==null&&n!==void 0&&n.defaultProps?xo(xo({},e.type.defaultProps),e.props):e.props,o=i.stackId;if(gl(o)){var c=r[o];if(c){var a=c.items.indexOf(e);return a>=0?c.stackedData[a]:null}}return null},D1t=function(e){return e.reduce(function(r,n){return[UF(n.concat([r[0]]).filter(Kr)),zF(n.concat([r[1]]).filter(Kr))]},[1/0,-1/0])},nEe=function(e,r,n){return Object.keys(e).reduce(function(i,o){var c=e[o],a=c.stackedData,f=a.reduce(function(p,y){var v=D1t(y.slice(r,n+1));return[Math.min(p[0],v[0]),Math.max(p[1],v[1])]},[1/0,-1/0]);return[Math.min(f[0],i[0]),Math.max(f[1],i[1])]},[1/0,-1/0]).map(function(i){return i===1/0||i===-1/0?0:i})},soe=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,aoe=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,pq=function(e,r,n){if(_i(e))return e(r,n);if(!Array.isArray(e))return r;var i=[];if(Kr(e[0]))i[0]=n?e[0]:Math.min(e[0],r[0]);else if(soe.test(e[0])){var o=+soe.exec(e[0])[1];i[0]=r[0]-o}else _i(e[0])?i[0]=e[0](r[0]):i[0]=r[0];if(Kr(e[1]))i[1]=n?e[1]:Math.max(e[1],r[1]);else if(aoe.test(e[1])){var c=+aoe.exec(e[1])[1];i[1]=r[1]+c}else _i(e[1])?i[1]=e[1](r[1]):i[1]=r[1];return i},GM=function(e,r,n){if(e&&e.scale&&e.scale.bandwidth){var i=e.scale.bandwidth();if(!n||i>0)return i}if(e&&r&&r.length>=2){for(var o=EW(r,function(v){return v.coordinate}),c=1/0,a=1,f=o.length;at.length)&&(e=t.length);for(var r=0,n=new Array(e);r2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(e-(n.left||0)-(n.right||0)),Math.abs(r-(n.top||0)-(n.bottom||0)))/2},q1t=function(e,r,n,i,o){var c=e.width,a=e.height,f=e.startAngle,p=e.endAngle,y=eu(e.cx,c,c/2),v=eu(e.cy,a,a/2),T=aEe(c,a,n),E=eu(e.innerRadius,T,0),k=eu(e.outerRadius,T,T*.8),P=Object.keys(r);return P.reduce(function(R,D){var M=r[D],B=M.domain,V=M.reversed,G;if(zi(M.range))i==="angleAxis"?G=[f,p]:i==="radiusAxis"&&(G=[E,k]),V&&(G=[G[1],G[0]]);else{G=M.range;var W=G,Y=F1t(W,2);f=Y[0],p=Y[1]}var J=eEe(M,o),Q=J.realScaleType,ee=J.scale;ee.domain(B).range(G),tEe(ee);var le=rEe(ee,jp(jp({},M),{},{realScaleType:Q})),pe=jp(jp(jp({},M),le),{},{range:G,radius:k,realScaleType:Q,scale:ee,cx:y,cy:v,innerRadius:E,outerRadius:k,startAngle:f,endAngle:p});return jp(jp({},R),{},sEe({},D,pe))},{})},G1t=function(e,r){var n=e.x,i=e.y,o=r.x,c=r.y;return Math.sqrt(Math.pow(n-o,2)+Math.pow(i-c,2))},H1t=function(e,r){var n=e.x,i=e.y,o=r.cx,c=r.cy,a=G1t({x:n,y:i},{x:o,y:c});if(a<=0)return{radius:a};var f=(n-o)/a,p=Math.acos(f);return i>c&&(p=2*Math.PI-p),{radius:a,angle:V1t(p),angleInRadian:p}},W1t=function(e){var r=e.startAngle,n=e.endAngle,i=Math.floor(r/360),o=Math.floor(n/360),c=Math.min(i,o);return{startAngle:r-c*360,endAngle:n-c*360}},K1t=function(e,r){var n=r.startAngle,i=r.endAngle,o=Math.floor(n/360),c=Math.floor(i/360),a=Math.min(o,c);return e+a*360},uoe=function(e,r){var n=e.x,i=e.y,o=H1t({x:n,y:i},r),c=o.radius,a=o.angle,f=r.innerRadius,p=r.outerRadius;if(cp)return!1;if(c===0)return!0;var y=W1t(r),v=y.startAngle,T=y.endAngle,E=a,k;if(v<=T){for(;E>T;)E-=360;for(;E=v&&E<=T}else{for(;E>v;)E-=360;for(;E=T&&E<=v}return k?jp(jp({},r),{},{radius:c,angle:K1t(E,r)}):null},oEe=function(e){return!C.isValidElement(e)&&!_i(e)&&typeof e!="boolean"?e.className:""};function Ok(t){"@babel/helpers - typeof";return Ok=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ok(t)}var Y1t=["offset"];function Z1t(t){return eSt(t)||J1t(t)||Q1t(t)||X1t()}function X1t(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Q1t(t,e){if(t){if(typeof t=="string")return gq(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return gq(t,e)}}function J1t(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function eSt(t){if(Array.isArray(t))return gq(t)}function gq(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function rSt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function doe(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function sl(t){for(var e=1;e=0?1:-1,B,V;i==="insideStart"?(B=E+M*c,V=P):i==="insideEnd"?(B=k-M*c,V=!P):i==="end"&&(B=k+M*c,V=P),V=D<=0?V:!V;var G=_a(p,y,R,B),W=_a(p,y,R,B+(V?1:-1)*359),Y="M".concat(G.x,",").concat(G.y,` A`).concat(R,",").concat(R,",0,1,").concat(V?0:1,`, `).concat(W.x,",").concat(W.y),J=zi(e.id)?rN("recharts-radial-line-"):e.id;return Xe.createElement("text",Fk({},n,{dominantBaseline:"central",className:$i("recharts-radial-bar-label",a)}),Xe.createElement("defs",null,Xe.createElement("path",{id:J,d:Y})),Xe.createElement("textPath",{xlinkHref:"#".concat(J)},r))},cSt=function(e){var r=e.viewBox,n=e.offset,i=e.position,o=r,c=o.cx,a=o.cy,f=o.innerRadius,p=o.outerRadius,y=o.startAngle,v=o.endAngle,T=(y+v)/2;if(i==="outside"){var E=_a(c,a,p+n,T),k=E.x,P=E.y;return{x:k,y:P,textAnchor:k>=c?"start":"end",verticalAnchor:"middle"}}if(i==="center")return{x:c,y:a,textAnchor:"middle",verticalAnchor:"middle"};if(i==="centerTop")return{x:c,y:a,textAnchor:"middle",verticalAnchor:"start"};if(i==="centerBottom")return{x:c,y:a,textAnchor:"middle",verticalAnchor:"end"};var R=(f+p)/2,D=_a(c,a,R,T),M=D.x,B=D.y;return{x:M,y:B,textAnchor:"middle",verticalAnchor:"middle"}},uSt=function(e){var r=e.viewBox,n=e.parentViewBox,i=e.offset,o=e.position,c=r,a=c.x,f=c.y,p=c.width,y=c.height,v=y>=0?1:-1,T=v*i,E=v>0?"end":"start",k=v>0?"start":"end",P=p>=0?1:-1,R=P*i,D=P>0?"end":"start",M=P>0?"start":"end";if(o==="top"){var B={x:a+p/2,y:f-v*i,textAnchor:"middle",verticalAnchor:E};return sl(sl({},B),n?{height:Math.max(f-n.y,0),width:p}:{})}if(o==="bottom"){var V={x:a+p/2,y:f+y+T,textAnchor:"middle",verticalAnchor:k};return sl(sl({},V),n?{height:Math.max(n.y+n.height-(f+y),0),width:p}:{})}if(o==="left"){var G={x:a-R,y:f+y/2,textAnchor:D,verticalAnchor:"middle"};return sl(sl({},G),n?{width:Math.max(G.x-n.x,0),height:y}:{})}if(o==="right"){var W={x:a+p+R,y:f+y/2,textAnchor:M,verticalAnchor:"middle"};return sl(sl({},W),n?{width:Math.max(n.x+n.width-W.x,0),height:y}:{})}var Y=n?{width:p,height:y}:{};return o==="insideLeft"?sl({x:a+R,y:f+y/2,textAnchor:M,verticalAnchor:"middle"},Y):o==="insideRight"?sl({x:a+p-R,y:f+y/2,textAnchor:D,verticalAnchor:"middle"},Y):o==="insideTop"?sl({x:a+p/2,y:f+T,textAnchor:"middle",verticalAnchor:k},Y):o==="insideBottom"?sl({x:a+p/2,y:f+y-T,textAnchor:"middle",verticalAnchor:E},Y):o==="insideTopLeft"?sl({x:a+R,y:f+T,textAnchor:M,verticalAnchor:k},Y):o==="insideTopRight"?sl({x:a+p-R,y:f+T,textAnchor:D,verticalAnchor:k},Y):o==="insideBottomLeft"?sl({x:a+R,y:f+y-T,textAnchor:M,verticalAnchor:E},Y):o==="insideBottomRight"?sl({x:a+p-R,y:f+y-T,textAnchor:D,verticalAnchor:E},Y):bT(o)&&(Kr(o.x)||kv(o.x))&&(Kr(o.y)||kv(o.y))?sl({x:a+eu(o.x,p),y:f+eu(o.y,y),textAnchor:"end",verticalAnchor:"end"},Y):sl({x:a+p/2,y:f+y/2,textAnchor:"middle",verticalAnchor:"middle"},Y)},dSt=function(e){return"cx"in e&&Kr(e.cx)};function Ll(t){var e=t.offset,r=e===void 0?5:e,n=tSt(t,Y1t),i=sl({offset:r},n),o=i.viewBox,c=i.position,a=i.value,f=i.children,p=i.content,y=i.className,v=y===void 0?"":y,T=i.textBreakAll;if(!o||zi(a)&&zi(f)&&!C.isValidElement(p)&&!_i(p))return null;if(C.isValidElement(p))return C.cloneElement(p,i);var E;if(_i(p)){if(E=C.createElement(p,i),C.isValidElement(E))return E}else E=aSt(i);var k=dSt(o),P=fi(i,!0);if(k&&(c==="insideStart"||c==="insideEnd"||c==="end"))return lSt(i,E,P);var R=k?cSt(i):uSt(i);return Xe.createElement(d_,Fk({className:$i("recharts-label",v)},P,R,{breakAll:T}),E)}Ll.displayName="Label";var lEe=function(e){var r=e.cx,n=e.cy,i=e.angle,o=e.startAngle,c=e.endAngle,a=e.r,f=e.radius,p=e.innerRadius,y=e.outerRadius,v=e.x,T=e.y,E=e.top,k=e.left,P=e.width,R=e.height,D=e.clockWise,M=e.labelViewBox;if(M)return M;if(Kr(P)&&Kr(R)){if(Kr(v)&&Kr(T))return{x:v,y:T,width:P,height:R};if(Kr(E)&&Kr(k))return{x:E,y:k,width:P,height:R}}return Kr(v)&&Kr(T)?{x:v,y:T,width:0,height:0}:Kr(r)&&Kr(n)?{cx:r,cy:n,startAngle:o||i||0,endAngle:c||i||0,innerRadius:p||0,outerRadius:y||f||a||0,clockWise:D}:e.viewBox?e.viewBox:{}},hSt=function(e,r){return e?e===!0?Xe.createElement(Ll,{key:"label-implicit",viewBox:r}):gl(e)?Xe.createElement(Ll,{key:"label-implicit",viewBox:r,value:e}):C.isValidElement(e)?e.type===Ll?C.cloneElement(e,{key:"label-implicit",viewBox:r}):Xe.createElement(Ll,{key:"label-implicit",content:e,viewBox:r}):_i(e)?Xe.createElement(Ll,{key:"label-implicit",content:e,viewBox:r}):bT(e)?Xe.createElement(Ll,Fk({viewBox:r},e,{key:"label-implicit"})):null:null},fSt=function(e,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!e||!e.children&&n&&!e.label)return null;var i=e.children,o=lEe(e),c=uh(i,Ll).map(function(f,p){return C.cloneElement(f,{viewBox:r||o,key:"label-".concat(p)})});if(!n)return c;var a=hSt(e.label,r||o);return[a].concat(Z1t(c))};Ll.parseViewBox=lEe;Ll.renderCallByParent=fSt;function mSt(t){var e=t==null?0:t.length;return e?t[e-1]:void 0}var pSt=mSt;const gSt=ds(pSt);function Bk(t){"@babel/helpers - typeof";return Bk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Bk(t)}var ySt=["valueAccessor"],xSt=["data","dataKey","clockWise","id","textBreakAll"];function vSt(t){return SSt(t)||wSt(t)||bSt(t)||_St()}function _St(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function bSt(t,e){if(t){if(typeof t=="string")return yq(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return yq(t,e)}}function wSt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function SSt(t){if(Array.isArray(t))return yq(t)}function yq(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function ASt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var kSt=function(e){return Array.isArray(e.value)?gSt(e.value):e.value};function ax(t){var e=t.valueAccessor,r=e===void 0?kSt:e,n=moe(t,ySt),i=n.data,o=n.dataKey,c=n.clockWise,a=n.id,f=n.textBreakAll,p=moe(n,xSt);return!i||!i.length?null:Xe.createElement(Vs,{className:"recharts-label-list"},i.map(function(y,v){var T=zi(o)?r(y,v):ec(y&&y.payload,o),E=zi(a)?{}:{id:"".concat(a,"-").concat(v)};return Xe.createElement(Ll,WM({},fi(y,!0),p,E,{parentViewBox:y.parentViewBox,value:T,textBreakAll:f,viewBox:Ll.parseViewBox(zi(c)?y:foe(foe({},y),{},{clockWise:c})),key:"label-".concat(v),index:v}))}))}ax.displayName="LabelList";function CSt(t,e){return t?t===!0?Xe.createElement(ax,{key:"labelList-implicit",data:e}):Xe.isValidElement(t)||_i(t)?Xe.createElement(ax,{key:"labelList-implicit",data:e,content:t}):bT(t)?Xe.createElement(ax,WM({data:e},t,{key:"labelList-implicit"})):null:null}function NSt(t,e){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!t||!t.children&&r&&!t.label)return null;var n=t.children,i=uh(n,ax).map(function(c,a){return C.cloneElement(c,{data:e,key:"labelList-".concat(a)})});if(!r)return i;var o=CSt(t.label,e);return[o].concat(vSt(i))}ax.renderCallByParent=NSt;function $k(t){"@babel/helpers - typeof";return $k=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},$k(t)}function xq(){return xq=Object.assign?Object.assign.bind():function(t){for(var e=1;e180),",").concat(+(c>p),`, `).concat(v.x,",").concat(v.y,` `);if(i>0){var E=_a(r,n,i,c),k=_a(r,n,i,p);T+="L ".concat(k.x,",").concat(k.y,` A `).concat(i,",").concat(i,`,0, `).concat(+(Math.abs(f)>180),",").concat(+(c<=p),`, `).concat(E.x,",").concat(E.y," Z")}else T+="L ".concat(r,",").concat(n," Z");return T},DSt=function(e){var r=e.cx,n=e.cy,i=e.innerRadius,o=e.outerRadius,c=e.cornerRadius,a=e.forceCornerRadius,f=e.cornerIsExternal,p=e.startAngle,y=e.endAngle,v=Jc(y-p),T=MR({cx:r,cy:n,radius:o,angle:p,sign:v,cornerRadius:c,cornerIsExternal:f}),E=T.circleTangency,k=T.lineTangency,P=T.theta,R=MR({cx:r,cy:n,radius:o,angle:y,sign:-v,cornerRadius:c,cornerIsExternal:f}),D=R.circleTangency,M=R.lineTangency,B=R.theta,V=f?Math.abs(p-y):Math.abs(p-y)-P-B;if(V<0)return a?"M ".concat(k.x,",").concat(k.y,` a`).concat(c,",").concat(c,",0,0,1,").concat(c*2,`,0 a`).concat(c,",").concat(c,",0,0,1,").concat(-c*2,`,0 `):cEe({cx:r,cy:n,innerRadius:i,outerRadius:o,startAngle:p,endAngle:y});var G="M ".concat(k.x,",").concat(k.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(v<0),",").concat(E.x,",").concat(E.y,` A`).concat(o,",").concat(o,",0,").concat(+(V>180),",").concat(+(v<0),",").concat(D.x,",").concat(D.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(v<0),",").concat(M.x,",").concat(M.y,` `);if(i>0){var W=MR({cx:r,cy:n,radius:i,angle:p,sign:v,isExternal:!0,cornerRadius:c,cornerIsExternal:f}),Y=W.circleTangency,J=W.lineTangency,Q=W.theta,ee=MR({cx:r,cy:n,radius:i,angle:y,sign:-v,isExternal:!0,cornerRadius:c,cornerIsExternal:f}),le=ee.circleTangency,pe=ee.lineTangency,Se=ee.theta,je=f?Math.abs(p-y):Math.abs(p-y)-Q-Se;if(je<0&&c===0)return"".concat(G,"L").concat(r,",").concat(n,"Z");G+="L".concat(pe.x,",").concat(pe.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(v<0),",").concat(le.x,",").concat(le.y,` A`).concat(i,",").concat(i,",0,").concat(+(je>180),",").concat(+(v>0),",").concat(Y.x,",").concat(Y.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(v<0),",").concat(J.x,",").concat(J.y,"Z")}else G+="L".concat(r,",").concat(n,"Z");return G},MSt={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},uEe=function(e){var r=goe(goe({},MSt),e),n=r.cx,i=r.cy,o=r.innerRadius,c=r.outerRadius,a=r.cornerRadius,f=r.forceCornerRadius,p=r.cornerIsExternal,y=r.startAngle,v=r.endAngle,T=r.className;if(c0&&Math.abs(y-v)<360?R=DSt({cx:n,cy:i,innerRadius:o,outerRadius:c,cornerRadius:Math.min(P,k/2),forceCornerRadius:f,cornerIsExternal:p,startAngle:y,endAngle:v}):R=cEe({cx:n,cy:i,innerRadius:o,outerRadius:c,startAngle:y,endAngle:v}),Xe.createElement("path",xq({},fi(r,!0),{className:E,d:R,role:"img"}))};function zk(t){"@babel/helpers - typeof";return zk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},zk(t)}function vq(){return vq=Object.assign?Object.assign.bind():function(t){for(var e=1;e0;)if(!r.equals(t[n],e[n],n,n,t,e,r))return!1;return!0}function XSt(t,e){return IT(t.getTime(),e.getTime())}function Toe(t,e,r){if(t.size!==e.size)return!1;for(var n={},i=t.entries(),o=0,c,a;(c=i.next())&&!c.done;){for(var f=e.entries(),p=!1,y=0;(a=f.next())&&!a.done;){var v=c.value,T=v[0],E=v[1],k=a.value,P=k[0],R=k[1];!p&&!n[y]&&(p=r.equals(T,P,o,y,t,e,r)&&r.equals(E,R,T,P,t,e,r))&&(n[y]=!0),y++}if(!p)return!1;o++}return!0}function QSt(t,e,r){var n=Soe(t),i=n.length;if(Soe(e).length!==i)return!1;for(var o;i-- >0;)if(o=n[i],o===pEe&&(t.$$typeof||e.$$typeof)&&t.$$typeof!==e.$$typeof||!mEe(e,o)||!r.equals(t[o],e[o],o,o,t,e,r))return!1;return!0}function w2(t,e,r){var n=boe(t),i=n.length;if(boe(e).length!==i)return!1;for(var o,c,a;i-- >0;)if(o=n[i],o===pEe&&(t.$$typeof||e.$$typeof)&&t.$$typeof!==e.$$typeof||!mEe(e,o)||!r.equals(t[o],e[o],o,o,t,e,r)||(c=woe(t,o),a=woe(e,o),(c||a)&&(!c||!a||c.configurable!==a.configurable||c.enumerable!==a.enumerable||c.writable!==a.writable)))return!1;return!0}function JSt(t,e){return IT(t.valueOf(),e.valueOf())}function eTt(t,e){return t.source===e.source&&t.flags===e.flags}function Eoe(t,e,r){if(t.size!==e.size)return!1;for(var n={},i=t.values(),o,c;(o=i.next())&&!o.done;){for(var a=e.values(),f=!1,p=0;(c=a.next())&&!c.done;)!f&&!n[p]&&(f=r.equals(o.value,c.value,o.value,c.value,t,e,r))&&(n[p]=!0),p++;if(!f)return!1}return!0}function tTt(t,e){var r=t.length;if(e.length!==r)return!1;for(;r-- >0;)if(t[r]!==e[r])return!1;return!0}var rTt="[object Arguments]",nTt="[object Boolean]",iTt="[object Date]",sTt="[object Map]",aTt="[object Number]",oTt="[object Object]",lTt="[object RegExp]",cTt="[object Set]",uTt="[object String]",dTt=Array.isArray,joe=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,Aoe=Object.assign,hTt=Object.prototype.toString.call.bind(Object.prototype.toString);function fTt(t){var e=t.areArraysEqual,r=t.areDatesEqual,n=t.areMapsEqual,i=t.areObjectsEqual,o=t.arePrimitiveWrappersEqual,c=t.areRegExpsEqual,a=t.areSetsEqual,f=t.areTypedArraysEqual;return function(y,v,T){if(y===v)return!0;if(y==null||v==null||typeof y!="object"||typeof v!="object")return y!==y&&v!==v;var E=y.constructor;if(E!==v.constructor)return!1;if(E===Object)return i(y,v,T);if(dTt(y))return e(y,v,T);if(joe!=null&&joe(y))return f(y,v,T);if(E===Date)return r(y,v,T);if(E===RegExp)return c(y,v,T);if(E===Map)return n(y,v,T);if(E===Set)return a(y,v,T);var k=hTt(y);return k===iTt?r(y,v,T):k===lTt?c(y,v,T):k===sTt?n(y,v,T):k===cTt?a(y,v,T):k===oTt?typeof y.then!="function"&&typeof v.then!="function"&&i(y,v,T):k===rTt?i(y,v,T):k===nTt||k===aTt||k===uTt?o(y,v,T):!1}}function mTt(t){var e=t.circular,r=t.createCustomConfig,n=t.strict,i={areArraysEqual:n?w2:ZSt,areDatesEqual:XSt,areMapsEqual:n?_oe(Toe,w2):Toe,areObjectsEqual:n?w2:QSt,arePrimitiveWrappersEqual:JSt,areRegExpsEqual:eTt,areSetsEqual:n?_oe(Eoe,w2):Eoe,areTypedArraysEqual:n?w2:tTt};if(r&&(i=Aoe({},i,r(i))),e){var o=FR(i.areArraysEqual),c=FR(i.areMapsEqual),a=FR(i.areObjectsEqual),f=FR(i.areSetsEqual);i=Aoe({},i,{areArraysEqual:o,areMapsEqual:c,areObjectsEqual:a,areSetsEqual:f})}return i}function pTt(t){return function(e,r,n,i,o,c,a){return t(e,r,a)}}function gTt(t){var e=t.circular,r=t.comparator,n=t.createState,i=t.equals,o=t.strict;if(n)return function(f,p){var y=n(),v=y.cache,T=v===void 0?e?new WeakMap:void 0:v,E=y.meta;return r(f,p,{cache:T,equals:i,meta:E,strict:o})};if(e)return function(f,p){return r(f,p,{cache:new WeakMap,equals:i,meta:void 0,strict:o})};var c={cache:void 0,equals:i,meta:void 0,strict:o};return function(f,p){return r(f,p,c)}}var yTt=Gx();Gx({strict:!0});Gx({circular:!0});Gx({circular:!0,strict:!0});Gx({createInternalComparator:function(){return IT}});Gx({strict:!0,createInternalComparator:function(){return IT}});Gx({circular:!0,createInternalComparator:function(){return IT}});Gx({circular:!0,createInternalComparator:function(){return IT},strict:!0});function Gx(t){t===void 0&&(t={});var e=t.circular,r=e===void 0?!1:e,n=t.createInternalComparator,i=t.createState,o=t.strict,c=o===void 0?!1:o,a=mTt(t),f=fTt(a),p=n?n(f):pTt(f);return gTt({circular:r,comparator:f,createState:i,equals:p,strict:c})}function xTt(t){typeof requestAnimationFrame<"u"&&requestAnimationFrame(t)}function koe(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=-1,n=function i(o){r<0&&(r=o),o-r>e?(t(o),r=-1):xTt(i)};requestAnimationFrame(n)}function bq(t){"@babel/helpers - typeof";return bq=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},bq(t)}function vTt(t){return STt(t)||wTt(t)||bTt(t)||_Tt()}function _Tt(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function bTt(t,e){if(t){if(typeof t=="string")return Coe(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Coe(t,e)}}function Coe(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);rt.length)&&(e=t.length);for(var r=0,n=new Array(e);r1?1:D<0?0:D},P=function(D){for(var M=D>1?1:D,B=M,V=0;V<8;++V){var G=v(B)-M,W=E(B);if(Math.abs(G-M)0&&arguments[0]!==void 0?arguments[0]:{},r=e.stiff,n=r===void 0?100:r,i=e.damping,o=i===void 0?8:i,c=e.dt,a=c===void 0?17:c,f=function(y,v,T){var E=-(y-v)*n,k=T*o,P=T+(E-k)*a/1e3,R=T*a/1e3+y;return Math.abs(R-v)t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function eEt(t,e){if(t==null)return{};var r={},n=Object.keys(t),i,o;for(o=0;o=0)&&(r[i]=t[i]);return r}function qz(t){return iEt(t)||nEt(t)||rEt(t)||tEt()}function tEt(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function rEt(t,e){if(t){if(typeof t=="string")return jq(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return jq(t,e)}}function nEt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function iEt(t){if(Array.isArray(t))return jq(t)}function jq(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function ZM(t){return ZM=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},ZM(t)}var og=function(t){cEt(r,t);var e=uEt(r);function r(n,i){var o;sEt(this,r),o=e.call(this,n,i);var c=o.props,a=c.isActive,f=c.attributeName,p=c.from,y=c.to,v=c.steps,T=c.children,E=c.duration;if(o.handleStyleChange=o.handleStyleChange.bind(Cq(o)),o.changeStyle=o.changeStyle.bind(Cq(o)),!a||E<=0)return o.state={style:{}},typeof T=="function"&&(o.state={style:y}),kq(o);if(v&&v.length)o.state={style:v[0].style};else if(p){if(typeof T=="function")return o.state={style:p},kq(o);o.state={style:f?H2({},f,p):p}}else o.state={style:{}};return o}return oEt(r,[{key:"componentDidMount",value:function(){var i=this.props,o=i.isActive,c=i.canBegin;this.mounted=!0,!(!o||!c)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(i){var o=this.props,c=o.isActive,a=o.canBegin,f=o.attributeName,p=o.shouldReAnimate,y=o.to,v=o.from,T=this.state.style;if(a){if(!c){var E={style:f?H2({},f,y):y};this.state&&T&&(f&&T[f]!==y||!f&&T!==y)&&this.setState(E);return}if(!(yTt(i.to,y)&&i.canBegin&&i.isActive)){var k=!i.canBegin||!i.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var P=k||p?v:i.to;if(this.state&&T){var R={style:f?H2({},f,P):P};(f&&T[f]!==P||!f&&T!==P)&&this.setState(R)}this.runAnimation(zh(zh({},this.props),{},{from:P,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var i=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),i&&i()}},{key:"handleStyleChange",value:function(i){this.changeStyle(i)}},{key:"changeStyle",value:function(i){this.mounted&&this.setState({style:i})}},{key:"runJSAnimation",value:function(i){var o=this,c=i.from,a=i.to,f=i.duration,p=i.easing,y=i.begin,v=i.onAnimationEnd,T=i.onAnimationStart,E=XTt(c,a,$Tt(p),f,this.changeStyle),k=function(){o.stopJSAnimation=E()};this.manager.start([T,y,k,f,v])}},{key:"runStepAnimation",value:function(i){var o=this,c=i.steps,a=i.begin,f=i.onAnimationStart,p=c[0],y=p.style,v=p.duration,T=v===void 0?0:v,E=function(P,R,D){if(D===0)return P;var M=R.duration,B=R.easing,V=B===void 0?"ease":B,G=R.style,W=R.properties,Y=R.onAnimationEnd,J=D>0?c[D-1]:R,Q=W||Object.keys(G);if(typeof V=="function"||V==="spring")return[].concat(qz(P),[o.runJSAnimation.bind(o,{from:J.style,to:G,duration:M,easing:V}),M]);var ee=Poe(Q,M,V),le=zh(zh(zh({},J.style),G),{},{transition:ee});return[].concat(qz(P),[le,M,Y]).filter(kTt)};return this.manager.start([f].concat(qz(c.reduce(E,[y,Math.max(T,a)])),[i.onAnimationEnd]))}},{key:"runAnimation",value:function(i){this.manager||(this.manager=TTt());var o=i.begin,c=i.duration,a=i.attributeName,f=i.to,p=i.easing,y=i.onAnimationStart,v=i.onAnimationEnd,T=i.steps,E=i.children,k=this.manager;if(this.unSubscribe=k.subscribe(this.handleStyleChange),typeof p=="function"||typeof E=="function"||p==="spring"){this.runJSAnimation(i);return}if(T.length>1){this.runStepAnimation(i);return}var P=a?H2({},a,f):f,R=Poe(Object.keys(P),c,p);k.start([y,o,zh(zh({},P),{},{transition:R}),c,v])}},{key:"render",value:function(){var i=this.props,o=i.children;i.begin;var c=i.duration;i.attributeName,i.easing;var a=i.isActive;i.steps,i.from,i.to,i.canBegin,i.onAnimationEnd,i.shouldReAnimate,i.onAnimationReStart;var f=JTt(i,QTt),p=C.Children.count(o),y=this.state.style;if(typeof o=="function")return o(y);if(!a||p===0||c<=0)return o;var v=function(E){var k=E.props,P=k.style,R=P===void 0?{}:P,D=k.className,M=C.cloneElement(E,zh(zh({},f),{},{style:zh(zh({},R),y),className:D}));return M};return p===1?v(C.Children.only(o)):Xe.createElement("div",null,C.Children.map(o,function(T){return v(T)}))}}]),r}(C.PureComponent);og.displayName="Animate";og.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};og.propTypes={from:Rs.oneOfType([Rs.object,Rs.string]),to:Rs.oneOfType([Rs.object,Rs.string]),attributeName:Rs.string,duration:Rs.number,begin:Rs.number,easing:Rs.oneOfType([Rs.string,Rs.func]),steps:Rs.arrayOf(Rs.shape({duration:Rs.number.isRequired,style:Rs.object.isRequired,easing:Rs.oneOfType([Rs.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),Rs.func]),properties:Rs.arrayOf("string"),onAnimationEnd:Rs.func})),children:Rs.oneOfType([Rs.node,Rs.func]),isActive:Rs.bool,canBegin:Rs.bool,onAnimationEnd:Rs.func,shouldReAnimate:Rs.bool,onAnimationStart:Rs.func,onAnimationReStart:Rs.func};function qk(t){"@babel/helpers - typeof";return qk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},qk(t)}function XM(){return XM=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0?1:-1,f=n>=0?1:-1,p=i>=0&&n>=0||i<0&&n<0?1:0,y;if(c>0&&o instanceof Array){for(var v=[0,0,0,0],T=0,E=4;Tc?c:o[T];y="M".concat(e,",").concat(r+a*v[0]),v[0]>0&&(y+="A ".concat(v[0],",").concat(v[0],",0,0,").concat(p,",").concat(e+f*v[0],",").concat(r)),y+="L ".concat(e+n-f*v[1],",").concat(r),v[1]>0&&(y+="A ".concat(v[1],",").concat(v[1],",0,0,").concat(p,`, `).concat(e+n,",").concat(r+a*v[1])),y+="L ".concat(e+n,",").concat(r+i-a*v[2]),v[2]>0&&(y+="A ".concat(v[2],",").concat(v[2],",0,0,").concat(p,`, `).concat(e+n-f*v[2],",").concat(r+i)),y+="L ".concat(e+f*v[3],",").concat(r+i),v[3]>0&&(y+="A ".concat(v[3],",").concat(v[3],",0,0,").concat(p,`, `).concat(e,",").concat(r+i-a*v[3])),y+="Z"}else if(c>0&&o===+o&&o>0){var k=Math.min(c,o);y="M ".concat(e,",").concat(r+a*k,` A `).concat(k,",").concat(k,",0,0,").concat(p,",").concat(e+f*k,",").concat(r,` L `).concat(e+n-f*k,",").concat(r,` A `).concat(k,",").concat(k,",0,0,").concat(p,",").concat(e+n,",").concat(r+a*k,` L `).concat(e+n,",").concat(r+i-a*k,` A `).concat(k,",").concat(k,",0,0,").concat(p,",").concat(e+n-f*k,",").concat(r+i,` L `).concat(e+f*k,",").concat(r+i,` A `).concat(k,",").concat(k,",0,0,").concat(p,",").concat(e,",").concat(r+i-a*k," Z")}else y="M ".concat(e,",").concat(r," h ").concat(n," v ").concat(i," h ").concat(-n," Z");return y},_Et=function(e,r){if(!e||!r)return!1;var n=e.x,i=e.y,o=r.x,c=r.y,a=r.width,f=r.height;if(Math.abs(a)>0&&Math.abs(f)>0){var p=Math.min(o,o+a),y=Math.max(o,o+a),v=Math.min(c,c+f),T=Math.max(c,c+f);return n>=p&&n<=y&&i>=v&&i<=T}return!1},bEt={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},QW=function(e){var r=$oe($oe({},bEt),e),n=C.useRef(),i=C.useState(-1),o=hEt(i,2),c=o[0],a=o[1];C.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var V=n.current.getTotalLength();V&&a(V)}catch{}},[]);var f=r.x,p=r.y,y=r.width,v=r.height,T=r.radius,E=r.className,k=r.animationEasing,P=r.animationDuration,R=r.animationBegin,D=r.isAnimationActive,M=r.isUpdateAnimationActive;if(f!==+f||p!==+p||y!==+y||v!==+v||y===0||v===0)return null;var B=$i("recharts-rectangle",E);return M?Xe.createElement(og,{canBegin:c>0,from:{width:y,height:v,x:f,y:p},to:{width:y,height:v,x:f,y:p},duration:P,animationEasing:k,isActive:M},function(V){var G=V.width,W=V.height,Y=V.x,J=V.y;return Xe.createElement(og,{canBegin:c>0,from:"0px ".concat(c===-1?1:c,"px"),to:"".concat(c,"px 0px"),attributeName:"strokeDasharray",begin:R,duration:P,isActive:D,easing:k},Xe.createElement("path",XM({},fi(r,!0),{className:B,d:zoe(Y,J,G,W,T),ref:n})))}):Xe.createElement("path",XM({},fi(r,!0),{className:B,d:zoe(f,p,y,v,T)}))},wEt=["points","className","baseLinePoints","connectNulls"];function r1(){return r1=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function TEt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function Uoe(t){return kEt(t)||AEt(t)||jEt(t)||EEt()}function EEt(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function jEt(t,e){if(t){if(typeof t=="string")return Nq(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Nq(t,e)}}function AEt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function kEt(t){if(Array.isArray(t))return Nq(t)}function Nq(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0&&arguments[0]!==void 0?arguments[0]:[],r=[[]];return e.forEach(function(n){Voe(n)?r[r.length-1].push(n):r[r.length-1].length>0&&r.push([])}),Voe(e[0])&&r[r.length-1].push(e[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},wA=function(e,r){var n=CEt(e);r&&(n=[n.reduce(function(o,c){return[].concat(Uoe(o),Uoe(c))},[])]);var i=n.map(function(o){return o.reduce(function(c,a,f){return"".concat(c).concat(f===0?"M":"L").concat(a.x,",").concat(a.y)},"")}).join("");return n.length===1?"".concat(i,"Z"):i},NEt=function(e,r,n){var i=wA(e,n);return"".concat(i.slice(-1)==="Z"?i.slice(0,-1):i,"L").concat(wA(r.reverse(),n).slice(1))},IEt=function(e){var r=e.points,n=e.className,i=e.baseLinePoints,o=e.connectNulls,c=SEt(e,wEt);if(!r||!r.length)return null;var a=$i("recharts-polygon",n);if(i&&i.length){var f=c.stroke&&c.stroke!=="none",p=NEt(r,i,o);return Xe.createElement("g",{className:a},Xe.createElement("path",r1({},fi(c,!0),{fill:p.slice(-1)==="Z"?c.fill:"none",stroke:"none",d:p})),f?Xe.createElement("path",r1({},fi(c,!0),{fill:"none",d:wA(r,o)})):null,f?Xe.createElement("path",r1({},fi(c,!0),{fill:"none",d:wA(i,o)})):null)}var y=wA(r,o);return Xe.createElement("path",r1({},fi(c,!0),{fill:y.slice(-1)==="Z"?c.fill:"none",className:a,d:y}))};function Iq(){return Iq=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function FEt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var BEt=function(e,r,n,i,o,c){return"M".concat(e,",").concat(o,"v").concat(i,"M").concat(c,",").concat(r,"h").concat(n)},$Et=function(e){var r=e.x,n=r===void 0?0:r,i=e.y,o=i===void 0?0:i,c=e.top,a=c===void 0?0:c,f=e.left,p=f===void 0?0:f,y=e.width,v=y===void 0?0:y,T=e.height,E=T===void 0?0:T,k=e.className,P=OEt(e,PEt),R=REt({x:n,y:o,top:a,left:p,width:v,height:E},P);return!Kr(n)||!Kr(o)||!Kr(v)||!Kr(E)||!Kr(a)||!Kr(p)?null:Xe.createElement("path",Pq({},fi(R,!0),{className:$i("recharts-cross",k),d:BEt(n,o,v,E,a,p)}))},zEt=$F,UEt=PTe,VEt=Mm;function qEt(t,e){return t&&t.length?zEt(t,VEt(e),UEt):void 0}var GEt=qEt;const HEt=ds(GEt);var WEt=$F,KEt=Mm,YEt=RTe;function ZEt(t,e){return t&&t.length?WEt(t,KEt(e),YEt):void 0}var XEt=ZEt;const QEt=ds(XEt);var JEt=["cx","cy","angle","ticks","axisLine"],ejt=["ticks","tick","angle","tickFormatter","stroke"];function kS(t){"@babel/helpers - typeof";return kS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},kS(t)}function SA(){return SA=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function tjt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function rjt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Woe(t,e){for(var r=0;rZoe?c=i==="outer"?"start":"end":o<-Zoe?c=i==="outer"?"end":"start":c="middle",c}},{key:"renderAxisLine",value:function(){var n=this.props,i=n.cx,o=n.cy,c=n.radius,a=n.axisLine,f=n.axisLineType,p=ov(ov({},fi(this.props,!1)),{},{fill:"none"},fi(a,!1));if(f==="circle")return Xe.createElement(JW,bv({className:"recharts-polar-angle-axis-line"},p,{cx:i,cy:o,r:c}));var y=this.props.ticks,v=y.map(function(T){return _a(i,o,c,T.coordinate)});return Xe.createElement(IEt,bv({className:"recharts-polar-angle-axis-line"},p,{points:v}))}},{key:"renderTicks",value:function(){var n=this,i=this.props,o=i.ticks,c=i.tick,a=i.tickLine,f=i.tickFormatter,p=i.stroke,y=fi(this.props,!1),v=fi(c,!1),T=ov(ov({},y),{},{fill:"none"},fi(a,!1)),E=o.map(function(k,P){var R=n.getTickLineCoord(k),D=n.getTickTextAnchor(k),M=ov(ov(ov({textAnchor:D},y),{},{stroke:"none",fill:p},v),{},{index:P,payload:k,x:R.x2,y:R.y2});return Xe.createElement(Vs,bv({className:$i("recharts-polar-angle-axis-tick",oEe(c)),key:"tick-".concat(k.coordinate)},u_(n.props,k,P)),a&&Xe.createElement("line",bv({className:"recharts-polar-angle-axis-tick-line"},T,R)),c&&e.renderTickItem(c,M,f?f(k.value,P):k.value))});return Xe.createElement(Vs,{className:"recharts-polar-angle-axis-ticks"},E)}},{key:"render",value:function(){var n=this.props,i=n.ticks,o=n.radius,c=n.axisLine;return o<=0||!i||!i.length?null:Xe.createElement(Vs,{className:$i("recharts-polar-angle-axis",this.props.className)},c&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(n,i,o){var c;return Xe.isValidElement(n)?c=Xe.cloneElement(n,i):_i(n)?c=n(i):c=Xe.createElement(d_,bv({},i,{className:"recharts-polar-angle-axis-tick-value"}),o),c}}])}(C.PureComponent);YF(ZF,"displayName","PolarAngleAxis");YF(ZF,"axisType","angleAxis");YF(ZF,"defaultProps",{type:"category",angleAxisId:0,scale:"auto",cx:0,cy:0,orientation:"outer",axisLine:!0,tickLine:!0,tickSize:8,tick:!0,hide:!1,allowDuplicatedCategory:!0});var yjt=kSe,xjt=yjt(Object.getPrototypeOf,Object),vjt=xjt,_jt=pg,bjt=vjt,wjt=gg,Sjt="[object Object]",Tjt=Function.prototype,Ejt=Object.prototype,jEe=Tjt.toString,jjt=Ejt.hasOwnProperty,Ajt=jEe.call(Object);function kjt(t){if(!wjt(t)||_jt(t)!=Sjt)return!1;var e=bjt(t);if(e===null)return!0;var r=jjt.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&jEe.call(r)==Ajt}var Cjt=kjt;const Njt=ds(Cjt);var Ijt=pg,Pjt=gg,Rjt="[object Boolean]";function Ljt(t){return t===!0||t===!1||Pjt(t)&&Ijt(t)==Rjt}var Djt=Ljt;const Mjt=ds(Djt);function Hk(t){"@babel/helpers - typeof";return Hk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Hk(t)}function eO(){return eO=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r0,from:{upperWidth:0,lowerWidth:0,height:T,x:f,y:p},to:{upperWidth:y,lowerWidth:v,height:T,x:f,y:p},duration:P,animationEasing:k,isActive:D},function(B){var V=B.upperWidth,G=B.lowerWidth,W=B.height,Y=B.x,J=B.y;return Xe.createElement(og,{canBegin:c>0,from:"0px ".concat(c===-1?1:c,"px"),to:"".concat(c,"px 0px"),attributeName:"strokeDasharray",begin:R,duration:P,easing:k},Xe.createElement("path",eO({},fi(r,!0),{className:M,d:ele(Y,J,V,G,W),ref:n})))}):Xe.createElement("g",null,Xe.createElement("path",eO({},fi(r,!0),{className:M,d:ele(f,p,y,v,T)})))},Wjt=["option","shapeType","propTransformer","activeClassName","isActive"];function Wk(t){"@babel/helpers - typeof";return Wk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Wk(t)}function Kjt(t,e){if(t==null)return{};var r=Yjt(t,e),n,i;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Yjt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function tle(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function tO(t){for(var e=1;e0?md(B,"paddingAngle",0):0;if(G){var Y=Sy(G.endAngle-G.startAngle,B.endAngle-B.startAngle),J=ga(ga({},B),{},{startAngle:M+W,endAngle:M+Y(P)+W});R.push(J),M=J.endAngle}else{var Q=B.endAngle,ee=B.startAngle,le=Sy(0,Q-ee),pe=le(P),Se=ga(ga({},B),{},{startAngle:M+W,endAngle:M+pe+W});R.push(Se),M=Se.endAngle}}),Xe.createElement(Vs,null,n.renderSectorsStatically(R))})}},{key:"attachKeyboardHandlers",value:function(n){var i=this;n.onkeydown=function(o){if(!o.altKey)switch(o.key){case"ArrowLeft":{var c=++i.state.sectorToFocus%i.sectorRefs.length;i.sectorRefs[c].focus(),i.setState({sectorToFocus:c});break}case"ArrowRight":{var a=--i.state.sectorToFocus<0?i.sectorRefs.length-1:i.state.sectorToFocus%i.sectorRefs.length;i.sectorRefs[a].focus(),i.setState({sectorToFocus:a});break}case"Escape":{i.sectorRefs[i.state.sectorToFocus].blur(),i.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var n=this.props,i=n.sectors,o=n.isAnimationActive,c=this.state.prevSectors;return o&&i&&i.length&&(!c||!VF(c,i))?this.renderSectorsWithAnimation():this.renderSectorsStatically(i)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var n=this,i=this.props,o=i.hide,c=i.sectors,a=i.className,f=i.label,p=i.cx,y=i.cy,v=i.innerRadius,T=i.outerRadius,E=i.isAnimationActive,k=this.state.isAnimationFinished;if(o||!c||!c.length||!Kr(p)||!Kr(y)||!Kr(v)||!Kr(T))return null;var P=$i("recharts-pie",a);return Xe.createElement(Vs,{tabIndex:this.props.rootTabIndex,className:P,ref:function(D){n.pieRef=D}},this.renderSectors(),f&&this.renderLabels(c),Ll.renderCallByParent(this.props,null,!1),(!E||k)&&ax.renderCallByParent(this.props,c,!1))}}],[{key:"getDerivedStateFromProps",value:function(n,i){return i.prevIsAnimationActive!==n.isAnimationActive?{prevIsAnimationActive:n.isAnimationActive,prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:[],isAnimationFinished:!0}:n.isAnimationActive&&n.animationId!==i.prevAnimationId?{prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:i.curSectors,isAnimationFinished:!0}:n.sectors!==i.curSectors?{curSectors:n.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(n,i){return n>i?"start":n=360?M:M-1)*f,V=R-M*E-B,G=i.reduce(function(J,Q){var ee=ec(Q,D,0);return J+(Kr(ee)?ee:0)},0),W;if(G>0){var Y;W=i.map(function(J,Q){var ee=ec(J,D,0),le=ec(J,y,Q),pe=(Kr(ee)?ee:0)/G,Se;Q?Se=Y.endAngle+Jc(P)*f*(ee!==0?1:0):Se=c;var je=Se+Jc(P)*((ee!==0?E:0)+pe*V),Le=(Se+je)/2,Ae=(k.innerRadius+k.outerRadius)/2,be=[{name:le,value:ee,payload:J,dataKey:D,type:T}],me=_a(k.cx,k.cy,Ae,Le);return Y=ga(ga(ga({percent:pe,cornerRadius:o,name:le,tooltipPayload:be,midAngle:Le,middleRadius:Ae,tooltipPosition:me},J),k),{},{value:ec(J,D),startAngle:Se,endAngle:je,payload:J,paddingAngle:Jc(P)*f}),Y})}return ga(ga({},k),{},{sectors:W,data:i})});var g2t=Math.ceil,y2t=Math.max;function x2t(t,e,r,n){for(var i=-1,o=y2t(g2t((e-t)/(r||1)),0),c=Array(o);o--;)c[n?o:++i]=t,t+=r;return c}var v2t=x2t,_2t=WSe,sle=1/0,b2t=17976931348623157e292;function w2t(t){if(!t)return t===0?t:0;if(t=_2t(t),t===sle||t===-sle){var e=t<0?-1:1;return e*b2t}return t===t?t:0}var NEe=w2t,S2t=v2t,T2t=PF,Gz=NEe;function E2t(t){return function(e,r,n){return n&&typeof n!="number"&&T2t(e,r,n)&&(r=n=void 0),e=Gz(e),r===void 0?(r=e,e=0):r=Gz(r),n=n===void 0?e0&&n.handleDrag(i.changedTouches[0])}),ed(n,"handleDragEnd",function(){n.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var i=n.props,o=i.endIndex,c=i.onDragEnd,a=i.startIndex;c==null||c({endIndex:o,startIndex:a})}),n.detachDragEndListener()}),ed(n,"handleLeaveWrapper",function(){(n.state.isTravellerMoving||n.state.isSlideMoving)&&(n.leaveTimer=window.setTimeout(n.handleDragEnd,n.props.leaveTimeOut))}),ed(n,"handleEnterSlideOrTraveller",function(){n.setState({isTextActive:!0})}),ed(n,"handleLeaveSlideOrTraveller",function(){n.setState({isTextActive:!1})}),ed(n,"handleSlideDragStart",function(i){var o=ule(i)?i.changedTouches[0]:i;n.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:o.pageX}),n.attachDragEndListener()}),n.travellerDragStartHandlers={startX:n.handleTravellerDragStart.bind(n,"startX"),endX:n.handleTravellerDragStart.bind(n,"endX")},n.state={},n}return B2t(e,t),D2t(e,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(n){var i=n.startX,o=n.endX,c=this.state.scaleValues,a=this.props,f=a.gap,p=a.data,y=p.length-1,v=Math.min(i,o),T=Math.max(i,o),E=e.getIndexInRange(c,v),k=e.getIndexInRange(c,T);return{startIndex:E-E%f,endIndex:k===y?y:k-k%f}}},{key:"getTextOfTick",value:function(n){var i=this.props,o=i.data,c=i.tickFormatter,a=i.dataKey,f=ec(o[n],a,n);return _i(c)?c(f,n):f}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(n){var i=this.state,o=i.slideMoveStartX,c=i.startX,a=i.endX,f=this.props,p=f.x,y=f.width,v=f.travellerWidth,T=f.startIndex,E=f.endIndex,k=f.onChange,P=n.pageX-o;P>0?P=Math.min(P,p+y-v-a,p+y-v-c):P<0&&(P=Math.max(P,p-c,p-a));var R=this.getIndex({startX:c+P,endX:a+P});(R.startIndex!==T||R.endIndex!==E)&&k&&k(R),this.setState({startX:c+P,endX:a+P,slideMoveStartX:n.pageX})}},{key:"handleTravellerDragStart",value:function(n,i){var o=ule(i)?i.changedTouches[0]:i;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:n,brushMoveStartX:o.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(n){var i=this.state,o=i.brushMoveStartX,c=i.movingTravellerId,a=i.endX,f=i.startX,p=this.state[c],y=this.props,v=y.x,T=y.width,E=y.travellerWidth,k=y.onChange,P=y.gap,R=y.data,D={startX:this.state.startX,endX:this.state.endX},M=n.pageX-o;M>0?M=Math.min(M,v+T-E-p):M<0&&(M=Math.max(M,v-p)),D[c]=p+M;var B=this.getIndex(D),V=B.startIndex,G=B.endIndex,W=function(){var J=R.length-1;return c==="startX"&&(a>f?V%P===0:G%P===0)||af?G%P===0:V%P===0)||a>f&&G===J};this.setState(ed(ed({},c,p+M),"brushMoveStartX",n.pageX),function(){k&&W()&&k(B)})}},{key:"handleTravellerMoveKeyboard",value:function(n,i){var o=this,c=this.state,a=c.scaleValues,f=c.startX,p=c.endX,y=this.state[i],v=a.indexOf(y);if(v!==-1){var T=v+n;if(!(T===-1||T>=a.length)){var E=a[T];i==="startX"&&E>=p||i==="endX"&&E<=f||this.setState(ed({},i,E),function(){o.props.onChange(o.getIndex({startX:o.state.startX,endX:o.state.endX}))})}}}},{key:"renderBackground",value:function(){var n=this.props,i=n.x,o=n.y,c=n.width,a=n.height,f=n.fill,p=n.stroke;return Xe.createElement("rect",{stroke:p,fill:f,x:i,y:o,width:c,height:a})}},{key:"renderPanorama",value:function(){var n=this.props,i=n.x,o=n.y,c=n.width,a=n.height,f=n.data,p=n.children,y=n.padding,v=C.Children.only(p);return v?Xe.cloneElement(v,{x:i,y:o,width:c,height:a,margin:y,compact:!0,data:f}):null}},{key:"renderTravellerLayer",value:function(n,i){var o,c,a=this,f=this.props,p=f.y,y=f.travellerWidth,v=f.height,T=f.traveller,E=f.ariaLabel,k=f.data,P=f.startIndex,R=f.endIndex,D=Math.max(n,this.props.x),M=Hz(Hz({},fi(this.props,!1)),{},{x:D,y:p,width:y,height:v}),B=E||"Min value: ".concat((o=k[P])===null||o===void 0?void 0:o.name,", Max value: ").concat((c=k[R])===null||c===void 0?void 0:c.name);return Xe.createElement(Vs,{tabIndex:0,role:"slider","aria-label":B,"aria-valuenow":n,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[i],onTouchStart:this.travellerDragStartHandlers[i],onKeyDown:function(G){["ArrowLeft","ArrowRight"].includes(G.key)&&(G.preventDefault(),G.stopPropagation(),a.handleTravellerMoveKeyboard(G.key==="ArrowRight"?1:-1,i))},onFocus:function(){a.setState({isTravellerFocused:!0})},onBlur:function(){a.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},e.renderTraveller(T,M))}},{key:"renderSlide",value:function(n,i){var o=this.props,c=o.y,a=o.height,f=o.stroke,p=o.travellerWidth,y=Math.min(n,i)+p,v=Math.max(Math.abs(i-n)-p,0);return Xe.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:f,fillOpacity:.2,x:y,y:c,width:v,height:a})}},{key:"renderText",value:function(){var n=this.props,i=n.startIndex,o=n.endIndex,c=n.y,a=n.height,f=n.travellerWidth,p=n.stroke,y=this.state,v=y.startX,T=y.endX,E=5,k={pointerEvents:"none",fill:p};return Xe.createElement(Vs,{className:"recharts-brush-texts"},Xe.createElement(d_,iO({textAnchor:"end",verticalAnchor:"middle",x:Math.min(v,T)-E,y:c+a/2},k),this.getTextOfTick(i)),Xe.createElement(d_,iO({textAnchor:"start",verticalAnchor:"middle",x:Math.max(v,T)+f+E,y:c+a/2},k),this.getTextOfTick(o)))}},{key:"render",value:function(){var n=this.props,i=n.data,o=n.className,c=n.children,a=n.x,f=n.y,p=n.width,y=n.height,v=n.alwaysShowText,T=this.state,E=T.startX,k=T.endX,P=T.isTextActive,R=T.isSlideMoving,D=T.isTravellerMoving,M=T.isTravellerFocused;if(!i||!i.length||!Kr(a)||!Kr(f)||!Kr(p)||!Kr(y)||p<=0||y<=0)return null;var B=$i("recharts-brush",o),V=Xe.Children.count(c)===1,G=R2t("userSelect","none");return Xe.createElement(Vs,{className:B,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:G},this.renderBackground(),V&&this.renderPanorama(),this.renderSlide(E,k),this.renderTravellerLayer(E,"startX"),this.renderTravellerLayer(k,"endX"),(P||R||D||M||v)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(n){var i=n.x,o=n.y,c=n.width,a=n.height,f=n.stroke,p=Math.floor(o+a/2)-1;return Xe.createElement(Xe.Fragment,null,Xe.createElement("rect",{x:i,y:o,width:c,height:a,fill:f,stroke:"none"}),Xe.createElement("line",{x1:i+1,y1:p,x2:i+c-1,y2:p,fill:"none",stroke:"#fff"}),Xe.createElement("line",{x1:i+1,y1:p+2,x2:i+c-1,y2:p+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(n,i){var o;return Xe.isValidElement(n)?o=Xe.cloneElement(n,i):_i(n)?o=n(i):o=e.renderDefaultTraveller(i),o}},{key:"getDerivedStateFromProps",value:function(n,i){var o=n.data,c=n.width,a=n.x,f=n.travellerWidth,p=n.updateId,y=n.startIndex,v=n.endIndex;if(o!==i.prevData||p!==i.prevUpdateId)return Hz({prevData:o,prevTravellerWidth:f,prevUpdateId:p,prevX:a,prevWidth:c},o&&o.length?z2t({data:o,width:c,x:a,travellerWidth:f,startIndex:y,endIndex:v}):{scale:null,scaleValues:null});if(i.scale&&(c!==i.prevWidth||a!==i.prevX||f!==i.prevTravellerWidth)){i.scale.range([a,a+c-f]);var T=i.scale.domain().map(function(E){return i.scale(E)});return{prevData:o,prevTravellerWidth:f,prevUpdateId:p,prevX:a,prevWidth:c,startX:i.scale(n.startIndex),endX:i.scale(n.endIndex),scaleValues:T}}return null}},{key:"getIndexInRange",value:function(n,i){for(var o=n.length,c=0,a=o-1;a-c>1;){var f=Math.floor((c+a)/2);n[f]>i?a=f:c=f}return i>=n[a]?a:c}}])}(C.PureComponent);ed(PS,"displayName","Brush");ed(PS,"defaultProps",{height:40,travellerWidth:5,gap:1,fill:"#fff",stroke:"#666",padding:{top:1,right:1,bottom:1,left:1},leaveTimeOut:1e3,alwaysShowText:!1});var U2t=TW;function V2t(t,e){var r;return U2t(t,function(n,i,o){return r=e(n,i,o),!r}),!!r}var q2t=V2t,G2t=_Se,H2t=Mm,W2t=q2t,K2t=$u,Y2t=PF;function Z2t(t,e,r){var n=K2t(t)?G2t:W2t;return r&&Y2t(t,e,r)&&(e=void 0),n(t,H2t(e))}var X2t=Z2t;const Q2t=ds(X2t);var vm=function(e,r){var n=e.alwaysShow,i=e.ifOverflow;return n&&(i="extendDomain"),i===r},dle=USe;function J2t(t,e,r){e=="__proto__"&&dle?dle(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var eAt=J2t,tAt=eAt,rAt=$Se,nAt=Mm;function iAt(t,e){var r={};return e=nAt(e),rAt(t,function(n,i,o){tAt(r,i,e(n,i,o))}),r}var sAt=iAt;const aAt=ds(sAt);function oAt(t,e){for(var r=-1,n=t==null?0:t.length;++r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function TAt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function EAt(t,e){var r=t.x,n=t.y,i=SAt(t,vAt),o="".concat(r),c=parseInt(o,10),a="".concat(n),f=parseInt(a,10),p="".concat(e.height||i.height),y=parseInt(p,10),v="".concat(e.width||i.width),T=parseInt(v,10);return S2(S2(S2(S2(S2({},e),i),c?{x:c}:{}),f?{y:f}:{}),{},{height:y,width:T,name:e.name,radius:e.radius})}function fle(t){return Xe.createElement(AEe,Oq({shapeType:"rectangle",propTransformer:EAt,activeClassName:"recharts-active-bar"},t))}var jAt=function(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(n,i){if(typeof e=="number")return e;var o=Kr(n)||lct(n);return o?e(n,i):(o||f_(),r)}},AAt=["value","background"],DEe;function RS(t){"@babel/helpers - typeof";return RS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},RS(t)}function kAt(t,e){if(t==null)return{};var r=CAt(t,e),n,i;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function CAt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function aO(){return aO=Object.assign?Object.assign.bind():function(t){for(var e=1;e0&&Math.abs(Le)0&&Math.abs(je)0&&(Se=Math.min((tt||0)-(je[at-1]||0),Se))}),Number.isFinite(Se)){var Le=Se/pe,Ae=P.layout==="vertical"?n.height:n.width;if(P.padding==="gap"&&(Y=Le*Ae/2),P.padding==="no-gap"){var be=eu(e.barCategoryGap,Le*Ae),me=Le*Ae/2;Y=me-be-(me-be)/Ae*be}}}i==="xAxis"?J=[n.left+(B.left||0)+(Y||0),n.left+n.width-(B.right||0)-(Y||0)]:i==="yAxis"?J=f==="horizontal"?[n.top+n.height-(B.bottom||0),n.top+(B.top||0)]:[n.top+(B.top||0)+(Y||0),n.top+n.height-(B.bottom||0)-(Y||0)]:J=P.range,G&&(J=[J[1],J[0]]);var Te=eEe(P,o,T),Ne=Te.scale,Ee=Te.realScaleType;Ne.domain(D).range(J),tEe(Ne);var we=rEe(Ne,Jh(Jh({},P),{},{realScaleType:Ee}));i==="xAxis"?(le=R==="top"&&!V||R==="bottom"&&V,Q=n.left,ee=v[W]-le*P.height):i==="yAxis"&&(le=R==="left"&&!V||R==="right"&&V,Q=v[W]-le*P.width,ee=n.top);var He=Jh(Jh(Jh({},P),we),{},{realScaleType:Ee,x:Q,y:ee,scale:Ne,width:i==="xAxis"?n.width:P.width,height:i==="yAxis"?n.height:P.height});return He.bandSize=GM(He,we),!P.hide&&i==="xAxis"?v[W]+=(le?-1:1)*He.height:P.hide||(v[W]+=(le?-1:1)*He.width),Jh(Jh({},E),{},JF({},k,He))},{})},BEe=function(e,r){var n=e.x,i=e.y,o=r.x,c=r.y;return{x:Math.min(n,o),y:Math.min(i,c),width:Math.abs(o-n),height:Math.abs(c-i)}},zAt=function(e){var r=e.x1,n=e.y1,i=e.x2,o=e.y2;return BEe({x:r,y:n},{x:i,y:o})},$Ee=function(){function t(e){OAt(this,t),this.scale=e}return FAt(t,[{key:"domain",get:function(){return this.scale.domain}},{key:"range",get:function(){return this.scale.range}},{key:"rangeMin",get:function(){return this.range()[0]}},{key:"rangeMax",get:function(){return this.range()[1]}},{key:"bandwidth",get:function(){return this.scale.bandwidth}},{key:"apply",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=n.bandAware,o=n.position;if(r!==void 0){if(o)switch(o){case"start":return this.scale(r);case"middle":{var c=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+c}case"end":{var a=this.bandwidth?this.bandwidth():0;return this.scale(r)+a}default:return this.scale(r)}if(i){var f=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+f}return this.scale(r)}}},{key:"isInRange",value:function(r){var n=this.range(),i=n[0],o=n[n.length-1];return i<=o?r>=i&&r<=o:r>=o&&r<=i}}],[{key:"create",value:function(r){return new t(r)}}])}();JF($Ee,"EPS",1e-4);var eK=function(e){var r=Object.keys(e).reduce(function(n,i){return Jh(Jh({},n),{},JF({},i,$Ee.create(e[i])))},{});return Jh(Jh({},r),{},{apply:function(i){var o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},c=o.bandAware,a=o.position;return aAt(i,function(f,p){return r[p].apply(f,{bandAware:c,position:a})})},isInRange:function(i){return LEe(i,function(o,c){return r[c].isInRange(o)})}})};function UAt(t){return(t%180+180)%180}var VAt=function(e){var r=e.width,n=e.height,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=UAt(i),c=o*Math.PI/180,a=Math.atan(n/r),f=c>a&&c-1?i[o?e[c]:c]:void 0}}var KAt=WAt,YAt=NEe;function ZAt(t){var e=YAt(t),r=e%1;return e===e?r?e-r:e:0}var XAt=ZAt,QAt=LSe,JAt=Mm,ekt=XAt,tkt=Math.max;function rkt(t,e,r){var n=t==null?0:t.length;if(!n)return-1;var i=r==null?0:ekt(r);return i<0&&(i=tkt(n+i,0)),QAt(t,JAt(e),i)}var nkt=rkt,ikt=KAt,skt=nkt,akt=ikt(skt),okt=akt;const lkt=ds(okt);var ckt=hlt(function(t){return{x:t.left,y:t.top,width:t.width,height:t.height}},function(t){return["l",t.left,"t",t.top,"w",t.width,"h",t.height].join("")}),tK=C.createContext(void 0),rK=C.createContext(void 0),zEe=C.createContext(void 0),UEe=C.createContext({}),VEe=C.createContext(void 0),qEe=C.createContext(0),GEe=C.createContext(0),xle=function(e){var r=e.state,n=r.xAxisMap,i=r.yAxisMap,o=r.offset,c=e.clipPathId,a=e.children,f=e.width,p=e.height,y=ckt(o);return Xe.createElement(tK.Provider,{value:n},Xe.createElement(rK.Provider,{value:i},Xe.createElement(UEe.Provider,{value:o},Xe.createElement(zEe.Provider,{value:y},Xe.createElement(VEe.Provider,{value:c},Xe.createElement(qEe.Provider,{value:p},Xe.createElement(GEe.Provider,{value:f},a)))))))},ukt=function(){return C.useContext(VEe)},HEe=function(e){var r=C.useContext(tK);r==null&&f_();var n=r[e];return n==null&&f_(),n},dkt=function(){var e=C.useContext(tK);return Iy(e)},hkt=function(){var e=C.useContext(rK),r=lkt(e,function(n){return LEe(n.domain,Number.isFinite)});return r||Iy(e)},WEe=function(e){var r=C.useContext(rK);r==null&&f_();var n=r[e];return n==null&&f_(),n},fkt=function(){var e=C.useContext(zEe);return e},mkt=function(){return C.useContext(UEe)},nK=function(){return C.useContext(GEe)},iK=function(){return C.useContext(qEe)};function LS(t){"@babel/helpers - typeof";return LS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},LS(t)}function pkt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function gkt(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);rt*i)return!1;var o=r();return t*(e-t*o/2-n)>=0&&t*(e+t*o/2-i)<=0}function Xkt(t,e){return eje(t,e+1)}function Qkt(t,e,r,n,i){for(var o=(n||[]).slice(),c=e.start,a=e.end,f=0,p=1,y=c,v=function(){var k=n==null?void 0:n[f];if(k===void 0)return{v:eje(n,p)};var P=f,R,D=function(){return R===void 0&&(R=r(k,P)),R},M=k.coordinate,B=f===0||dO(t,M,D,y,a);B||(f=0,y=c,p+=1),B&&(y=M+t*(D()/2+i),f+=p)},T;p<=o.length;)if(T=v(),T)return T.v;return[]}function Qk(t){"@babel/helpers - typeof";return Qk=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Qk(t)}function jle(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function bc(t){for(var e=1;e0?E.coordinate-R*t:E.coordinate})}else o[T]=E=bc(bc({},E),{},{tickCoord:E.coordinate});var D=dO(t,E.tickCoord,P,a,f);D&&(f=E.tickCoord-t*(P()/2+i),o[T]=bc(bc({},E),{},{isShow:!0}))},y=c-1;y>=0;y--)p(y);return o}function nCt(t,e,r,n,i,o){var c=(n||[]).slice(),a=c.length,f=e.start,p=e.end;if(o){var y=n[a-1],v=r(y,a-1),T=t*(y.coordinate+t*v/2-p);c[a-1]=y=bc(bc({},y),{},{tickCoord:T>0?y.coordinate-T*t:y.coordinate});var E=dO(t,y.tickCoord,function(){return v},f,p);E&&(p=y.tickCoord-t*(v/2+i),c[a-1]=bc(bc({},y),{},{isShow:!0}))}for(var k=o?a-1:a,P=function(M){var B=c[M],V,G=function(){return V===void 0&&(V=r(B,M)),V};if(M===0){var W=t*(B.coordinate-t*G()/2-f);c[M]=B=bc(bc({},B),{},{tickCoord:W<0?B.coordinate-W*t:B.coordinate})}else c[M]=B=bc(bc({},B),{},{tickCoord:B.coordinate});var Y=dO(t,B.tickCoord,G,f,p);Y&&(f=B.tickCoord+t*(G()/2+i),c[M]=bc(bc({},B),{},{isShow:!0}))},R=0;R=2?Jc(i[1].coordinate-i[0].coordinate):1,D=Zkt(o,R,E);return f==="equidistantPreserveStart"?Qkt(R,D,P,i,c):(f==="preserveStart"||f==="preserveStartEnd"?T=nCt(R,D,P,i,c,f==="preserveStartEnd"):T=rCt(R,D,P,i,c),T.filter(function(M){return M.isShow}))}var iCt=["viewBox"],sCt=["viewBox"],aCt=["ticks"];function OS(t){"@babel/helpers - typeof";return OS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},OS(t)}function i1(){return i1=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function oCt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function lCt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function kle(t,e){for(var r=0;r0?f(this.props):f(E)),c<=0||a<=0||!k||!k.length?null:Xe.createElement(Vs,{className:$i("recharts-cartesian-axis",p),ref:function(R){n.layerReference=R}},o&&this.renderAxisLine(),this.renderTicks(k,this.state.fontSize,this.state.letterSpacing),Ll.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(n,i,o){var c,a=$i(i.className,"recharts-cartesian-axis-tick-value");return Xe.isValidElement(n)?c=Xe.cloneElement(n,il(il({},i),{},{className:a})):_i(n)?c=n(il(il({},i),{},{className:a})):c=Xe.createElement(d_,i1({},i,{className:"recharts-cartesian-axis-tick-value"}),o),c}}])}(C.Component);lK(PT,"displayName","CartesianAxis");lK(PT,"defaultProps",{x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd"});var pCt=["x1","y1","x2","y2","key"],gCt=["offset"];function m_(t){"@babel/helpers - typeof";return m_=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},m_(t)}function Cle(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function Sc(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function _Ct(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var bCt=function(e){var r=e.fill;if(!r||r==="none")return null;var n=e.fillOpacity,i=e.x,o=e.y,c=e.width,a=e.height,f=e.ry;return Xe.createElement("rect",{x:i,y:o,ry:f,width:c,height:a,stroke:"none",fill:r,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function nje(t,e){var r;if(Xe.isValidElement(t))r=Xe.cloneElement(t,e);else if(_i(t))r=t(e);else{var n=e.x1,i=e.y1,o=e.x2,c=e.y2,a=e.key,f=Nle(e,pCt),p=fi(f,!1);p.offset;var y=Nle(p,gCt);r=Xe.createElement("line",Iv({},y,{x1:n,y1:i,x2:o,y2:c,fill:"none",key:a}))}return r}function wCt(t){var e=t.x,r=t.width,n=t.horizontal,i=n===void 0?!0:n,o=t.horizontalPoints;if(!i||!o||!o.length)return null;var c=o.map(function(a,f){var p=Sc(Sc({},t),{},{x1:e,y1:a,x2:e+r,y2:a,key:"line-".concat(f),index:f});return nje(i,p)});return Xe.createElement("g",{className:"recharts-cartesian-grid-horizontal"},c)}function SCt(t){var e=t.y,r=t.height,n=t.vertical,i=n===void 0?!0:n,o=t.verticalPoints;if(!i||!o||!o.length)return null;var c=o.map(function(a,f){var p=Sc(Sc({},t),{},{x1:a,y1:e,x2:a,y2:e+r,key:"line-".concat(f),index:f});return nje(i,p)});return Xe.createElement("g",{className:"recharts-cartesian-grid-vertical"},c)}function TCt(t){var e=t.horizontalFill,r=t.fillOpacity,n=t.x,i=t.y,o=t.width,c=t.height,a=t.horizontalPoints,f=t.horizontal,p=f===void 0?!0:f;if(!p||!e||!e.length)return null;var y=a.map(function(T){return Math.round(T+i-i)}).sort(function(T,E){return T-E});i!==y[0]&&y.unshift(0);var v=y.map(function(T,E){var k=!y[E+1],P=k?i+c-T:y[E+1]-T;if(P<=0)return null;var R=E%e.length;return Xe.createElement("rect",{key:"react-".concat(E),y:T,x:n,height:P,width:o,stroke:"none",fill:e[R],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return Xe.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},v)}function ECt(t){var e=t.vertical,r=e===void 0?!0:e,n=t.verticalFill,i=t.fillOpacity,o=t.x,c=t.y,a=t.width,f=t.height,p=t.verticalPoints;if(!r||!n||!n.length)return null;var y=p.map(function(T){return Math.round(T+o-o)}).sort(function(T,E){return T-E});o!==y[0]&&y.unshift(0);var v=y.map(function(T,E){var k=!y[E+1],P=k?o+a-T:y[E+1]-T;if(P<=0)return null;var R=E%n.length;return Xe.createElement("rect",{key:"react-".concat(E),x:T,y:c,width:P,height:f,stroke:"none",fill:n[R],fillOpacity:i,className:"recharts-cartesian-grid-bg"})});return Xe.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},v)}var jCt=function(e,r){var n=e.xAxis,i=e.width,o=e.height,c=e.offset;return JTe(oK(Sc(Sc(Sc({},PT.defaultProps),n),{},{ticks:Fp(n,!0),viewBox:{x:0,y:0,width:i,height:o}})),c.left,c.left+c.width,r)},ACt=function(e,r){var n=e.yAxis,i=e.width,o=e.height,c=e.offset;return JTe(oK(Sc(Sc(Sc({},PT.defaultProps),n),{},{ticks:Fp(n,!0),viewBox:{x:0,y:0,width:i,height:o}})),c.top,c.top+c.height,r)},Sw={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function ije(t){var e,r,n,i,o,c,a=nK(),f=iK(),p=mkt(),y=Sc(Sc({},t),{},{stroke:(e=t.stroke)!==null&&e!==void 0?e:Sw.stroke,fill:(r=t.fill)!==null&&r!==void 0?r:Sw.fill,horizontal:(n=t.horizontal)!==null&&n!==void 0?n:Sw.horizontal,horizontalFill:(i=t.horizontalFill)!==null&&i!==void 0?i:Sw.horizontalFill,vertical:(o=t.vertical)!==null&&o!==void 0?o:Sw.vertical,verticalFill:(c=t.verticalFill)!==null&&c!==void 0?c:Sw.verticalFill,x:Kr(t.x)?t.x:p.left,y:Kr(t.y)?t.y:p.top,width:Kr(t.width)?t.width:p.width,height:Kr(t.height)?t.height:p.height}),v=y.x,T=y.y,E=y.width,k=y.height,P=y.syncWithTicks,R=y.horizontalValues,D=y.verticalValues,M=dkt(),B=hkt();if(!Kr(E)||E<=0||!Kr(k)||k<=0||!Kr(v)||v!==+v||!Kr(T)||T!==+T)return null;var V=y.verticalCoordinatesGenerator||jCt,G=y.horizontalCoordinatesGenerator||ACt,W=y.horizontalPoints,Y=y.verticalPoints;if((!W||!W.length)&&_i(G)){var J=R&&R.length,Q=G({yAxis:B?Sc(Sc({},B),{},{ticks:J?R:B.ticks}):void 0,width:a,height:f,offset:p},J?!0:P);mf(Array.isArray(Q),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(m_(Q),"]")),Array.isArray(Q)&&(W=Q)}if((!Y||!Y.length)&&_i(V)){var ee=D&&D.length,le=V({xAxis:M?Sc(Sc({},M),{},{ticks:ee?D:M.ticks}):void 0,width:a,height:f,offset:p},ee?!0:P);mf(Array.isArray(le),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(m_(le),"]")),Array.isArray(le)&&(Y=le)}return Xe.createElement("g",{className:"recharts-cartesian-grid"},Xe.createElement(bCt,{fill:y.fill,fillOpacity:y.fillOpacity,x:y.x,y:y.y,width:y.width,height:y.height,ry:y.ry}),Xe.createElement(wCt,Iv({},y,{offset:p,horizontalPoints:W,xAxis:M,yAxis:B})),Xe.createElement(SCt,Iv({},y,{offset:p,verticalPoints:Y,xAxis:M,yAxis:B})),Xe.createElement(TCt,Iv({},y,{horizontalPoints:W})),Xe.createElement(ECt,Iv({},y,{verticalPoints:Y})))}ije.displayName="CartesianGrid";function FS(t){"@babel/helpers - typeof";return FS=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},FS(t)}function kCt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function CCt(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function pNt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function gNt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function yNt(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);r0?c:e&&e.length&&Kr(i)&&Kr(o)?e.slice(i,o+1):[]};function xje(t){return t==="number"?[0,"auto"]:void 0}var eG=function(e,r,n,i){var o=e.graphicalItems,c=e.tooltipAxis,a=a5(r,e);return n<0||!o||!o.length||n>=a.length?null:o.reduce(function(f,p){var y,v=(y=p.props.data)!==null&&y!==void 0?y:r;v&&e.dataStartIndex+e.dataEndIndex!==0&&e.dataEndIndex-e.dataStartIndex>=n&&(v=v.slice(e.dataStartIndex,e.dataEndIndex+1));var T;if(c.dataKey&&!c.allowDuplicatedCategory){var E=v===void 0?a:v;T=yM(E,c.dataKey,i)}else T=v&&v[n]||a[n];return T?[].concat(zS(f),[iEe(p,T)]):f},[])},Mle=function(e,r,n,i){var o=i||{x:e.chartX,y:e.chartY},c=CNt(o,n),a=e.orderedTooltipTicks,f=e.tooltipAxis,p=e.tooltipTicks,y=_1t(c,a,p,f);if(y>=0&&p){var v=p[y]&&p[y].value,T=eG(e,r,y,v),E=NNt(n,a,y,o);return{activeTooltipIndex:y,activeLabel:v,activePayload:T,activeCoordinate:E}}return null},INt=function(e,r){var n=r.axes,i=r.graphicalItems,o=r.axisType,c=r.axisIdKey,a=r.stackGroups,f=r.dataStartIndex,p=r.dataEndIndex,y=e.layout,v=e.children,T=e.stackOffset,E=QTe(y,o);return n.reduce(function(k,P){var R,D=P.type.defaultProps!==void 0?_r(_r({},P.type.defaultProps),P.props):P.props,M=D.type,B=D.dataKey,V=D.allowDataOverflow,G=D.allowDuplicatedCategory,W=D.scale,Y=D.ticks,J=D.includeHidden,Q=D[c];if(k[Q])return k;var ee=a5(e.data,{graphicalItems:i.filter(function(we){var He,tt=c in we.props?we.props[c]:(He=we.type.defaultProps)===null||He===void 0?void 0:He[c];return tt===Q}),dataStartIndex:f,dataEndIndex:p}),le=ee.length,pe,Se,je;nNt(D.domain,V,M)&&(pe=pq(D.domain,null,V),E&&(M==="number"||W!=="auto")&&(je=_A(ee,B,"category")));var Le=xje(M);if(!pe||pe.length===0){var Ae,be=(Ae=D.domain)!==null&&Ae!==void 0?Ae:Le;if(B){if(pe=_A(ee,B,M),M==="category"&&E){var me=uct(pe);G&&me?(Se=pe,pe=nO(0,le)):G||(pe=ooe(be,pe,P).reduce(function(we,He){return we.indexOf(He)>=0?we:[].concat(zS(we),[He])},[]))}else if(M==="category")G?pe=pe.filter(function(we){return we!==""&&!zi(we)}):pe=ooe(be,pe,P).reduce(function(we,He){return we.indexOf(He)>=0||He===""||zi(He)?we:[].concat(zS(we),[He])},[]);else if(M==="number"){var Te=E1t(ee,i.filter(function(we){var He,tt,at=c in we.props?we.props[c]:(He=we.type.defaultProps)===null||He===void 0?void 0:He[c],Et="hide"in we.props?we.props.hide:(tt=we.type.defaultProps)===null||tt===void 0?void 0:tt.hide;return at===Q&&(J||!Et)}),B,o,y);Te&&(pe=Te)}E&&(M==="number"||W!=="auto")&&(je=_A(ee,B,"category"))}else E?pe=nO(0,le):a&&a[Q]&&a[Q].hasStack&&M==="number"?pe=T==="expand"?[0,1]:nEe(a[Q].stackGroups,f,p):pe=XTe(ee,i.filter(function(we){var He=c in we.props?we.props[c]:we.type.defaultProps[c],tt="hide"in we.props?we.props.hide:we.type.defaultProps.hide;return He===Q&&(J||!tt)}),M,y,!0);if(M==="number")pe=Xq(v,pe,Q,o,Y),be&&(pe=pq(be,pe,V));else if(M==="category"&&be){var Ne=be,Ee=pe.every(function(we){return Ne.indexOf(we)>=0});Ee&&(pe=Ne)}}return _r(_r({},k),{},oi({},Q,_r(_r({},D),{},{axisType:o,domain:pe,categoricalDomain:je,duplicateDomain:Se,originalDomain:(R=D.domain)!==null&&R!==void 0?R:Le,isCategorical:E,layout:y})))},{})},PNt=function(e,r){var n=r.graphicalItems,i=r.Axis,o=r.axisType,c=r.axisIdKey,a=r.stackGroups,f=r.dataStartIndex,p=r.dataEndIndex,y=e.layout,v=e.children,T=a5(e.data,{graphicalItems:n,dataStartIndex:f,dataEndIndex:p}),E=T.length,k=QTe(y,o),P=-1;return n.reduce(function(R,D){var M=D.type.defaultProps!==void 0?_r(_r({},D.type.defaultProps),D.props):D.props,B=M[c],V=xje("number");if(!R[B]){P++;var G;return k?G=nO(0,E):a&&a[B]&&a[B].hasStack?(G=nEe(a[B].stackGroups,f,p),G=Xq(v,G,B,o)):(G=pq(V,XTe(T,n.filter(function(W){var Y,J,Q=c in W.props?W.props[c]:(Y=W.type.defaultProps)===null||Y===void 0?void 0:Y[c],ee="hide"in W.props?W.props.hide:(J=W.type.defaultProps)===null||J===void 0?void 0:J.hide;return Q===B&&!ee}),"number",y),i.defaultProps.allowDataOverflow),G=Xq(v,G,B,o)),_r(_r({},R),{},oi({},B,_r(_r({axisType:o},i.defaultProps),{},{hide:!0,orientation:md(ANt,"".concat(o,".").concat(P%2),null),domain:G,originalDomain:V,isCategorical:k,layout:y})))}return R},{})},RNt=function(e,r){var n=r.axisType,i=n===void 0?"xAxis":n,o=r.AxisComp,c=r.graphicalItems,a=r.stackGroups,f=r.dataStartIndex,p=r.dataEndIndex,y=e.children,v="".concat(i,"Id"),T=uh(y,o),E={};return T&&T.length?E=INt(e,{axes:T,graphicalItems:c,axisType:i,axisIdKey:v,stackGroups:a,dataStartIndex:f,dataEndIndex:p}):c&&c.length&&(E=PNt(e,{Axis:o,graphicalItems:c,axisType:i,axisIdKey:v,stackGroups:a,dataStartIndex:f,dataEndIndex:p})),E},LNt=function(e){var r=Iy(e),n=Fp(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:EW(n,function(i){return i.coordinate}),tooltipAxis:r,tooltipAxisBandSize:GM(r,n)}},Ole=function(e){var r=e.children,n=e.defaultShowTooltip,i=id(r,PS),o=0,c=0;return e.data&&e.data.length!==0&&(c=e.data.length-1),i&&i.props&&(i.props.startIndex>=0&&(o=i.props.startIndex),i.props.endIndex>=0&&(c=i.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:o,dataEndIndex:c,activeTooltipIndex:-1,isTooltipActive:!!n}},DNt=function(e){return!e||!e.length?!1:e.some(function(r){var n=Up(r&&r.type);return n&&n.indexOf("Bar")>=0})},Fle=function(e){return e==="horizontal"?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:e==="vertical"?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:e==="centric"?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},MNt=function(e,r){var n=e.props,i=e.graphicalItems,o=e.xAxisMap,c=o===void 0?{}:o,a=e.yAxisMap,f=a===void 0?{}:a,p=n.width,y=n.height,v=n.children,T=n.margin||{},E=id(v,PS),k=id(v,T1),P=Object.keys(f).reduce(function(G,W){var Y=f[W],J=Y.orientation;return!Y.mirror&&!Y.hide?_r(_r({},G),{},oi({},J,G[J]+Y.width)):G},{left:T.left||0,right:T.right||0}),R=Object.keys(c).reduce(function(G,W){var Y=c[W],J=Y.orientation;return!Y.mirror&&!Y.hide?_r(_r({},G),{},oi({},J,md(G,"".concat(J))+Y.height)):G},{top:T.top||0,bottom:T.bottom||0}),D=_r(_r({},R),P),M=D.bottom;E&&(D.bottom+=E.props.height||PS.defaultProps.height),k&&r&&(D=S1t(D,i,n,r));var B=p-D.left-D.right,V=y-D.top-D.bottom;return _r(_r({brushBottom:M},D),{},{width:Math.max(B,0),height:Math.max(V,0)})},ONt=function(e,r){if(r==="xAxis")return e[r].width;if(r==="yAxis")return e[r].height},vje=function(e){var r=e.chartName,n=e.GraphicalChild,i=e.defaultTooltipEventType,o=i===void 0?"axis":i,c=e.validateTooltipEventTypes,a=c===void 0?["axis"]:c,f=e.axisComponents,p=e.legendContent,y=e.formatAxisMap,v=e.defaultProps,T=function(D,M){var B=M.graphicalItems,V=M.stackGroups,G=M.offset,W=M.updateId,Y=M.dataStartIndex,J=M.dataEndIndex,Q=D.barSize,ee=D.layout,le=D.barGap,pe=D.barCategoryGap,Se=D.maxBarSize,je=Fle(ee),Le=je.numericAxisName,Ae=je.cateAxisName,be=DNt(B),me=[];return B.forEach(function(Te,Ne){var Ee=a5(D.data,{graphicalItems:[Te],dataStartIndex:Y,dataEndIndex:J}),we=Te.type.defaultProps!==void 0?_r(_r({},Te.type.defaultProps),Te.props):Te.props,He=we.dataKey,tt=we.maxBarSize,at=we["".concat(Le,"Id")],Et=we["".concat(Ae,"Id")],vt={},Gt=f.reduce(function(jt,er){var Pr=M["".concat(er.axisType,"Map")],dr=we["".concat(er.axisType,"Id")];Pr&&Pr[dr]||er.axisType==="zAxis"||f_();var ar=Pr[dr];return _r(_r({},jt),{},oi(oi({},er.axisType,ar),"".concat(er.axisType,"Ticks"),Fp(ar)))},vt),pt=Gt[Ae],Pt=Gt["".concat(Ae,"Ticks")],tr=V&&V[at]&&V[at].hasStack&&L1t(Te,V[at].stackGroups),_t=Up(Te.type).indexOf("Bar")>=0,cr=GM(pt,Pt),Tr=[],sn=be&&b1t({barSize:Q,stackGroups:V,totalSize:ONt(Gt,Ae)});if(_t){var ur,xr,rr=zi(tt)?Se:tt,vn=(ur=(xr=GM(pt,Pt,!0))!==null&&xr!==void 0?xr:rr)!==null&&ur!==void 0?ur:0;Tr=w1t({barGap:le,barCategoryGap:pe,bandSize:vn!==cr?vn:cr,sizeList:sn[Et],maxBarSize:rr}),vn!==cr&&(Tr=Tr.map(function(jt){return _r(_r({},jt),{},{position:_r(_r({},jt.position),{},{offset:jt.position.offset-vn/2})})}))}var ct=Te&&Te.type&&Te.type.getComposedData;ct&&me.push({props:_r(_r({},ct(_r(_r({},Gt),{},{displayedData:Ee,props:D,dataKey:He,item:Te,bandSize:cr,barPosition:Tr,offset:G,stackedData:tr,layout:ee,dataStartIndex:Y,dataEndIndex:J}))),{},oi(oi(oi({key:Te.key||"item-".concat(Ne)},Le,Gt[Le]),Ae,Gt[Ae]),"animationId",W)),childIndex:wct(Te,D.children),item:Te})}),me},E=function(D,M){var B=D.props,V=D.dataStartIndex,G=D.dataEndIndex,W=D.updateId;if(!tse({props:B}))return null;var Y=B.children,J=B.layout,Q=B.stackOffset,ee=B.data,le=B.reverseStackOrder,pe=Fle(J),Se=pe.numericAxisName,je=pe.cateAxisName,Le=uh(Y,n),Ae=P1t(ee,Le,"".concat(Se,"Id"),"".concat(je,"Id"),Q,le),be=f.reduce(function(we,He){var tt="".concat(He.axisType,"Map");return _r(_r({},we),{},oi({},tt,RNt(B,_r(_r({},He),{},{graphicalItems:Le,stackGroups:He.axisType===Se&&Ae,dataStartIndex:V,dataEndIndex:G}))))},{}),me=MNt(_r(_r({},be),{},{props:B,graphicalItems:Le}),M==null?void 0:M.legendBBox);Object.keys(be).forEach(function(we){be[we]=y(B,be[we],me,we.replace("Map",""),r)});var Te=be["".concat(je,"Map")],Ne=LNt(Te),Ee=T(B,_r(_r({},be),{},{dataStartIndex:V,dataEndIndex:G,updateId:W,graphicalItems:Le,stackGroups:Ae,offset:me}));return _r(_r({formattedGraphicalItems:Ee,graphicalItems:Le,offset:me,stackGroups:Ae},Ne),be)},k=function(R){function D(M){var B,V,G;return gNt(this,D),G=vNt(this,D,[M]),oi(G,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),oi(G,"accessibilityManager",new rNt),oi(G,"handleLegendBBoxUpdate",function(W){if(W){var Y=G.state,J=Y.dataStartIndex,Q=Y.dataEndIndex,ee=Y.updateId;G.setState(_r({legendBBox:W},E({props:G.props,dataStartIndex:J,dataEndIndex:Q,updateId:ee},_r(_r({},G.state),{},{legendBBox:W}))))}}),oi(G,"handleReceiveSyncEvent",function(W,Y,J){if(G.props.syncId===W){if(J===G.eventEmitterSymbol&&typeof G.props.syncMethod!="function")return;G.applySyncEvent(Y)}}),oi(G,"handleBrushChange",function(W){var Y=W.startIndex,J=W.endIndex;if(Y!==G.state.dataStartIndex||J!==G.state.dataEndIndex){var Q=G.state.updateId;G.setState(function(){return _r({dataStartIndex:Y,dataEndIndex:J},E({props:G.props,dataStartIndex:Y,dataEndIndex:J,updateId:Q},G.state))}),G.triggerSyncEvent({dataStartIndex:Y,dataEndIndex:J})}}),oi(G,"handleMouseEnter",function(W){var Y=G.getMouseInfo(W);if(Y){var J=_r(_r({},Y),{},{isTooltipActive:!0});G.setState(J),G.triggerSyncEvent(J);var Q=G.props.onMouseEnter;_i(Q)&&Q(J,W)}}),oi(G,"triggeredAfterMouseMove",function(W){var Y=G.getMouseInfo(W),J=Y?_r(_r({},Y),{},{isTooltipActive:!0}):{isTooltipActive:!1};G.setState(J),G.triggerSyncEvent(J);var Q=G.props.onMouseMove;_i(Q)&&Q(J,W)}),oi(G,"handleItemMouseEnter",function(W){G.setState(function(){return{isTooltipActive:!0,activeItem:W,activePayload:W.tooltipPayload,activeCoordinate:W.tooltipPosition||{x:W.cx,y:W.cy}}})}),oi(G,"handleItemMouseLeave",function(){G.setState(function(){return{isTooltipActive:!1}})}),oi(G,"handleMouseMove",function(W){W.persist(),G.throttleTriggeredAfterMouseMove(W)}),oi(G,"handleMouseLeave",function(W){G.throttleTriggeredAfterMouseMove.cancel();var Y={isTooltipActive:!1};G.setState(Y),G.triggerSyncEvent(Y);var J=G.props.onMouseLeave;_i(J)&&J(Y,W)}),oi(G,"handleOuterEvent",function(W){var Y=bct(W),J=md(G.props,"".concat(Y));if(Y&&_i(J)){var Q,ee;/.*touch.*/i.test(Y)?ee=G.getMouseInfo(W.changedTouches[0]):ee=G.getMouseInfo(W),J((Q=ee)!==null&&Q!==void 0?Q:{},W)}}),oi(G,"handleClick",function(W){var Y=G.getMouseInfo(W);if(Y){var J=_r(_r({},Y),{},{isTooltipActive:!0});G.setState(J),G.triggerSyncEvent(J);var Q=G.props.onClick;_i(Q)&&Q(J,W)}}),oi(G,"handleMouseDown",function(W){var Y=G.props.onMouseDown;if(_i(Y)){var J=G.getMouseInfo(W);Y(J,W)}}),oi(G,"handleMouseUp",function(W){var Y=G.props.onMouseUp;if(_i(Y)){var J=G.getMouseInfo(W);Y(J,W)}}),oi(G,"handleTouchMove",function(W){W.changedTouches!=null&&W.changedTouches.length>0&&G.throttleTriggeredAfterMouseMove(W.changedTouches[0])}),oi(G,"handleTouchStart",function(W){W.changedTouches!=null&&W.changedTouches.length>0&&G.handleMouseDown(W.changedTouches[0])}),oi(G,"handleTouchEnd",function(W){W.changedTouches!=null&&W.changedTouches.length>0&&G.handleMouseUp(W.changedTouches[0])}),oi(G,"handleDoubleClick",function(W){var Y=G.props.onDoubleClick;if(_i(Y)){var J=G.getMouseInfo(W);Y(J,W)}}),oi(G,"handleContextMenu",function(W){var Y=G.props.onContextMenu;if(_i(Y)){var J=G.getMouseInfo(W);Y(J,W)}}),oi(G,"triggerSyncEvent",function(W){G.props.syncId!==void 0&&Kz.emit(Yz,G.props.syncId,W,G.eventEmitterSymbol)}),oi(G,"applySyncEvent",function(W){var Y=G.props,J=Y.layout,Q=Y.syncMethod,ee=G.state.updateId,le=W.dataStartIndex,pe=W.dataEndIndex;if(W.dataStartIndex!==void 0||W.dataEndIndex!==void 0)G.setState(_r({dataStartIndex:le,dataEndIndex:pe},E({props:G.props,dataStartIndex:le,dataEndIndex:pe,updateId:ee},G.state)));else if(W.activeTooltipIndex!==void 0){var Se=W.chartX,je=W.chartY,Le=W.activeTooltipIndex,Ae=G.state,be=Ae.offset,me=Ae.tooltipTicks;if(!be)return;if(typeof Q=="function")Le=Q(me,W);else if(Q==="value"){Le=-1;for(var Te=0;Te=0){var tr,_t;if(Se.dataKey&&!Se.allowDuplicatedCategory){var cr=typeof Se.dataKey=="function"?Pt:"payload.".concat(Se.dataKey.toString());tr=yM(Te,cr,Le),_t=Ne&&Ee&&yM(Ee,cr,Le)}else tr=Te==null?void 0:Te[je],_t=Ne&&Ee&&Ee[je];if(Et||at){var Tr=W.props.activeIndex!==void 0?W.props.activeIndex:je;return[C.cloneElement(W,_r(_r(_r({},Q.props),Gt),{},{activeIndex:Tr})),null,null]}if(!zi(tr))return[pt].concat(zS(G.renderActivePoints({item:Q,activePoint:tr,basePoint:_t,childIndex:je,isRange:Ne})))}else{var sn,ur=(sn=G.getItemByXY(G.state.activeCoordinate))!==null&&sn!==void 0?sn:{graphicalItem:pt},xr=ur.graphicalItem,rr=xr.item,vn=rr===void 0?W:rr,ct=xr.childIndex,jt=_r(_r(_r({},Q.props),Gt),{},{activeIndex:ct});return[C.cloneElement(vn,jt),null,null]}return Ne?[pt,null,null]:[pt,null]}),oi(G,"renderCustomized",function(W,Y,J){return C.cloneElement(W,_r(_r({key:"recharts-customized-".concat(J)},G.props),G.state))}),oi(G,"renderMap",{CartesianGrid:{handler:$R,once:!0},ReferenceArea:{handler:G.renderReferenceElement},ReferenceLine:{handler:$R},ReferenceDot:{handler:G.renderReferenceElement},XAxis:{handler:$R},YAxis:{handler:$R},Brush:{handler:G.renderBrush,once:!0},Bar:{handler:G.renderGraphicChild},Line:{handler:G.renderGraphicChild},Area:{handler:G.renderGraphicChild},Radar:{handler:G.renderGraphicChild},RadialBar:{handler:G.renderGraphicChild},Scatter:{handler:G.renderGraphicChild},Pie:{handler:G.renderGraphicChild},Funnel:{handler:G.renderGraphicChild},Tooltip:{handler:G.renderCursor,once:!0},PolarGrid:{handler:G.renderPolarGrid,once:!0},PolarAngleAxis:{handler:G.renderPolarAxis},PolarRadiusAxis:{handler:G.renderPolarAxis},Customized:{handler:G.renderCustomized}}),G.clipPathId="".concat((B=M.id)!==null&&B!==void 0?B:rN("recharts"),"-clip"),G.throttleTriggeredAfterMouseMove=KSe(G.triggeredAfterMouseMove,(V=M.throttleDelay)!==null&&V!==void 0?V:1e3/60),G.state={},G}return wNt(D,R),xNt(D,[{key:"componentDidMount",value:function(){var B,V;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(B=this.props.margin.left)!==null&&B!==void 0?B:0,top:(V=this.props.margin.top)!==null&&V!==void 0?V:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var B=this.props,V=B.children,G=B.data,W=B.height,Y=B.layout,J=id(V,Qh);if(J){var Q=J.props.defaultIndex;if(!(typeof Q!="number"||Q<0||Q>this.state.tooltipTicks.length-1)){var ee=this.state.tooltipTicks[Q]&&this.state.tooltipTicks[Q].value,le=eG(this.state,G,Q,ee),pe=this.state.tooltipTicks[Q].coordinate,Se=(this.state.offset.top+W)/2,je=Y==="horizontal",Le=je?{x:pe,y:Se}:{y:pe,x:Se},Ae=this.state.formattedGraphicalItems.find(function(me){var Te=me.item;return Te.type.name==="Scatter"});Ae&&(Le=_r(_r({},Le),Ae.props.points[Q].tooltipPosition),le=Ae.props.points[Q].tooltipPayload);var be={activeTooltipIndex:Q,isTooltipActive:!0,activeLabel:ee,activePayload:le,activeCoordinate:Le};this.setState(be),this.renderCursor(J),this.accessibilityManager.setIndex(Q)}}}},{key:"getSnapshotBeforeUpdate",value:function(B,V){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==V.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==B.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==B.margin){var G,W;this.accessibilityManager.setDetails({offset:{left:(G=this.props.margin.left)!==null&&G!==void 0?G:0,top:(W=this.props.margin.top)!==null&&W!==void 0?W:0}})}return null}},{key:"componentDidUpdate",value:function(B){C8([id(B.children,Qh)],[id(this.props.children,Qh)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var B=id(this.props.children,Qh);if(B&&typeof B.props.shared=="boolean"){var V=B.props.shared?"axis":"item";return a.indexOf(V)>=0?V:o}return o}},{key:"getMouseInfo",value:function(B){if(!this.container)return null;var V=this.container,G=V.getBoundingClientRect(),W=K0t(G),Y={chartX:Math.round(B.pageX-W.left),chartY:Math.round(B.pageY-W.top)},J=G.width/V.offsetWidth||1,Q=this.inRange(Y.chartX,Y.chartY,J);if(!Q)return null;var ee=this.state,le=ee.xAxisMap,pe=ee.yAxisMap,Se=this.getTooltipEventType(),je=Mle(this.state,this.props.data,this.props.layout,Q);if(Se!=="axis"&&le&&pe){var Le=Iy(le).scale,Ae=Iy(pe).scale,be=Le&&Le.invert?Le.invert(Y.chartX):null,me=Ae&&Ae.invert?Ae.invert(Y.chartY):null;return _r(_r({},Y),{},{xValue:be,yValue:me},je)}return je?_r(_r({},Y),je):null}},{key:"inRange",value:function(B,V){var G=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,W=this.props.layout,Y=B/G,J=V/G;if(W==="horizontal"||W==="vertical"){var Q=this.state.offset,ee=Y>=Q.left&&Y<=Q.left+Q.width&&J>=Q.top&&J<=Q.top+Q.height;return ee?{x:Y,y:J}:null}var le=this.state,pe=le.angleAxisMap,Se=le.radiusAxisMap;if(pe&&Se){var je=Iy(pe);return uoe({x:Y,y:J},je)}return null}},{key:"parseEventsOfWrapper",value:function(){var B=this.props.children,V=this.getTooltipEventType(),G=id(B,Qh),W={};G&&V==="axis"&&(G.props.trigger==="click"?W={onClick:this.handleClick}:W={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var Y=xM(this.props,this.handleOuterEvent);return _r(_r({},Y),W)}},{key:"addListener",value:function(){Kz.on(Yz,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){Kz.removeListener(Yz,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(B,V,G){for(var W=this.state.formattedGraphicalItems,Y=0,J=W.length;Y");return t}const wje=C.forwardRef(({id:t,className:e,children:r,config:n,...i},o)=>{const c=C.useId(),a=`chart-${t||c.replace(/:/g,"")}`;return s.jsx(_je.Provider,{value:{config:n},children:s.jsxs("div",{"data-chart":a,ref:o,className:qt("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",e),...i,children:[s.jsx(zNt,{id:a,config:n}),s.jsx(Q8,{children:r})]})})});wje.displayName="Chart";const zNt=({id:t,config:e})=>{const r=Object.entries(e).filter(([n,i])=>i.theme||i.color);return r.length?s.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries($Nt).map(([n,i])=>` ${i} [data-chart=${t}] { ${r.map(([o,c])=>{var f;const a=((f=c.theme)==null?void 0:f[n])||c.color;return a?` --color-${o}: ${a};`:null}).join(` `)} } `).join(` `)}}):null},Sje=C.forwardRef(({active:t,payload:e,className:r,indicator:n="dot",hideLabel:i=!1,hideIndicator:o=!1,label:c,labelFormatter:a,labelClassName:f,formatter:p,color:y,nameKey:v,labelKey:T},E)=>{const{config:k}=bje(),P=C.useMemo(()=>{var G;if(i||!(e!=null&&e.length))return null;const[D]=e,M=`${T||D.dataKey||D.name||"value"}`,B=tG(k,D,M),V=!T&&typeof c=="string"?((G=k[c])==null?void 0:G.label)||c:B==null?void 0:B.label;return a?s.jsx("div",{className:qt("font-medium",f),children:a(V,e)}):V?s.jsx("div",{className:qt("font-medium",f),children:V}):null},[c,a,e,i,f,k,T]);if(!t||!(e!=null&&e.length))return null;const R=e.length===1&&n!=="dot";return s.jsxs("div",{ref:E,className:qt("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",r),children:[R?null:P,s.jsx("div",{className:"grid gap-1.5",children:e.map((D,M)=>{const B=`${v||D.name||D.dataKey||"value"}`,V=tG(k,D,B),G=y||D.payload.fill||D.color;return s.jsx("div",{className:qt("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",n==="dot"&&"items-center"),children:p&&(D==null?void 0:D.value)!==void 0&&D.name?p(D.value,D.name,D,M,D.payload):s.jsxs(s.Fragment,{children:[V!=null&&V.icon?s.jsx(V.icon,{}):!o&&s.jsx("div",{className:qt("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":n==="dot","w-1":n==="line","w-0 border-[1.5px] border-dashed bg-transparent":n==="dashed","my-0.5":R&&n==="dashed"}),style:{"--color-bg":G,"--color-border":G}}),s.jsxs("div",{className:qt("flex flex-1 justify-between leading-none",R?"items-end":"items-center"),children:[s.jsxs("div",{className:"grid gap-1.5",children:[R?P:null,s.jsx("span",{className:"text-muted-foreground",children:(V==null?void 0:V.label)||D.name})]}),D.value&&s.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:D.value.toLocaleString()})]})]})},D.dataKey)})})]})});Sje.displayName="ChartTooltip";const UNt=C.forwardRef(({className:t,hideIcon:e=!1,payload:r,verticalAlign:n="bottom",nameKey:i},o)=>{const{config:c}=bje();return r!=null&&r.length?s.jsx("div",{ref:o,className:qt("flex items-center justify-center gap-4",n==="top"?"pb-3":"pt-3",t),children:r.map(a=>{const f=`${i||a.dataKey||"value"}`,p=tG(c,a,f);return s.jsxs("div",{className:qt("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[p!=null&&p.icon&&!e?s.jsx(p.icon,{}):s.jsx("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:a.color}}),p==null?void 0:p.label]},a.value)})}):null});UNt.displayName="ChartLegend";function tG(t,e,r){if(typeof e!="object"||e===null)return;const n="payload"in e&&typeof e.payload=="object"&&e.payload!==null?e.payload:void 0;let i=r;return r in e&&typeof e[r]=="string"?i=e[r]:n&&r in n&&typeof n[r]=="string"&&(i=n[r]),i in t?t[i]:t[r]}const zR=["hsl(var(--primary))","hsl(var(--secondary))","hsl(210, 70%, 50%)","hsl(170, 60%, 45%)","hsl(280, 60%, 55%)","hsl(30, 70%, 50%)","hsl(340, 65%, 55%)","hsl(200, 65%, 50%)"];function Tje({stats:t,year:e}){const r=t.transactionsByMonth.some(i=>i.count>0),n=t.leadSourceBreakdown.length>0;return!r&&!n?s.jsx($n,{children:s.jsx(Kn,{className:"py-12 text-center text-muted-foreground",children:"Add transactions to see your performance charts"})}):s.jsxs("div",{className:"grid gap-6",children:[r&&s.jsxs($n,{className:"overflow-hidden",children:[s.jsx(ud,{children:s.jsx(dd,{className:"text-base",children:"Transactions by Month"})}),s.jsx(Kn,{className:"overflow-hidden",children:s.jsx(wje,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:s.jsx(Q8,{width:"100%",height:"100%",children:s.jsxs(FNt,{data:t.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[s.jsx(ije,{strokeDasharray:"3 3",className:"stroke-muted"}),s.jsx(i5,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),s.jsx(s5,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),s.jsx(Qh,{content:s.jsx(Sje,{})}),s.jsx(N_,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),n&&s.jsxs($n,{children:[s.jsx(ud,{children:s.jsx(dd,{className:"text-base",children:"Lead Sources"})}),s.jsxs(Kn,{children:[s.jsx("div",{className:"h-[250px]",children:s.jsx(Q8,{width:"100%",height:"100%",children:s.jsxs(BNt,{children:[s.jsx(xg,{data:t.leadSourceBreakdown,dataKey:"count",nameKey:"name",cx:"50%",cy:"50%",outerRadius:80,label:({name:i,percent:o})=>o>.05?`${i} (${(o*100).toFixed(0)}%)`:"",labelLine:!1,children:t.leadSourceBreakdown.map((i,o)=>s.jsx(RF,{fill:zR[o%zR.length]},`cell-${o}`))}),s.jsx(Qh,{formatter:(i,o)=>[`${i} deals`,o]})]})})}),s.jsx("div",{className:"flex flex-wrap gap-2 mt-2 justify-center",children:t.leadSourceBreakdown.slice(0,6).map((i,o)=>s.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[s.jsx("div",{className:"w-3 h-3 rounded-sm",style:{backgroundColor:zR[o%zR.length]}}),s.jsx("span",{className:"text-muted-foreground",children:i.name})]},i.name))})]})]})]})}const VNt=ZS("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),Eje=C.forwardRef(({className:t,variant:e,...r},n)=>s.jsx("div",{ref:n,role:"alert",className:qt(VNt({variant:e}),t),...r}));Eje.displayName="Alert";const qNt=C.forwardRef(({className:t,...e},r)=>s.jsx("h5",{ref:r,className:qt("mb-1 font-medium leading-none tracking-tight",t),...e}));qNt.displayName="AlertTitle";const jje=C.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:qt("text-sm [&_p]:leading-relaxed",t),...e}));jje.displayName="AlertDescription";function GNt(t){if(!t||!t.trim())return null;const e=t.trim(),r=["yyyy-MM-dd","M/d/yyyy","MM/dd/yyyy","M-d-yyyy","MM-dd-yyyy","MM/dd/yy","M/d/yy"];for(const n of r)try{const i=xKe(e,n,new Date);if(UV(i))return Ri(i,"yyyy-MM-dd")}catch{}try{const n=new Date(e);if(UV(n))return Ri(n,"yyyy-MM-dd")}catch{}return null}const HNt=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function WNt({open:t,onOpenChange:e}){const[r,n]=C.useState([]),[i,o]=C.useState(!1),[c,a]=C.useState(0),{data:f}=YH(),{data:p}=eW(),y=ZH(),v=()=>{const D=HNt.join(","),M=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),B=`${D} ${M}`,V=new Blob([B],{type:"text/csv"}),G=URL.createObjectURL(V),W=document.createElement("a");W.href=G,W.download="transaction-import-template.csv",W.click(),URL.revokeObjectURL(G)},T=D=>{const M=D.split(` `).filter(V=>V.trim());if(M.length<2)return[];const B=M[0].split(",").map(V=>V.trim().toLowerCase().replace(/['"]/g,""));return M.slice(1).map((V,G)=>{var be,me,Te,Ne;const W=[];let Y="",J=!1;for(const Ee of V)Ee==='"'?J=!J:Ee===","&&!J?(W.push(Y.trim()),Y=""):Y+=Ee;W.push(Y.trim());const Q=Ee=>{var He;const we=B.indexOf(Ee);return we>=0?(He=W[we])==null?void 0:He.replace(/^["']|["']$/g,"").trim():""},ee=(be=Q("transaction_type"))==null?void 0:be.toLowerCase(),le=(me=Q("sale_price"))==null?void 0:me.replace(/[$,]/g,""),pe=(Te=Q("commission_amount"))==null?void 0:Te.replace(/[$,]/g,""),Se=(Ne=Q("is_win"))==null?void 0:Ne.toLowerCase(),je=Q("close_date"),Le=GNt(je);let Ae;return Q("property_address")?["buyer","seller"].includes(ee)?Le?(!le||isNaN(Number(le)))&&(Ae="Invalid sale price"):Ae=`Invalid date format: "${je}" - use MM/DD/YYYY or YYYY-MM-DD`:Ae='Transaction type must be "buyer" or "seller"':Ae="Missing property address",{property_address:Q("property_address"),city:Q("city"),state:Q("state"),zip:Q("zip"),transaction_type:ee==="seller"?"seller":"buyer",close_date:Le||"",sale_price:Number(le)||0,commission_amount:pe?Number(pe):null,lead_source_name:Q("lead_source"),client_type_name:Q("client_type"),is_win:["yes","true","1"].includes(Se),notes:Q("notes"),error:Ae}})},E=D=>{var V;const M=(V=D.target.files)==null?void 0:V[0];if(!M)return;const B=new FileReader;B.onload=G=>{var J;const W=(J=G.target)==null?void 0:J.result,Y=T(W);n(Y)},B.readAsText(M)},k=async()=>{const D=r.filter(V=>!V.error);if(D.length===0){Vt.error("No valid transactions to import");return}o(!0),a(0);let M=0,B=0;for(let V=0;VJ.name.toLowerCase()===G.lead_source_name.toLowerCase()),Y=p==null?void 0:p.find(J=>J.name.toLowerCase()===G.client_type_name.toLowerCase());await y.mutateAsync({property_address:G.property_address,city:G.city||null,state:G.state||null,zip:G.zip||null,transaction_type:G.transaction_type,close_date:G.close_date,sale_price:G.sale_price,commission_amount:G.commission_amount,lead_source_id:(W==null?void 0:W.id)||null,client_type_id:(Y==null?void 0:Y.id)||null,contact_id:null,notes:G.notes||null,is_win:G.is_win}),M++}catch(W){B++,console.error("Failed to import transaction:",W)}a(Math.round((V+1)/D.length*100))}o(!1),M>0&&Vt.success(`Imported ${M} transaction${M>1?"s":""}`),B>0&&Vt.error(`Failed to import ${B} transaction${B>1?"s":""}`),n([]),e(!1)},P=r.filter(D=>!D.error).length,R=r.filter(D=>D.error).length;return s.jsx(lo,{open:t,onOpenChange:e,children:s.jsxs(qa,{className:"max-w-2xl max-h-[90vh]",children:[s.jsxs(xl,{children:[s.jsx(Xo,{children:"Import Transactions"}),s.jsx(wd,{children:"Upload a CSV file with your past transactions"})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg bg-muted/50",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:"Download Template"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Get a CSV template with the correct format"})]}),s.jsxs(Bt,{variant:"outline",onClick:v,children:[s.jsx(sc,{className:"h-4 w-4 mr-2"}),"Template"]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(Mr,{htmlFor:"csv-file",children:"Upload CSV File"}),s.jsx(Br,{id:"csv-file",type:"file",accept:".csv",onChange:E})]}),r.length>0&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(ss,{variant:"outline",children:[r.length," rows found"]}),P>0&&s.jsxs(ss,{className:"bg-green-500 text-white",children:[s.jsx(no,{className:"h-3 w-3 mr-1"}),P," valid"]}),R>0&&s.jsxs(ss,{variant:"destructive",children:[s.jsx(dme,{className:"h-3 w-3 mr-1"}),R," errors"]})]}),s.jsx(Lm,{className:"h-[200px] border rounded-lg",children:s.jsxs("div",{className:"p-2 space-y-2",children:[r.slice(0,10).map((D,M)=>s.jsxs("div",{className:`p-2 rounded text-sm ${D.error?"bg-destructive/10":"bg-muted/50"}`,children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"font-medium",children:D.property_address||"(no address)"}),s.jsx(ss,{variant:D.transaction_type==="buyer"?"default":"secondary",children:D.transaction_type})]}),s.jsxs("div",{className:"text-muted-foreground",children:[D.close_date," • $",D.sale_price.toLocaleString()]}),D.error&&s.jsx(Eje,{variant:"destructive",className:"mt-1 py-1",children:s.jsx(jje,{className:"text-xs",children:D.error})})]},M)),r.length>10&&s.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",r.length-10," more"]})]})}),i&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:s.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${c}%`}})}),s.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",c,"%"]})]})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[s.jsx(Bt,{variant:"outline",onClick:()=>e(!1),children:"Cancel"}),s.jsxs(Bt,{onClick:k,disabled:P===0||i,children:[s.jsx($U,{className:"h-4 w-4 mr-2"}),"Import ",P," Transaction",P!==1?"s":""]})]})]})]})})}const KNt=mg({transactions_goal:dA().min(0).optional(),volume_goal:dA().min(0).optional(),gci_goal:dA().min(0).optional()});function YNt({open:t,onOpenChange:e,year:r,existingGoals:n}){const i=nst(),{data:o}=cF(),c=(o==null?void 0:o.show_commission)??!0,a=M7({resolver:O7(KNt),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});C.useEffect(()=>{n?a.reset({transactions_goal:n.transactions_goal??void 0,volume_goal:n.volume_goal?Number(n.volume_goal):void 0,gci_goal:n.gci_goal?Number(n.gci_goal):void 0}):a.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[n,a,t]);const f=async p=>{await i.mutateAsync({year:r,transactions_goal:p.transactions_goal??null,volume_goal:p.volume_goal??null,gci_goal:c?p.gci_goal??null:null}),e(!1)};return s.jsx(lo,{open:t,onOpenChange:e,children:s.jsxs(qa,{className:"max-w-md",children:[s.jsxs(xl,{children:[s.jsxs(Xo,{children:[r," Goals"]}),s.jsx(wd,{children:"Set your annual targets to track your progress throughout the year."})]}),s.jsx(H7,{...a,children:s.jsxs("form",{onSubmit:a.handleSubmit(f),className:"space-y-4",children:[s.jsx(ll,{control:a.control,name:"transactions_goal",render:({field:p})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"Transactions Goal"}),s.jsx(Go,{children:s.jsx(Br,{type:"number",placeholder:"e.g., 24",...p,value:p.value??"",onChange:y=>p.onChange(y.target.value?Number(y.target.value):void 0)})}),s.jsx(NL,{children:"Total number of deals you want to close"}),s.jsx(lf,{})]})}),s.jsx(ll,{control:a.control,name:"volume_goal",render:({field:p})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"Volume Goal ($)"}),s.jsx(Go,{children:s.jsx(Br,{type:"number",placeholder:"e.g., 5000000",...p,value:p.value??"",onChange:y=>p.onChange(y.target.value?Number(y.target.value):void 0)})}),s.jsx(NL,{children:"Total sales volume you want to achieve"}),s.jsx(lf,{})]})}),c&&s.jsx(ll,{control:a.control,name:"gci_goal",render:({field:p})=>s.jsxs(Vo,{children:[s.jsx(qo,{children:"GCI Goal ($)"}),s.jsx(Go,{children:s.jsx(Br,{type:"number",placeholder:"e.g., 150000",...p,value:p.value??"",onChange:y=>p.onChange(y.target.value?Number(y.target.value):void 0)})}),s.jsx(NL,{children:"Gross commission income target"}),s.jsx(lf,{})]})}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(Bt,{type:"button",variant:"outline",onClick:()=>e(!1),children:"Cancel"}),s.jsx(Bt,{type:"submit",disabled:i.isPending,children:"Save Goals"})]})]})})]})})}function Aje({transactions:t,isLoading:e}){const r=C.useRef(null),n=C.useRef(null),i=C.useRef([]),o=C.useRef(null),{isAdmin:c}=Hn(),[a,f]=C.useState(""),[p,y]=C.useState(!0),[v,T]=C.useState(0),[E,k]=C.useState(!1),P=t.filter(D=>D.latitude!=null&&D.longitude!=null),R=t.filter(D=>D.latitude==null||D.longitude==null);return C.useEffect(()=>{(async()=>{y(!0);try{const{data:M}=await Re.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();M!=null&&M.value&&f(M.value)}catch(M){console.error("Error fetching mapbox token:",M)}y(!1)})()},[]),C.useEffect(()=>{if(!a||R.length===0||E)return;(async()=>{var B;k(!0);let M=0;for(const V of R){const G=[V.property_address,V.city,V.state,V.zip].filter(Boolean).join(", ");if(G)try{const Y=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(G)}.json?access_token=${a}&limit=1`)).json();if((B=Y.features)!=null&&B[0]){const[J,Q]=Y.features[0].center;await Re.from("scorecard_transactions").update({latitude:Q,longitude:J}).eq("id",V.id),V.latitude=Q,V.longitude=J,M++}}catch(W){console.error("Geocode error:",W)}}T(M),k(!1)})()},[a,t]),C.useEffect(()=>{if(!r.current||!a||n.current)return;th.accessToken=a;const D=t.filter(V=>V.latitude!=null&&V.longitude!=null);let M=[-98.5795,39.8283],B=4;if(D.length>0){const V=D.reduce((W,Y)=>W+Y.longitude,0)/D.length,G=D.reduce((W,Y)=>W+Y.latitude,0)/D.length;M=[V,G],B=D.length===1?12:10}return n.current=new th.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:B,center:M}),n.current.addControl(new th.NavigationControl,"top-right"),()=>{var V;(V=n.current)==null||V.remove(),n.current=null}},[a]),C.useEffect(()=>{var M;if(!n.current||!a)return;i.current.forEach(B=>B.remove()),i.current=[],(M=o.current)==null||M.remove();const D=t.filter(B=>B.latitude!=null&&B.longitude!=null);if(D.forEach(B=>{var Q;const V=B.transaction_type==="buyer",G=V?"#3B82F6":"#10B981",W=document.createElement("div");W.className="cursor-pointer",W.innerHTML=`
${V?'':''}
`;const Y=new th.Popup({offset:25,closeButton:!0}).setHTML(`
${B.property_address}
${B.city?`
${B.city}${B.state?", "+B.state:""} ${B.zip||""}
`:""}
${V?"Buyer":"Seller"} $${Number(B.sale_price).toLocaleString()}
Closed: ${gS(B.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(Q=B.lead_source)!=null&&Q.name?" · "+B.lead_source.name:""}
${B.contact?`
Client: ${B.contact.first_name} ${B.contact.last_name||""}
`:""}
`),J=new th.Marker(W).setLngLat([B.longitude,B.latitude]).setPopup(Y).addTo(n.current);i.current.push(J)}),D.length>1){const B=new th.LngLatBounds;D.forEach(V=>B.extend([V.longitude,V.latitude])),n.current.fitBounds(B,{padding:60,maxZoom:13})}else D.length===1&&n.current.flyTo({center:[D[0].longitude,D[0].latitude],zoom:12})},[t,a,E]),p||e?s.jsx($n,{children:s.jsx(Kn,{className:"flex items-center justify-center h-[50vh]",children:s.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):a?t.length===0?s.jsx($n,{children:s.jsxs(Kn,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[s.jsx(Es,{className:"h-12 w-12 text-muted-foreground"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold",children:"No Transactions Yet"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Add transactions to see them plotted on the map."})]})]})}):s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#3B82F6"}}),s.jsx("span",{children:"Buyer"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#10B981"}}),s.jsx("span",{children:"Seller"})]}),s.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[P.length," of ",t.length," mapped",E&&" · Geocoding..."]})]}),s.jsx("div",{ref:r,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):s.jsx($n,{children:s.jsxs(Kn,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[s.jsx(dme,{className:"h-12 w-12 text-muted-foreground"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:c?"Set up your Mapbox token in the Popby Map to enable maps across the platform.":"The map feature has not been configured yet. Please contact your administrator."})]})]})})}const kje=()=>{const{data:t}=hT();return mr({queryKey:["team-scorecard-members",t==null?void 0:t.teamId],queryFn:async()=>{const{data:e,error:r}=await Re.from("team_members").select("user_id").eq("team_id",t.teamId);if(r)throw r;const n=e.map(c=>c.user_id),{data:i,error:o}=await Re.from("profiles").select("id, name, email, avatar_url").in("id",n);if(o)throw o;return i||[]},enabled:!!(t!=null&&t.teamId)&&(t==null?void 0:t.role)==="team_leader"})},ZNt=t=>{const{data:e}=hT(),{data:r}=kje();return mr({queryKey:["team-scorecard-transactions",e==null?void 0:e.teamId,t],queryFn:async()=>{const n=r.map(a=>a.id);let i=Re.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).in("owner_user_id",n).order("close_date",{ascending:!1});t&&(i=i.gte("close_date",`${t}-01-01`).lte("close_date",`${t}-12-31`));const{data:o,error:c}=await i;if(c)throw c;return o},enabled:!!r&&r.length>0})};function XNt(t,e){const r=e.filter(o=>o.owner_user_id===t.id),n=r.reduce((o,c)=>o+Number(c.sale_price),0),i=r.reduce((o,c)=>o+(Number(c.commission_amount)||0),0);return{member:t,totalTransactions:r.length,buyerCount:r.filter(o=>o.transaction_type==="buyer").length,sellerCount:r.filter(o=>o.transaction_type==="seller").length,totalVolume:n,averagePrice:r.length>0?n/r.length:0,totalGCI:i}}function QNt(t,e){return t?t.split(" ").map(r=>r[0]).join("").toUpperCase().slice(0,2):e[0].toUpperCase()}function JNt({year:t}){var T;const{data:e,isLoading:r}=kje(),{data:n,isLoading:i}=ZNt(t),o=Hs(),c=r||i,{aggregate:a,memberStats:f,topPerformer:p,agentNameMap:y,teamChartStats:v}=C.useMemo(()=>{if(!e||!n)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const E=e.map(ee=>XNt(ee,n));E.sort((ee,le)=>le.totalVolume-ee.totalVolume);const k={};e.forEach(ee=>{k[ee.id]=ee.name||ee.email});const P=n.length,R=n.reduce((ee,le)=>ee+Number(le.sale_price),0),D=n.reduce((ee,le)=>ee+(Number(le.commission_amount)||0),0),M=n.filter(ee=>ee.transaction_type==="buyer").length,B=n.filter(ee=>ee.transaction_type==="seller").length,V={};n.forEach(ee=>{var pe;const le=((pe=ee.lead_source)==null?void 0:pe.name)||"Unknown";V[le]=(V[le]||0)+1});const G=Object.entries(V).sort((ee,le)=>le[1]-ee[1])[0],W={};n.forEach(ee=>{const le=gS(ee.close_date).toLocaleString("default",{month:"short"});W[le]=(W[le]||0)+1});const J=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(ee=>({month:ee,count:W[ee]||0})),Q=Object.entries(V).map(([ee,le])=>({name:ee,count:le})).sort((ee,le)=>le.count-ee.count);return{aggregate:{totalTxns:P,buyerCount:M,sellerCount:B,totalVolume:R,avgPrice:P>0?R/P:0,totalGCI:D,topSource:G?{name:G[0],count:G[1]}:null,memberCount:e.length},memberStats:E,topPerformer:E[0]||null,agentNameMap:k,teamChartStats:{transactionsByMonth:J,leadSourceBreakdown:Q}}},[e,n]);return c?s.jsxs("div",{className:"space-y-6",children:[s.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(E=>s.jsx(ml,{className:"h-24"},E))}),s.jsx(ml,{className:"h-64"})]}):!a||f.length===0?s.jsx($n,{className:"py-12",children:s.jsxs(Kn,{className:"text-center space-y-2",children:[s.jsx(fl,{className:"h-10 w-10 mx-auto text-muted-foreground"}),s.jsx("h3",{className:"text-lg font-semibold",children:"No Team Data"}),s.jsxs("p",{className:"text-muted-foreground",children:["No scorecard transactions found for your team members in ",t,"."]})]})}):s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:[s.jsx($n,{children:s.jsxs(Kn,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(fl,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Members"})]}),s.jsx("p",{className:"text-2xl font-bold",children:a.memberCount})]})}),s.jsx($n,{children:s.jsxs(Kn,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(va,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Team Transactions"})]}),s.jsx("p",{className:"text-2xl font-bold",children:a.totalTxns}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[a.buyerCount,"B / ",a.sellerCount,"S"]})]})}),s.jsx($n,{children:s.jsxs(Kn,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx($p,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Team Volume"})]}),s.jsx("p",{className:"text-2xl font-bold",children:$a(a.totalVolume,!0)})]})}),s.jsx($n,{children:s.jsxs(Kn,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(Nx,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),s.jsx("p",{className:"text-2xl font-bold",children:$a(a.avgPrice,!0)})]})}),s.jsx($n,{children:s.jsxs(Kn,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx($p,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Team GCI"})]}),s.jsx("p",{className:"text-2xl font-bold",children:$a(a.totalGCI,!0)})]})}),s.jsx($n,{children:s.jsxs(Kn,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(f1,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),s.jsx("p",{className:"text-lg font-bold truncate",children:((T=a.topSource)==null?void 0:T.name)||"-"}),a.topSource&&s.jsxs("p",{className:"text-xs text-muted-foreground",children:[a.topSource.count," deals"]})]})})]}),p&&p.totalTransactions>0&&s.jsx($n,{className:"border-primary/30 bg-primary/5",children:s.jsxs(Kn,{className:"pt-4 flex items-center gap-4",children:[s.jsx("div",{className:"flex items-center justify-center h-10 w-10 rounded-full bg-primary/10",children:s.jsx(ND,{className:"h-5 w-5 text-primary"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("p",{className:"text-sm font-medium text-muted-foreground",children:["Top Performer — ",t]}),s.jsx("p",{className:"text-lg font-bold",children:p.member.name||p.member.email})]}),s.jsxs("div",{className:"text-right",children:[s.jsxs("p",{className:"text-sm text-muted-foreground",children:[p.totalTransactions," deals"]}),s.jsx("p",{className:"font-semibold",children:$a(p.totalVolume,!0)})]})]})}),s.jsxs($n,{children:[s.jsx(ud,{children:s.jsx(dd,{className:"text-lg",children:"Member Performance"})}),s.jsx(Kn,{children:s.jsx("div",{className:"overflow-x-auto",children:s.jsxs(XH,{children:[s.jsx(QH,{children:s.jsxs(vk,{children:[s.jsx(Yl,{children:"Agent"}),s.jsx(Yl,{className:"text-center",children:"Transactions"}),s.jsx(Yl,{className:"text-center",children:"B / S"}),s.jsx(Yl,{className:"text-right",children:"Volume"}),s.jsx(Yl,{className:"text-right",children:"Avg Price"}),s.jsx(Yl,{className:"text-right",children:"GCI"}),s.jsx(Yl,{className:"text-right"})]})}),s.jsx(JH,{children:f.map((E,k)=>s.jsxs(vk,{children:[s.jsx(Zl,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("div",{className:"relative",children:[k===0&&E.totalTransactions>0&&s.jsx(ND,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),s.jsxs(vd,{className:"h-8 w-8",children:[s.jsx(_d,{src:E.member.avatar_url||void 0}),s.jsx(bd,{className:"text-xs",children:QNt(E.member.name,E.member.email)})]})]}),s.jsxs("div",{children:[s.jsx("p",{className:"font-medium text-sm",children:E.member.name||E.member.email}),E.member.name&&s.jsx("p",{className:"text-xs text-muted-foreground",children:E.member.email})]})]})}),s.jsx(Zl,{className:"text-center font-semibold",children:E.totalTransactions}),s.jsxs(Zl,{className:"text-center text-sm",children:[E.buyerCount," / ",E.sellerCount]}),s.jsx(Zl,{className:"text-right font-medium",children:$a(E.totalVolume,!0)}),s.jsx(Zl,{className:"text-right text-sm",children:$a(E.averagePrice,!0)}),s.jsx(Zl,{className:"text-right font-medium",children:$a(E.totalGCI,!0)}),s.jsx(Zl,{className:"text-right",children:s.jsx(Bt,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/scorecard/${E.member.id}`),children:s.jsx(KO,{className:"h-4 w-4"})})})]},E.member.id))})]})})})]}),s.jsxs(dH,{defaultValue:"transactions",className:"space-y-4",children:[s.jsxs(Y3,{children:[s.jsxs(zp,{value:"transactions",children:[s.jsx(FU,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),s.jsxs(zp,{value:"charts",children:[s.jsx(HA,{className:"h-4 w-4 mr-1"}),"Charts"]}),s.jsxs(zp,{value:"map",children:[s.jsx(Es,{className:"h-4 w-4 mr-1"}),"Map"]})]}),s.jsx(ix,{value:"transactions",children:s.jsx(R1e,{transactions:n||[],showCommission:!0,isLoading:i,agentNameMap:y,readOnly:!0})}),s.jsx(ix,{value:"charts",children:v&&s.jsx(Tje,{stats:v,year:t})}),s.jsx(ix,{value:"map",children:s.jsx(Aje,{transactions:n||[],isLoading:i})})]})]})}const GL=new Date().getFullYear(),Ble=Array.from({length:10},(t,e)=>GL-e),UR="all";function eIt(){var pe;const[t,e]=C.useState(GL),r=t===null?UR:String(t),n=Se=>e(Se===UR?null:Number(Se)),[i,o]=C.useState(!1),[c,a]=C.useState(!1),[f,p]=C.useState(!1),[y,v]=C.useState(!1),[T,E]=C.useState("my"),{data:k}=hT(),P=(k==null?void 0:k.role)==="team_leader",{data:R,isLoading:D}=p1e(t??void 0),{yearStats:M,lifetimeStats:B,isLoading:V,showCommission:G}=sst(t??void 0),{data:W,isLoading:Y}=rst(t??GL),{data:J}=cF(),Q=ist(),ee=()=>{if(!R||R.length===0)return;const Se=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...G?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],je=R.map(Te=>{var Ne,Ee;return[Te.property_address,Te.city||"",Te.state||"",Te.zip||"",Te.transaction_type,Te.close_date,Te.sale_price,...G?[Te.commission_amount||""]:[],((Ne=Te.lead_source)==null?void 0:Ne.name)||"",((Ee=Te.client_type)==null?void 0:Ee.name)||"",Te.contact?`${Te.contact.first_name} ${Te.contact.last_name||""}`.trim():"",Te.is_win?"Yes":"No",Te.notes||""]}),Le=[Se,...je].map(Te=>Te.map(Ne=>`"${String(Ne).replace(/"/g,'""')}"`).join(",")).join(` `),Ae=new Blob([Le],{type:"text/csv"}),be=URL.createObjectURL(Ae),me=document.createElement("a");me.href=be,me.download=t===null?"transactions-all.csv":`transactions-${t}.csv`,me.click(),URL.revokeObjectURL(be)},le=!R||R.length===0;return s.jsxs(hS,{title:"Scorecard",children:[s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Scorecard"}),s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500/50 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),P&&s.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[s.jsx(Bt,{variant:T==="my"?"default":"ghost",size:"sm",onClick:()=>E("my"),className:"h-8",children:"My Scorecard"}),s.jsxs(Bt,{variant:T==="team"?"default":"ghost",size:"sm",onClick:()=>E("team"),className:"h-8",children:[s.jsx(fl,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),T==="team"&&P?s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Team Performance"}),s.jsx("p",{className:"text-muted-foreground text-sm",children:"Aggregate stats and member comparison"})]}),s.jsxs(ba,{value:r,onValueChange:n,children:[s.jsx(oa,{className:"w-[140px]",children:s.jsx(wa,{})}),s.jsxs(la,{children:[s.jsx(mn,{value:UR,children:"All Years"}),Ble.map(Se=>s.jsx(mn,{value:String(Se),children:Se},Se))]})]})]}),s.jsx(JNt,{year:t??void 0})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Business Scorecard"}),s.jsx("p",{className:"text-muted-foreground",children:"Track your transactions, goals, and performance"})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(ba,{value:r,onValueChange:n,children:[s.jsx(oa,{className:"w-[140px]",children:s.jsx(wa,{})}),s.jsxs(la,{children:[s.jsx(mn,{value:UR,children:"All Years"}),Ble.map(Se=>s.jsx(mn,{value:String(Se),children:Se},Se))]})]}),s.jsx(Bt,{variant:"outline",size:"icon",onClick:()=>v(!y),children:s.jsx(A9,{className:"h-4 w-4"})})]})]}),y&&s.jsxs($n,{children:[s.jsx(ud,{className:"pb-3",children:s.jsx(dd,{className:"text-lg",children:"Settings"})}),s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsx(Mr,{children:"Show Commission"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),s.jsx(gT,{checked:(J==null?void 0:J.show_commission)??!0,onCheckedChange:Se=>Q.mutate({show_commission:Se})})]})})]}),le&&!D?s.jsx($n,{className:"py-12",children:s.jsxs(Kn,{className:"text-center space-y-4",children:[s.jsx("div",{className:"w-16 h-16 mx-auto rounded-full bg-primary/10 flex items-center justify-center",children:s.jsx(HA,{className:"h-8 w-8 text-primary"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-lg font-semibold",children:"Start Tracking Your Success"}),s.jsx("p",{className:"text-muted-foreground max-w-md mx-auto mt-1",children:"Add your past transactions to see your performance metrics, track your goals, and celebrate your wins."})]}),s.jsxs("div",{className:"flex flex-wrap justify-center gap-2 pt-2",children:[s.jsxs(Bt,{onClick:()=>o(!0),children:[s.jsx(gm,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),s.jsxs(Bt,{variant:"outline",onClick:()=>a(!0),children:[s.jsx($U,{className:"h-4 w-4 mr-2"}),"Import CSV"]})]}),s.jsxs("div",{className:"pt-4 border-t mt-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Need help formatting your data?"}),s.jsx(Bt,{variant:"link",className:"h-auto p-0",asChild:!0,children:s.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[s.jsx(sc,{className:"h-4 w-4 mr-2"}),"Download CSV Template"]})})]})]})}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs(Bt,{onClick:()=>o(!0),children:[s.jsx(gm,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),s.jsxs(Bt,{variant:"outline",onClick:()=>p(!0),children:[s.jsx(TC,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),s.jsxs(Bt,{variant:"outline",onClick:()=>a(!0),children:[s.jsx($U,{className:"h-4 w-4 mr-2"}),"Import"]}),s.jsxs(Bt,{variant:"outline",onClick:ee,disabled:le,children:[s.jsx(sc,{className:"h-4 w-4 mr-2"}),"Export"]}),s.jsx(Bt,{variant:"ghost",size:"sm",asChild:!0,children:s.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[s.jsx(sc,{className:"h-4 w-4 mr-2"}),"CSV Template"]})})]}),s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[s.jsx($n,{children:s.jsxs(Kn,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(va,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),s.jsx("p",{className:"text-2xl font-bold",children:M.totalTransactions}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[B.totalTransactions," lifetime"]})]})}),s.jsx($n,{children:s.jsxs(Kn,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(fl,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),s.jsxs("p",{className:"text-2xl font-bold",children:[M.buyerCount,"/",M.sellerCount]}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),s.jsx($n,{children:s.jsxs(Kn,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx($p,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),s.jsx("p",{className:"text-2xl font-bold",children:$a(M.totalVolume,!0)}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[$a(B.totalVolume,!0)," lifetime"]})]})}),s.jsx($n,{children:s.jsxs(Kn,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(Nx,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),s.jsx("p",{className:"text-2xl font-bold",children:$a(M.averagePrice,!0)})]})}),s.jsx($n,{children:s.jsxs(Kn,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(f1,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),s.jsx("p",{className:"text-lg font-bold truncate",children:((pe=M.topLeadSource)==null?void 0:pe.name)||"-"}),M.topLeadSource&&s.jsxs("p",{className:"text-xs text-muted-foreground",children:[M.topLeadSource.count," deals"]})]})}),G&&s.jsx($n,{children:s.jsxs(Kn,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx($p,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),s.jsx("p",{className:"text-2xl font-bold",children:$a(M.totalCommission,!0)}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[$a(B.totalCommission,!0)," lifetime"]})]})}),G&&M.totalNetToAgent>0&&M.totalNetToAgent!==M.totalCommission&&s.jsx($n,{children:s.jsxs(Kn,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-teal-600 dark:text-teal-400 mb-1",children:[s.jsx($p,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Net to Agent"})]}),s.jsx("p",{className:"text-2xl font-bold text-teal-600 dark:text-teal-400",children:$a(M.totalNetToAgent,!0)}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[$a(B.totalNetToAgent,!0)," lifetime"]})]})})]}),t!==null&&W&&s.jsx(Cst,{goals:W,stats:M,year:t,showCommission:G}),s.jsxs(dH,{defaultValue:"transactions",className:"space-y-4",children:[s.jsxs(Y3,{children:[s.jsx(zp,{value:"transactions",children:"Transactions"}),s.jsx(zp,{value:"charts",children:"Charts"}),s.jsxs(zp,{value:"map",children:[s.jsx(Es,{className:"h-4 w-4 mr-1"}),"Map"]})]}),s.jsx(ix,{value:"transactions",children:s.jsx(R1e,{transactions:R||[],showCommission:G,isLoading:D})}),s.jsx(ix,{value:"charts",children:s.jsx(Tje,{stats:M,year:t??void 0})}),s.jsx(ix,{value:"map",children:s.jsx(Aje,{transactions:R||[],isLoading:D})})]})]})]})]}),s.jsx(P1e,{open:i,onOpenChange:o}),s.jsx(WNt,{open:c,onOpenChange:a}),s.jsx(YNt,{open:f,onOpenChange:p,year:t??GL,existingGoals:W})]})}function tIt(){const t=Li();return mr({queryKey:["deal-tasks",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Re.from("deal_tasks").select(` *, deal:deal_pipeline(id, deal_name, stage_id), contact:innercircle_contacts(id, first_name, last_name, phone, email), stage:deal_pipeline_stages(id, name, color) `).or(`owner_user_id.eq.${t},assignee_user_id.eq.${t}`).order("sort_order",{ascending:!0});if(r)throw r;return e},enabled:!!t})}function B7t(t){const e=Li();return mr({queryKey:["deal-tasks","deal",t,e],queryFn:async()=>{if(!e||!t)return[];const{data:r,error:n}=await Re.from("deal_tasks").select(` *, stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",e).eq("deal_id",t).order("sort_order",{ascending:!0});if(n)throw n;return r},enabled:!!e&&!!t})}function Cje(){const t=Li(),e=Ar();return Sr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Re.from("deal_tasks").insert({owner_user_id:t,title:r.title,description:r.description||null,deal_id:r.deal_id||null,contact_id:r.contact_id||null,stage_id:r.stage_id||null,priority:r.priority||"medium",status:r.status||"todo",due_date:r.due_date||null,sort_order:r.sort_order||0,assignee_user_id:r.assignee_user_id||null,assigned_by_user_id:r.assignee_user_id?t:null}).select().single();if(i)throw i;return n},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-tasks"]})}})}function rIt(){const t=Ar();return Sr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Re.from("deal_tasks").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-tasks"]}),r.status==="done"&&$x("task_completed")}})}function nIt(){const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("deal_tasks").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}function cK(){const t=Ar();return Sr({mutationFn:async({id:e,status:r})=>{const{data:n,error:i}=await Re.from("deal_tasks").update({status:r,completed_at:r==="done"?new Date().toISOString():null}).eq("id",e).select().single();if(i)throw i;return n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-tasks"]}),r.status==="done"&&$x("task_completed")}})}function $7t(){const t=Ar();return Sr({mutationFn:async e=>{if(e.length===0)return;const{error:r}=await Re.from("deal_tasks").update({status:"done",completed_at:new Date().toISOString()}).in("id",e);if(r)throw r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-tasks"]}),r.length>0&&$x("task_completed")}})}function iIt(t){const e=Li();return mr({queryKey:["deal-task-templates",e,t],queryFn:async()=>{if(!e)return[];let r=Re.from("deal_task_templates").select("*").eq("owner_user_id",e).order("sort_order",{ascending:!0});t&&(r=r.eq("stage_id",t));const{data:n,error:i}=await r;if(i)throw i;return n},enabled:!!e})}function sIt(){const t=Li(),e=Ar();return Sr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Re.from("deal_task_templates").insert({owner_user_id:t,stage_id:r.stage_id,title:r.title,description:r.description||null,priority:r.priority||"medium",default_due_offset_days:r.default_due_offset_days||null,sort_order:r.sort_order||0}).select().single();if(i)throw i;return n},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-task-templates"]})}})}function aIt(){const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("deal_task_templates").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function z7t(){const t=Li(),e=Ar();return Sr({mutationFn:async({dealId:r,stageId:n})=>{if(!t)throw new Error("Not authenticated");const{data:i,error:o}=await Re.from("deal_task_templates").select("*").eq("owner_user_id",t).eq("stage_id",n).order("sort_order");if(o)throw o;if(!i||i.length===0)return[];const{data:c}=await Re.from("deal_tasks").select("title, stage_id").eq("deal_id",r).eq("stage_id",n),a=new Set((c||[]).map(v=>v.title)),f=i.filter(v=>!a.has(v.title)).map((v,T)=>({owner_user_id:t,deal_id:r,stage_id:n,title:v.title,description:v.description,priority:v.priority,due_date:v.default_due_offset_days?new Date(Date.now()+v.default_due_offset_days*864e5).toISOString().split("T")[0]:null,sort_order:T,status:"todo"}));if(f.length===0)return[];const{data:p,error:y}=await Re.from("deal_tasks").insert(f).select();if(y)throw y;return p},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-tasks"]})}})}function oIt(){const t=Ar();return Sr({mutationFn:async({ids:e,due_date:r})=>{if(!e.length)return;const{error:n}=await Re.from("deal_tasks").update({due_date:r}).in("id",e);if(n)throw n},onSuccess:()=>t.invalidateQueries({queryKey:["deal-tasks"]})})}function U7t(t,e=!0){return mr({queryKey:["deal-tasks","team",t],enabled:!!t&&e,queryFn:async()=>{const{data:r,error:n}=await Re.rpc("get_team_tasks",{_team_id:t});if(n)throw n;return r||[]}})}function T2(t){const e=t.expected_commission,r=Number(t.bonus_amount)||0;if(!e)return r>0?r:null;if((t.commission_calc_method||"standard")==="referral_first"){let o=e;t.referral_fee_pct&&(o-=e*(t.referral_fee_pct/100));let c=o;return t.brokerage_split_pct&&(c-=o*(t.brokerage_split_pct/100)),t.team_split_pct&&(c-=e*(t.team_split_pct/100)),t.franchise_fee_pct&&(c-=e*(t.franchise_fee_pct/100)),t.transaction_fee&&(c-=t.transaction_fee),Math.max(0,c)+r}let i=e;return t.brokerage_split_pct&&(i-=e*(t.brokerage_split_pct/100)),t.team_split_pct&&(i-=e*(t.team_split_pct/100)),t.franchise_fee_pct&&(i-=e*(t.franchise_fee_pct/100)),t.referral_fee_pct&&(i-=e*(t.referral_fee_pct/100)),t.transaction_fee&&(i-=t.transaction_fee),Math.max(0,i)+r}function lIt(){const t=Li();return mr({queryKey:["deal-pipeline-stages",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Re.from("deal_pipeline_stages").select("*").eq("owner_user_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e},enabled:!!t})}function V7t(){const t=Li(),e=Ar();return Sr({mutationFn:async()=>{if(!t)throw new Error("Not authenticated");const{error:r}=await Re.rpc("initialize_deal_pipeline_stages",{p_user_id:t});if(r)throw r},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function cIt(){const t=Li();return mr({queryKey:["deal-pipeline-deals",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Re.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at) `).eq("owner_user_id",t).order("updated_at",{ascending:!1});if(r)throw r;return e},enabled:!!t})}function q7t(){const t=Li(),e=Ar();return Sr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");if(!r.deal_name||!r.deal_type)throw new Error("Deal name and type are required");const{data:n,error:i}=await Re.from("deal_pipeline").insert({deal_name:r.deal_name,deal_type:r.deal_type,stage_id:r.stage_id||null,contact_id:r.contact_id||null,listing_id:r.listing_id||null,property_address:r.property_address||null,city:r.city||null,state:r.state||null,zip_code:r.zip_code||null,expected_price:r.expected_price||null,expected_commission:r.expected_commission??null,commission_percentage:r.commission_percentage===void 0?3:r.commission_percentage,brokerage_split_pct:r.brokerage_split_pct??null,team_split_pct:r.team_split_pct??null,referral_fee_pct:r.referral_fee_pct??null,franchise_fee_pct:r.franchise_fee_pct??null,transaction_fee:r.transaction_fee??null,bonus_amount:r.bonus_amount??null,commission_calc_method:r.commission_calc_method??"standard",target_close_date:r.target_close_date||null,contract_date:r.contract_date||null,listing_date:r.listing_date||null,priority:r.priority||"medium",probability:r.probability||50,notes:r.notes||null,owner_user_id:t}).select().single();if(i)throw i;return await Re.from("deal_activities").insert([{deal_id:n.id,activity_type:"system",title:"Deal created",description:`Deal "${r.deal_name}" was created`}]),n},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-pipeline-deals"]}),e.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function G7t(){const t=Ar();return Sr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Re.from("deal_pipeline").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function H7t(){const t=Ar();return Sr({mutationFn:async({dealId:e,stageId:r,stageName:n})=>{const{data:i}=await Re.from("deal_pipeline_stages").select("default_probability").eq("id",r).maybeSingle(),o={stage_id:r};typeof(i==null?void 0:i.default_probability)=="number"&&(o.probability=i.default_probability);const{data:c,error:a}=await Re.from("deal_pipeline").update(o).eq("id",e).select().single();if(a)throw a;return await Re.from("deal_activities").insert({deal_id:e,activity_type:"stage_change",title:`Moved to ${n}`,metadata:{new_stage_id:r,new_stage_name:n}}),c},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-activities"]})}})}function W7t(){const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("deal_pipeline").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function K7t(t){return mr({queryKey:["deal-activities",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("deal_activities").select("*").eq("deal_id",t).order("created_at",{ascending:!1});if(r)throw r;return e},enabled:!!t})}function Y7t(){const t=Ar();return Sr({mutationFn:async e=>{const{data:r,error:n}=await Re.from("deal_activities").insert([{deal_id:e.deal_id,activity_type:e.activity_type,title:e.title,description:e.description||null}]).select().single();if(n)throw n;return r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-activities",r.deal_id]})}})}function Z7t(t){return mr({queryKey:["deal-checklist",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("deal_checklist_items").select("*").eq("deal_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e},enabled:!!t})}function X7t(){const t=Ar();return Sr({mutationFn:async({id:e,is_completed:r,deal_id:n})=>{const{data:i,error:o}=await Re.from("deal_checklist_items").update({is_completed:r,completed_at:r?new Date().toISOString():null}).eq("id",e).select().single();if(o)throw o;return i},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-checklist",r.deal_id]})}})}function Q7t(){const t=Ar();return Sr({mutationFn:async e=>{const{data:r,error:n}=await Re.from("deal_checklist_items").insert([{deal_id:e.deal_id,title:e.title,description:e.description||null,due_date:e.due_date||null,sort_order:e.sort_order||0}]).select().single();if(n)throw n;return r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-checklist",r.deal_id]})}})}function J7t(){const t=Li();return mr({queryKey:["deal-pipeline-stats",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Re.from("deal_pipeline").select("*, deal_pipeline_stages(name, is_won_stage, is_lost_stage)").eq("owner_user_id",t);if(r)throw r;const n=(e==null?void 0:e.filter(a=>{var f,p,y;return!((f=a.deal_pipeline_stages)!=null&&f.is_won_stage)&&!((p=a.deal_pipeline_stages)!=null&&p.is_lost_stage)&&((y=a.deal_pipeline_stages)==null?void 0:y.name)!=="Cancelled"}))||[],i=(e==null?void 0:e.filter(a=>{var f;return(f=a.deal_pipeline_stages)==null?void 0:f.is_won_stage}))||[],o=new Date().getFullYear(),c=i.filter(a=>{const f=a.actual_close_date;return f?new Date(f).getFullYear()===o:!0});return{totalDeals:(e==null?void 0:e.length)||0,activeDeals:n.length,wonDeals:i.length,pipelineValue:n.reduce((a,f)=>a+(f.expected_price||0),0),expectedCommission:n.reduce((a,f)=>a+(f.expected_commission||0)+(f.bonus_amount||0),0),expectedNetToAgent:n.reduce((a,f)=>a+(T2(f)||0),0),wonValue:i.reduce((a,f)=>a+(f.expected_price||0),0),weightedGCI:n.reduce((a,f)=>{const p=(f.probability??50)/100;return a+((f.expected_commission||0)+(f.bonus_amount||0))*p},0),weightedNet:n.reduce((a,f)=>{const p=(f.probability??50)/100;return a+(T2(f)||0)*p},0),ytdWonDeals:c.length,ytdWonGCI:c.reduce((a,f)=>a+(f.expected_commission||0)+(f.bonus_amount||0),0),ytdWonNet:c.reduce((a,f)=>a+(T2(f)||0),0),projectedAnnualNet:c.reduce((a,f)=>a+(T2(f)||0),0)+n.reduce((a,f)=>{const p=(f.probability??50)/100;return a+(T2(f)||0)*p},0)}},enabled:!!t})}function eHt(t){const e=Li();return mr({queryKey:["deal-by-listing",t,e],queryFn:async()=>{if(!e||!t)return null;const{data:r,error:n}=await Re.from("deal_pipeline").select(` *, deal_pipeline_stages(id, name, color) `).eq("owner_user_id",e).eq("listing_id",t).maybeSingle();if(n)throw n;return r},enabled:!!e&&!!t})}function tHt(){const t=Ar();return Sr({mutationFn:async({dealId:e,listingId:r})=>{const{data:n,error:i}=await Re.from("deal_pipeline").update({listing_id:r}).eq("id",e).select().single();if(i)throw i;return await Re.from("deal_activities").insert({deal_id:e,activity_type:"system",title:"Linked to Listing Exchange",description:"This deal is now synced with Listing Exchange",metadata:{listing_id:r}}),n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-by-listing",r.listingId]})}})}function rHt(){const t=Ar();return Sr({mutationFn:async({dealId:e,listingId:r})=>{const{data:n,error:i}=await Re.from("deal_pipeline").update({listing_id:null}).eq("id",e).select().single();if(i)throw i;return{data:n,listingId:r}},onSuccess:e=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-by-listing",e.listingId]})}})}function Nje(){const t=Li();return mr({queryKey:["drip-task-assignees",t],enabled:!!t,staleTime:5*6e4,queryFn:async()=>{const{data:e}=await Re.from("team_members").select("team_id").eq("user_id",t),r=(e||[]).map(p=>p.team_id);if(!r.length)return[];const[{data:n},{data:i}]=await Promise.all([Re.from("team_members").select("user_id, team_id").in("team_id",r),Re.from("teams").select("id, name").in("id",r)]),o=new Map((i||[]).map(p=>[p.id,p.name])),c=[...new Set((n||[]).map(p=>p.user_id).filter(p=>p!==t))];if(!c.length)return[];const{data:a}=await Re.from("profiles").select("id, name, email, avatar_url").in("id",c),f=new Map((a||[]).map(p=>[p.id,p]));return c.map(p=>{const y=f.get(p),v=(n||[]).find(T=>T.user_id===p);return{id:p,name:(y==null?void 0:y.name)||(y==null?void 0:y.email)||"Teammate",avatar_url:y==null?void 0:y.avatar_url,teamName:o.get(v==null?void 0:v.team_id)}}).sort((p,y)=>p.name.localeCompare(y.name))}})}var hi=function(){return hi=Object.assign||function(e){for(var r,n=1,i=arguments.length;n1&&(f||!p),v=e>1&&(p||!f),T=function(){n&&o(n)},E=function(){i&&o(i)};return s.jsx(UIt,{displayMonth:t.displayMonth,hideNext:y,hidePrevious:v,nextMonth:i,previousMonth:n,onPreviousClick:T,onNextClick:E})}function VIt(t){var e,r=Sa(),n=r.classNames,i=r.disableNavigation,o=r.styles,c=r.captionLayout,a=r.components,f=(e=a==null?void 0:a.CaptionLabel)!==null&&e!==void 0?e:Rje,p;return i?p=s.jsx(f,{id:t.id,displayMonth:t.displayMonth}):c==="dropdown"?p=s.jsx($le,{displayMonth:t.displayMonth,id:t.id}):c==="dropdown-buttons"?p=s.jsxs(s.Fragment,{children:[s.jsx($le,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),s.jsx(zle,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id})]}):p=s.jsxs(s.Fragment,{children:[s.jsx(f,{id:t.id,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),s.jsx(zle,{displayMonth:t.displayMonth,id:t.id})]}),s.jsx("div",{className:n.caption,style:o.caption,children:p})}function qIt(t){var e=Sa(),r=e.footer,n=e.styles,i=e.classNames.tfoot;return r?s.jsx("tfoot",{className:i,style:n.tfoot,children:s.jsx("tr",{children:s.jsx("td",{colSpan:8,children:r})})}):s.jsx(s.Fragment,{})}function GIt(t,e,r){for(var n=r?ng(new Date):jc(new Date,{locale:t,weekStartsOn:e}),i=[],o=0;o<7;o++){var c=Rl(n,o);i.push(c)}return i}function HIt(){var t=Sa(),e=t.classNames,r=t.styles,n=t.showWeekNumber,i=t.locale,o=t.weekStartsOn,c=t.ISOWeek,a=t.formatters.formatWeekdayName,f=t.labels.labelWeekday,p=GIt(i,o,c);return s.jsxs("tr",{style:r.head_row,className:e.head_row,children:[n&&s.jsx("td",{style:r.head_cell,className:e.head_cell}),p.map(function(y,v){return s.jsx("th",{scope:"col",className:e.head_cell,style:r.head_cell,"aria-label":f(y,{locale:i}),children:a(y,{locale:i})},v)})]})}function WIt(){var t,e=Sa(),r=e.classNames,n=e.styles,i=e.components,o=(t=i==null?void 0:i.HeadRow)!==null&&t!==void 0?t:HIt;return s.jsx("thead",{style:n.head,className:r.head,children:s.jsx(o,{})})}function KIt(t){var e=Sa(),r=e.locale,n=e.formatters.formatDay;return s.jsx(s.Fragment,{children:n(t.date,{locale:r})})}var uK=C.createContext(void 0);function YIt(t){if(!lN(t.initialProps)){var e={selected:void 0,modifiers:{disabled:[]}};return s.jsx(uK.Provider,{value:e,children:t.children})}return s.jsx(ZIt,{initialProps:t.initialProps,children:t.children})}function ZIt(t){var e=t.initialProps,r=t.children,n=e.selected,i=e.min,o=e.max,c=function(p,y,v){var T,E;(T=e.onDayClick)===null||T===void 0||T.call(e,p,y,v);var k=!!(y.selected&&i&&(n==null?void 0:n.length)===i);if(!k){var P=!!(!y.selected&&o&&(n==null?void 0:n.length)===o);if(!P){var R=n?Ije([],n):[];if(y.selected){var D=R.findIndex(function(M){return rc(p,M)});R.splice(D,1)}else R.push(p);(E=e.onSelect)===null||E===void 0||E.call(e,R,p,y,v)}}},a={disabled:[]};n&&a.disabled.push(function(p){var y=o&&n.length>o-1,v=n.some(function(T){return rc(T,p)});return!!(y&&!v)});var f={selected:n,onDayClick:c,modifiers:a};return s.jsx(uK.Provider,{value:f,children:r})}function dK(){var t=C.useContext(uK);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function XIt(t,e){var r=e||{},n=r.from,i=r.to;return n&&i?rc(i,t)&&rc(n,t)?void 0:rc(i,t)?{from:i,to:void 0}:rc(n,t)?void 0:ck(n,t)?{from:t,to:i}:{from:n,to:t}:i?ck(t,i)?{from:i,to:t}:{from:t,to:i}:n?rH(t,n)?{from:t,to:n}:{from:n,to:t}:{from:t,to:void 0}}var hK=C.createContext(void 0);function QIt(t){if(!cN(t.initialProps)){var e={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return s.jsx(hK.Provider,{value:e,children:t.children})}return s.jsx(JIt,{initialProps:t.initialProps,children:t.children})}function JIt(t){var e=t.initialProps,r=t.children,n=e.selected,i=n||{},o=i.from,c=i.to,a=e.min,f=e.max,p=function(E,k,P){var R,D;(R=e.onDayClick)===null||R===void 0||R.call(e,E,k,P);var M=XIt(E,n);(D=e.onSelect)===null||D===void 0||D.call(e,M,E,k,P)},y={range_start:[],range_end:[],range_middle:[],disabled:[]};if(o?(y.range_start=[o],c?(y.range_end=[c],rc(o,c)||(y.range_middle=[{after:o,before:c}])):y.range_end=[o]):c&&(y.range_start=[c],y.range_end=[c]),a&&(o&&!c&&y.disabled.push({after:V$(o,a-1),before:Rl(o,a-1)}),o&&c&&y.disabled.push({after:o,before:Rl(o,a-1)}),!o&&c&&y.disabled.push({after:V$(c,a-1),before:Rl(c,a-1)})),f){if(o&&!c&&(y.disabled.push({before:Rl(o,-f+1)}),y.disabled.push({after:Rl(o,f-1)})),o&&c){var v=cf(c,o)+1,T=f-v;y.disabled.push({before:V$(o,T)}),y.disabled.push({after:Rl(c,T)})}!o&&c&&(y.disabled.push({before:Rl(c,-f+1)}),y.disabled.push({after:Rl(c,f-1)}))}return s.jsx(hK.Provider,{value:{selected:n,onDayClick:p,modifiers:y},children:r})}function fK(){var t=C.useContext(hK);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function HL(t){return Array.isArray(t)?Ije([],t):t!==void 0?[t]:[]}function ePt(t){var e={};return Object.entries(t).forEach(function(r){var n=r[0],i=r[1];e[n]=HL(i)}),e}var xf;(function(t){t.Outside="outside",t.Disabled="disabled",t.Selected="selected",t.Hidden="hidden",t.Today="today",t.RangeStart="range_start",t.RangeEnd="range_end",t.RangeMiddle="range_middle"})(xf||(xf={}));var tPt=xf.Selected,xp=xf.Disabled,rPt=xf.Hidden,nPt=xf.Today,Xz=xf.RangeEnd,Qz=xf.RangeMiddle,Jz=xf.RangeStart,iPt=xf.Outside;function sPt(t,e,r){var n,i=(n={},n[tPt]=HL(t.selected),n[xp]=HL(t.disabled),n[rPt]=HL(t.hidden),n[nPt]=[t.today],n[Xz]=[],n[Qz]=[],n[Jz]=[],n[iPt]=[],n);return t.fromDate&&i[xp].push({before:t.fromDate}),t.toDate&&i[xp].push({after:t.toDate}),lN(t)?i[xp]=i[xp].concat(e.modifiers[xp]):cN(t)&&(i[xp]=i[xp].concat(r.modifiers[xp]),i[Jz]=r.modifiers[Jz],i[Qz]=r.modifiers[Qz],i[Xz]=r.modifiers[Xz]),i}var Mje=C.createContext(void 0);function aPt(t){var e=Sa(),r=dK(),n=fK(),i=sPt(e,r,n),o=ePt(e.modifiers),c=hi(hi({},i),o);return s.jsx(Mje.Provider,{value:c,children:t.children})}function Oje(){var t=C.useContext(Mje);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function oPt(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function lPt(t){return!!(t&&typeof t=="object"&&"from"in t)}function cPt(t){return!!(t&&typeof t=="object"&&"after"in t)}function uPt(t){return!!(t&&typeof t=="object"&&"before"in t)}function dPt(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function hPt(t,e){var r,n=e.from,i=e.to;if(n&&i){var o=cf(i,n)<0;o&&(r=[i,n],n=r[0],i=r[1]);var c=cf(t,n)>=0&&cf(i,t)>=0;return c}return i?rc(i,t):n?rc(n,t):!1}function fPt(t){return Q7(t)}function mPt(t){return Array.isArray(t)&&t.every(Q7)}function pPt(t,e){return e.some(function(r){if(typeof r=="boolean")return r;if(fPt(r))return rc(t,r);if(mPt(r))return r.includes(t);if(lPt(r))return hPt(t,r);if(dPt(r))return r.dayOfWeek.includes(t.getDay());if(oPt(r)){var n=cf(r.before,t),i=cf(r.after,t),o=n>0,c=i<0,a=ck(r.before,r.after);return a?c&&o:o||c}return cPt(r)?cf(t,r.after)>0:uPt(r)?cf(r.before,t)>0:typeof r=="function"?r(t):!1})}function mK(t,e,r){var n=Object.keys(e).reduce(function(o,c){var a=e[c];return pPt(t,a)&&o.push(c),o},[]),i={};return n.forEach(function(o){return i[o]=!0}),r&&!V3(t,r)&&(i.outside=!0),i}function gPt(t,e){for(var r=iu(t[0]),n=VC(t[t.length-1]),i,o,c=r;c<=n;){var a=mK(c,e),f=!a.disabled&&!a.hidden;if(!f){c=Rl(c,1);continue}if(a.selected)return c;a.today&&!o&&(o=c),i||(i=c),c=Rl(c,1)}return o||i}var yPt=365;function Fje(t,e){var r=e.moveBy,n=e.direction,i=e.context,o=e.modifiers,c=e.retry,a=c===void 0?{count:0,lastFocused:t}:c,f=i.weekStartsOn,p=i.fromDate,y=i.toDate,v=i.locale,T={day:Rl,week:zV,month:Sd,year:pHe,startOfWeek:function(R){return i.ISOWeek?ng(R):jc(R,{locale:v,weekStartsOn:f})},endOfWeek:function(R){return i.ISOWeek?xve(R):z3(R,{locale:v,weekStartsOn:f})}},E=T[r](t,n==="after"?1:-1);n==="before"&&p?E=gHe([p,E]):n==="after"&&y&&(E=yHe([y,E]));var k=!0;if(o){var P=mK(E,o);k=!P.disabled&&!P.hidden}return k?E:a.count>yPt?a.lastFocused:Fje(E,{moveBy:r,direction:n,context:i,modifiers:o,retry:hi(hi({},a),{count:a.count+1})})}var Bje=C.createContext(void 0);function xPt(t){var e=uN(),r=Oje(),n=C.useState(),i=n[0],o=n[1],c=C.useState(),a=c[0],f=c[1],p=gPt(e.displayMonths,r),y=i??(a&&e.isDateDisplayed(a))?a:p,v=function(){f(i),o(void 0)},T=function(R){o(R)},E=Sa(),k=function(R,D){if(i){var M=Fje(i,{moveBy:R,direction:D,context:E,modifiers:r});rc(i,M)||(e.goToDate(M,i),T(M))}},P={focusedDay:i,focusTarget:y,blur:v,focus:T,focusDayAfter:function(){return k("day","after")},focusDayBefore:function(){return k("day","before")},focusWeekAfter:function(){return k("week","after")},focusWeekBefore:function(){return k("week","before")},focusMonthBefore:function(){return k("month","before")},focusMonthAfter:function(){return k("month","after")},focusYearBefore:function(){return k("year","before")},focusYearAfter:function(){return k("year","after")},focusStartOfWeek:function(){return k("startOfWeek","before")},focusEndOfWeek:function(){return k("endOfWeek","after")}};return s.jsx(Bje.Provider,{value:P,children:t.children})}function pK(){var t=C.useContext(Bje);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function vPt(t,e){var r=Oje(),n=mK(t,r,e);return n}var gK=C.createContext(void 0);function _Pt(t){if(!o5(t.initialProps)){var e={selected:void 0};return s.jsx(gK.Provider,{value:e,children:t.children})}return s.jsx(bPt,{initialProps:t.initialProps,children:t.children})}function bPt(t){var e=t.initialProps,r=t.children,n=function(o,c,a){var f,p,y;if((f=e.onDayClick)===null||f===void 0||f.call(e,o,c,a),c.selected&&!e.required){(p=e.onSelect)===null||p===void 0||p.call(e,void 0,o,c,a);return}(y=e.onSelect)===null||y===void 0||y.call(e,o,o,c,a)},i={selected:e.selected,onDayClick:n};return s.jsx(gK.Provider,{value:i,children:r})}function $je(){var t=C.useContext(gK);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function wPt(t,e){var r=Sa(),n=$je(),i=dK(),o=fK(),c=pK(),a=c.focusDayAfter,f=c.focusDayBefore,p=c.focusWeekAfter,y=c.focusWeekBefore,v=c.blur,T=c.focus,E=c.focusMonthBefore,k=c.focusMonthAfter,P=c.focusYearBefore,R=c.focusYearAfter,D=c.focusStartOfWeek,M=c.focusEndOfWeek,B=function(be){var me,Te,Ne,Ee;o5(r)?(me=n.onDayClick)===null||me===void 0||me.call(n,t,e,be):lN(r)?(Te=i.onDayClick)===null||Te===void 0||Te.call(i,t,e,be):cN(r)?(Ne=o.onDayClick)===null||Ne===void 0||Ne.call(o,t,e,be):(Ee=r.onDayClick)===null||Ee===void 0||Ee.call(r,t,e,be)},V=function(be){var me;T(t),(me=r.onDayFocus)===null||me===void 0||me.call(r,t,e,be)},G=function(be){var me;v(),(me=r.onDayBlur)===null||me===void 0||me.call(r,t,e,be)},W=function(be){var me;(me=r.onDayMouseEnter)===null||me===void 0||me.call(r,t,e,be)},Y=function(be){var me;(me=r.onDayMouseLeave)===null||me===void 0||me.call(r,t,e,be)},J=function(be){var me;(me=r.onDayPointerEnter)===null||me===void 0||me.call(r,t,e,be)},Q=function(be){var me;(me=r.onDayPointerLeave)===null||me===void 0||me.call(r,t,e,be)},ee=function(be){var me;(me=r.onDayTouchCancel)===null||me===void 0||me.call(r,t,e,be)},le=function(be){var me;(me=r.onDayTouchEnd)===null||me===void 0||me.call(r,t,e,be)},pe=function(be){var me;(me=r.onDayTouchMove)===null||me===void 0||me.call(r,t,e,be)},Se=function(be){var me;(me=r.onDayTouchStart)===null||me===void 0||me.call(r,t,e,be)},je=function(be){var me;(me=r.onDayKeyUp)===null||me===void 0||me.call(r,t,e,be)},Le=function(be){var me;switch(be.key){case"ArrowLeft":be.preventDefault(),be.stopPropagation(),r.dir==="rtl"?a():f();break;case"ArrowRight":be.preventDefault(),be.stopPropagation(),r.dir==="rtl"?f():a();break;case"ArrowDown":be.preventDefault(),be.stopPropagation(),p();break;case"ArrowUp":be.preventDefault(),be.stopPropagation(),y();break;case"PageUp":be.preventDefault(),be.stopPropagation(),be.shiftKey?P():E();break;case"PageDown":be.preventDefault(),be.stopPropagation(),be.shiftKey?R():k();break;case"Home":be.preventDefault(),be.stopPropagation(),D();break;case"End":be.preventDefault(),be.stopPropagation(),M();break}(me=r.onDayKeyDown)===null||me===void 0||me.call(r,t,e,be)},Ae={onClick:B,onFocus:V,onBlur:G,onKeyDown:Le,onKeyUp:je,onMouseEnter:W,onMouseLeave:Y,onPointerEnter:J,onPointerLeave:Q,onTouchCancel:ee,onTouchEnd:le,onTouchMove:pe,onTouchStart:Se};return Ae}function SPt(){var t=Sa(),e=$je(),r=dK(),n=fK(),i=o5(t)?e.selected:lN(t)?r.selected:cN(t)?n.selected:void 0;return i}function TPt(t){return Object.values(xf).includes(t)}function EPt(t,e){var r=[t.classNames.day];return Object.keys(e).forEach(function(n){var i=t.modifiersClassNames[n];if(i)r.push(i);else if(TPt(n)){var o=t.classNames["day_".concat(n)];o&&r.push(o)}}),r}function jPt(t,e){var r=hi({},t.styles.day);return Object.keys(e).forEach(function(n){var i;r=hi(hi({},r),(i=t.modifiersStyles)===null||i===void 0?void 0:i[n])}),r}function APt(t,e,r){var n,i,o,c=Sa(),a=pK(),f=vPt(t,e),p=wPt(t,f),y=SPt(),v=!!(c.onDayClick||c.mode!=="default");C.useEffect(function(){var W;f.outside||a.focusedDay&&v&&rc(a.focusedDay,t)&&((W=r.current)===null||W===void 0||W.focus())},[a.focusedDay,t,r,v,f.outside]);var T=EPt(c,f).join(" "),E=jPt(c,f),k=!!(f.outside&&!c.showOutsideDays||f.hidden),P=(o=(i=c.components)===null||i===void 0?void 0:i.DayContent)!==null&&o!==void 0?o:KIt,R=s.jsx(P,{date:t,displayMonth:e,activeModifiers:f}),D={style:E,className:T,children:R,role:"gridcell"},M=a.focusTarget&&rc(a.focusTarget,t)&&!f.outside,B=a.focusedDay&&rc(a.focusedDay,t),V=hi(hi(hi({},D),(n={disabled:f.disabled,role:"gridcell"},n["aria-selected"]=f.selected,n.tabIndex=B||M?0:-1,n)),p),G={isButton:v,isHidden:k,activeModifiers:f,selectedDays:y,buttonProps:V,divProps:D};return G}function kPt(t){var e=C.useRef(null),r=APt(t.date,t.displayMonth,e);return r.isHidden?s.jsx("div",{role:"gridcell"}):r.isButton?s.jsx(gO,hi({name:"day",ref:e},r.buttonProps)):s.jsx("div",hi({},r.divProps))}function CPt(t){var e=t.number,r=t.dates,n=Sa(),i=n.onWeekNumberClick,o=n.styles,c=n.classNames,a=n.locale,f=n.labels.labelWeekNumber,p=n.formatters.formatWeekNumber,y=p(Number(e),{locale:a});if(!i)return s.jsx("span",{className:c.weeknumber,style:o.weeknumber,children:y});var v=f(Number(e),{locale:a}),T=function(E){i(e,r,E)};return s.jsx(gO,{name:"week-number","aria-label":v,className:c.weeknumber,style:o.weeknumber,onClick:T,children:y})}function NPt(t){var e,r,n=Sa(),i=n.styles,o=n.classNames,c=n.showWeekNumber,a=n.components,f=(e=a==null?void 0:a.Day)!==null&&e!==void 0?e:kPt,p=(r=a==null?void 0:a.WeekNumber)!==null&&r!==void 0?r:CPt,y;return c&&(y=s.jsx("td",{className:o.cell,style:i.cell,children:s.jsx(p,{number:t.weekNumber,dates:t.dates})})),s.jsxs("tr",{className:o.row,style:i.row,children:[y,t.dates.map(function(v){return s.jsx("td",{className:o.cell,style:i.cell,role:"presentation",children:s.jsx(f,{displayMonth:t.displayMonth,date:v})},wWe(v))})]})}function Ule(t,e,r){for(var n=r!=null&&r.ISOWeek?xve(e):z3(e,r),i=r!=null&&r.ISOWeek?ng(t):jc(t,r),o=cf(n,i),c=[],a=0;a<=o;a++)c.push(Rl(i,a));var f=c.reduce(function(p,y){var v=r!=null&&r.ISOWeek?J7(y):tH(y,r),T=p.find(function(E){return E.weekNumber===v});return T?(T.dates.push(y),p):(p.push({weekNumber:v,dates:[y]}),p)},[]);return f}function IPt(t,e){var r=Ule(iu(t),VC(t),e);if(e!=null&&e.useFixedWeeks){var n=TWe(t,e);if(n<6){var i=r[r.length-1],o=i.dates[i.dates.length-1],c=zV(o,6-n),a=Ule(zV(o,1),c,e);r.push.apply(r,a)}}return r}function PPt(t){var e,r,n,i=Sa(),o=i.locale,c=i.classNames,a=i.styles,f=i.hideHead,p=i.fixedWeeks,y=i.components,v=i.weekStartsOn,T=i.firstWeekContainsDate,E=i.ISOWeek,k=IPt(t.displayMonth,{useFixedWeeks:!!p,ISOWeek:E,locale:o,weekStartsOn:v,firstWeekContainsDate:T}),P=(e=y==null?void 0:y.Head)!==null&&e!==void 0?e:WIt,R=(r=y==null?void 0:y.Row)!==null&&r!==void 0?r:NPt,D=(n=y==null?void 0:y.Footer)!==null&&n!==void 0?n:qIt;return s.jsxs("table",{id:t.id,className:c.table,style:a.table,role:"grid","aria-labelledby":t["aria-labelledby"],children:[!f&&s.jsx(P,{}),s.jsx("tbody",{className:c.tbody,style:a.tbody,children:k.map(function(M){return s.jsx(R,{displayMonth:t.displayMonth,dates:M.dates,weekNumber:M.weekNumber},M.weekNumber)})}),s.jsx(D,{displayMonth:t.displayMonth})]})}function RPt(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var LPt=RPt()?C.useLayoutEffect:C.useEffect,e6=!1,DPt=0;function Vle(){return"react-day-picker-".concat(++DPt)}function MPt(t){var e,r=t??(e6?Vle():null),n=C.useState(r),i=n[0],o=n[1];return LPt(function(){i===null&&o(Vle())},[]),C.useEffect(function(){e6===!1&&(e6=!0)},[]),(e=t??i)!==null&&e!==void 0?e:void 0}function OPt(t){var e,r,n=Sa(),i=n.dir,o=n.classNames,c=n.styles,a=n.components,f=uN().displayMonths,p=MPt(n.id?"".concat(n.id,"-").concat(t.displayIndex):void 0),y=n.id?"".concat(n.id,"-grid-").concat(t.displayIndex):void 0,v=[o.month],T=c.month,E=t.displayIndex===0,k=t.displayIndex===f.length-1,P=!E&&!k;i==="rtl"&&(e=[E,k],k=e[0],E=e[1]),E&&(v.push(o.caption_start),T=hi(hi({},T),c.caption_start)),k&&(v.push(o.caption_end),T=hi(hi({},T),c.caption_end)),P&&(v.push(o.caption_between),T=hi(hi({},T),c.caption_between));var R=(r=a==null?void 0:a.Caption)!==null&&r!==void 0?r:VIt;return s.jsxs("div",{className:v.join(" "),style:T,children:[s.jsx(R,{id:p,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),s.jsx(PPt,{id:y,"aria-labelledby":p,displayMonth:t.displayMonth})]},t.displayIndex)}function FPt(t){var e=Sa(),r=e.classNames,n=e.styles;return s.jsx("div",{className:r.months,style:n.months,children:t.children})}function BPt(t){var e,r,n=t.initialProps,i=Sa(),o=pK(),c=uN(),a=C.useState(!1),f=a[0],p=a[1];C.useEffect(function(){i.initialFocus&&o.focusTarget&&(f||(o.focus(o.focusTarget),p(!0)))},[i.initialFocus,f,o.focus,o.focusTarget,o]);var y=[i.classNames.root,i.className];i.numberOfMonths>1&&y.push(i.classNames.multiple_months),i.showWeekNumber&&y.push(i.classNames.with_weeknumber);var v=hi(hi({},i.styles.root),i.style),T=Object.keys(n).filter(function(k){return k.startsWith("data-")}).reduce(function(k,P){var R;return hi(hi({},k),(R={},R[P]=n[P],R))},{}),E=(r=(e=n.components)===null||e===void 0?void 0:e.Months)!==null&&r!==void 0?r:FPt;return s.jsx("div",hi({className:y.join(" "),style:v,dir:i.dir,id:i.id,nonce:n.nonce,title:n.title,lang:n.lang},T,{children:s.jsx(E,{children:c.displayMonths.map(function(k,P){return s.jsx(OPt,{displayIndex:P,displayMonth:k},P)})})}))}function $Pt(t){var e=t.children,r=uIt(t,["children"]);return s.jsx(CIt,{initialProps:r,children:s.jsx(BIt,{children:s.jsx(_Pt,{initialProps:r,children:s.jsx(YIt,{initialProps:r,children:s.jsx(QIt,{initialProps:r,children:s.jsx(aPt,{children:s.jsx(xPt,{children:e})})})})})})})}function zPt(t){return s.jsx($Pt,hi({},t,{children:s.jsx(BPt,{initialProps:t})}))}function zje({className:t,classNames:e,showOutsideDays:r=!0,captionLayout:n,...i}){const o=n==="dropdown"?"dropdown-buttons":n;return s.jsx(zPt,{showOutsideDays:r,captionLayout:o,className:qt("p-3",t),classNames:{months:"flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",month:"space-y-4",caption:"flex justify-center pt-1 relative items-center min-h-8",caption_label:"text-sm font-medium",caption_dropdowns:"flex gap-2 items-center justify-center px-9 [&_[aria-hidden=true]]:hidden",vhidden:"sr-only",nav:"space-x-1 flex items-center",nav_button:qt(YA({variant:"outline"}),"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-y-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell:"h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",day:qt(YA({variant:"ghost"}),"h-9 w-9 p-0 font-normal aria-selected:opacity-100"),day_range_end:"day-range-end",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",dropdown:"h-8 rounded-md border border-input bg-background px-2 py-1 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",...e},components:{IconLeft:({...c})=>s.jsx(Cm,{className:"h-4 w-4"}),IconRight:({...c})=>s.jsx(jd,{className:"h-4 w-4"})},...i})}zje.displayName="Calendar";function Uje({open:t,onOpenChange:e,editTask:r,defaultDealId:n,defaultStageId:i}){var be;const o=Cje(),c=rIt(),{data:a}=cIt(),f=Li(),{data:p}=mr({queryKey:["contacts-for-tasks",f],queryFn:async()=>{if(!f)return[];const me=[],Te=1e3;for(let Ne=0;;Ne+=Te){const{data:Ee,error:we}=await Re.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",f).order("first_name").order("id").range(Ne,Ne+Te-1);if(we)throw we;if(me.push(...Ee||[]),!Ee||Ee.length{r?(v(r.title),E(r.description||""),P(r.deal_id||"none"),D(r.contact_id||"none"),B(r.priority),G(r.status),Y(r.due_date?Zc(r.due_date):void 0),Q(r.assignee_user_id&&r.assignee_user_id!==r.owner_user_id?r.assignee_user_id:"me")):(v(""),E(""),P(n||"none"),D("none"),B("medium"),G("todo"),Y(void 0),Q("me"))},[r,t,n]);const Ae=async()=>{if(!y.trim()){Vt.error("Task title is required");return}try{const me={title:y.trim(),description:T.trim()||null,deal_id:k==="none"?null:k,contact_id:R==="none"?null:R,stage_id:i||null,priority:M,status:V,due_date:W?Ri(W,"yyyy-MM-dd"):null},Te=J==="me"?null:J;if(r){if(le)await c.mutateAsync({id:r.id,...me,assignee_user_id:Te,assigned_by_user_id:Te?f:null});else{const{deal_id:Ne,contact_id:Ee,stage_id:we,...He}=me;await c.mutateAsync({id:r.id,...He})}Vt.success("Task updated")}else await o.mutateAsync({...me,assignee_user_id:Te}),$x("task_created"),Vt.success("Task created");e(!1)}catch{Vt.error("Failed to save task")}};return s.jsx(lo,{open:t,onOpenChange:e,children:s.jsxs(qa,{className:"sm:max-w-[480px]",children:[s.jsx(xl,{children:s.jsx(Xo,{children:r?"Edit Task":"New Task"})}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(Mr,{children:"Title *"}),s.jsx(Br,{value:y,onChange:me=>v(me.target.value),placeholder:"e.g., Send inspection report"})]}),s.jsxs("div",{children:[s.jsx(Mr,{children:"Description"}),s.jsx(Ad,{value:T,onChange:me=>E(me.target.value),placeholder:"Optional details...",rows:2})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(Mr,{children:"Priority"}),s.jsxs(ba,{value:M,onValueChange:me=>B(me),children:[s.jsx(oa,{children:s.jsx(wa,{})}),s.jsxs(la,{children:[s.jsx(mn,{value:"low",children:"🟢 Low"}),s.jsx(mn,{value:"medium",children:"🟡 Medium"}),s.jsx(mn,{value:"high",children:"🟠 High"}),s.jsx(mn,{value:"urgent",children:"🔴 Urgent"})]})]})]}),s.jsxs("div",{children:[s.jsx(Mr,{children:"Status"}),s.jsxs(ba,{value:V,onValueChange:me=>G(me),children:[s.jsx(oa,{children:s.jsx(wa,{})}),s.jsxs(la,{children:[s.jsx(mn,{value:"todo",children:"To Do"}),s.jsx(mn,{value:"in_progress",children:"In Progress"}),s.jsx(mn,{value:"done",children:"Done"})]})]})]})]}),s.jsxs("div",{children:[s.jsx(Mr,{children:"Due Date"}),s.jsxs(UL,{children:[s.jsx(VL,{asChild:!0,children:s.jsxs(Bt,{variant:"outline",className:qt("w-full justify-start text-left font-normal",!W&&"text-muted-foreground"),children:[s.jsx(oo,{className:"mr-2 h-4 w-4"}),W?Ri(W,"PPP"):"Pick a date"]})}),s.jsx(yA,{className:"w-auto p-0",align:"start",children:s.jsx(zje,{mode:"single",selected:W,onSelect:Y,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),le&&ee.length>0&&s.jsxs("div",{children:[s.jsx(Mr,{children:"Assign to"}),s.jsxs(ba,{value:J,onValueChange:Q,children:[s.jsx(oa,{children:s.jsx(wa,{})}),s.jsxs(la,{children:[s.jsx(mn,{value:"me",children:"Me"}),ee.map(me=>s.jsxs(mn,{value:me.id,children:[me.name,me.teamName?` · ${me.teamName}`:""]},me.id))]})]})]}),le&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx(Mr,{children:"Link to Deal"}),s.jsxs(UL,{open:pe,onOpenChange:Se,children:[s.jsx(VL,{asChild:!0,children:s.jsxs(Bt,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[s.jsxs("span",{className:"flex items-center gap-2 truncate",children:[s.jsx(_o,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),k!=="none"?((be=a==null?void 0:a.find(me=>me.id===k))==null?void 0:be.deal_name)||"Select deal":"No Deal"]}),s.jsx(LU,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),s.jsx(yA,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:s.jsxs(uk,{children:[s.jsx(dk,{placeholder:"Search deals..."}),s.jsxs(hk,{children:[s.jsx(fk,{children:"No deals found."}),s.jsxs(Rp,{children:[s.jsxs(nf,{value:"no-deal",onSelect:()=>{P("none"),Se(!1)},children:[s.jsx(no,{className:qt("mr-2 h-4 w-4",k==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),a==null?void 0:a.map(me=>s.jsxs(nf,{value:me.deal_name,onSelect:()=>{P(me.id),Se(!1)},children:[s.jsx(no,{className:qt("mr-2 h-4 w-4",k===me.id?"opacity-100":"opacity-0")}),me.deal_name]},me.id))]})]})]})})]})]}),s.jsxs("div",{children:[s.jsx(Mr,{children:"Link to Contact"}),s.jsxs(UL,{open:je,onOpenChange:Le,children:[s.jsx(VL,{asChild:!0,children:s.jsxs(Bt,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[s.jsxs("span",{className:"flex items-center gap-2 truncate",children:[s.jsx(Ml,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),R!=="none"?(()=>{const me=p==null?void 0:p.find(Te=>Te.id===R);return me?`${me.first_name} ${me.last_name}`:"Select contact"})():"No Contact"]}),s.jsx(LU,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),s.jsx(yA,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:s.jsxs(uk,{children:[s.jsx(dk,{placeholder:"Search contacts..."}),s.jsxs(hk,{children:[s.jsx(fk,{children:"No contacts found."}),s.jsxs(Rp,{children:[s.jsxs(nf,{value:"no-contact",onSelect:()=>{D("none"),Le(!1)},children:[s.jsx(no,{className:qt("mr-2 h-4 w-4",R==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),p==null?void 0:p.map(me=>s.jsxs(nf,{value:`${me.first_name??""} ${me.last_name??""} ${me.id}`,onSelect:()=>{D(me.id),Le(!1)},children:[s.jsx(no,{className:qt("mr-2 h-4 w-4",R===me.id?"opacity-100":"opacity-0")}),me.first_name," ",me.last_name]},me.id))]})]})]})})]})]})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[s.jsx(Bt,{variant:"outline",onClick:()=>e(!1),children:"Cancel"}),s.jsx(Bt,{onClick:Ae,disabled:o.isPending||c.isPending,children:r?"Save Changes":"Create Task"})]})]})]})})}const UPt={urgent:{label:"Urgent",color:"bg-red-500/10 text-red-600 border-red-200",dot:"🔴"},high:{label:"High",color:"bg-orange-500/10 text-orange-600 border-orange-200",dot:"🟠"},medium:{label:"Medium",color:"bg-amber-500/10 text-amber-600 border-amber-200",dot:"🟡"},low:{label:"Low",color:"bg-emerald-500/10 text-emerald-600 border-emerald-200",dot:"🟢"}};function VPt({tasks:t}){const e=cK(),r=nIt(),n=Hs(),[i,o]=C.useState(null),c=async y=>{const v=y.status==="done"?"todo":"done";try{await e.mutateAsync({id:y.id,status:v})}catch{Vt.error("Failed to update task")}},a=async y=>{try{await r.mutateAsync(y),Vt.success("Task deleted")}catch{Vt.error("Failed to delete task")}};if(t.length===0)return s.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[s.jsx(oc,{className:"h-12 w-12 text-muted-foreground/30 mb-3"}),s.jsx("p",{className:"text-muted-foreground font-medium",children:"No tasks found"}),s.jsx("p",{className:"text-muted-foreground/60 text-sm",children:"Create a new task to get started"})]});const f=new Map,p=[];return t.forEach(y=>{if(y.deal){const v=f.get(y.deal.id)||{dealName:y.deal.deal_name,tasks:[]};v.tasks.push(y),f.set(y.deal.id,v)}else p.push(y)}),s.jsxs("div",{className:"space-y-4",children:[p.length>0&&s.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[s.jsx("div",{className:"bg-muted/30 px-4 py-2 border-b",children:s.jsx("h3",{className:"font-medium text-sm text-muted-foreground",children:"General Tasks"})}),p.map(y=>s.jsx(qle,{task:y,onToggle:c,onDelete:a,onEdit:o,onNavigateDeal:v=>n(`/mission-control/pipeline?deal=${v}`)},y.id))]}),Array.from(f.entries()).map(([y,v])=>s.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[s.jsxs("button",{onClick:()=>n(`/mission-control/pipeline?deal=${y}`),className:"w-full bg-muted/30 px-4 py-2 border-b flex items-center gap-2 hover:bg-muted/50 transition-colors text-left",children:[s.jsx(_o,{className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("h3",{className:"font-medium text-sm",children:v.dealName}),s.jsxs(ss,{variant:"secondary",className:"ml-auto text-xs",children:[v.tasks.filter(T=>T.status==="done").length,"/",v.tasks.length]}),s.jsx(jd,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),v.tasks.map(T=>s.jsx(qle,{task:T,onToggle:c,onDelete:a,onEdit:o,onNavigateDeal:E=>n(`/mission-control/pipeline?deal=${E}`)},T.id))]},y)),i&&s.jsx(Uje,{open:!!i,onOpenChange:()=>o(null),editTask:i})]})}function qPt({task:t,onToggle:e}){const r=dst(),{data:n}=cst(),i=t.contact;if(!i||t.status==="done")return null;const o="h-7 w-7 inline-flex items-center justify-center rounded-md border bg-background text-muted-foreground hover:text-primary hover:border-primary/40 transition-colors",c=async()=>{const a=(n==null?void 0:n.find(f=>/call/i.test(f.name)))||(n==null?void 0:n[0]);if(!a){Vt.error("No touch types available");return}try{await r.mutateAsync({contactId:i.id,actionTypeId:a.id,notes:`Task: ${t.title}`}),e(t),Vt.success(`Touch logged for ${i.first_name} and task completed`)}catch{Vt.error("Could not log touch")}};return s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[i.phone&&s.jsx("a",{href:`tel:${i.phone}`,className:o,title:`Call ${i.first_name}`,children:s.jsx(ri,{className:"h-3.5 w-3.5"})}),i.phone&&s.jsx("a",{href:`sms:${i.phone}`,className:o,title:`Text ${i.first_name}`,children:s.jsx(fh,{className:"h-3.5 w-3.5"})}),i.email&&s.jsx("a",{href:`mailto:${i.email}`,className:o,title:`Email ${i.first_name}`,children:s.jsx(mi,{className:"h-3.5 w-3.5"})}),s.jsx("button",{onClick:c,disabled:r.isPending,className:o,title:"Log touch & complete",children:s.jsx(WDe,{className:"h-3.5 w-3.5"})})]})}function qle({task:t,onToggle:e,onDelete:r,onEdit:n,onNavigateDeal:i}){const o=t.status==="done",c=!o&&t.due_date&&dS(Zc(t.due_date))&&!lh(Zc(t.due_date)),a=!o&&t.due_date&&lh(Zc(t.due_date)),f=UPt[t.priority],p=Li(),{data:y=[]}=Nje(),v=k=>{var P;return((P=y.find(R=>R.id===k))==null?void 0:P.name)||"Teammate"},T=t.owner_user_id===p&&t.assignee_user_id&&t.assignee_user_id!==p,E=t.owner_user_id!==p&&t.assignee_user_id===p;return s.jsxs("div",{className:qt("flex items-center gap-3 px-4 py-3 border-b last:border-b-0 group hover:bg-muted/30 transition-colors",o&&"opacity-60"),children:[s.jsx("button",{onClick:()=>e(t),className:"shrink-0",children:o?s.jsx(oc,{className:"h-5 w-5 text-emerald-500"}):s.jsx(t_,{className:"h-5 w-5 text-muted-foreground hover:text-primary transition-colors"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:qt("text-sm font-medium truncate",o&&"line-through text-muted-foreground"),children:t.title}),s.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[t.stage&&s.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full font-medium",style:{backgroundColor:t.stage.color+"20",color:t.stage.color},children:t.stage.name}),t.contact&&s.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[s.jsx(Ml,{className:"h-2.5 w-2.5"}),t.contact.first_name," ",t.contact.last_name]}),T&&s.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary flex items-center gap-0.5",children:[s.jsx(zU,{className:"h-2.5 w-2.5"})," Assigned to ",v(t.assignee_user_id)]}),E&&s.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-accent text-accent-foreground flex items-center gap-0.5",children:[s.jsx(zU,{className:"h-2.5 w-2.5"})," From ",v(t.owner_user_id)]})]})]}),s.jsx(qPt,{task:t,onToggle:e}),s.jsxs(ss,{variant:"outline",className:qt("text-[10px] shrink-0",f.color),children:[f.dot," ",f.label]}),t.due_date&&s.jsxs("span",{className:qt("text-xs shrink-0 flex items-center gap-1",c&&"text-destructive font-medium",a&&"text-amber-600 font-medium",!c&&!a&&"text-muted-foreground"),children:[s.jsx(Dl,{className:"h-3 w-3"}),Ri(Zc(t.due_date),"MMM d")]}),s.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[s.jsx("button",{onClick:()=>n(t),className:"p-1 hover:bg-muted rounded",children:s.jsx(BU,{className:"h-3.5 w-3.5 text-muted-foreground"})}),t.owner_user_id===p&&s.jsx("button",{onClick:()=>r(t.id),className:"p-1 hover:bg-destructive/10 rounded",children:s.jsx(CD,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const GPt=[{status:"todo",label:"To Do",icon:t_,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:E9,color:"border-t-blue-500"},{status:"done",label:"Done",icon:oc,color:"border-t-emerald-500"}],HPt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function WPt({tasks:t}){const e=cK(),r=C.useMemo(()=>{const o={todo:[],in_progress:[],done:[]};return t.forEach(c=>o[c.status].push(c)),o},[t]),n=(o,c)=>{o.dataTransfer.setData("taskId",c)},i=async(o,c)=>{o.preventDefault();const a=o.dataTransfer.getData("taskId");if(!a)return;const f=t.find(p=>p.id===a);if(!(!f||f.status===c))try{await e.mutateAsync({id:a,status:c})}catch{Vt.error("Failed to move task")}};return s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:GPt.map(o=>s.jsxs("div",{className:qt("border rounded-lg border-t-4 bg-muted/20",o.color),onDragOver:c=>c.preventDefault(),onDrop:c=>i(c,o.status),children:[s.jsxs("div",{className:"px-4 py-3 flex items-center gap-2",children:[s.jsx(o.icon,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("h3",{className:"font-semibold text-sm",children:o.label}),s.jsx(ss,{variant:"secondary",className:"ml-auto text-xs",children:r[o.status].length})]}),s.jsxs("div",{className:"p-2 space-y-2 min-h-[200px]",children:[r[o.status].map(c=>s.jsx(KPt,{task:c,onDragStart:n},c.id)),r[o.status].length===0&&s.jsx("p",{className:"text-xs text-muted-foreground text-center py-8",children:"Drag tasks here"})]})]},o.status))})}function KPt({task:t,onDragStart:e}){const r=t.status==="done",n=!r&&t.due_date&&dS(Zc(t.due_date))&&!lh(Zc(t.due_date)),i=!r&&t.due_date&&lh(Zc(t.due_date));return s.jsx("div",{draggable:!0,onDragStart:o=>e(o,t.id),className:qt("bg-background border rounded-lg p-3 cursor-grab active:cursor-grabbing shadow-sm hover:shadow-md transition-shadow",n&&"border-destructive/50"),children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"text-xs mt-0.5",children:HPt[t.priority]}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:qt("text-sm font-medium",r&&"line-through text-muted-foreground"),children:t.title}),s.jsxs("div",{className:"flex items-center gap-2 mt-1.5 flex-wrap",children:[t.deal&&s.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[s.jsx(_o,{className:"h-2.5 w-2.5"}),t.deal.deal_name]}),t.contact&&s.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[s.jsx(Ml,{className:"h-2.5 w-2.5"}),t.contact.first_name," ",t.contact.last_name]})]}),t.due_date&&s.jsxs("div",{className:qt("text-[10px] mt-1.5 flex items-center gap-1",n&&"text-destructive font-medium",i&&"text-amber-600 font-medium",!n&&!i&&"text-muted-foreground"),children:[s.jsx(Dl,{className:"h-2.5 w-2.5"}),n?"Overdue — ":i?"Due today — ":"",Ri(Zc(t.due_date),"MMM d")]}),t.stage&&s.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full font-medium mt-1.5",style:{backgroundColor:t.stage.color+"20",color:t.stage.color},children:t.stage.name})]})]})})}const Gle={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function YPt({tasks:t}){const[e,r]=C.useState(new Date),n=cK(),i=iu(e),o=VC(e),c=jc(i),a=z3(o),f=jHe({start:c,end:a}),p=C.useMemo(()=>{const T=new Map;return t.forEach(E=>{if(!E.due_date)return;const k=E.due_date,P=T.get(k)||[];P.push(E),T.set(k,P)}),T},[t]),y=C.useMemo(()=>t.filter(T=>!T.due_date),[t]),v=async T=>{const E=T.status==="done"?"todo":"done";try{await n.mutateAsync({id:T.id,status:E})}catch{Vt.error("Failed to update task")}};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(Bt,{variant:"ghost",size:"icon",onClick:()=>r(FKe(e,1)),children:s.jsx(Cm,{className:"h-4 w-4"})}),s.jsx("h3",{className:"font-semibold",children:Ri(e,"MMMM yyyy")}),s.jsx(Bt,{variant:"ghost",size:"icon",onClick:()=>r(Sd(e,1)),children:s.jsx(jd,{className:"h-4 w-4"})})]}),s.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(T=>s.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:T},T))}),s.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:f.map(T=>{const E=Ri(T,"yyyy-MM-dd"),k=p.get(E)||[],P=V3(T,e),R=lh(T);return s.jsxs("div",{className:qt("border-r border-b min-h-[100px] p-1",!P&&"bg-muted/30",R&&"bg-primary/5"),children:[s.jsx("div",{className:qt("text-xs font-medium mb-1 text-right px-1",!P&&"text-muted-foreground/40",R&&"text-primary font-bold"),children:Ri(T,"d")}),s.jsxs("div",{className:"space-y-0.5",children:[k.slice(0,3).map(D=>s.jsxs("button",{onClick:()=>v(D),className:qt("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",D.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[D.status==="done"?s.jsx(oc,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):s.jsx(t_,{className:"h-2.5 w-2.5 shrink-0"}),s.jsxs("span",{className:"truncate",children:[Gle[D.priority]," ",D.title]})]},D.id)),k.length>3&&s.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",k.length-3," more"]})]})]},E)})}),y.length>0&&s.jsxs("div",{className:"border rounded-lg p-3",children:[s.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",y.length,")"]}),s.jsx("div",{className:"space-y-1",children:y.map(T=>s.jsxs("button",{onClick:()=>v(T),className:qt("w-full text-left text-xs px-2 py-1.5 rounded flex items-center gap-2 hover:bg-muted transition-colors",T.status==="done"&&"opacity-50 line-through"),children:[T.status==="done"?s.jsx(oc,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):s.jsx(t_,{className:"h-3.5 w-3.5 shrink-0"}),s.jsxs("span",{className:"truncate",children:[Gle[T.priority]," ",T.title]}),T.deal&&s.jsxs("span",{className:"text-muted-foreground ml-auto shrink-0",children:["• ",T.deal.deal_name]})]},T.id))})]})]})}const ZPt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function XPt({open:t,onOpenChange:e,stages:r}){var D;const[n,i]=C.useState(((D=r[0])==null?void 0:D.id)||""),{data:o,isLoading:c}=iIt(n||void 0),a=sIt(),f=aIt(),[p,y]=C.useState(""),[v,T]=C.useState("medium"),[E,k]=C.useState(""),P=async()=>{if(!(!p.trim()||!n))try{await a.mutateAsync({stage_id:n,title:p.trim(),priority:v,default_due_offset_days:E?parseInt(E):null,sort_order:((o==null?void 0:o.length)||0)+1}),y(""),k(""),Vt.success("Template added")}catch{Vt.error("Failed to add template")}},R=async M=>{try{await f.mutateAsync(M),Vt.success("Template deleted")}catch{Vt.error("Failed to delete template")}};return s.jsx(lo,{open:t,onOpenChange:e,children:s.jsxs(qa,{className:"sm:max-w-[560px]",children:[s.jsx(xl,{children:s.jsxs(Xo,{className:"flex items-center gap-2",children:[s.jsx(IDe,{className:"h-5 w-5"}),"Task Templates by Stage"]})}),s.jsx("p",{className:"text-sm text-muted-foreground -mt-2",children:"Create default tasks that auto-populate when a deal enters a stage."}),s.jsxs("div",{children:[s.jsx(Mr,{children:"Pipeline Stage"}),s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:r.filter(M=>!M.is_won_stage&&!M.is_lost_stage).map(M=>s.jsx("button",{onClick:()=>i(M.id),className:qt("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",n===M.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:M.name},M.id))})]}),s.jsx(Lm,{className:"max-h-[250px]",children:s.jsxs("div",{className:"space-y-1.5",children:[o==null?void 0:o.map((M,B)=>s.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border rounded-lg group",children:[s.jsx("span",{className:"text-xs",children:ZPt[M.priority]}),s.jsx("span",{className:"text-sm flex-1 truncate",children:M.title}),M.default_due_offset_days&&s.jsxs(ss,{variant:"outline",className:"text-[10px]",children:["+",M.default_due_offset_days,"d"]}),s.jsx("button",{onClick:()=>R(M.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:s.jsx(CD,{className:"h-3.5 w-3.5 text-destructive"})})]},M.id)),(o==null?void 0:o.length)===0&&n&&s.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),n&&s.jsxs("div",{className:"space-y-3 border-t pt-3",children:[s.jsx(Mr,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Br,{placeholder:"Task title...",value:p,onChange:M=>y(M.target.value),className:"flex-1",onKeyDown:M=>M.key==="Enter"&&P()}),s.jsxs(ba,{value:v,onValueChange:M=>T(M),children:[s.jsx(oa,{className:"w-[100px]",children:s.jsx(wa,{})}),s.jsxs(la,{children:[s.jsx(mn,{value:"low",children:"🟢 Low"}),s.jsx(mn,{value:"medium",children:"🟡 Med"}),s.jsx(mn,{value:"high",children:"🟠 High"}),s.jsx(mn,{value:"urgent",children:"🔴 Urgent"})]})]})]}),s.jsxs("div",{className:"flex gap-2 items-end",children:[s.jsxs("div",{className:"flex-1",children:[s.jsx(Mr,{className:"text-xs",children:"Due offset (days from entering stage)"}),s.jsx(Br,{type:"number",placeholder:"e.g., 7",value:E,onChange:M=>k(M.target.value)})]}),s.jsxs(Bt,{onClick:P,disabled:!p.trim()||a.isPending,children:[s.jsx(gm,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}const l5=t=>`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`,QPt=t=>{const[e,r,n]=t.split(/[-/T]/).map(Number);return new Date(e,r-1,n)},TA=(t,e)=>{const r=new Date(t.getFullYear(),t.getMonth(),t.getDate()+e);return l5(r)},Vje=t=>{const r=(8-t.getDay())%7||7;return TA(t,r)},JPt=(t,e)=>!!t&&t.slice(0,10)t==="today"?l5(e):t==="plus3"?TA(e,3):Vje(e),tRt=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];function rRt(t,e){let r=` ${t.trim()} `,n=null,i=null;const o=r.match(/\s!(low|medium|high|urgent)\b/i)||r.match(/\s(urgent|high priority|low priority)\b/i);o&&(i=o[1].toLowerCase().replace(" priority",""),r=r.replace(o[0]," "));const c=[[/\s(today)\b/i,()=>l5(e)],[/\s(tomorrow|tmrw)\b/i,()=>TA(e,1)],[/\s(next week)\b/i,()=>Vje(e)],[/\sin (\d{1,2}) days?\b/i,()=>""]];for(const[a,f]of c){const p=r.match(a);if(p){n=a.source.includes("\\d")?TA(e,Number(p[1])):f(),r=r.replace(p[0]," ");break}}if(!n){const a=r.match(/\s(?:on |next )?(sunday|monday|tuesday|wednesday|thursday|friday|saturday)\b/i);if(a){const p=(tRt.indexOf(a[1].toLowerCase())-e.getDay()+7)%7||7;n=TA(e,p),r=r.replace(a[0]," ")}}return{title:r.replace(/\s+/g," ").trim(),due:n,priority:i}}function nRt({tasks:t}){const e=oIt(),r=new Date,n=t.filter(o=>o.status!=="done"&&JPt(o.due_date,r));if(!n.length)return null;const i=async(o,c)=>{try{await e.mutateAsync({ids:n.map(a=>a.id),due_date:eRt(o,new Date)}),Vt.success(`${n.length} task${n.length===1?"":"s"} moved to ${c}`)}catch{Vt.error("Could not reschedule tasks")}};return s.jsxs("div",{className:"flex flex-col md:flex-row md:items-center gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx(JS,{className:"h-4 w-4 text-destructive"}),s.jsxs("span",{children:[s.jsxs("strong",{children:[n.length," overdue"]})," — clear the backlog in one click."]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 md:ml-auto",children:[s.jsxs(Bt,{size:"sm",variant:"outline",disabled:e.isPending,onClick:()=>i("today","today"),children:[s.jsx(T9,{className:"h-3.5 w-3.5 mr-1"})," Move all to today"]}),s.jsx(Bt,{size:"sm",variant:"outline",disabled:e.isPending,onClick:()=>i("plus3","3 days from now"),children:"Push +3 days"}),s.jsx(Bt,{size:"sm",variant:"outline",disabled:e.isPending,onClick:()=>i("monday","Monday"),children:"Push to Monday"})]})]})}function iRt({contactId:t,dealId:e}){const[r,n]=C.useState(""),i=Cje(),o=r.trim()?rRt(r,new Date):null,c=async()=>{if(o!=null&&o.title)try{await i.mutateAsync({title:o.title,due_date:o.due,priority:o.priority||"medium",contact_id:t||null,deal_id:e||null}),$x("task_created"),n(""),Vt.success("Task added")}catch{Vt.error("Could not add task")}};return s.jsxs("div",{className:"rounded-lg border bg-card px-3 py-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(gm,{className:"h-4 w-4 text-muted-foreground shrink-0"}),s.jsx(Br,{value:r,onChange:a=>n(a.target.value),onKeyDown:a=>{a.key==="Enter"&&c()},placeholder:'Quick add… try "Call Sarah tomorrow !high" or "Send CMA friday"',className:"border-0 shadow-none focus-visible:ring-0 px-0"}),s.jsx(Bt,{size:"sm",onClick:c,disabled:!(o!=null&&o.title)||i.isPending,children:"Add"})]}),o&&(o.due||o.priority)&&s.jsxs("p",{className:"flex items-center gap-1 text-[11px] text-muted-foreground mt-1 pl-6",children:[s.jsx(xs,{className:"h-3 w-3 text-primary"}),o.due&&s.jsxs(s.Fragment,{children:["Due ",Ri(QPt(o.due),"EEE, MMM d")]}),o.priority&&s.jsxs(s.Fragment,{children:[" · ",o.priority," priority"]})]})]})}function sRt(){const{data:t,isLoading:e}=tIt(),{data:r}=lIt(),[n,i]=C.useState("list"),[o,c]=C.useState(""),[a,f]=C.useState("active"),[p,y]=C.useState("all"),[v,T]=C.useState("all"),[E,k]=C.useState("all"),P=Li(),[R,D]=C.useState(!1),[M,B]=C.useState(!1),V=C.useMemo(()=>{if(!t)return[];const Y=new Map;return t.forEach(J=>{J.deal&&Y.set(J.deal.id,J.deal.deal_name)}),Array.from(Y,([J,Q])=>({id:J,name:Q}))},[t]),G=C.useMemo(()=>t?t.filter(Y=>{var Ae,be,me,Te;const J=o.toLowerCase(),Q=!J||Y.title.toLowerCase().includes(J)||((be=(Ae=Y.deal)==null?void 0:Ae.deal_name)==null?void 0:be.toLowerCase().includes(J))||`${((me=Y.contact)==null?void 0:me.first_name)||""} ${((Te=Y.contact)==null?void 0:Te.last_name)||""}`.toLowerCase().includes(J),ee=a==="all"||a==="active"&&Y.status!=="done"||a==="todo"&&Y.status==="todo"||a==="in_progress"&&Y.status==="in_progress"||a==="done"&&Y.status==="done"||a==="overdue"&&Y.status!=="done"&&Y.due_date&&dS(Zc(Y.due_date))&&!lh(Zc(Y.due_date)),le=p==="all"||Y.priority===p,pe=v==="all"||v==="no_deal"&&!Y.deal_id||Y.deal_id===v,Se=Y.owner_user_id===P&&!!Y.assignee_user_id&&Y.assignee_user_id!==P,je=Y.owner_user_id!==P&&Y.assignee_user_id===P;return Q&&ee&&le&&pe&&(E==="all"||E==="mine"&&!Se||E==="delegated"&&Se||E==="assigned"&&je)}):[],[t,o,a,p,v,E,P]),W=C.useMemo(()=>{if(!t)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const Y=t.filter(J=>J.status!=="done");return{total:Y.length,overdue:Y.filter(J=>J.due_date&&dS(Zc(J.due_date))&&!lh(Zc(J.due_date))).length,dueToday:Y.filter(J=>J.due_date&&lh(Zc(J.due_date))).length,dueThisWeek:Y.filter(J=>J.due_date&&wKe(Zc(J.due_date))).length,completed:t.filter(J=>J.status==="done").length}},[t]);return s.jsx(hS,{children:s.jsxs("div",{className:"space-y-6 p-4 md:p-6 max-w-[1600px] mx-auto",children:[s.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Tasks"}),s.jsx("p",{className:"text-muted-foreground text-sm",children:"Manage tasks across deals and contacts"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(Bt,{variant:"outline",size:"sm",onClick:()=>B(!0),children:[s.jsx(PDe,{className:"h-4 w-4 mr-1"}),"Templates"]}),s.jsxs(Bt,{size:"sm",onClick:()=>D(!0),children:[s.jsx(gm,{className:"h-4 w-4 mr-1"}),"New Task"]})]})]}),s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[s.jsxs("button",{onClick:()=>f("active"),className:`p-3 rounded-lg border text-left transition-colors ${a==="active"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs font-medium",children:[s.jsx(FU,{className:"h-3.5 w-3.5"}),"Active"]}),s.jsx("p",{className:"text-xl font-bold mt-1",children:W.total})]}),s.jsxs("button",{onClick:()=>f("overdue"),className:`p-3 rounded-lg border text-left transition-colors ${a==="overdue"?"border-destructive bg-destructive/5":"hover:bg-muted/50"}`,children:[s.jsxs("div",{className:"flex items-center gap-2 text-destructive text-xs font-medium",children:[s.jsx(JS,{className:"h-3.5 w-3.5"}),"Overdue"]}),s.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:W.overdue})]}),s.jsxs("button",{onClick:()=>{f("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs font-medium",children:[s.jsx(Dl,{className:"h-3.5 w-3.5"}),"Due Today"]}),s.jsx("p",{className:"text-xl font-bold mt-1",children:W.dueToday})]}),s.jsxs("button",{onClick:()=>{f("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 text-blue-600 text-xs font-medium",children:[s.jsx(pm,{className:"h-3.5 w-3.5"}),"This Week"]}),s.jsx("p",{className:"text-xl font-bold mt-1",children:W.dueThisWeek})]}),s.jsxs("button",{onClick:()=>f("done"),className:`p-3 rounded-lg border text-left transition-colors ${a==="done"?"border-emerald-500 bg-emerald-500/5":"hover:bg-muted/50"}`,children:[s.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 text-xs font-medium",children:[s.jsx(oc,{className:"h-3.5 w-3.5"}),"Completed"]}),s.jsx("p",{className:"text-xl font-bold mt-1",children:W.completed})]})]}),s.jsx(nRt,{tasks:t||[]}),s.jsx(iRt,{}),s.jsxs("div",{className:"flex flex-col md:flex-row gap-3 items-start md:items-center",children:[s.jsxs("div",{className:"relative flex-1 max-w-sm",children:[s.jsx(xd,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(Br,{placeholder:"Search tasks...",value:o,onChange:Y=>c(Y.target.value),className:"pl-9"})]}),s.jsxs(ba,{value:p,onValueChange:y,children:[s.jsx(oa,{className:"w-[130px]",children:s.jsx(wa,{placeholder:"Priority"})}),s.jsxs(la,{children:[s.jsx(mn,{value:"all",children:"All Priorities"}),s.jsx(mn,{value:"urgent",children:"🔴 Urgent"}),s.jsx(mn,{value:"high",children:"🟠 High"}),s.jsx(mn,{value:"medium",children:"🟡 Medium"}),s.jsx(mn,{value:"low",children:"🟢 Low"})]})]}),s.jsxs(ba,{value:v,onValueChange:T,children:[s.jsx(oa,{className:"w-[160px]",children:s.jsx(wa,{placeholder:"Deal"})}),s.jsxs(la,{children:[s.jsx(mn,{value:"all",children:"All Deals"}),s.jsx(mn,{value:"no_deal",children:"No Deal"}),V.map(Y=>s.jsx(mn,{value:Y.id,children:Y.name},Y.id))]})]}),s.jsxs(ba,{value:E,onValueChange:Y=>k(Y),children:[s.jsx(oa,{className:"w-[170px]",children:s.jsx(wa,{})}),s.jsxs(la,{children:[s.jsx(mn,{value:"all",children:"Everyone's"}),s.jsx(mn,{value:"mine",children:"My to-dos"}),s.jsx(mn,{value:"assigned",children:"Assigned to me"}),s.jsx(mn,{value:"delegated",children:"Delegated by me"})]})]}),s.jsxs("div",{className:"flex items-center border rounded-lg p-0.5 ml-auto",children:[s.jsx("button",{onClick:()=>i("list"),className:`p-1.5 rounded-md transition-colors ${n==="list"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:s.jsx(FU,{className:"h-4 w-4"})}),s.jsx("button",{onClick:()=>i("kanban"),className:`p-1.5 rounded-md transition-colors ${n==="kanban"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:s.jsx(j9,{className:"h-4 w-4"})}),s.jsx("button",{onClick:()=>i("calendar"),className:`p-1.5 rounded-md transition-colors ${n==="calendar"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:s.jsx(pm,{className:"h-4 w-4"})})]})]}),e?s.jsx("div",{className:"flex items-center justify-center py-20",children:s.jsx("div",{className:"animate-spin h-8 w-8 border-2 border-primary border-t-transparent rounded-full"})}):s.jsxs(s.Fragment,{children:[n==="list"&&s.jsx(VPt,{tasks:G}),n==="kanban"&&s.jsx(WPt,{tasks:G}),n==="calendar"&&s.jsx(YPt,{tasks:G})]}),s.jsx(Uje,{open:R,onOpenChange:D}),s.jsx(XPt,{open:M,onOpenChange:B,stages:r||[]})]})})}const nHt={pending_payment:"Pending Payment",order_submitted:"Order Submitted",awaiting_proof_approval:"Awaiting Proof Approval",proof_approved:"Proof Approved",processing:"Processing",in_production:"In Production",shipped:"Shipped",completed:"Completed",cancelled:"Cancelled",refunded:"Refunded"},iHt={pending_payment:"bg-yellow-100 text-yellow-800",order_submitted:"bg-blue-100 text-blue-800",awaiting_proof_approval:"bg-orange-100 text-orange-800",proof_approved:"bg-green-100 text-green-800",processing:"bg-purple-100 text-purple-800",in_production:"bg-indigo-100 text-indigo-800",shipped:"bg-cyan-100 text-cyan-800",completed:"bg-green-200 text-green-900",cancelled:"bg-red-100 text-red-800",refunded:"bg-gray-100 text-gray-800"};function aRt(t=!0){return mr({queryKey:["marketplace-categories",t],queryFn:async()=>{let e=Re.from("marketplace_categories").select("*").order("sort_order",{ascending:!0});t&&(e=e.eq("is_active",!0));const{data:r,error:n}=await e;if(n)throw n;return r}})}function sHt(){const t=Ar();return Sr({mutationFn:async e=>{const{data:r,error:n}=await Re.from("marketplace_categories").insert([e]).select().single();if(n)throw n;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-categories"]}),Vt.success("Category created successfully")},onError:e=>{Vt.error("Failed to create category: "+e.message)}})}function aHt(){const t=Ar();return Sr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Re.from("marketplace_categories").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-categories"]}),Vt.success("Category updated successfully")},onError:e=>{Vt.error("Failed to update category: "+e.message)}})}function oHt(){const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("marketplace_categories").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-categories"]}),Vt.success("Category deleted successfully")},onError:e=>{Vt.error("Failed to delete category: "+e.message)}})}function oRt(t,e=!0){return mr({queryKey:["marketplace-products",t,e],queryFn:async()=>{let r=Re.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).order("sort_order",{ascending:!0});t&&(r=r.eq("category_id",t)),e&&(r=r.eq("is_active",!0));const{data:n,error:i}=await r;if(i)throw i;return n}})}function lHt(t){return mr({queryKey:["marketplace-product",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).eq("id",t).single();if(r)throw r;return e},enabled:!!t})}function cHt(){const t=Ar();return Sr({mutationFn:async e=>{const{data:r,error:n}=await Re.from("marketplace_products").insert([e]).select().single();if(n)throw n;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-products"]}),Vt.success("Product created successfully")},onError:e=>{Vt.error("Failed to create product: "+e.message)}})}function uHt(){const t=Ar();return Sr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Re.from("marketplace_products").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["marketplace-products"]}),t.invalidateQueries({queryKey:["marketplace-product",r.id]}),Vt.success("Product updated successfully")},onError:e=>{Vt.error("Failed to update product: "+e.message)}})}function dHt(){const t=Ar();return Sr({mutationFn:async e=>{const{error:r}=await Re.from("marketplace_products").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-products"]}),Vt.success("Product deleted successfully")},onError:e=>{Vt.error("Failed to delete product: "+e.message)}})}function hHt(){const t=Ar();return Sr({mutationFn:async e=>{const{data:r,error:n}=await Re.from("marketplace_product_images").insert([e]).select().single();if(n)throw n;return r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["marketplace-products"]}),t.invalidateQueries({queryKey:["marketplace-product",r.product_id]})}})}function fHt(){const t=Ar();return Sr({mutationFn:async({id:e,productId:r})=>{const{error:n}=await Re.from("marketplace_product_images").delete().eq("id",e);if(n)throw n;return r},onSuccess:e=>{t.invalidateQueries({queryKey:["marketplace-products"]}),t.invalidateQueries({queryKey:["marketplace-product",e]}),Vt.success("Image deleted successfully")},onError:e=>{Vt.error("Failed to delete image: "+e.message)}})}function mHt(){const t=Ar();return Sr({mutationFn:async({imageId:e,productId:r})=>{const{error:n}=await Re.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",r);if(n)throw n;const{error:i}=await Re.from("marketplace_product_images").update({is_primary:!0}).eq("id",e);if(i)throw i;return r},onSuccess:e=>{t.invalidateQueries({queryKey:["marketplace-products"]}),t.invalidateQueries({queryKey:["marketplace-product",e]}),Vt.success("Primary image updated")},onError:e=>{Vt.error("Failed to set primary image: "+e.message)}})}function pHt(){const t=Ar();return Sr({mutationFn:async e=>{const{data:r,error:n}=await Re.from("marketplace_product_variants").insert([e]).select().single();if(n)throw n;return r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["marketplace-products"]}),t.invalidateQueries({queryKey:["marketplace-product",r.product_id]}),Vt.success("Variant added successfully")}})}function gHt(){const t=Ar();return Sr({mutationFn:async({id:e,productId:r})=>{const{error:n}=await Re.from("marketplace_product_variants").delete().eq("id",e);if(n)throw n;return r},onSuccess:e=>{t.invalidateQueries({queryKey:["marketplace-products"]}),t.invalidateQueries({queryKey:["marketplace-product",e]}),Vt.success("Variant deleted successfully")}})}function yHt(){const t=Ar();return Sr({mutationFn:async({productId:e,videoUrl:r})=>{await Re.from("marketplace_product_videos").delete().eq("product_id",e);const{data:n,error:i}=await Re.from("marketplace_product_videos").insert({product_id:e,video_url:r}).select().single();if(i)throw i;return n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["marketplace-products"]}),t.invalidateQueries({queryKey:["marketplace-product",r.productId]}),Vt.success("Video updated successfully")}})}function xHt(t){const{isAdmin:e}=Hn();return mr({queryKey:["marketplace-orders",t,e],queryFn:async()=>{let r=Re.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).order("created_at",{ascending:!1});const{data:n,error:i}=await r;if(i)throw i;if(e&&n){const o=[...new Set(n.map(f=>f.user_id))],{data:c}=await Re.from("profiles").select("id, name, email").in("id",o),a=new Map((c==null?void 0:c.map(f=>[f.id,f]))||[]);return n.map(f=>({...f,user:a.get(f.user_id)}))}return n}})}function vHt(){const{user:t}=Hn();return mr({queryKey:["my-marketplace-orders",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await Re.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("user_id",t.id).order("created_at",{ascending:!1});if(r)throw r;return e},enabled:!!(t!=null&&t.id)})}function _Ht(t){return mr({queryKey:["marketplace-order",t],queryFn:async()=>{const{data:e,error:r}=await Re.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("id",t).single();if(r)throw r;return e},enabled:!!t})}function bHt(){const t=Ar(),{user:e}=Hn();return Sr({mutationFn:async({orderId:r,status:n,notes:i,trackingNumber:o,trackingUrl:c,previousStatus:a})=>{const f={status:n};o!==void 0&&(f.tracking_number=o),c!==void 0&&(f.tracking_url=c);const{error:p}=await Re.from("marketplace_orders").update(f).eq("id",r);if(p)throw p;const{error:y}=await Re.from("marketplace_order_status_history").insert({order_id:r,status:n,notes:i,created_by:e==null?void 0:e.id});if(y)throw y;if(["shipped","in_production","processing","completed"].includes(n)&&n!==a)try{await Re.functions.invoke("marketplace-order-notify",{body:{orderId:r,notificationType:n==="shipped"?"shipped":"status_update",newStatus:n,trackingNumber:o,trackingUrl:c}})}catch(T){console.error("Failed to send notification email:",T)}},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["marketplace-orders"]}),t.invalidateQueries({queryKey:["marketplace-order",n.orderId]}),t.invalidateQueries({queryKey:["my-marketplace-orders"]}),Vt.success("Order status updated")},onError:r=>{Vt.error("Failed to update order: "+r.message)}})}function wHt(){const t=Ar();return Sr({mutationFn:async({itemId:e,proofUrl:r,proofNotes:n,orderId:i})=>{const{error:o}=await Re.from("marketplace_order_items").update({proof_url:r,proof_notes:n,proof_status:"pending"}).eq("id",e);if(o)throw o;await Re.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",i);try{await Re.functions.invoke("marketplace-order-notify",{body:{orderId:i,notificationType:"proof_ready"}})}catch(c){console.error("Failed to send proof notification:",c)}return i},onSuccess:e=>{t.invalidateQueries({queryKey:["marketplace-orders"]}),t.invalidateQueries({queryKey:["marketplace-order",e]}),t.invalidateQueries({queryKey:["my-marketplace-orders"]}),Vt.success("Proof uploaded & customer notified")}})}function SHt(){const t=Ar();return Sr({mutationFn:async({itemId:e,orderId:r})=>{const{error:n}=await Re.from("marketplace_order_items").update({proof_status:"approved"}).eq("id",e);if(n)throw n;return r},onSuccess:e=>{t.invalidateQueries({queryKey:["marketplace-orders"]}),t.invalidateQueries({queryKey:["marketplace-order",e]}),t.invalidateQueries({queryKey:["my-marketplace-orders"]}),Vt.success("Proof approved")}})}function THt(){const t=Ar();return Sr({mutationFn:async({itemId:e,orderId:r,reason:n})=>{const{error:i}=await Re.from("marketplace_order_items").update({proof_status:"rejected",proof_notes:n}).eq("id",e);if(i)throw i;return r},onSuccess:e=>{t.invalidateQueries({queryKey:["marketplace-orders"]}),t.invalidateQueries({queryKey:["marketplace-order",e]}),t.invalidateQueries({queryKey:["my-marketplace-orders"]}),Vt.success("Proof rejected - please upload a new proof")}})}function lRt(){const t=Hs(),[e,r]=C.useState(null),{data:n,isLoading:i}=oRt(e||void 0,!0),{data:o,isLoading:c}=aRt(!0),{cartItems:a}=c_e(),f=a.reduce((y,v)=>y+v.quantity,0),p=y=>{t(`/marketplace/${y.id}`)};return i||c?s.jsx(hS,{title:"Marketplace",children:s.jsxs("div",{className:"space-y-6",children:[s.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[1,2,3].map(y=>s.jsx(ml,{className:"h-10 w-24 flex-shrink-0"},y))}),s.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:[1,2,3,4].map(y=>s.jsx(ml,{className:"h-72 w-full"},y))})]})}):s.jsx(hS,{title:"Marketplace",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Marketplace"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"Shop exclusive products for LevelUp members"})]}),s.jsxs(Bt,{variant:"outline",onClick:()=>t("/marketplace/cart"),className:"relative",children:[s.jsx(_me,{className:"h-4 w-4 mr-2"}),"Cart",f>0&&s.jsx(ss,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:f})]})]}),o&&o.length>0&&s.jsxs("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[s.jsx(Bt,{variant:e===null?"default":"outline",size:"sm",onClick:()=>r(null),children:"All"}),o.map(y=>s.jsx(Bt,{variant:e===y.id?"default":"outline",size:"sm",onClick:()=>r(y.id),children:y.name},y.id))]}),n&&n.length>0?s.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:n.map(y=>{var v;return s.jsxs($n,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>p(y),children:[s.jsxs("div",{className:"aspect-square bg-muted relative",children:[y.images&&y.images.length>0?s.jsx("img",{src:((v=y.images.find(T=>T.is_primary))==null?void 0:v.image_url)||y.images[0].image_url,alt:y.name,className:"w-full h-full object-cover"}):s.jsx("div",{className:"flex items-center justify-center h-full",children:s.jsx($ee,{className:"h-12 w-12 text-muted-foreground"})}),y.category&&s.jsx(ss,{className:"absolute top-2 left-2",variant:"secondary",children:y.category.name})]}),s.jsxs(Kn,{className:"p-4",children:[s.jsx("h3",{className:"font-semibold mb-1 line-clamp-1",children:y.name}),y.description&&s.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:y.description}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("span",{className:"font-bold text-lg",children:["$",Number(y.base_price).toFixed(2)]}),y.variants&&y.variants.length>0&&s.jsxs("span",{className:"text-xs text-muted-foreground",children:[y.variants.length," options"]})]})]})]},y.id)})}):s.jsxs("div",{className:"text-center py-12",children:[s.jsx($ee,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),s.jsx("p",{className:"text-muted-foreground",children:"No products available yet."})]})]})})}const dN={home_anniversary:{title:["Happy Home","Anniversary"],icon:"🏡",emojis:["🏡","✨","🎉","❤️","🎊","🏠"],defaultMessage:"Wishing you many more wonderful years of memories in your beautiful home. Thank you for letting me be part of your journey."},wedding_anniversary:{title:["Happy","Anniversary"],icon:"💍",emojis:["💍","💐","❤️","🥂","💕","✨"],defaultMessage:"Wishing you both a wonderful anniversary filled with love, laughter, and cherished memories. Here's to many more years together!"},just_listed:{title:["Just","Listed!"],icon:"🏠",emojis:["🏠","📋","🔑","⭐","🎯","✨"],defaultMessage:"Exciting news — this beautiful property just hit the market! Contact me for a private showing."},just_sold:{title:["Just","Sold!"],icon:"🎉",emojis:["🎉","🏡","🔑","🥂","🎊","💰"],defaultMessage:"Another successful closing! Congratulations to the new homeowners. It was a pleasure making this happen."},congratulations:{title:["Congratulations!",""],icon:"🏆",emojis:["🎉","🥳","🏆","⭐","🎊","✨"],defaultMessage:"What an incredible milestone! I'm so happy for you. Wishing you all the best in this exciting new chapter."},birthday:{title:["Happy","Birthday!"],icon:"🎂",emojis:["🎂","🎈","🎁","🥳","🎉","🧁"],defaultMessage:"Wishing you the happiest of birthdays! May this year bring you joy, laughter, and everything you've been dreaming of."},holiday:{title:["Happy","Holidays!"],icon:"🎄",emojis:["🎄","❄️","🎁","⭐","🕯️","🎅"],defaultMessage:"Wishing you and your family a season filled with warmth, joy, and cherished moments. Happy Holidays!"},thank_you:{title:["Thank","You!"],icon:"💐",emojis:["💐","🙏","❤️","⭐","✨","🤝"],defaultMessage:"Thank you so much for your trust and confidence. It truly means the world to me. I'm always here for you!"},thinking_of_you:{title:["Thinking","Of You"],icon:"💭",emojis:["💭","❤️","🌸","☀️","🦋","💫"],defaultMessage:"Just wanted to reach out and let you know I'm thinking of you. I hope you're doing well — don't hesitate to reach out anytime!"}};function E2({delay:t,x:e,y:r,size:n}){return s.jsx(fr.div,{className:"absolute rounded-full bg-slate-300/30 dark:bg-slate-500/20",style:{left:e,top:r,width:n,height:n},animate:{y:[0,-20,0],opacity:[.3,.7,.3],scale:[1,1.2,1]},transition:{duration:4,delay:t,repeat:1/0,ease:"easeInOut"}})}function cRt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:o,agentName:c,agentPhotoUrl:a,agentPhone:f,agentEmail:p,agentBrokerage:y,propertyPhotoUrl:v,videoUrl:T}=t,E=dN[e];return s.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-blue-50/30 to-white dark:from-slate-950 dark:to-slate-900 flex items-center justify-center p-4 overflow-hidden relative",children:[s.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[s.jsx(fr.div,{className:"absolute -top-20 -right-20 w-72 h-72 rounded-full bg-gradient-to-br from-blue-100/40 to-slate-100/20 blur-3xl",animate:{scale:[1,1.1,1],rotate:[0,5,0]},transition:{duration:8,repeat:1/0,ease:"easeInOut"}}),s.jsx(fr.div,{className:"absolute -bottom-20 -left-20 w-64 h-64 rounded-full bg-gradient-to-tr from-slate-200/30 to-blue-100/20 blur-3xl",animate:{scale:[1,1.15,1],rotate:[0,-5,0]},transition:{duration:10,repeat:1/0,ease:"easeInOut"}}),s.jsx(E2,{delay:0,x:"15%",y:"20%",size:8}),s.jsx(E2,{delay:1,x:"80%",y:"30%",size:6}),s.jsx(E2,{delay:2,x:"60%",y:"70%",size:10}),s.jsx(E2,{delay:.5,x:"25%",y:"80%",size:7}),s.jsx(E2,{delay:1.5,x:"70%",y:"15%",size:5})]}),s.jsxs(fr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,ease:"easeOut"},children:[s.jsxs(fr.div,{className:"bg-white/80 dark:bg-slate-900/80 backdrop-blur-xl rounded-3xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.1)] overflow-hidden border border-slate-200/60 dark:border-slate-700/50",initial:{scale:.95},animate:{scale:1},transition:{duration:.6,delay:.2},children:[s.jsx("div",{className:"relative h-2 bg-gradient-to-r from-slate-200 via-blue-300 to-slate-200 dark:from-slate-700 dark:via-blue-500 dark:to-slate-700 overflow-hidden",children:s.jsx(fr.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/60 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:3,repeat:1/0,repeatDelay:2,ease:"easeInOut"}})}),s.jsxs("div",{className:"px-8 py-10 text-center",children:[s.jsxs(fr.div,{className:"mx-auto mb-6 h-20 w-20 rounded-2xl bg-gradient-to-br from-slate-100 to-blue-50 dark:from-slate-800 dark:to-slate-700 flex items-center justify-center shadow-lg relative",initial:{scale:0,rotate:-10},animate:{scale:1,rotate:0},transition:{duration:.5,delay:.4,type:"spring",stiffness:200},children:[s.jsx(fr.div,{className:"absolute inset-0 rounded-2xl border-2 border-slate-200/50 dark:border-slate-600/50",animate:{scale:[1,1.15,1],opacity:[.5,0,.5]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut"}}),s.jsx("span",{className:"text-4xl",children:E.icon})]}),e==="home_anniversary"&&i!==null&&i>0&&s.jsx(fr.div,{className:"inline-block mb-4",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:s.jsxs("span",{className:"text-sm font-semibold tracking-[0.25em] uppercase text-blue-400 dark:text-blue-300",children:[i," ",i===1?"Year":"Years"]})}),s.jsx(fr.h1,{className:"text-4xl font-light text-slate-800 dark:text-slate-100 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:E.title[0]}),E.title[1]&&s.jsx(fr.h2,{className:"text-4xl font-bold text-slate-800 dark:text-slate-100 mb-8 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:E.title[1]}),s.jsxs(fr.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,delay:1},children:[s.jsx("p",{className:"text-xl font-medium text-slate-700 dark:text-slate-200 mb-1",children:r}),n&&s.jsx("p",{className:"text-sm text-slate-400 dark:text-slate-500 mb-6",children:n})]}),s.jsx(fr.div,{className:"h-px bg-gradient-to-r from-transparent via-slate-300 dark:via-slate-600 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"80%"},transition:{duration:.8,delay:1.1},style:{margin:"0 auto 1.5rem"}}),v&&s.jsx(fr.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:s.jsx("img",{src:v,alt:"Property",className:"w-full h-48 object-cover"})}),T&&s.jsx(fr.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:s.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),s.jsx(fr.p,{className:"text-sm text-slate-500 dark:text-slate-400 leading-relaxed max-w-xs mx-auto mb-8 italic",initial:{opacity:0},animate:{opacity:1},transition:{duration:.6,delay:1.3},children:o||E.defaultMessage}),s.jsxs(fr.div,{className:"border-t border-slate-100 dark:border-slate-800 pt-6",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.5,delay:1.5},children:[s.jsxs("div",{className:"flex items-center justify-center gap-3",children:[a?s.jsx(fr.img,{src:a,alt:c,className:"h-12 w-12 rounded-full object-cover ring-2 ring-slate-200 dark:ring-slate-700 shadow-md",whileHover:{scale:1.1}}):s.jsx("div",{className:"h-12 w-12 rounded-full bg-gradient-to-br from-slate-200 to-blue-100 dark:from-slate-700 dark:to-slate-600 flex items-center justify-center shadow-md",children:s.jsx("span",{className:"text-sm font-semibold text-slate-600 dark:text-slate-300",children:c.charAt(0)})}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:"text-sm font-semibold text-slate-700 dark:text-slate-200",children:c}),y&&s.jsx("p",{className:"text-xs text-slate-400 dark:text-slate-500",children:y})]})]}),s.jsxs("div",{className:"flex items-center justify-center gap-3 mt-4",children:[f&&s.jsxs(fr.a,{href:`tel:${f}`,className:"flex items-center gap-1.5 px-4 py-2 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors shadow-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(ri,{className:"h-3.5 w-3.5"})," Call"]}),p&&s.jsxs(fr.a,{href:`mailto:${p}`,className:"flex items-center gap-1.5 px-4 py-2 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors shadow-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(mi,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),s.jsx(fr.p,{className:"text-center text-[10px] text-slate-400 dark:text-slate-600 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function t6({delay:t,x:e,y:r,color:n,size:i}){return s.jsx(fr.div,{className:`absolute rounded-full blur-2xl ${n}`,style:{left:e,top:r,width:i,height:i},animate:{scale:[1,1.4,1],opacity:[.2,.5,.2]},transition:{duration:5,delay:t,repeat:1/0,ease:"easeInOut"}})}function j2({delay:t,x:e,y:r}){return s.jsx(fr.div,{className:"absolute text-white/30 text-lg",style:{left:e,top:r},animate:{opacity:[0,1,0],scale:[.5,1,.5],rotate:[0,180,360]},transition:{duration:3,delay:t,repeat:1/0,ease:"easeInOut"},children:"✦"})}const Hle={home_anniversary:{bg:"from-violet-950 via-purple-900 to-fuchsia-950",orbs:["bg-violet-500/30","bg-fuchsia-500/25","bg-purple-400/20"]},birthday:{bg:"from-pink-950 via-rose-900 to-fuchsia-950",orbs:["bg-pink-500/30","bg-rose-500/25","bg-fuchsia-400/20"]},just_sold:{bg:"from-emerald-950 via-teal-900 to-cyan-950",orbs:["bg-emerald-500/30","bg-teal-500/25","bg-cyan-400/20"]},just_listed:{bg:"from-amber-950 via-orange-900 to-yellow-950",orbs:["bg-amber-500/30","bg-orange-500/25","bg-yellow-400/20"]},thank_you:{bg:"from-rose-950 via-pink-900 to-red-950",orbs:["bg-rose-500/30","bg-pink-500/25","bg-red-400/20"]},congratulations:{bg:"from-yellow-950 via-amber-900 to-orange-950",orbs:["bg-yellow-500/30","bg-amber-500/25","bg-orange-400/20"]},holiday:{bg:"from-red-950 via-rose-900 to-emerald-950",orbs:["bg-red-500/30","bg-green-500/25","bg-rose-400/20"]},thinking_of_you:{bg:"from-indigo-950 via-violet-900 to-purple-950",orbs:["bg-indigo-500/30","bg-violet-500/25","bg-purple-400/20"]}};function uRt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:o,agentName:c,agentPhotoUrl:a,agentPhone:f,agentEmail:p,agentBrokerage:y,propertyPhotoUrl:v,videoUrl:T}=t,E=dN[e],k=Hle[e]||Hle.home_anniversary;return s.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${k.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[s.jsx(t6,{delay:0,x:"10%",y:"10%",color:k.orbs[0],size:200}),s.jsx(t6,{delay:1,x:"70%",y:"60%",color:k.orbs[1],size:180}),s.jsx(t6,{delay:2,x:"50%",y:"20%",color:k.orbs[2],size:150}),s.jsx(j2,{delay:0,x:"20%",y:"25%"}),s.jsx(j2,{delay:.8,x:"75%",y:"15%"}),s.jsx(j2,{delay:1.6,x:"85%",y:"65%"}),s.jsx(j2,{delay:2.4,x:"10%",y:"75%"}),s.jsx(j2,{delay:.4,x:"45%",y:"85%"}),s.jsxs(fr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.7,ease:"easeOut"},children:[s.jsxs(fr.div,{className:"relative rounded-3xl overflow-hidden",initial:{scale:.9},animate:{scale:1},transition:{duration:.5,delay:.2,type:"spring",stiffness:150},children:[s.jsx(fr.div,{className:"absolute -inset-[1px] rounded-3xl bg-gradient-to-r from-violet-500 via-fuchsia-500 to-violet-500 opacity-50",animate:{backgroundPosition:["0% 50%","100% 50%","0% 50%"]},transition:{duration:4,repeat:1/0,ease:"linear"},style:{backgroundSize:"200% 200%"}}),s.jsxs("div",{className:"relative bg-white/5 backdrop-blur-xl border border-white/10 rounded-3xl px-8 py-10 text-center m-[1px]",children:[s.jsxs(fr.div,{className:"mx-auto mb-6 h-20 w-20 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-2xl shadow-violet-500/40 relative",initial:{scale:0,rotate:-20},animate:{scale:1,rotate:0},transition:{duration:.6,delay:.4,type:"spring",stiffness:200},children:[s.jsx(fr.div,{className:"absolute inset-0 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500",animate:{scale:[1,1.3,1],opacity:[.6,0,.6]},transition:{duration:2,repeat:1/0,ease:"easeInOut"}}),s.jsx("span",{className:"text-4xl relative z-10",children:E.icon})]}),e==="home_anniversary"&&i!==null&&i>0&&s.jsxs(fr.div,{className:"inline-flex items-center gap-2 mb-5 px-5 py-2 rounded-full bg-white/10 border border-white/15 backdrop-blur-sm",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:[s.jsx(fr.span,{className:"text-3xl font-black text-white",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.8},children:i}),s.jsx("span",{className:"text-xs font-semibold text-violet-200 uppercase tracking-widest",children:i===1?"Year":"Years"})]}),s.jsx(fr.h1,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-violet-200 via-white to-fuchsia-200 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:E.title[0]}),E.title[1]&&s.jsx(fr.h2,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-fuchsia-300 via-violet-200 to-purple-300 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:E.title[1]}),s.jsx(fr.div,{className:"text-3xl mb-4",initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},transition:{duration:.4,delay:1,type:"spring",stiffness:300},children:E.emojis.slice(0,3).join("")}),s.jsxs(fr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[s.jsx("p",{className:"text-xl font-semibold text-white/90 mb-1",children:r}),n&&s.jsxs("p",{className:"text-sm text-violet-300/70 mb-6 flex items-center justify-center gap-1.5",children:[s.jsx(va,{className:"h-3.5 w-3.5"}),n]})]}),v&&s.jsx(fr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:s.jsx("img",{src:v,alt:"Property",className:"w-full h-48 object-cover"})}),T&&s.jsx(fr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:s.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),s.jsx(fr.div,{className:"bg-white/5 rounded-2xl p-5 border border-white/10 mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:s.jsx("p",{className:"text-sm text-violet-100/80 leading-relaxed",children:o||E.defaultMessage})}),s.jsxs(fr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[s.jsxs("div",{className:"flex items-center justify-center gap-3",children:[a?s.jsx(fr.img,{src:a,alt:c,className:"h-12 w-12 rounded-xl object-cover ring-2 ring-violet-500/40 shadow-lg",whileHover:{scale:1.1}}):s.jsx("div",{className:"h-12 w-12 rounded-xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-lg",children:s.jsx("span",{className:"text-sm font-bold text-white",children:c.charAt(0)})}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:"text-sm font-bold text-white",children:c}),y&&s.jsx("p",{className:"text-xs text-violet-300/60",children:y})]})]}),s.jsxs("div",{className:"flex items-center justify-center gap-2 mt-5",children:[f&&s.jsxs(fr.a,{href:`tel:${f}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-violet-500/30 to-fuchsia-500/30 text-xs font-semibold text-white hover:from-violet-500/50 hover:to-fuchsia-500/50 transition-all border border-white/15 shadow-lg",whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(ri,{className:"h-3.5 w-3.5"})," Call Me"]}),p&&s.jsxs(fr.a,{href:`mailto:${p}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-violet-500/30 to-fuchsia-500/30 text-xs font-semibold text-white hover:from-violet-500/50 hover:to-fuchsia-500/50 transition-all border border-white/15 shadow-lg",whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(mi,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),s.jsx(fr.p,{className:"text-center text-[10px] text-violet-400/40 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function dRt({emoji:t,delay:e,x:r,duration:n}){return s.jsx(fr.div,{className:"absolute text-2xl pointer-events-none",style:{left:r,bottom:-20},animate:{y:[0,-600],opacity:[0,1,1,0],x:[0,15,-10,5],rotate:[0,20,-15,10]},transition:{duration:n,delay:e,repeat:1/0,ease:"easeOut"},children:t})}const Wle={home_anniversary:{bg:"from-amber-50 via-orange-50 to-rose-50",header:"from-amber-400 via-orange-400 to-rose-400",accent:"text-amber-900",text:"text-amber-800"},birthday:{bg:"from-pink-50 via-rose-50 to-fuchsia-50",header:"from-pink-400 via-rose-400 to-fuchsia-400",accent:"text-pink-900",text:"text-pink-800"},just_sold:{bg:"from-emerald-50 via-teal-50 to-cyan-50",header:"from-emerald-400 via-teal-400 to-cyan-400",accent:"text-emerald-900",text:"text-emerald-800"},just_listed:{bg:"from-sky-50 via-blue-50 to-indigo-50",header:"from-sky-400 via-blue-400 to-indigo-400",accent:"text-blue-900",text:"text-blue-800"},thank_you:{bg:"from-rose-50 via-pink-50 to-red-50",header:"from-rose-400 via-pink-400 to-red-400",accent:"text-rose-900",text:"text-rose-800"},congratulations:{bg:"from-yellow-50 via-amber-50 to-orange-50",header:"from-yellow-400 via-amber-400 to-orange-400",accent:"text-amber-900",text:"text-amber-800"},holiday:{bg:"from-red-50 via-green-50 to-emerald-50",header:"from-red-500 via-green-500 to-emerald-500",accent:"text-green-900",text:"text-green-800"},thinking_of_you:{bg:"from-violet-50 via-purple-50 to-indigo-50",header:"from-violet-400 via-purple-400 to-indigo-400",accent:"text-violet-900",text:"text-violet-800"}};function hRt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:o,agentName:c,agentPhotoUrl:a,agentPhone:f,agentEmail:p,agentBrokerage:y,propertyPhotoUrl:v,videoUrl:T}=t,E=dN[e],k=Wle[e]||Wle.home_anniversary;return s.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${k.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[E.emojis.map((P,R)=>s.jsx(dRt,{emoji:P,delay:R*1.2,x:`${15+R*14}%`,duration:5+R%3},R)),s.jsx(fr.div,{className:"absolute top-1/4 left-1/2 -translate-x-1/2 w-96 h-96 bg-gradient-to-r from-amber-200/30 to-rose-200/30 rounded-full blur-[100px]",animate:{scale:[1,1.2,1],opacity:[.3,.5,.3]},transition:{duration:6,repeat:1/0,ease:"easeInOut"}}),s.jsxs(fr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.7},children:[s.jsxs(fr.div,{className:"bg-white rounded-3xl shadow-[0_20px_60px_-15px_rgba(251,146,60,0.2)] overflow-hidden border border-amber-100",initial:{scale:.9},animate:{scale:1},transition:{duration:.5,delay:.2,type:"spring",stiffness:150},children:[s.jsxs(fr.div,{className:`h-28 bg-gradient-to-r ${k.header} relative overflow-hidden`,children:[s.jsx(fr.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:3,repeat:1/0,repeatDelay:2,ease:"easeInOut"}}),s.jsx(fr.div,{className:"absolute top-3 left-10 text-5xl",animate:{rotate:[0,10,-5,0],y:[0,-3,0]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:E.emojis[0]}),s.jsx(fr.div,{className:"absolute top-2 right-14 text-3xl",animate:{scale:[1,1.3,1],rotate:[0,15,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut",delay:.5},children:E.emojis[1]}),s.jsx(fr.div,{className:"absolute bottom-2 left-1/2 -translate-x-1/2 text-3xl",animate:{y:[0,-5,0],scale:[1,1.1,1]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut",delay:1},children:E.emojis[2]})]}),s.jsxs("div",{className:"px-8 py-8 text-center -mt-10 relative",children:[s.jsx(fr.div,{className:"mx-auto mb-4 h-20 w-20 rounded-full bg-white shadow-xl flex items-center justify-center border-4 border-white relative",initial:{scale:0},animate:{scale:1},transition:{delay:.4,type:"spring",stiffness:300},children:s.jsx(fr.div,{animate:{scale:[1,1.2,1]},transition:{duration:1.5,repeat:1/0,ease:"easeInOut"},children:s.jsx("span",{className:"text-3xl",children:E.icon})})}),e==="home_anniversary"&&i!==null&&i>0&&s.jsx(fr.div,{className:"mb-3",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{delay:.6},children:s.jsxs("span",{className:`inline-flex items-baseline gap-1.5 ${k.accent}`,children:[s.jsx(fr.span,{className:"text-5xl font-black",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.8},children:i}),s.jsx("span",{className:"text-sm font-semibold",children:i===1?"year":"wonderful years"})]})}),s.jsxs(fr.h1,{className:`text-3xl font-bold ${k.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[E.title.join(" ")," ",E.emojis[4]]}),s.jsxs(fr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[s.jsx("p",{className:`text-lg font-semibold ${k.text} mb-1`,children:r}),n&&s.jsxs("p",{className:`text-sm ${k.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[s.jsx(Es,{className:"h-3 w-3"}),n]})]}),v&&s.jsx(fr.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:s.jsx("img",{src:v,alt:"Property",className:"w-full h-48 object-cover"})}),T&&s.jsx(fr.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:s.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),s.jsx(fr.div,{className:"bg-gradient-to-br from-amber-50 to-orange-50 rounded-2xl p-5 mb-6 border border-amber-100 shadow-inner",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:s.jsxs("p",{className:`text-sm ${k.text} leading-relaxed italic`,children:['"',o||E.defaultMessage,'"']})}),s.jsxs(fr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[s.jsxs("div",{className:"flex items-center gap-3 justify-center",children:[a?s.jsx(fr.img,{src:a,alt:c,className:"h-12 w-12 rounded-full object-cover ring-2 ring-amber-200 shadow-md",whileHover:{scale:1.1}}):s.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${k.header} flex items-center justify-center shadow-md`,children:s.jsx("span",{className:"text-sm font-bold text-white",children:c.charAt(0)})}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:`text-sm font-bold ${k.accent}`,children:c}),y&&s.jsx("p",{className:`text-xs ${k.text} opacity-60`,children:y})]})]}),s.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[f&&s.jsxs(fr.a,{href:`tel:${f}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${k.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(ri,{className:"h-3.5 w-3.5"})," Call"]}),p&&s.jsxs(fr.a,{href:`mailto:${p}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${k.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(mi,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),s.jsx(fr.p,{className:"text-center text-[10px] text-amber-400 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function VR({delay:t,x:e,y:r,size:n,color:i}){return s.jsx(fr.div,{className:`absolute rounded-full ${i} blur-3xl`,style:{left:e,top:r,width:n,height:n},animate:{scale:[1,1.3,1],opacity:[.4,.7,.4],x:[0,20,-10,0],y:[0,-15,10,0]},transition:{duration:8,delay:t,repeat:1/0,ease:"easeInOut"}})}function r6({delay:t,x:e,y:r,size:n}){return s.jsx(fr.div,{className:"absolute rounded-full border border-white/10",style:{left:e,top:r,width:n,height:n},animate:{scale:[1,1.2,1],opacity:[.1,.3,.1],rotate:[0,180,360]},transition:{duration:12,delay:t,repeat:1/0,ease:"linear"}})}const Kle={home_anniversary:{mesh:["bg-sky-400/40","bg-indigo-500/30","bg-violet-400/25"],accent:"text-sky-200",glow:"shadow-sky-500/20"},birthday:{mesh:["bg-pink-400/40","bg-fuchsia-500/30","bg-purple-400/25"],accent:"text-pink-200",glow:"shadow-pink-500/20"},just_sold:{mesh:["bg-emerald-400/40","bg-teal-500/30","bg-cyan-400/25"],accent:"text-emerald-200",glow:"shadow-emerald-500/20"},just_listed:{mesh:["bg-amber-400/40","bg-orange-500/30","bg-yellow-400/25"],accent:"text-amber-200",glow:"shadow-amber-500/20"},thank_you:{mesh:["bg-rose-400/40","bg-pink-500/30","bg-red-400/25"],accent:"text-rose-200",glow:"shadow-rose-500/20"},congratulations:{mesh:["bg-yellow-400/40","bg-amber-500/30","bg-orange-400/25"],accent:"text-yellow-200",glow:"shadow-yellow-500/20"},holiday:{mesh:["bg-red-400/40","bg-emerald-500/30","bg-green-400/25"],accent:"text-red-200",glow:"shadow-red-500/20"},thinking_of_you:{mesh:["bg-violet-400/40","bg-indigo-500/30","bg-blue-400/25"],accent:"text-violet-200",glow:"shadow-violet-500/20"}};function fRt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:o,agentName:c,agentPhotoUrl:a,agentPhone:f,agentEmail:p,agentBrokerage:y,propertyPhotoUrl:v,videoUrl:T}=t,E=dN[e],k=Kle[e]||Kle.home_anniversary;return s.jsxs("div",{className:"min-h-screen bg-slate-950 flex items-center justify-center p-4 overflow-hidden relative",children:[s.jsx(VR,{delay:0,x:"5%",y:"10%",size:300,color:k.mesh[0]}),s.jsx(VR,{delay:2,x:"60%",y:"50%",size:250,color:k.mesh[1]}),s.jsx(VR,{delay:4,x:"30%",y:"70%",size:200,color:k.mesh[2]}),s.jsx(VR,{delay:1,x:"80%",y:"15%",size:180,color:k.mesh[0]}),s.jsx(r6,{delay:0,x:"15%",y:"20%",size:100}),s.jsx(r6,{delay:3,x:"70%",y:"60%",size:140}),s.jsx(r6,{delay:6,x:"40%",y:"10%",size:80}),s.jsx("div",{className:"absolute inset-0 opacity-[0.03]",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E")`}}),s.jsxs(fr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.8,ease:[.16,1,.3,1]},children:[s.jsxs(fr.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${k.glow}`,initial:{scale:.92},animate:{scale:1},transition:{duration:.6,delay:.2,type:"spring",stiffness:120},children:[s.jsx("div",{className:"relative h-[2px] bg-gradient-to-r from-transparent via-white/20 to-transparent overflow-hidden",children:s.jsx(fr.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/60 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:4,repeat:1/0,repeatDelay:3,ease:"easeInOut"}})}),s.jsxs("div",{className:"px-8 py-10 text-center",children:[s.jsxs(fr.div,{className:"mx-auto mb-6 h-24 w-24 rounded-3xl bg-white/[0.08] backdrop-blur-xl border border-white/[0.15] flex items-center justify-center relative",initial:{scale:0,rotate:-15},animate:{scale:1,rotate:0},transition:{duration:.6,delay:.4,type:"spring",stiffness:180},children:[s.jsx(fr.div,{className:"absolute -inset-1 rounded-3xl border border-white/[0.08]",animate:{scale:[1,1.1,1],opacity:[.3,0,.3]},transition:{duration:3,repeat:1/0,ease:"easeInOut"}}),s.jsx(fr.span,{className:"text-5xl",animate:{scale:[1,1.08,1]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:E.icon})]}),e==="home_anniversary"&&i!==null&&i>0&&s.jsxs(fr.div,{className:"inline-flex items-center gap-2 mb-5 px-5 py-2 rounded-full bg-white/[0.06] border border-white/[0.1] backdrop-blur-sm",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:[s.jsx(fr.span,{className:"text-3xl font-black text-white",initial:{opacity:0},animate:{opacity:1},transition:{delay:.8},children:i}),s.jsx("span",{className:`text-[10px] font-bold uppercase tracking-[0.2em] ${k.accent}`,children:i===1?"Year":"Years"})]}),s.jsx(fr.h1,{className:"text-4xl font-extralight text-white/90 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.7},children:E.title[0]}),E.title[1]&&s.jsx(fr.h2,{className:"text-4xl font-bold text-white mb-6 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.85},children:E.title[1]}),s.jsxs(fr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1},children:[s.jsx("p",{className:"text-xl font-medium text-white/80 mb-1",children:r}),n&&s.jsxs("p",{className:"text-sm text-white/30 mb-6 flex items-center justify-center gap-1.5",children:[s.jsx(Es,{className:"h-3 w-3"})," ",n]})]}),s.jsx(fr.div,{className:"h-px bg-gradient-to-r from-transparent via-white/15 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"70%"},transition:{duration:1,delay:1.1},style:{margin:"0 auto 1.5rem"}}),v&&s.jsx(fr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:s.jsx("img",{src:v,alt:"Property",className:"w-full h-48 object-cover"})}),T&&s.jsx(fr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:s.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),s.jsx(fr.div,{className:"bg-white/[0.04] rounded-2xl p-5 border border-white/[0.08] mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:s.jsxs("p",{className:"text-sm text-white/60 leading-relaxed italic",children:['"',o||E.defaultMessage,'"']})}),s.jsxs(fr.div,{className:"border-t border-white/[0.06] pt-6",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[s.jsxs("div",{className:"flex items-center justify-center gap-3",children:[a?s.jsx(fr.img,{src:a,alt:c,className:"h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10",whileHover:{scale:1.08}}):s.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white/[0.08] border border-white/[0.1] flex items-center justify-center",children:s.jsx("span",{className:"text-sm font-semibold text-white/60",children:c.charAt(0)})}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:"text-sm font-semibold text-white/80",children:c}),y&&s.jsx("p",{className:"text-xs text-white/30",children:y})]})]}),s.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[f&&s.jsxs(fr.a,{href:`tel:${f}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/70 hover:bg-white/[0.12] transition-colors backdrop-blur-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(ri,{className:"h-3.5 w-3.5"})," Call"]}),p&&s.jsxs(fr.a,{href:`mailto:${p}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/70 hover:bg-white/[0.12] transition-colors backdrop-blur-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(mi,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),s.jsx(fr.p,{className:"text-center text-[10px] text-white/20 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function n6({delay:t,x:e,angle:r,color:n}){return s.jsx(fr.div,{className:`absolute h-[400px] w-[1px] ${n} origin-top`,style:{left:e,top:"-10%",transform:`rotate(${r}deg)`},animate:{opacity:[0,.4,0],scaleY:[.5,1,.5]},transition:{duration:6,delay:t,repeat:1/0,ease:"easeInOut"}})}function qR({delay:t,x:e}){return s.jsx(fr.div,{className:"absolute w-1 h-1 rounded-full bg-amber-400/60",style:{left:e,bottom:"20%"},animate:{y:[0,-200,-400],x:[0,15,-10],opacity:[0,.8,0],scale:[0,1.5,0]},transition:{duration:4,delay:t,repeat:1/0,ease:"easeOut"}})}const Yle={home_anniversary:{gradient:"from-slate-950 via-blue-950 to-slate-950",accent:"from-blue-400 to-cyan-300",stripe:"bg-blue-400/20"},birthday:{gradient:"from-slate-950 via-rose-950 to-slate-950",accent:"from-rose-400 to-pink-300",stripe:"bg-rose-400/20"},just_sold:{gradient:"from-slate-950 via-emerald-950 to-slate-950",accent:"from-emerald-400 to-green-300",stripe:"bg-emerald-400/20"},just_listed:{gradient:"from-slate-950 via-amber-950 to-slate-950",accent:"from-amber-400 to-yellow-300",stripe:"bg-amber-400/20"},thank_you:{gradient:"from-slate-950 via-pink-950 to-slate-950",accent:"from-pink-400 to-rose-300",stripe:"bg-pink-400/20"},congratulations:{gradient:"from-slate-950 via-yellow-950 to-slate-950",accent:"from-yellow-400 to-amber-300",stripe:"bg-yellow-400/20"},holiday:{gradient:"from-slate-950 via-red-950 to-slate-950",accent:"from-red-400 to-green-400",stripe:"bg-red-400/20"},thinking_of_you:{gradient:"from-slate-950 via-purple-950 to-slate-950",accent:"from-purple-400 to-violet-300",stripe:"bg-purple-400/20"}};function mRt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:o,agentName:c,agentPhotoUrl:a,agentPhone:f,agentEmail:p,agentBrokerage:y,propertyPhotoUrl:v,videoUrl:T}=t,E=dN[e],k=Yle[e]||Yle.home_anniversary;return s.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${k.gradient} flex items-center justify-center p-4 overflow-hidden relative`,children:[s.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(255,255,255,0.04)_0%,transparent_60%)]"}),s.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_bottom,rgba(0,0,0,0.6)_0%,transparent_60%)]"}),s.jsx(n6,{delay:0,x:"20%",angle:15,color:k.stripe}),s.jsx(n6,{delay:2,x:"75%",angle:-12,color:k.stripe}),s.jsx(n6,{delay:4,x:"50%",angle:5,color:k.stripe}),s.jsx(qR,{delay:0,x:"30%"}),s.jsx(qR,{delay:1.5,x:"60%"}),s.jsx(qR,{delay:3,x:"45%"}),s.jsx(qR,{delay:.7,x:"75%"}),s.jsx("div",{className:"absolute inset-0 opacity-[0.015] mix-blend-overlay",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 512 512' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.7' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`}}),s.jsxs(fr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[s.jsx(fr.div,{className:"relative overflow-hidden",initial:{y:50},animate:{y:0},transition:{duration:.8,delay:.3,ease:[.16,1,.3,1]},children:s.jsxs("div",{className:"px-8 py-12 text-center",children:[s.jsx(fr.div,{className:"mx-auto mb-8 relative",initial:{scale:0},animate:{scale:1},transition:{duration:.8,delay:.5,type:"spring",stiffness:100},children:s.jsx(fr.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${k.accent} flex items-center justify-center shadow-2xl`,animate:{boxShadow:["0 0 40px rgba(255,255,255,0.05)","0 0 80px rgba(255,255,255,0.1)","0 0 40px rgba(255,255,255,0.05)"]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:s.jsx("span",{className:"text-4xl",children:E.icon})})}),e==="home_anniversary"&&i!==null&&i>0&&s.jsxs(fr.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[s.jsx(fr.span,{className:`text-6xl font-black bg-gradient-to-r ${k.accent} bg-clip-text text-transparent`,initial:{scale:.5,opacity:0},animate:{scale:1,opacity:1},transition:{delay:.9,type:"spring"},children:i}),s.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-white/30 mt-1",children:i===1?"Year":"Years"})]}),s.jsx("div",{className:"overflow-hidden mb-2",children:s.jsx(fr.h1,{className:"text-5xl font-thin text-white/90 tracking-wide",initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.8,ease:[.16,1,.3,1]},children:E.title[0]})}),E.title[1]&&s.jsx("div",{className:"overflow-hidden mb-8",children:s.jsx(fr.h2,{className:`text-5xl font-black bg-gradient-to-r ${k.accent} bg-clip-text text-transparent`,initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.95,ease:[.16,1,.3,1]},children:E.title[1]})}),s.jsxs(fr.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.1,duration:.6},children:[s.jsx("p",{className:"text-lg font-light text-white/70 tracking-wide",children:r}),n&&s.jsxs("p",{className:"text-xs text-white/25 mt-1 flex items-center justify-center gap-1",children:[s.jsx(Es,{className:"h-3 w-3"})," ",n]})]}),s.jsxs(fr.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[s.jsx(fr.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-r from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"right"}}),s.jsx(fr.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),s.jsx(fr.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-l from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"left"}})]}),v&&s.jsxs(fr.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.3,duration:.6},children:[s.jsx("img",{src:v,alt:"Property",className:"w-full h-48 object-cover"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-950/30 to-transparent pointer-events-none"})]}),T&&s.jsx(fr.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.35,duration:.6},children:s.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),s.jsx(fr.p,{className:"text-sm text-white/40 leading-relaxed max-w-xs mx-auto mb-10 font-light",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.4,duration:.8},children:o||E.defaultMessage}),s.jsxs(fr.div,{className:"pt-6 border-t border-white/[0.04]",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{delay:1.6,duration:.6},children:[s.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[a?s.jsx(fr.img,{src:a,alt:c,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/10 shadow-xl",whileHover:{scale:1.1}}):s.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${k.accent} flex items-center justify-center shadow-xl`,children:s.jsx("span",{className:"text-sm font-bold text-slate-900",children:c.charAt(0)})}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:"text-sm font-medium text-white/70",children:c}),y&&s.jsx("p",{className:"text-[11px] text-white/25",children:y})]})]}),s.jsxs("div",{className:"flex items-center justify-center gap-2",children:[f&&s.jsxs(fr.a,{href:`tel:${f}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${k.accent} text-xs font-semibold text-slate-900 shadow-lg`,whileHover:{scale:1.05,boxShadow:"0 10px 40px rgba(255,255,255,0.15)"},whileTap:{scale:.95},children:[s.jsx(ri,{className:"h-3.5 w-3.5"})," Call"]}),p&&s.jsxs(fr.a,{href:`mailto:${p}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/60 hover:bg-white/[0.12] transition-colors",whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(mi,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),s.jsx(fr.p,{className:"text-center text-[10px] text-white/10 mt-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:2.2},children:"Powered by LevelUp"})]})]})}function qje(){const{shareToken:t}=Pm(),{data:e,isLoading:r,error:n}=mr({queryKey:["public-sendable-card",t],queryFn:async()=>{const{data:c,error:a}=await Re.from("sendable_cards").select("*").eq("share_token",t).single();if(a)throw a;return c},enabled:!!t});if(C.useEffect(()=>{if(!e)return;const c=(e.recipient_name||"").trim().split(/\s+/)[0],f={home_anniversary:"Happy Home Anniversary",birthday:"Happy Birthday",wedding_anniversary:"Happy Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",holiday:"Happy Holidays",thank_you:"Thank You",thinking_of_you:"Thinking of You"}[e.card_type]||"A card for you";document.title=c?`${f}, ${c}!`:`${f}!`},[e]),C.useEffect(()=>{t&&Re.rpc("log_sendable_card_view",{p_share_token:t}).then(({error:c})=>{c&&console.error("Error tracking view:",c)})},[t]),r)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:s.jsxs("div",{className:"animate-pulse space-y-4 text-center",children:[s.jsx("div",{className:"h-8 w-48 bg-muted rounded mx-auto"}),s.jsx("div",{className:"h-4 w-32 bg-muted rounded mx-auto"})]})});if(n||!e)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Card not found"}),s.jsx("p",{className:"text-muted-foreground",children:"This card may have been removed or the link is invalid."})]})});const i=e.home_anniversary_date?Math.floor((Date.now()-gS(e.home_anniversary_date).getTime())/(365.25*24*60*60*1e3)):null,o={cardType:e.card_type||"home_anniversary",recipientName:e.recipient_name,propertyAddress:e.property_address,anniversaryYears:i,customMessage:e.custom_message,agentName:e.agent_name,agentPhotoUrl:e.agent_photo_url,agentPhone:e.agent_phone,agentEmail:e.agent_email,agentBrokerage:e.agent_brokerage,propertyPhotoUrl:e.property_photo_url,videoUrl:e.video_url||null};switch(e.template){case"bold":return s.jsx(uRt,{...o});case"warm":return s.jsx(hRt,{...o});case"glass":return s.jsx(fRt,{...o});case"cinematic":return s.jsx(mRt,{...o});case"elegant":default:return s.jsx(cRt,{...o})}}const pRt=Object.freeze(Object.defineProperty({__proto__:null,default:qje},Symbol.toStringTag,{value:"Module"})),Gje=()=>{const t=ki();return C.useEffect(()=>{if(/[?&]authorization_id=/.test(t.search)||t.pathname.startsWith("/oauth")){window.location.replace(`https://dashboard.relevelup.com/oauth-connect${t.search}`);return}console.error("404 Error: User attempted to access non-existent route:",t.pathname)},[t.pathname,t.search]),s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-100",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"mb-4 text-4xl font-bold",children:"404"}),s.jsx("p",{className:"mb-4 text-xl text-gray-600",children:"Oops! Page not found"}),s.jsx("a",{href:"/",className:"text-blue-500 underline hover:text-blue-700",children:"Return to Home"})]})})};function gRt(){return C.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),s.jsxs(Cy,{children:[s.jsx(xe,{path:"/c/:shareToken",element:s.jsx(qje,{})}),s.jsx(xe,{path:"*",element:s.jsx(Gje,{})})]})}function yRt(t,e){return e?t.find(r=>r.id===e)??null:null}const i6={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"},xRt=["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","America/Anchorage","Pacific/Honolulu","Europe/London","Europe/Paris","Asia/Dubai","Asia/Singapore","Asia/Tokyo","Australia/Sydney"];function vRt(t,e,r){const[n,i,o]=t.split("-").map(Number),[c,a]=e.split(":").map(Number),f=Date.UTC(n,i-1,o,c,a),p=new Intl.DateTimeFormat("en-US",{timeZone:r,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}),y=Object.fromEntries(p.formatToParts(new Date(f)).filter(T=>T.type!=="literal").map(T=>[T.type,T.value])),v=Date.UTC(Number(y.year),Number(y.month)-1,Number(y.day),Number(y.hour)%24,Number(y.minute));return f+(f-v)}function s6(t){var e;try{return((e=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"short"}).formatToParts(new Date).find(n=>n.type==="timeZoneName"))==null?void 0:e.value)||t}catch{return t}}function Hje({slugOverride:t}){const e=Pm(),r=t||e.slug,[n]=Px(),i=n.get("type"),[o,c]=C.useState("types"),[a,f]=C.useState(null),[p,y]=C.useState(null),[v,T]=C.useState(null),[E,k]=C.useState(new Date),[P,R]=C.useState({name:"",email:"",phone:"",message:""}),[D,M]=C.useState(!1),[B,V]=C.useState(null),[G,W]=C.useState(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"America/New_York"}catch{return"America/New_York"}}),{data:Y,isLoading:J}=mr({queryKey:["public-booking-settings",r],queryFn:async()=>{const{data:we,error:He}=await Re.from("agent_booking_settings").select("*").eq("slug",r).eq("is_active",!0).single();if(He)throw He;return we},enabled:!!r}),{data:Q}=mr({queryKey:["public-booking-profile",Y==null?void 0:Y.user_id],queryFn:async()=>{const{data:we,error:He}=await Re.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",Y.user_id).single();if(He)throw He;return we},enabled:!!(Y!=null&&Y.user_id)}),{data:ee=[]}=mr({queryKey:["public-booking-types",Y==null?void 0:Y.user_id],queryFn:async()=>{const{data:we,error:He}=await Re.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",Y.user_id).eq("is_active",!0).eq("is_coaching_only",!1).order("sort_order");if(He)throw He;return we},enabled:!!(Y!=null&&Y.user_id)});C.useEffect(()=>{if(!i||a||ee.length===0)return;const we=yRt(ee,i);we&&(f(we),c("date"))},[i,ee,a]);const le=Ri(E,"yyyy-MM"),{data:pe={},isFetching:Se}=mr({queryKey:["public-availability-map",r,a==null?void 0:a.id,le],enabled:!!r&&!!a,staleTime:6e4,queryFn:async()=>{const we=new Date(E.getFullYear(),E.getMonth(),1),He=yx(new Date),tt=ck(He,we)?He:we,at=new Date(E.getFullYear(),E.getMonth()+1,0),Et=Math.max(1,Math.round((at.getTime()-tt.getTime())/864e5)+1),{data:vt,error:Gt}=await Re.functions.invoke("agent-booking",{body:{action:"availability",slug:r,booking_type_id:a.id,start:Ri(tt,"yyyy-MM-dd"),days:Math.min(Et,90)}});if(Gt)throw Gt;if(vt!=null&&vt.error)throw new Error(vt.error);return(vt==null?void 0:vt.availability)||{}}}),je=we=>{const He=yx(new Date),tt=Rl(He,(Y==null?void 0:Y.max_advance_days)||30);return rH(we,He)||ck(we,tt)?!1:(pe[Ri(we,"yyyy-MM-dd")]||[]).length>0},Le=C.useMemo(()=>p?pe[Ri(p,"yyyy-MM-dd")]||[]:[],[p,pe]),Ae=C.useMemo(()=>{const we=E.getFullYear(),He=E.getMonth(),tt=new Date(we,He,1),at=new Date(we,He+1,0),Et=tt.getDay(),vt=[];for(let Gt=0;Gt{var we,He;if(!(!a||!p||!v||!P.name||!Y)){M(!0);try{const tt=Ri(p,"yyyy-MM-dd"),{data:at,error:Et}=await Re.functions.invoke("agent-booking",{body:{action:"create",slug:r,booking_type_id:a.id,date:tt,time:v,guest_name:P.name,guest_email:P.email||null,guest_phone:P.phone||null,guest_message:P.message||null,guest_timezone:G}});if(Et){let pt=Et.message;try{const Pt=await((He=(we=Et.context)==null?void 0:we.json)==null?void 0:He.call(we));Pt!=null&&Pt.error&&(pt=Pt.error)}catch{}throw new Error(pt)}if(at!=null&&at.error)throw new Error(at.error);const vt=(at==null?void 0:at.end_time)||v,Gt=at!=null&&at.manage_token?`${window.location.origin}/booking/manage/${at.manage_token}`:null;V(Gt),Re.functions.invoke("booking-notify",{body:{agentUserId:Y.user_id,guestName:P.name,guestEmail:P.email||null,guestPhone:P.phone||null,guestMessage:P.message||null,bookingTypeName:a.name,bookingDate:tt,startTime:v,endTime:vt,durationMinutes:a.duration_minutes,meetingLink:Y.meeting_link||null,manageUrl:Gt}}).catch(pt=>console.error("Booking notify error:",pt)),c("confirmed")}catch(tt){Vt.error("Failed to book: "+tt.message)}finally{M(!1)}}},me=we=>{const[He,tt]=we.split(":").map(Number),at=He>=12?"PM":"AM";return`${He%12||12}:${tt.toString().padStart(2,"0")} ${at}`},Te=(Y==null?void 0:Y.timezone)||"America/New_York",Ne=G!==Te,Ee=(we,He)=>{if(!Ne)return me(He);try{return new Intl.DateTimeFormat("en-US",{timeZone:G,hour:"numeric",minute:"2-digit"}).format(new Date(vRt(we,He,Te)))}catch{return me(He)}};return J?s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center",children:s.jsxs("div",{className:"flex flex-col items-center gap-3",children:[s.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[#406E71] border-t-transparent"}),s.jsx("p",{className:"text-sm text-slate-500",children:"Loading booking page..."})]})}):Y?s.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8]",children:[s.jsx("div",{className:"h-1.5 bg-gradient-to-r from-[#406E71] via-[#5a9a9d] to-[#2a4c64]"}),s.jsxs("div",{className:"max-w-lg mx-auto px-4 py-6 sm:py-10",children:[s.jsxs("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden mb-6",children:[s.jsx("div",{className:"relative bg-gradient-to-r from-[#406E71] to-[#2a4c64] px-6 pt-6 pb-12",children:s.jsxs("div",{className:"absolute inset-0 opacity-10",children:[s.jsx("div",{className:"absolute top-2 right-8 w-20 h-20 rounded-full border-2 border-white/30"}),s.jsx("div",{className:"absolute bottom-4 left-12 w-10 h-10 rounded-full border border-white/20"})]})}),s.jsx("div",{className:"relative -mt-10 px-6",children:s.jsxs("div",{className:"flex items-end gap-4",children:[Q!=null&&Q.avatar_url?s.jsx("img",{src:Q.avatar_url,alt:(Q==null?void 0:Q.name)||"Agent",className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl object-cover border-4 border-white shadow-md"}):s.jsx("div",{className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl bg-gradient-to-br from-[#406E71] to-[#2a4c64] border-4 border-white shadow-md flex items-center justify-center",children:s.jsx(Ml,{className:"h-10 w-10 text-white"})}),s.jsxs("div",{className:"pb-1.5",children:[s.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-slate-800 leading-tight",children:(Q==null?void 0:Q.name)||"Agent"}),(Q==null?void 0:Q.title)&&s.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:Q.title})]})]})}),s.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(Q==null?void 0:Q.phone)&&s.jsxs("a",{href:`tel:${Q.phone}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#406E71]/8 hover:bg-[#406E71]/15 text-[#406E71] text-xs font-medium transition-colors",children:[s.jsx(ri,{className:"h-3.5 w-3.5"}),s.jsx("span",{className:"hidden sm:inline",children:Q.phone}),s.jsx("span",{className:"sm:hidden",children:"Call"})]}),(Q==null?void 0:Q.email)&&s.jsxs("a",{href:`mailto:${Q.email}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#2a4c64]/8 hover:bg-[#2a4c64]/15 text-[#2a4c64] text-xs font-medium transition-colors",children:[s.jsx(mi,{className:"h-3.5 w-3.5"}),s.jsx("span",{className:"hidden sm:inline",children:Q.email}),s.jsx("span",{className:"sm:hidden",children:"Email"})]})]})]}),s.jsx("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden",children:s.jsxs("div",{className:"p-5 sm:p-6",children:[o==="types"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Select a meeting type"}),s.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Choose the type of meeting you'd like to schedule"})]}),s.jsx("div",{className:"space-y-2.5",children:ee.map(we=>s.jsx("button",{onClick:()=>{f(we),c("date")},className:"w-full text-left group",children:s.jsx("div",{className:"relative rounded-xl border border-slate-150 p-4 transition-all duration-200 hover:shadow-md hover:border-[#406E71]/30 hover:-translate-y-0.5 active:translate-y-0",style:{borderLeftWidth:"3px",borderLeftColor:we.color},children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[s.jsx("span",{className:"text-2xl shrink-0 mt-0.5",children:i6[we.icon]||"📅"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"font-semibold text-sm text-slate-800 group-hover:text-[#406E71] transition-colors",children:we.name}),we.description&&s.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:we.description})]})]}),s.jsxs("div",{className:"shrink-0 flex items-center gap-1 px-2.5 py-1 rounded-full bg-slate-100 text-slate-600 text-xs font-medium",children:[s.jsx(Dl,{className:"h-3 w-3"}),we.duration_minutes,"m"]})]})})},we.id))})]}),o==="date"&&a&&s.jsxs("div",{className:"space-y-5",children:[s.jsxs("button",{onClick:()=>{c("types"),y(null),T(null)},className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[s.jsx(dx,{className:"h-3.5 w-3.5"})," Back to meeting types"]}),s.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl border",style:{borderColor:a.color+"40",backgroundColor:a.color+"08"},children:[s.jsx("span",{className:"text-xl",children:i6[a.icon]||"📅"}),s.jsx("div",{className:"flex-1 min-w-0",children:s.jsx("p",{className:"font-semibold text-sm text-slate-800",children:a.name})}),s.jsxs("div",{className:"flex items-center gap-1 text-xs text-slate-500 font-medium",children:[s.jsx(Dl,{className:"h-3 w-3"}),a.duration_minutes," min"]})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Ri(E,"MMMM yyyy")}),s.jsxs("div",{className:"flex gap-1",children:[s.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>k(new Date(E.getFullYear(),E.getMonth()-1)),children:s.jsx(Cm,{className:"h-4 w-4"})}),s.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>k(new Date(E.getFullYear(),E.getMonth()+1)),children:s.jsx(jd,{className:"h-4 w-4"})})]})]}),s.jsxs("div",{className:"grid grid-cols-7 gap-0.5 text-center",children:[["Su","Mo","Tu","We","Th","Fr","Sa"].map(we=>s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:we},we)),Ae.map((we,He)=>{if(!we)return s.jsx("div",{},`pad-${He}`);const tt=je(we),at=p&&rc(we,p),Et=rc(we,new Date);return s.jsx("button",{disabled:!tt,onClick:()=>{y(we),T(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${at?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":tt?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${Et&&!at?"ring-1 ring-[#406E71]/40":""}`,children:we.getDate()},we.toISOString())})]})]}),p&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(pm,{className:"h-4 w-4 text-[#406E71]"}),s.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Ri(p,"EEEE, MMMM d")})]}),s.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl bg-slate-50 border border-slate-100 px-3 py-2",children:[s.jsx("span",{className:"text-[11px] text-slate-500",children:"Times shown in your timezone"}),s.jsx("select",{value:G,onChange:we=>W(we.target.value),className:"text-[11px] font-medium text-slate-700 bg-transparent focus:outline-none cursor-pointer",children:Array.from(new Set([G,Te,...xRt])).map(we=>s.jsxs("option",{value:we,children:[we.replace(/_/g," ")," (",s6(we),")"]},we))})]}),Se&&Le.length===0?s.jsxs("div",{className:"text-center py-8 space-y-2",children:[s.jsx(su,{className:"h-6 w-6 text-slate-300 mx-auto animate-spin"}),s.jsx("p",{className:"text-sm text-slate-400",children:"Checking live availability…"})]}):Le.length===0?s.jsxs("div",{className:"text-center py-8 space-y-2",children:[s.jsx(Dl,{className:"h-8 w-8 text-slate-300 mx-auto"}),s.jsx("p",{className:"text-sm text-slate-400",children:"No available times on this day"}),s.jsx("p",{className:"text-xs text-slate-400",children:"Try selecting a different date"})]}):s.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 max-h-52 overflow-y-auto pr-1 custom-scrollbar",children:Le.map(we=>{const He=v===we;return s.jsx("button",{onClick:()=>T(we),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${He?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-[1.02]":"bg-slate-50 text-slate-700 hover:bg-[#406E71]/10 hover:text-[#406E71] border border-slate-150"}`,children:Ee(Ri(p,"yyyy-MM-dd"),we)},we)})}),v&&s.jsx(Bt,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg",onClick:()=>c("form"),children:"Continue to Details"})]})]}),o==="form"&&a&&p&&v&&s.jsxs("div",{className:"space-y-5",children:[s.jsxs("button",{onClick:()=>c("date"),className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[s.jsx(dx,{className:"h-3.5 w-3.5"})," Back"]}),s.jsxs("div",{className:"rounded-xl bg-gradient-to-r from-[#406E71]/5 to-[#2a4c64]/5 border border-[#406E71]/15 p-4 space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-lg",children:i6[a.icon]||"📅"}),s.jsx("p",{className:"font-semibold text-sm text-slate-800",children:a.name})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-slate-600",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(pm,{className:"h-3.5 w-3.5 text-[#406E71]"}),Ri(p,"EEE, MMM d, yyyy")]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Dl,{className:"h-3.5 w-3.5 text-[#406E71]"}),Ee(Ri(p,"yyyy-MM-dd"),v)," (",s6(G),") · ",a.duration_minutes," min"]})]})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Mr,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),s.jsx(Br,{value:P.name,onChange:we=>R({...P,name:we.target.value}),placeholder:"Jane Smith",className:"h-11 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Mr,{className:"text-xs font-semibold text-slate-700",children:"Email"}),s.jsxs("div",{className:"relative",children:[s.jsx(mi,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),s.jsx(Br,{type:"email",value:P.email,onChange:we=>R({...P,email:we.target.value}),placeholder:"jane@email.com",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Mr,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),s.jsxs("div",{className:"relative",children:[s.jsx(ri,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),s.jsx(Br,{type:"tel",value:P.phone,onChange:we=>R({...P,phone:we.target.value}),placeholder:"(555) 123-4567",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(Mr,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),s.jsx(Ad,{value:P.message,onChange:we=>R({...P,message:we.target.value}),placeholder:"Anything you'd like the agent to know ahead of time?",rows:3,className:"rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20 resize-none"})]})]}),s.jsx(Bt,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg disabled:opacity-60",onClick:be,disabled:!P.name||D,children:D?s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"}),"Booking..."]}):"Confirm Booking"})]}),o==="confirmed"&&s.jsxs("div",{className:"text-center space-y-5 py-6",children:[s.jsxs("div",{className:"relative mx-auto w-20 h-20",children:[s.jsx("div",{className:"absolute inset-0 rounded-full bg-emerald-100 animate-ping opacity-30"}),s.jsx("div",{className:"relative w-20 h-20 rounded-full bg-gradient-to-br from-emerald-400 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-200",children:s.jsx(oc,{className:"h-10 w-10 text-white"})})]}),s.jsxs("div",{children:[s.jsx("h2",{className:"text-2xl font-bold text-slate-800",children:"You're booked!"}),s.jsxs("p",{className:"text-slate-500 mt-1.5",children:[a==null?void 0:a.name," with ",(Q==null?void 0:Q.name)||"your agent"]})]}),s.jsx("div",{className:"inline-flex items-center gap-3 px-5 py-3 rounded-xl bg-slate-50 border border-slate-100",children:s.jsxs("div",{className:"text-left text-sm",children:[s.jsx("p",{className:"font-semibold text-slate-800",children:p&&Ri(p,"EEEE, MMMM d, yyyy")}),s.jsxs("p",{className:"text-slate-500",children:[p&&v?`${Ee(Ri(p,"yyyy-MM-dd"),v)} (${s6(G)})`:""," · ",a==null?void 0:a.duration_minutes," min"]})]})}),s.jsx("p",{className:"text-sm text-slate-400 max-w-xs mx-auto",children:"A confirmation with meeting details will be sent to you shortly."}),B&&s.jsx("div",{className:"pt-1",children:s.jsx("a",{href:B,className:"inline-flex items-center gap-1.5 text-xs font-semibold text-[#406E71] underline underline-offset-4",children:"Reschedule or cancel this meeting"})}),((Q==null?void 0:Q.phone)||(Q==null?void 0:Q.email))&&s.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[s.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wider font-semibold",children:"Contact"}),s.jsxs("div",{className:"flex gap-3",children:[(Q==null?void 0:Q.phone)&&s.jsxs("a",{href:`tel:${Q.phone}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#406E71]/10 text-[#406E71] text-xs font-medium hover:bg-[#406E71]/20 transition-colors",children:[s.jsx(ri,{className:"h-3.5 w-3.5"})," Call"]}),(Q==null?void 0:Q.email)&&s.jsxs("a",{href:`mailto:${Q.email}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#2a4c64]/10 text-[#2a4c64] text-xs font-medium hover:bg-[#2a4c64]/20 transition-colors",children:[s.jsx(mi,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]})}),s.jsx("p",{className:"text-center text-[10px] text-slate-300 mt-6 font-medium tracking-wide uppercase",children:"Powered by LevelUp"})]})]}):s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center p-4",children:s.jsxs("div",{className:"max-w-sm w-full text-center space-y-4",children:[s.jsx("div",{className:"mx-auto w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center",children:s.jsx(pm,{className:"h-8 w-8 text-slate-400"})}),s.jsx("h2",{className:"text-lg font-semibold text-slate-700",children:"Page Not Available"}),s.jsx("p",{className:"text-sm text-slate-500",children:"This booking page doesn't exist or is currently inactive."})]})})}const _Rt=Object.freeze(Object.defineProperty({__proto__:null,default:Hje},Symbol.toStringTag,{value:"Module"}));function bRt(){const e=ki().pathname.slice(1).split("/")[0];return C.useEffect(()=>{document.body.classList.add("booking-page");const r=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(o=>{document.querySelectorAll(o).forEach(c=>{c.style.display="none"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("booking-page"),n.forEach(clearTimeout)}},[]),e?s.jsx(Hje,{slugOverride:e}):s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-950 dark:to-slate-900 flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"LevelUp Scheduler"}),s.jsx("p",{className:"text-muted-foreground",children:"Visit a specific agent's booking URL to schedule a meeting."})]})})}const wRt="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",SRt="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",TRt="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",ERt="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",jRt="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",ARt="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",a6={"minimal-mono":{key:"minimal-mono",label:"Minimal Mono",description:"Clean paper white, restrained.",bg:"#f7f7f5",surface:"#ffffff",border:"#e6e5e0",text:"#111111",textMuted:"#6b6b6b",accent:"#111111",accentText:"#ffffff",headingFont:'"Fraunces", ui-serif, Georgia, serif',bodyFont:'"Inter", system-ui, sans-serif',swatch:["#f7f7f5","#111111","#6b6b6b","#e6e5e0"],defaultCover:ARt},"warm-coastal":{key:"warm-coastal",label:"Warm Coastal",description:"Sand and soft teal.",bg:"linear-gradient(180deg,#faf6ef 0%,#f2ece1 100%)",surface:"#ffffff",border:"#e6dfd1",text:"#2b2a26",textMuted:"#7a746a",accent:"#2f7a7d",accentText:"#ffffff",headingFont:'"Cormorant Garamond", ui-serif, Georgia, serif',bodyFont:'"Karla", system-ui, sans-serif',swatch:["#faf6ef","#2f7a7d","#c9b99a","#2b2a26"],defaultCover:wRt},"deep-luxe":{key:"deep-luxe",label:"Deep Luxe",description:"Charcoal with gold.",bg:"linear-gradient(180deg,#161616 0%,#0d0d0d 100%)",surface:"#1e1e1e",border:"#2c2c2c",text:"#f5f0e0",textMuted:"#a49a80",accent:"#c9a84c",accentText:"#111111",headingFont:'"Instrument Serif", ui-serif, Georgia, serif',bodyFont:'"Work Sans", system-ui, sans-serif',swatch:["#0d0d0d","#c9a84c","#f5f0e0","#2c2c2c"],defaultCover:SRt},sunset:{key:"sunset",label:"Sunset",description:"Peach into magenta.",bg:"linear-gradient(160deg,#ffe4d1 0%,#ffc9b0 40%,#f2a1c5 100%)",surface:"#ffffff",border:"#f6d5ce",text:"#2a1a2f",textMuted:"#7a5a70",accent:"#d84a7a",accentText:"#ffffff",headingFont:'"Sora", system-ui, sans-serif',bodyFont:'"Manrope", system-ui, sans-serif',swatch:["#ffe4d1","#ffc9b0","#f2a1c5","#d84a7a"],defaultCover:TRt},editorial:{key:"editorial",label:"Editorial",description:"Ink black on paper white.",bg:"#f5f3ee",surface:"#ffffff",border:"#d9d6ce",text:"#0d0d0d",textMuted:"#5a564d",accent:"#0d0d0d",accentText:"#f5f3ee",headingFont:'"DM Serif Display", ui-serif, Georgia, serif',bodyFont:'"Fira Sans", system-ui, sans-serif',swatch:["#f5f3ee","#0d0d0d","#d9d6ce","#5a564d"],defaultCover:ERt},playful:{key:"playful",label:"Playful",description:"Blush and lavender.",bg:"linear-gradient(180deg,#fdf3f7 0%,#efe5ff 100%)",surface:"#ffffff",border:"#ecd7e6",text:"#3a2450",textMuted:"#7c6a94",accent:"#9b72cf",accentText:"#ffffff",headingFont:'"Outfit", system-ui, sans-serif',bodyFont:'"Figtree", system-ui, sans-serif',swatch:["#fdf3f7","#efe5ff","#c9a0dc","#9b72cf"],defaultCover:jRt}},EHt=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function kRt(t){return t&&t in a6?a6[t]:a6["minimal-mono"]}function CRt(t,e){const r=e||t.accent;return{background:t.bg,color:t.text,fontFamily:t.bodyFont,"--c-bg":t.bg,"--c-surface":t.surface,"--c-border":t.border,"--c-text":t.text,"--c-text-muted":t.textMuted,"--c-accent":r,"--c-accent-text":t.accentText,"--c-heading-font":t.headingFont,"--c-body-font":t.bodyFont}}function Wje({slugOverride:t}={}){var wo;const{slug:e}=Pm(),r=t||e,[n]=Px(),i=n.get("t"),[o,c]=C.useState(!0),[a,f]=C.useState(null),[p,y]=C.useState(null),v=C.useRef(null),T=C.useRef(null),[E,k]=C.useState(null),[P,R]=C.useState(null),[D,M]=C.useState(!1),[B,V]=C.useState(!1),[G,W]=C.useState(0),[Y,J]=C.useState(!1),[Q,ee]=C.useState(""),[le,pe]=C.useState(""),[Se,je]=C.useState(""),[Le,Ae]=C.useState(""),[be,me]=C.useState(""),[Te,Ne]=C.useState(""),[Ee,we]=C.useState(""),[He,tt]=C.useState(""),[at,Et]=C.useState(""),[vt,Gt]=C.useState(""),[pt,Pt]=C.useState(""),[tr,_t]=C.useState(""),[cr,Tr]=C.useState(""),[sn,ur]=C.useState([]),[xr,rr]=C.useState([]),[vn,ct]=C.useState(""),[jt,er]=C.useState(""),[Pr,dr]=C.useState(""),[ar,Nt]=C.useState([]);C.useEffect(()=>{gr()},[r,i]);const gr=async()=>{if(!r)return;c(!0);const{data:Zr,error:fn}=await Re.from("contact_intake_pages").select("*").eq("slug",r).eq("is_active",!0).maybeSingle();if(fn||!Zr){J(!0),c(!1);return}y(Zr),T.current=Zr;const{data:xn}=await Re.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",Zr.user_id).single();if(xn){let Xr;if(xn.brokerage_id){const{data:Fn}=await Re.from("brokerages").select("name").eq("id",xn.brokerage_id).single();Xr=(Fn==null?void 0:Fn.name)||void 0}let ui=xn.avatar_url||null;if(!ui){const{data:Fn}=Re.storage.from("avatars").getPublicUrl(`${Zr.user_id}/avatar.jpg`);Fn!=null&&Fn.publicUrl&&(ui=`${Fn.publicUrl}?t=${Date.now()}`)}const en={...xn,avatar_url:ui,brokerage_name:Xr};f(en),v.current=en}if(i)try{console.log("[ConnectPage] Resolving token:",i,"for page:",Zr.id);const{data:Xr,error:ui}=await Re.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:i,page_id:Zr.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:Xr,resolveErr:ui}),!ui&&(Xr!=null&&Xr.contact_id)){R(Xr.contact_id);const en=Xr.contact;en&&(k(en),ee(en.first_name||""),pe(en.last_name||""),je(en.email||""),Ae(en.phone||""),me(en.address||""),Ne(en.city||""),we(en.state||""),tt(en.zip||""),Et(en.birthday||""),Gt(en.home_anniversary||""))}}catch(Xr){console.error("Failed to resolve token:",Xr)}c(!1)},En=async()=>{var Zr,fn;if(!Q.trim()){Vt.error("Please enter your first name");return}if(!r){Vt.error("Invalid page. Please refresh.");return}V(!0);try{let xn=(Zr=T.current)==null?void 0:Zr.id,Xr=(fn=T.current)==null?void 0:fn.user_id;if(!xn||!Xr){const{data:Fn}=await Re.from("contact_intake_pages").select("id, user_id").eq("slug",r).eq("is_active",!0).maybeSingle();if(!Fn){Vt.error("This page is no longer active. Please contact the agent directly."),V(!1);return}xn=Fn.id,Xr=Fn.user_id}const ui={intake_page_id:xn,agent_user_id:Xr,existing_contact_id:P,first_name:Q.trim(),last_name:le.trim()||null,email:Se.trim()||null,phone:Le.trim()||null,address:be.trim()||null,city:Te.trim()||null,state:Ee.trim()||null,zip:He.trim()||null,birthday:at||null,home_anniversary:vt||null,real_estate_interest:pt||null,message:tr.trim()||null,life_events:{spouse_name:cr.trim()||null,kids:sn.filter(Fn=>Fn.name.trim()),pets:xr.filter(Fn=>Fn.name.trim()),favorite_spots:vn.trim()||null,dream_neighborhood:jt.trim()||null,wedding_anniversary:Pr||null},referrals:ar.filter(Fn=>Fn.name.trim()&&Fn.contact.trim())},{error:en}=await Re.from("contact_intake_submissions").insert(ui);if(console.log("[ConnectPage] Insert result:",{error:en}),en)throw en;i&&await Re.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",i);try{const Fn=[Q.trim(),le.trim()].filter(Boolean).join(" ");await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/connect-page-notify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentUserId:Xr,contactName:Fn,contactEmail:Se.trim()||null,contactPhone:Le.trim()||null,slug:r})})}catch(Fn){console.warn("Connect page notification failed (non-blocking):",Fn)}M(!0)}catch(xn){console.error(xn),Vt.error("Something went wrong. Please try again.")}finally{V(!1)}};if(o)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:s.jsx(su,{className:"h-8 w-8 animate-spin text-slate-400"})});if(Y)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:s.jsxs("div",{className:"text-center space-y-3",children:[s.jsx("h1",{className:"text-2xl font-semibold text-slate-700",children:"Page Not Found"}),s.jsx("p",{className:"text-slate-500",children:"This connect page doesn't exist or is no longer active."})]})});if(D)return s.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50 p-4",children:[s.jsx(Zo,{children:s.jsxs("title",{children:["Thank You | ",a==null?void 0:a.name]})}),s.jsxs(fr.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"max-w-md w-full text-center space-y-6 p-8",children:[s.jsx(fr.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",delay:.2},className:"mx-auto w-20 h-20 rounded-full bg-emerald-100 flex items-center justify-center",children:s.jsx(oc,{className:"h-10 w-10 text-emerald-600"})}),s.jsx("h1",{className:"text-3xl font-bold text-slate-800",children:"Thank You!"}),s.jsxs("p",{className:"text-lg text-slate-600",children:[a==null?void 0:a.name," has received your info and will be in touch soon."]}),s.jsxs("div",{className:"flex items-center justify-center gap-1 text-sm text-slate-400 pt-4",children:[s.jsx(bm,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const ni=!!i&&!!E,ii=(p==null?void 0:p.show_little_things)??!0,Ui=[{title:ni?"Confirm Your Info":"Let's Get Connected",fields:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"First Name *"}),s.jsx("input",{type:"text",value:Q,onChange:Zr=>ee(Zr.target.value),placeholder:"Jane",className:"connect-input",required:!0})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Last Name"}),s.jsx("input",{type:"text",value:le,onChange:Zr=>pe(Zr.target.value),placeholder:"Smith",className:"connect-input"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Email"}),s.jsx("input",{type:"email",value:Se,onChange:Zr=>je(Zr.target.value),placeholder:"jane@email.com",className:"connect-input"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Phone"}),s.jsx("input",{type:"tel",value:Le,onChange:Zr=>Ae(Zr.target.value),placeholder:"(555) 123-4567",className:"connect-input"})]})]})},{title:"A Little More About You",fields:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Street Address"}),s.jsx("input",{type:"text",value:be,onChange:Zr=>me(Zr.target.value),placeholder:"123 Main St",className:"connect-input"})]}),s.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[s.jsxs("div",{className:"col-span-2",children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"City"}),s.jsx("input",{type:"text",value:Te,onChange:Zr=>Ne(Zr.target.value),placeholder:"Austin",className:"connect-input"})]}),s.jsxs("div",{className:"col-span-1",children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"State"}),s.jsx("input",{type:"text",value:Ee,onChange:Zr=>we(Zr.target.value),placeholder:"TX",maxLength:2,className:"connect-input"})]}),s.jsxs("div",{className:"col-span-2",children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Zip"}),s.jsx("input",{type:"text",value:He,onChange:Zr=>tt(Zr.target.value),placeholder:"78701",className:"connect-input"})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Birthday"}),s.jsx("input",{type:"date",value:at,onChange:Zr=>Et(Zr.target.value),className:"connect-input"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Home Anniversary"}),s.jsx("input",{type:"date",value:vt,onChange:Zr=>Gt(Zr.target.value),className:"connect-input"})]})]})]})},...ii?[{title:"The Little Things",subtitle:"Optional — helps me remember what matters to you.",fields:s.jsxs("div",{className:"space-y-5",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Spouse / partner's name"}),s.jsx("input",{type:"text",value:cr,onChange:Zr=>Tr(Zr.target.value),placeholder:"Alex",className:"connect-input"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Wedding anniversary"}),s.jsx("input",{type:"date",value:Pr,onChange:Zr=>dr(Zr.target.value),className:"connect-input"})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Kids"}),s.jsxs("button",{type:"button",onClick:()=>ur(Zr=>[...Zr,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[s.jsx(gm,{className:"h-3 w-3"})," Add"]})]}),s.jsxs("div",{className:"space-y-2",children:[sn.length===0&&s.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),sn.map((Zr,fn)=>s.jsxs("div",{className:"flex gap-2 items-center",children:[s.jsx("input",{type:"text",value:Zr.name,onChange:xn=>ur(Xr=>Xr.map((ui,en)=>en===fn?{...ui,name:xn.target.value}:ui)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),s.jsx("input",{type:"text",value:Zr.age,onChange:xn=>ur(Xr=>Xr.map((ui,en)=>en===fn?{...ui,age:xn.target.value}:ui)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),s.jsx("button",{type:"button",onClick:()=>ur(xn=>xn.filter((Xr,ui)=>ui!==fn)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:s.jsx(Os,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},fn))]})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Pets"}),s.jsxs("button",{type:"button",onClick:()=>rr(Zr=>[...Zr,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[s.jsx(gm,{className:"h-3 w-3"})," Add"]})]}),s.jsxs("div",{className:"space-y-2",children:[xr.length===0&&s.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),xr.map((Zr,fn)=>s.jsxs("div",{className:"flex gap-2 items-center",children:[s.jsx("input",{type:"text",value:Zr.name,onChange:xn=>rr(Xr=>Xr.map((ui,en)=>en===fn?{...ui,name:xn.target.value}:ui)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),s.jsx("input",{type:"text",value:Zr.kind,onChange:xn=>rr(Xr=>Xr.map((ui,en)=>en===fn?{...ui,kind:xn.target.value}:ui)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),s.jsx("button",{type:"button",onClick:()=>rr(xn=>xn.filter((Xr,ui)=>ui!==fn)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:s.jsx(Os,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},fn))]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Favorite local spots"}),s.jsx("input",{type:"text",value:vn,onChange:Zr=>ct(Zr.target.value),placeholder:"That coffee shop on Main, Town Lake…",className:"connect-input"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Dream neighborhood"}),s.jsx("input",{type:"text",value:jt,onChange:Zr=>er(Zr.target.value),placeholder:"Where you'd love to live someday",className:"connect-input"})]}),s.jsxs("div",{className:"rounded-xl p-4",style:{background:"color-mix(in srgb, var(--c-accent) 8%, transparent)"},children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium",style:{color:"var(--c-text)"},children:"Know someone who'd love an agent like me?"}),s.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"Refer a friend — up to 3."})]}),ar.length<3&&s.jsxs("button",{type:"button",onClick:()=>Nt(Zr=>[...Zr,{name:"",contact:""}]),className:"text-xs inline-flex items-center gap-1 px-2 py-1 rounded-md",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:[s.jsx(gm,{className:"h-3 w-3"})," Add"]})]}),s.jsx("div",{className:"space-y-2",children:ar.map((Zr,fn)=>s.jsxs("div",{className:"flex gap-2 items-center",children:[s.jsx("input",{type:"text",value:Zr.name,onChange:xn=>Nt(Xr=>Xr.map((ui,en)=>en===fn?{...ui,name:xn.target.value}:ui)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),s.jsx("input",{type:"text",value:Zr.contact,onChange:xn=>Nt(Xr=>Xr.map((ui,en)=>en===fn?{...ui,contact:xn.target.value}:ui)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),s.jsx("button",{type:"button",onClick:()=>Nt(xn=>xn.filter((Xr,ui)=>ui!==fn)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:s.jsx(Os,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},fn))})]})]})}]:[],{title:"One Last Thing",fields:s.jsxs("div",{className:"space-y-5",children:[s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-slate-600 mb-3",children:["Are you thinking about making a move anytime soon? ",s.jsx("span",{className:"text-slate-400 font-normal",children:"(totally optional)"})]}),s.jsx("div",{className:"grid grid-cols-2 gap-3",children:[{value:"buying",label:"🏠 Buying",desc:"Looking for a home"},{value:"selling",label:"📋 Selling",desc:"Thinking of selling"},{value:"both",label:"🔄 Both",desc:"Buy & sell"},{value:"not_now",label:"😊 Not right now",desc:"Just staying connected"}].map(Zr=>s.jsxs("button",{type:"button",onClick:()=>Pt(pt===Zr.value?"":Zr.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${pt===Zr.value?"border-blue-500 bg-blue-50 shadow-sm":"border-slate-200 bg-white hover:border-slate-300"}`,children:[s.jsx("span",{className:"block text-sm font-medium text-slate-800",children:Zr.label}),s.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:Zr.desc})]},Zr.value))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:["Anything else you'd like to share? ",s.jsx("span",{className:"text-slate-400 font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:tr,onChange:Zr=>_t(Zr.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],Ta=Ui.length,vi=kRt(p==null?void 0:p.theme),ca=CRt(vi,(p==null?void 0:p.accent_color)||null),Nr=(p==null?void 0:p.cover_image_url)||vi.defaultCover,Vn=(p==null?void 0:p.headline)||"Let's stay connected",Ks=(p==null?void 0:p.subheadline)||(a!=null&&a.brokerage_name?`${a==null?void 0:a.name} · ${a.brokerage_name}`:(a==null?void 0:a.name)||""),Ea=["deep-luxe"].includes((p==null?void 0:p.theme)||"");return s.jsxs("div",{className:"min-h-screen connect-shell",style:ca,children:[s.jsxs(Zo,{children:[s.jsxs("title",{children:["Connect with ",(a==null?void 0:a.name)||"Agent"]}),s.jsx("meta",{name:"description",content:`${Vn} — ${(a==null?void 0:a.name)||"your agent"}`}),Nr&&s.jsx("meta",{property:"og:image",content:Nr}),s.jsx("meta",{property:"og:title",content:`Connect with ${(a==null?void 0:a.name)||"me"}`}),s.jsx("meta",{property:"og:description",content:Vn}),s.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),s.jsx("style",{children:` .connect-shell { font-family: var(--c-body-font); color: var(--c-text); } .connect-shell h1, .connect-shell h2 { font-family: var(--c-heading-font); } .connect-input { width: 100%; padding: 0.75rem 1rem; border-radius: 0.75rem; border: 1px solid var(--c-border); background: var(--c-surface); color: var(--c-text); font-family: var(--c-body-font); font-size: 0.95rem; transition: border-color 150ms, box-shadow 150ms; } .connect-input::placeholder { color: var(--c-text-muted); opacity: 0.7; } .connect-input:focus { outline: none; border-color: var(--c-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--c-accent) 25%, transparent); } `}),s.jsxs("div",{className:"relative w-full overflow-hidden",style:{height:"clamp(200px, 30vh, 320px)"},children:[s.jsx(fr.img,{src:Nr,alt:"",initial:{scale:1.08},animate:{scale:1},transition:{duration:1.4,ease:"easeOut"},className:"absolute inset-0 w-full h-full object-cover"}),s.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(0,0,0,0) 20%, rgba(0,0,0,0.55) 100%)"}}),s.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-6 pb-16 text-center",children:[s.jsx(fr.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:vi.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:Vn}),Ks&&s.jsx(fr.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:Ks})]})]}),s.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[s.jsxs(fr.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.25},className:"text-center mb-6",children:[a!=null&&a.avatar_url?s.jsx("img",{src:a.avatar_url,alt:a.name,className:"w-24 h-24 rounded-full object-cover mx-auto shadow-xl",style:{border:"4px solid var(--c-surface)"}}):s.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center shadow-xl",style:{background:vi.accent,color:vi.accentText,border:"4px solid var(--c-surface)"},children:s.jsx("span",{className:"text-3xl font-bold",children:((wo=a==null?void 0:a.name)==null?void 0:wo.charAt(0))||"?"})}),(a==null?void 0:a.title)&&s.jsx("p",{className:"text-sm mt-3",style:{color:"var(--c-text-muted)"},children:a.title}),((a==null?void 0:a.phone)||(a==null?void 0:a.email))&&s.jsxs("div",{className:"flex items-center justify-center gap-2 mt-3",children:[(a==null?void 0:a.phone)&&s.jsx("a",{href:`tel:${a.phone}`,className:"flex items-center justify-center w-10 h-10 rounded-full transition-opacity hover:opacity-80",style:{background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)"},"aria-label":"Call agent",children:s.jsx(ri,{className:"h-4 w-4"})}),(a==null?void 0:a.email)&&s.jsx("a",{href:`mailto:${a.email}`,className:"flex items-center justify-center w-10 h-10 rounded-full transition-opacity hover:opacity-80",style:{background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)"},"aria-label":"Email agent",children:s.jsx(mi,{className:"h-4 w-4"})})]})]}),s.jsx(fr.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.35},className:"text-center mb-6 px-2 leading-relaxed text-sm",style:{color:"var(--c-text-muted)"},children:(p==null?void 0:p.welcome_message)||"I'd love to stay in touch — just a few quick details."}),s.jsx("div",{className:"flex gap-1.5 mb-6 px-2",children:Array.from({length:Ta}).map((Zr,fn)=>s.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:fn<=G?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},fn))}),s.jsxs(fr.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.4},className:"rounded-2xl p-6 sm:p-8",style:{background:"var(--c-surface)",border:"1px solid var(--c-border)",boxShadow:Ea?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[s.jsx(Rwe,{mode:"wait",children:s.jsxs(fr.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},children:[s.jsxs("div",{className:"mb-6",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(xs,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),s.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:Ui[G].title})]}),Ui[G].subtitle&&s.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:Ui[G].subtitle})]}),Ui[G].fields]},G)}),s.jsxs("div",{className:"flex justify-between mt-8",children:[G>0?s.jsx("button",{type:"button",onClick:()=>W(Zr=>Zr-1),className:"px-5 py-2.5 text-sm font-medium transition-opacity hover:opacity-70",style:{color:"var(--c-text-muted)"},children:"Back"}):s.jsx("div",{}),G{if(G===0&&!Q.trim()){Vt.error("Please enter your first name");return}W(Zr=>Zr+1)},className:"px-6 py-2.5 text-sm font-medium rounded-xl transition-transform hover:scale-[1.02] shadow-sm",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:"Continue"}):s.jsx("button",{type:"button",onClick:()=>En(),disabled:B,className:"px-6 py-2.5 text-sm font-medium rounded-xl transition-transform hover:scale-[1.02] shadow-sm disabled:opacity-50 flex items-center gap-2",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:B?s.jsxs(s.Fragment,{children:[s.jsx(su,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),G>0&&GW(Zr=>Zr+1),className:"text-xs transition-opacity hover:opacity-80",style:{color:"var(--c-text-muted)"},children:"Skip this step"})})]}),s.jsx("div",{className:"text-center mt-8",children:s.jsxs("div",{className:"flex items-center justify-center gap-1 text-xs",style:{color:"var(--c-text-muted)"},children:[s.jsx(bm,{className:"h-3 w-3"}),s.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const NRt=Object.freeze(Object.defineProperty({__proto__:null,default:Wje},Symbol.toStringTag,{value:"Module"}));function IRt(){const e=ki().pathname.slice(1);return C.useEffect(()=>{document.body.classList.add("connect-page");const r=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(o=>{document.querySelectorAll(o).forEach(c=>{c.style.display="none"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("connect-page"),n.forEach(clearTimeout)}},[]),!e||e===""?s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Connect"}),s.jsx("p",{className:"text-slate-500",children:"Stay connected with your real estate professional."}),s.jsx("p",{className:"text-slate-400 text-sm mt-2",children:"Visit a specific agent link to get started."})]})}):s.jsx(Wje,{slugOverride:e})}function PRt(t){try{const e=document.createElement("canvas"),r=e.width=Math.min(t.naturalWidth,64),n=e.height=Math.min(t.naturalHeight,64),i=e.getContext("2d");if(!i)return!0;i.drawImage(t,0,0,r,n);const o=i.getImageData(0,0,r,n).data,c=[[0,0],[r-1,0],[0,n-1],[r-1,n-1],[Math.floor(r/2),0],[Math.floor(r/2),n-1],[0,Math.floor(n/2)],[r-1,Math.floor(n/2)]];for(const[a,f]of c)if(o[(f*r+a)*4+3]<250)return!0;return!1}catch{return!0}}const RRt={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function LRt({page:t,fields:e,answers:r,setAnswers:n,onSubmit:i,isSubmitting:o,renderField:c}){const a=t.accent_color||"#E8B84A",f=t.primary_color||"#0F1B3D",p=RRt[t.heading_font||"playfair"],y=t.eyebrow||null,v=t.headline_accent||null,T=Array.isArray(t.trust_pills)?t.trust_pills:[],E=e,k=E.length>5;return s.jsxs("section",{className:"relative w-full min-h-screen md:min-h-[760px] overflow-hidden",style:{backgroundColor:f},children:[t.hero_image_url?s.jsx("img",{src:t.hero_image_url,alt:"",className:"absolute inset-0 w-full h-full object-cover",loading:"eager"}):s.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(135deg, ${f}, #000)`}}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/85 via-black/55 to-black/25"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/20"}),s.jsx("div",{className:"relative z-10 mx-auto w-full max-w-7xl px-6 md:px-10 py-16 md:py-24 min-h-screen md:min-h-[760px] flex items-center",children:s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-12 w-full items-center",children:[s.jsxs("div",{className:"lg:col-span-3 text-white",children:[t.logo_url&&s.jsx(DRt,{src:t.logo_url}),y&&s.jsx("p",{className:"text-xs md:text-sm font-semibold tracking-[0.22em] text-white/80 mb-4 uppercase",children:y}),s.jsxs("h1",{className:"font-bold leading-[1.04] mb-5 text-4xl sm:text-5xl md:text-6xl lg:text-[68px]",style:{fontFamily:p,letterSpacing:"-0.015em"},children:[t.hero_headline,v&&s.jsxs(s.Fragment,{children:[" ",s.jsx("span",{style:{color:a,fontStyle:"italic"},children:v})]})]}),t.hero_subtext&&s.jsx("p",{className:"text-base md:text-lg text-white/85 leading-relaxed max-w-xl",children:t.hero_subtext}),t.agent_name&&s.jsxs("div",{className:"mt-8 flex items-center gap-3",children:[t.agent_photo_url&&s.jsx("img",{src:t.agent_photo_url,alt:t.agent_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/30"}),s.jsxs("div",{className:"text-white/90",children:[s.jsx("p",{className:"font-semibold text-sm",children:t.agent_name}),s.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/70 mt-0.5",children:[t.agent_phone&&s.jsxs("a",{href:`tel:${t.agent_phone}`,className:"flex items-center gap-1 hover:text-white",children:[s.jsx(ri,{className:"h-3 w-3"})," ",t.agent_phone]}),t.agent_email&&s.jsxs("a",{href:`mailto:${t.agent_email}`,className:"flex items-center gap-1 hover:text-white",children:[s.jsx(mi,{className:"h-3 w-3"})," ",t.agent_email]})]})]})]})]}),s.jsx("div",{className:"lg:col-span-2",children:s.jsxs("div",{className:"rounded-2xl border border-white/15 bg-white/10 backdrop-blur-xl shadow-2xl p-5 md:p-6",children:[s.jsxs("form",{className:"space-y-3",onSubmit:i,children:[s.jsx("div",{className:k?"space-y-3 max-h-[52vh] overflow-y-auto pr-1 -mr-1":"space-y-3",children:E.map(P=>s.jsxs("div",{children:[s.jsxs(Mr,{className:"block text-[11px] font-semibold tracking-wider uppercase text-white/85 mb-1.5",children:[P.label,P.is_required&&s.jsx("span",{className:"ml-1",style:{color:a},children:"*"})]}),s.jsx("div",{className:"[&_input]:bg-white/95 [&_input]:border-0 [&_input]:text-neutral-900 [&_input]:placeholder:text-neutral-400 [&_textarea]:bg-white/95 [&_textarea]:border-0 [&_textarea]:text-neutral-900 [&_textarea]:placeholder:text-neutral-400 [&_button[role=combobox]]:bg-white/95 [&_button[role=combobox]]:border-0 [&_button[role=combobox]]:text-neutral-900 [&_span]:text-white/90 [&_button[role=checkbox]]:border-white/60 [&_button[role=checkbox]]:bg-white/20 [&_button[role=checkbox][data-state=checked]]:bg-white [&_button[role=checkbox][data-state=checked]]:text-neutral-900",children:c(P,r,n,f)})]},P.id))}),s.jsx("button",{type:"submit",disabled:o,className:"w-full px-6 py-3.5 rounded-lg font-bold text-neutral-900 text-base md:text-lg shadow-lg hover:brightness-110 active:brightness-95 transition-all disabled:opacity-60 mt-2",style:{backgroundColor:a},children:o?"Submitting...":t.cta_text||"Get Started"})]}),T.length>0&&s.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4",children:T.map((P,R)=>s.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] md:text-xs text-white/80 font-medium",children:[s.jsx("span",{className:"h-1 w-1 rounded-full",style:{backgroundColor:a}}),P]},R))})]})})]})})]})}function DRt({src:t}){const[e,r]=C.useState(null),n=s.jsx("img",{src:t,alt:"Logo",crossOrigin:"anonymous",className:"h-10 md:h-12 w-auto object-contain",onLoad:i=>r(PRt(i.currentTarget)),onError:()=>r(!0)});return e===!1?s.jsx("span",{className:"inline-flex items-center rounded-md bg-white/90 backdrop-blur px-3 py-2 mb-6 shadow-sm",children:n}):s.jsx("div",{className:"mb-6 inline-block drop-shadow-md",children:n})}const Zle={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function MRt({page:t,fields:e,answers:r,setAnswers:n,onSubmit:i,isSubmitting:o,renderField:c,activePath:a,setActivePath:f}){const p=C.useRef(null),[y,v]=C.useState(!1),T=t.primary_color||"#406E71",E=t.accent_color||"#2a4c64",k=t.settings||{},P=Zle[t.heading_font]||Zle.playfair,R=Array.isArray(t.trust_pills)?t.trust_pills:[],D={buyerLabel:k.buyer_button_label||"I'm a Buyer",buyerSub:k.buyer_button_subtext||"Find the right home, at the right price",sellerLabel:k.seller_button_label||"I'm a Seller",sellerSub:k.seller_button_subtext||"Get a free, no-obligation home evaluation",buyerTitle:k.buyer_form_title||"Tell me what you’re looking for",buyerSubtitle:k.buyer_form_subtext||"A few quick questions and I’ll send you matching homes.",sellerTitle:k.seller_form_title||"Get your free home evaluation",sellerSubtitle:k.seller_form_subtext||"Tell me about your home and I’ll prepare your value report.",buyerCta:k.buyer_submit_label||"Send me homes",sellerCta:k.seller_submit_label||"Get my home value"},M=C.useMemo(()=>{const W=e.filter(Q=>(Q.field_group||"default")==="buyer"),Y=e.filter(Q=>(Q.field_group||"default")==="seller"),J=e.filter(Q=>(Q.field_group||"default")==="default");return{buyer:W.length?[...J,...W]:[...J],seller:Y.length?[...J,...Y]:[...J]}},[e]),B=a?M[a]:[];C.useEffect(()=>{a&&p.current&&p.current.scrollIntoView({behavior:"smooth",block:"start"})},[a]);const V=B.filter(W=>W.is_required&&!r[W.label]),G=W=>{W.preventDefault(),v(!0),!(V.length>0)&&i(W)};return s.jsxs("div",{className:"min-h-screen bg-neutral-950",children:[s.jsxs("section",{className:"relative min-h-[78vh] flex items-center overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0",style:{background:t.hero_image_url?`url(${t.hero_image_url}) center/cover no-repeat`:`linear-gradient(135deg, ${T}, ${E})`}}),s.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(0,0,0,.72) 0%, rgba(0,0,0,.42) 38%, rgba(0,0,0,.82) 100%)"}}),s.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40",style:{background:"linear-gradient(180deg, transparent, #0a0a0a)"}}),s.jsxs("div",{className:"relative w-full max-w-6xl mx-auto px-5 py-20 text-center",children:[t.logo_url&&s.jsx("img",{src:t.logo_url,alt:"",className:"h-11 w-auto mx-auto mb-8 drop-shadow-lg"}),t.eyebrow&&s.jsx("p",{className:"text-[11px] md:text-xs uppercase tracking-[0.32em] text-white/70 mb-5",children:t.eyebrow}),s.jsxs("h1",{className:"text-white text-4xl md:text-6xl lg:text-7xl leading-[1.05] tracking-tight",style:{fontFamily:P},children:[t.hero_headline,t.headline_accent&&s.jsxs(s.Fragment,{children:[" ",s.jsx("em",{className:"italic",style:{color:"#fff",opacity:.85},children:t.headline_accent})]})]}),t.hero_subtext&&s.jsx("p",{className:"mt-5 text-base md:text-lg text-white/80 max-w-2xl mx-auto leading-relaxed",children:t.hero_subtext}),s.jsxs("div",{className:"mt-12 grid gap-4 sm:grid-cols-2 max-w-3xl mx-auto",children:[s.jsx(Xle,{active:a==="buyer",icon:s.jsx(pme,{className:"h-5 w-5"}),label:D.buyerLabel,sub:D.buyerSub,color:T,onClick:()=>{v(!1),f("buyer")}}),s.jsx(Xle,{active:a==="seller",icon:s.jsx(va,{className:"h-5 w-5"}),label:D.sellerLabel,sub:D.sellerSub,color:E,onClick:()=>{v(!1),f("seller")}})]}),R.length>0&&s.jsx("div",{className:"mt-9 flex flex-wrap items-center justify-center gap-2",children:R.map(W=>s.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-white/20 bg-white/10 px-3.5 py-1.5 text-[11px] font-medium text-white/85 backdrop-blur",children:[s.jsx(k9,{className:"h-3 w-3"})," ",W]},W))})]})]}),s.jsx("section",{ref:p,className:"relative bg-neutral-950 px-5 pb-20 pt-2 scroll-mt-4",children:s.jsxs("div",{className:"max-w-3xl mx-auto",children:[a?s.jsxs("div",{className:"-mt-14 rounded-3xl border border-white/10 bg-white shadow-[0_40px_80px_-30px_rgba(0,0,0,.8)] overflow-hidden",children:[s.jsxs("div",{className:"px-6 md:px-9 py-6",style:{background:`linear-gradient(120deg, ${a==="buyer"?T:E}, ${a==="buyer"?E:T})`},children:[s.jsxs("button",{type:"button",onClick:()=>f(null),className:"inline-flex items-center gap-1.5 text-[11px] uppercase tracking-widest text-white/75 hover:text-white transition-colors",children:[s.jsx(dx,{className:"h-3 w-3"})," Change"]}),s.jsx("h2",{className:"mt-3 text-2xl md:text-3xl text-white leading-tight",style:{fontFamily:P},children:a==="buyer"?D.buyerTitle:D.sellerTitle}),s.jsx("p",{className:"mt-1.5 text-sm text-white/80",children:a==="buyer"?D.buyerSubtitle:D.sellerSubtitle})]}),s.jsxs("form",{onSubmit:G,className:"px-6 md:px-9 py-7 space-y-4",children:[B.length===0&&s.jsx("p",{className:"text-sm text-neutral-500",children:"This form has no questions yet."}),B.map(W=>s.jsxs("div",{children:[s.jsxs(Mr,{className:"text-[13px] font-medium text-neutral-700",children:[W.label,W.is_required&&s.jsx("span",{className:"ml-1",style:{color:T},children:"*"})]}),c(W,r,n,T)]},W.id)),y&&V.length>0&&s.jsxs("p",{className:"text-sm text-red-600",children:["Please fill in: ",V.map(W=>W.label).join(", ")]}),s.jsxs(Bt,{type:"submit",disabled:o,className:"w-full h-12 text-white text-base rounded-xl shadow-lg hover:opacity-95",style:{backgroundColor:a==="buyer"?T:E},children:[o?"Sending…":a==="buyer"?D.buyerCta:D.sellerCta,!o&&s.jsx(Ds,{className:"h-4 w-4 ml-2"})]})]})]}):s.jsx("p",{className:"text-center text-white/45 text-sm py-10",children:"Choose an option above to get started."}),t.agent_name&&s.jsxs("div",{className:"mt-10 flex items-center justify-center gap-4 rounded-2xl border border-white/10 bg-white/[0.04] px-6 py-5 backdrop-blur",children:[t.agent_photo_url&&s.jsx("img",{src:t.agent_photo_url,alt:t.agent_name,className:"h-14 w-14 rounded-full object-cover ring-2 ring-white/20"}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:"text-white font-medium",children:t.agent_name}),s.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/65",children:[t.agent_phone&&s.jsxs("a",{href:`tel:${t.agent_phone}`,className:"inline-flex items-center gap-1 hover:text-white",children:[s.jsx(ri,{className:"h-3 w-3"})," ",t.agent_phone]}),t.agent_email&&s.jsxs("a",{href:`mailto:${t.agent_email}`,className:"inline-flex items-center gap-1 hover:text-white",children:[s.jsx(mi,{className:"h-3 w-3"})," ",t.agent_email]})]})]})]})]})})]})}function Xle({active:t,icon:e,label:r,sub:n,color:i,onClick:o}){return s.jsxs("button",{type:"button",onClick:o,className:`group relative overflow-hidden rounded-2xl border px-6 py-7 text-left transition-all duration-300 backdrop-blur-xl ${t?"border-white/60 bg-white/95 shadow-2xl -translate-y-0.5":"border-white/20 bg-white/10 hover:bg-white/20 hover:-translate-y-0.5"}`,children:[s.jsx("span",{className:"inline-flex h-11 w-11 items-center justify-center rounded-full",style:{backgroundColor:t?i:"rgba(255,255,255,.18)",color:"#fff"},children:e}),s.jsx("span",{className:`mt-4 block text-xl font-semibold ${t?"":"text-white"}`,style:t?{color:i}:void 0,children:r}),s.jsx("span",{className:`mt-1 block text-sm ${t?"text-neutral-600":"text-white/70"}`,children:n}),s.jsx(Ds,{className:`absolute right-5 top-7 h-4 w-4 transition-transform group-hover:translate-x-1 ${t?"":"text-white/60"}`,style:t?{color:i}:void 0})]})}function ORt(t){const e=Math.max(0,Math.floor(t/1e3));return{d:Math.floor(e/86400),h:Math.floor(e%86400/3600),m:Math.floor(e%3600/60),s:e%60}}function FRt(t,e,r){const n=new Date(e),i=new Date(n.getTime()+60*60*1e3),o=a=>a.toISOString().replace(/[-:]|\.\d{3}/g,""),c=new URL("https://www.google.com/calendar/render");return c.searchParams.set("action","TEMPLATE"),c.searchParams.set("text",t),c.searchParams.set("dates",`${o(n)}/${o(i)}`),r&&c.searchParams.set("location",r),c.toString()}function BRt(t,e,r){const n=new Date(e),i=new Date(n.getTime()+60*60*1e3),o=a=>a.toISOString().replace(/[-:]|\.\d{3}/g,""),c=["BEGIN:VCALENDAR","VERSION:2.0","BEGIN:VEVENT",`UID:${Date.now()}@levelup`,`DTSTAMP:${o(new Date)}`,`DTSTART:${o(n)}`,`DTEND:${o(i)}`,`SUMMARY:${t}`,r?`LOCATION:${r}`:"","END:VEVENT","END:VCALENDAR"].filter(Boolean).join(`\r `);return`data:text/calendar;charset=utf-8,${encodeURIComponent(c)}`}function $Rt({startsAt:t,locationName:e,address:r,title:n,accent:i}){const[o,c]=C.useState(Date.now());C.useEffect(()=>{const E=setInterval(()=>c(Date.now()),1e3);return()=>clearInterval(E)},[]);const a=new Date(t).getTime();if(!Number.isFinite(a))return null;const f=ORt(a-o),p=a-o<=0,y=new Date(t).toLocaleString("en-US",{weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"}),v=[e,r].filter(Boolean).join(" · "),T=r?`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(r)}`:null;return s.jsx("section",{className:"max-w-5xl mx-auto px-4 py-10",children:s.jsx("div",{className:"rounded-2xl border bg-white/80 backdrop-blur p-6 md:p-8 shadow-sm",children:s.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("div",{className:"text-xs uppercase tracking-wider font-medium",style:{color:i},children:p?"Just happened":"Event starts in"}),p?s.jsx("p",{className:"text-sm text-muted-foreground",children:"Missed this one? Submit the form and we'll let you know about the next one."}):s.jsx("div",{className:"flex items-baseline gap-3",children:[{v:f.d,l:"days"},{v:f.h,l:"hrs"},{v:f.m,l:"min"},{v:f.s,l:"sec"}].map(E=>s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"text-3xl md:text-4xl font-bold tabular-nums",style:{color:i},children:String(E.v).padStart(2,"0")}),s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:E.l})]},E.l))}),s.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 pt-2 text-sm text-neutral-700",children:[s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(Dl,{className:"h-3.5 w-3.5"})," ",y]}),v&&s.jsxs("a",{href:T||"#",target:T?"_blank":void 0,rel:"noreferrer",className:"inline-flex items-center gap-1.5 hover:underline",children:[s.jsx(Es,{className:"h-3.5 w-3.5"})," ",v]})]})]}),!p&&s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs("a",{href:FRt(n,t,v||null),target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 text-sm font-medium rounded-lg border px-3 py-2 hover:bg-neutral-50",children:[s.jsx(oo,{className:"h-4 w-4"})," Add to Google"]}),s.jsxs("a",{href:BRt(n,t,v||null),download:`${n.replace(/\W+/g,"-").toLowerCase()}.ics`,className:"inline-flex items-center gap-2 text-sm font-medium rounded-lg border px-3 py-2 hover:bg-neutral-50",children:[s.jsx(oo,{className:"h-4 w-4"})," Apple / Outlook"]})]})]})})})}function zRt(){try{const t="_lp_sid";let e=sessionStorage.getItem(t);return e||(e=crypto.randomUUID?crypto.randomUUID():`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,sessionStorage.setItem(t,e)),e}catch{return`s_${Date.now()}`}}function Kje({slugOverride:t}){var Se;const{slug:e}=Pm(),r=t||e,[n,i]=C.useState(!1),[o,c]=C.useState({}),[a,f]=C.useState(null),[p,y]=C.useState(0),[v,T]=C.useState(!1),[E,k]=C.useState(""),[P]=C.useState(()=>Date.now()),R=C.useState(()=>zRt())[0],{data:D,isLoading:M}=mr({queryKey:["public-landing-page",r],queryFn:async()=>{const{data:je,error:Le}=await Re.from("landing_pages").select("*").eq("slug",r).eq("is_published",!0).single();if(Le)throw Le;return je},enabled:!!r}),{data:B=[]}=mr({queryKey:["public-landing-page-fields",D==null?void 0:D.id],queryFn:async()=>{const{data:je,error:Le}=await Re.from("landing_page_fields").select("*").eq("page_id",D.id).order("sort_order");if(Le)throw Le;return je},enabled:!!(D!=null&&D.id)});C.useEffect(()=>{D!=null&&D.id&&Re.from("landing_pages").update({view_count:(D.view_count||0)+1}).eq("id",D.id).then(()=>{})},[D==null?void 0:D.id]),C.useEffect(()=>{if(!(D!=null&&D.id))return;const je=new URLSearchParams(window.location.search);Re.functions.invoke("landing-page-track",{body:{page_id:D.id,event_type:"view",session_id:R,utm_source:je.get("utm_source"),utm_medium:je.get("utm_medium"),utm_campaign:je.get("utm_campaign"),referrer:document.referrer||null,device:window.matchMedia("(max-width: 768px)").matches?"mobile":"desktop"}}).catch(()=>{})},[D==null?void 0:D.id,R]);const V=Sr({mutationFn:async()=>{const je=B.find(He=>He.field_type==="text"&&He.label.toLowerCase().includes("name")),Le=B.find(He=>He.field_type==="email"),Ae=B.find(He=>He.field_type==="phone"),be=je?String(o[je.label]||""):null,me=Le?String(o[Le.label]||""):null,Te=Ae?String(o[Ae.label]||""):null,Ne=new URLSearchParams(window.location.search),{data:Ee,error:we}=await Re.functions.invoke("landing-page-submit",{body:{page_id:D.id,answers:JSON.parse(JSON.stringify(a?{"I am a":a==="buyer"?"Buyer":"Seller",...o}:o)),contact_name:be,contact_email:me,contact_phone:Te,session_id:R,honeypot:E,rendered_at:P,utm_source:Ne.get("utm_source"),utm_medium:Ne.get("utm_medium"),utm_campaign:Ne.get("utm_campaign"),referrer:document.referrer||null}});if(we)throw we;return Ee},onSuccess:je=>{i(!0),je!=null&&je.redirect_url&&setTimeout(()=>{window.location.href=je.redirect_url},1500)}}),G=je=>{je.preventDefault(),!((D==null?void 0:D.page_type)!=="buyer_seller"&&B.filter(Ae=>Ae.is_required&&!o[Ae.label]).length>0)&&V.mutate()};if(M)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-gray-400 border-t-transparent"})});if(!D)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-gray-700",children:"Page Not Found"}),s.jsx("p",{className:"text-gray-500 mt-2",children:"This page doesn't exist or is no longer available."})]})});const W=D.primary_color||"#406E71",Y=D.accent_color||"#2a4c64",J=D,Q=D.page_type==="lead_magnet",ee=D.page_type==="just_listed"||D.page_type==="just_sold",le=Array.isArray(J.property_photos)?J.property_photos:[],pe=J.lead_magnet_file_url||J.lead_magnet_external_url;if(n)return s.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${W}, ${Y})`},children:s.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[s.jsx(oc,{className:"h-16 w-16 mx-auto mb-4",style:{color:W}}),s.jsx("h2",{className:"text-2xl font-bold mb-2",children:Q?"Your download is ready!":"Submitted!"}),s.jsx("p",{className:"text-gray-600",children:D.success_message}),Q&&pe&&s.jsxs("a",{href:pe,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 mt-6 px-6 py-3 rounded-lg text-white font-semibold transition-transform hover:scale-105",style:{backgroundColor:W},children:[s.jsx(sc,{className:"h-5 w-5"}),"Download ",J.lead_magnet_file_name||"Your File"]}),D.agent_name&&s.jsxs("div",{className:"mt-6 pt-4 border-t",children:[s.jsx("p",{className:"text-sm text-gray-500",children:"Contact"}),s.jsx("p",{className:"font-semibold",children:D.agent_name}),D.agent_phone&&s.jsxs("a",{href:`tel:${D.agent_phone}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:W},children:[s.jsx(ri,{className:"h-3 w-3"})," ",D.agent_phone]}),D.agent_email&&s.jsxs("a",{href:`mailto:${D.agent_email}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:W},children:[s.jsx(mi,{className:"h-3 w-3"})," ",D.agent_email]})]})]})});if(ee){const je=Le=>{const Ae=parseFloat(Le.replace(/[^0-9.]/g,""));return isNaN(Ae)?Le:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ae)};return s.jsxs("div",{className:"min-h-screen bg-gray-50",children:[v&&le.length>0&&s.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",onClick:()=>T(!1),children:[s.jsx("button",{onClick:()=>T(!1),className:"absolute top-4 right-4 text-white/80 hover:text-white z-10",children:s.jsx(Os,{className:"h-8 w-8"})}),s.jsx("button",{onClick:Le=>{Le.stopPropagation(),y(Ae=>Ae===0?le.length-1:Ae-1)},className:"absolute left-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/20 text-white rounded-full p-3 transition-colors z-10",children:s.jsx(Cm,{className:"h-6 w-6"})}),s.jsx("img",{src:le[p],alt:`Property photo ${p+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:Le=>Le.stopPropagation()}),s.jsx("button",{onClick:Le=>{Le.stopPropagation(),y(Ae=>Ae===le.length-1?0:Ae+1)},className:"absolute right-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/20 text-white rounded-full p-3 transition-colors z-10",children:s.jsx(jd,{className:"h-6 w-6"})}),s.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 text-white/70 text-sm",children:[p+1," / ",le.length]})]}),le.length>0&&s.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 pt-6",children:[s.jsx("div",{className:"absolute top-10 left-8 z-10 px-4 py-1.5 rounded-full text-white font-bold text-sm uppercase tracking-wider shadow-lg",style:{backgroundColor:J.property_status==="just_sold"?"#e74c3c":W},children:J.property_status==="just_sold"?"🎉 Just Sold":"🏡 Just Listed"}),le.length===1?s.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{y(0),T(!0)},children:[s.jsx("img",{src:le[0],alt:"Property",className:"w-full h-[50vh] object-cover group-hover:scale-105 transition-transform duration-500"}),s.jsxs("div",{className:"absolute bottom-4 right-4 bg-black/60 text-white px-3 py-1.5 rounded-lg text-sm flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[s.jsx(Uee,{className:"h-4 w-4"})," View"]})]}):le.length===2?s.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:le.slice(0,2).map((Le,Ae)=>s.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{y(Ae),T(!0)},children:s.jsx("img",{src:Le,alt:`Property ${Ae+1}`,className:"w-full h-[45vh] object-cover group-hover:scale-105 transition-transform duration-500"})},Ae))}):s.jsxs("div",{className:"grid grid-cols-4 gap-2 rounded-2xl overflow-hidden",style:{height:"55vh"},children:[s.jsx("div",{className:"col-span-2 row-span-2 cursor-pointer group relative",onClick:()=>{y(0),T(!0)},children:s.jsx("img",{src:le[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),le.slice(1,5).map((Le,Ae)=>s.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{y(Ae+1),T(!0)},children:[s.jsx("img",{src:Le,alt:`Property ${Ae+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),Ae===3&&le.length>5&&s.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",le.length-5," more"]})]},Ae))]}),le.length>2&&s.jsxs("button",{onClick:()=>{y(0),T(!0)},className:"absolute bottom-4 right-8 bg-white shadow-lg hover:shadow-xl text-gray-800 px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-shadow",children:[s.jsx(Uee,{className:"h-4 w-4"})," View all ",le.length," photos"]})]}),le.length===0&&s.jsx("div",{className:"relative py-16 px-4",style:{background:D.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${D.hero_image_url}) center/cover`:`linear-gradient(135deg, ${W}, ${Y})`},children:s.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[D.logo_url&&s.jsx("img",{src:D.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),s.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:D.hero_headline}),D.hero_subtext&&s.jsx("p",{className:"mt-3 text-lg opacity-90",children:D.hero_subtext})]})}),s.jsx("div",{className:"max-w-4xl mx-auto px-4 py-8",children:s.jsxs("div",{className:"grid md:grid-cols-5 gap-6",children:[s.jsx("div",{className:"md:col-span-3 space-y-6",children:s.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[J.property_price&&s.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:W},children:je(J.property_price)}),J.property_address&&s.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[s.jsx(Es,{className:"h-5 w-5 shrink-0"})," ",J.property_address]}),s.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[J.property_beds&&s.jsxs("div",{className:"text-center",children:[s.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[s.jsx(XS,{className:"h-5 w-5",style:{color:W}})," ",J.property_beds]}),s.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),J.property_baths&&s.jsxs("div",{className:"text-center",children:[s.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[s.jsx(__,{className:"h-5 w-5",style:{color:W}})," ",J.property_baths]}),s.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),J.property_sqft&&s.jsxs("div",{className:"text-center",children:[s.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[s.jsx(QO,{className:"h-5 w-5",style:{color:W}})," ",Number(J.property_sqft).toLocaleString()]}),s.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),J.property_description&&s.jsxs("div",{children:[s.jsx("h3",{className:"font-semibold text-gray-800 mb-2",children:"About This Property"}),s.jsx("p",{className:"text-gray-600 leading-relaxed whitespace-pre-line",children:J.property_description})]})]})}),s.jsx("div",{className:"md:col-span-2",children:s.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 sticky top-6",children:[s.jsx("h2",{className:"text-lg font-bold mb-1",style:{color:W},children:J.property_status==="just_sold"?"Want results like this?":"Interested in this property?"}),s.jsx("p",{className:"text-gray-500 text-sm mb-4",children:"Fill out the form and I'll be in touch!"}),D.agent_name&&s.jsxs("div",{className:"flex items-center gap-3 mb-5 pb-4 border-b",children:[D.agent_photo_url&&s.jsx("img",{src:D.agent_photo_url,alt:D.agent_name,className:"h-12 w-12 rounded-full object-cover"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold text-sm",children:D.agent_name}),s.jsxs("div",{className:"flex flex-col gap-0.5 text-xs text-gray-500",children:[D.agent_phone&&s.jsxs("a",{href:`tel:${D.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[s.jsx(ri,{className:"h-3 w-3"})," ",D.agent_phone]}),D.agent_email&&s.jsxs("a",{href:`mailto:${D.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[s.jsx(mi,{className:"h-3 w-3"})," ",D.agent_email]})]})]})]}),s.jsxs("form",{onSubmit:G,className:"space-y-3",children:[B.map(Le=>s.jsxs("div",{children:[s.jsxs(Mr,{className:"text-xs font-medium",children:[Le.label,Le.is_required&&s.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),GR(Le,o,c)]},Le.id)),s.jsx(Bt,{type:"submit",className:"w-full text-white",style:{backgroundColor:W},disabled:V.isPending,children:V.isPending?"Submitting...":"Submit"}),V.isError&&s.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})})]})}),s.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}return D.page_type==="buyer_seller"?s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",name:"company_website",tabIndex:-1,autoComplete:"off","aria-hidden":"true",value:E,onChange:je=>k(je.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),s.jsx(MRt,{page:D,fields:B,answers:o,setAnswers:c,onSubmit:G,isSubmitting:V.isPending,renderField:GR,activePath:a,setActivePath:f}),V.isError&&s.jsx("p",{className:"text-center text-sm text-red-500 pb-8 bg-neutral-950",children:"Something went wrong. Please try again."}),s.jsx("div",{className:"text-center py-6 text-xs text-white/30 bg-neutral-950",children:"Powered by LevelUp"})]}):D.theme_style!=="classic"&&!Q?s.jsxs("div",{className:"min-h-screen bg-neutral-50",children:[s.jsx("input",{type:"text",name:"company_website",tabIndex:-1,autoComplete:"off","aria-hidden":"true",value:E,onChange:je=>k(je.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),s.jsx(LRt,{page:D,fields:B,answers:o,setAnswers:c,onSubmit:G,isSubmitting:V.isPending,renderField:GR}),D.page_type==="event_registration"&&((Se=D.settings)==null?void 0:Se.event_starts_at)&&s.jsx($Rt,{startsAt:D.settings.event_starts_at,locationName:D.settings.event_location_name,address:D.settings.event_address,title:D.hero_headline||D.title,accent:D.accent_color||D.primary_color||"#406E71"}),V.isError&&s.jsx("p",{className:"text-sm text-red-500 text-center py-4",children:"Something went wrong. Please try again."}),s.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]}):s.jsxs("div",{className:"min-h-screen bg-gray-50",children:[s.jsx("div",{className:"relative py-16 px-4",style:{background:D.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${D.hero_image_url}) center/cover`:`linear-gradient(135deg, ${W}, ${Y})`},children:s.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[D.logo_url&&s.jsx("img",{src:D.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),s.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:D.hero_headline}),D.hero_subtext&&s.jsx("p",{className:"mt-3 text-lg opacity-90",children:D.hero_subtext}),Q&&J.lead_magnet_file_name&&s.jsxs("div",{className:"mt-6 inline-flex items-center gap-2 bg-white/20 backdrop-blur px-4 py-2 rounded-full text-sm",children:[s.jsx(sc,{className:"h-4 w-4"}),"Free Download: ",J.lead_magnet_file_name]})]})}),s.jsx("div",{className:"max-w-2xl mx-auto px-4 -mt-8",children:s.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[Q&&s.jsx("p",{className:"text-sm text-gray-500 mb-4 text-center",children:"Fill out the form below to get your free download!"}),D.agent_name&&s.jsxs("div",{className:"flex items-center gap-3 mb-6 pb-4 border-b",children:[D.agent_photo_url&&s.jsx("img",{src:D.agent_photo_url,alt:D.agent_name,className:"h-12 w-12 rounded-full object-cover"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold",children:D.agent_name}),s.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500",children:[D.agent_phone&&s.jsxs("a",{href:`tel:${D.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[s.jsx(ri,{className:"h-3 w-3"})," ",D.agent_phone]}),D.agent_email&&s.jsxs("a",{href:`mailto:${D.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[s.jsx(mi,{className:"h-3 w-3"})," ",D.agent_email]})]})]})]}),s.jsxs("form",{onSubmit:G,className:"space-y-4",children:[B.map(je=>s.jsxs("div",{children:[s.jsxs(Mr,{className:"text-sm font-medium",children:[je.label,je.is_required&&s.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),GR(je,o,c)]},je.id)),s.jsx(Bt,{type:"submit",className:"w-full text-white",style:{backgroundColor:W},disabled:V.isPending,children:V.isPending?"Submitting...":Q?"Get My Free Download":"Submit"}),V.isError&&s.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})}),s.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}function GR(t,e,r,n){const i=e[t.label]||"",o=Array.isArray(t.options)?t.options:[];switch(t.field_type){case"text":case"email":case"phone":return s.jsx(Br,{type:t.field_type==="email"?"email":t.field_type==="phone"?"tel":"text",value:String(i),onChange:c=>r(a=>({...a,[t.label]:c.target.value})),placeholder:t.placeholder||"",className:"mt-1"});case"textarea":return s.jsx(Ad,{value:String(i),onChange:c=>r(a=>({...a,[t.label]:c.target.value})),placeholder:t.placeholder||"",rows:3,className:"mt-1"});case"select":return s.jsxs(ba,{value:String(i),onValueChange:c=>r(a=>({...a,[t.label]:c})),children:[s.jsx(oa,{className:"mt-1",children:s.jsx(wa,{placeholder:"Select..."})}),s.jsx(la,{children:o.map(c=>s.jsx(mn,{value:c,children:c},c))})]});case"multiselect":return s.jsx("div",{className:"mt-1 space-y-2",children:o.map(c=>{const a=Array.isArray(i)?i:[];return s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx(WC,{checked:a.includes(c),onCheckedChange:f=>{const p=f?[...a,c]:a.filter(y=>y!==c);r(y=>({...y,[t.label]:p}))}}),s.jsx("span",{className:"text-sm",children:c})]},c)})});case"toggle":return s.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[s.jsx(gT,{checked:!!i,onCheckedChange:c=>r(a=>({...a,[t.label]:c?"Yes":"No"}))}),s.jsx("span",{className:"text-sm text-gray-600",children:i?"Yes":"No"})]});default:return s.jsx(Br,{value:String(i),onChange:c=>r(a=>({...a,[t.label]:c.target.value})),className:"mt-1"})}}const URt=Object.freeze(Object.defineProperty({__proto__:null,default:Kje},Symbol.toStringTag,{value:"Module"}));function VRt(){const e=ki().pathname.slice(1).split("/")[0];return C.useEffect(()=>{document.body.classList.add("landing-page-public");const r=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(o=>{document.querySelectorAll(o).forEach(c=>{c.style.display="none"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("landing-page-public"),n.forEach(clearTimeout)}},[]),e?s.jsx(Kje,{slugOverride:e}):s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"LevelUp Pages"}),s.jsx("p",{className:"text-gray-500",children:"Visit a specific page URL to view content."})]})})}const qRt=[{type:"hero",enabled:!0},{type:"featured_listings",enabled:!0},{type:"new_listings",enabled:!1},{type:"open_houses",enabled:!1},{type:"my_listings",enabled:!1},{type:"city_pages",enabled:!1},{type:"featured_areas",enabled:!0},{type:"about",enabled:!0},{type:"testimonials",enabled:!0},{type:"cta_banner",enabled:!0}],jHt={hero:"Hero Section",featured_listings:"Featured Listings",featured_areas:"Featured Areas",about:"About Me",testimonials:"Testimonials",agent_reviews:"Live Client Reviews",cta_banner:"Call To Action",new_listings:"New Listings Carousel",open_houses:"Open Houses Carousel",my_listings:"My Listings Carousel",city_pages:"City Pages Grid",property_types:"Property Types Gallery",advantages:"Advantages / Why Choose Us",rate_my_agent:"RateMyAgent Reviews",lifestyle_gallery:"Lifestyle Gallery",market_pulse:"Market Pulse",concierge_services:"Concierge Services",credentials:"Credentials & Clientele",land_use_guide:"Land Use Guide",land_valuation_cta:"Land Valuation CTA",acreage_showcase:"Acreage Showcase",featured_video:"Featured Video",schedule_cta:"Schedule a Consultation"},AHt={hero:"Full-screen background image with headline, subtitle, and search bar",featured_listings:"Grid of highlighted properties from the MLS",featured_areas:"Spotlight regions or neighborhoods that link to property search",about:"Agent photo, bio, and credentials section",testimonials:"Client reviews carousel with quotes",agent_reviews:"Real reviews you selected in the LevelUp Reviews app, updated automatically",cta_banner:"Call-to-action block to drive contact and search engagement",new_listings:"Horizontal carousel of newest listings, filterable by city",open_houses:"Horizontal carousel of open house listings, filterable by city",my_listings:"Showcase the agent's own active listings in a carousel",city_pages:"Grid of your city landing pages with photos and links",property_types:"Visual gallery of property categories (Ranch, Farm, Land, etc.)",advantages:"Feature cards highlighting your expertise and unique value",rate_my_agent:"Verified client reviews carousel powered by RateMyAgent",lifestyle_gallery:"Cinematic photo grid showcasing luxury living — pools, views, interiors",market_pulse:"Sleek market stats dashboard with avg price, days on market, inventory",concierge_services:"White-glove services showcase — staging, design, moving coordination",credentials:"Affiliation logos and specialty positioning (e.g. luxury and sports & entertainment divisions)",land_use_guide:"Interactive land use cards — Agriculture, Hunting, Equestrian, Recreational",land_valuation_cta:`"What's Your Land Worth?" — bold call-to-action for landowners`,acreage_showcase:"Large visual cards emphasizing lot size with aerial imagery",featured_video:"Embedded YouTube or Bunny video section for cinematic storytelling",schedule_cta:"Prominent booking section that sends visitors to your online scheduling calendar"},Qle={basic:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","agent_reviews","rate_my_agent","featured_video","schedule_cta","cta_banner"],luxury:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","agent_reviews","rate_my_agent","cta_banner","lifestyle_gallery","market_pulse","concierge_services","credentials","featured_video","schedule_cta"],"land-ranch":["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","agent_reviews","rate_my_agent","cta_banner","property_types","advantages","land_use_guide","land_valuation_cta","acreage_showcase","featured_video","schedule_cta"]};function kHt(t){return Qle[t]||Qle.basic}function GRt(t){const e=t.theme_config||{};return{themeTier:t.theme_tier||"basic",brandColor:t.brand_color||"#0f172a",accentColor:t.accent_color||"#3b82f6",fontFamily:t.font_family||"Inter",heroImageUrl:t.hero_image_url||null,homepageModules:Array.isArray(t.homepage_modules)&&t.homepage_modules.length?t.homepage_modules.map(r=>typeof r=="string"?{type:r,enabled:!0}:{enabled:!0,...r}):qRt,testimonials:Array.isArray(t.testimonials)?t.testimonials:[],featuredListingIds:t.featured_listing_ids||[],searchCities:Array.isArray(e.searchCities)?e.searchCities:[],searchZipCodes:Array.isArray(e.searchZipCodes)?e.searchZipCodes:[],searchCounties:Array.isArray(e.searchCounties)?e.searchCounties:[],searchSubdivisions:Array.isArray(e.searchSubdivisions)?e.searchSubdivisions:[],referralMode:e.referralMode===!0,referralPrimaryLabel:e.referralPrimaryLabel||void 0,referralPrimaryUrl:e.referralPrimaryUrl||void 0,referralSecondaryLabel:e.referralSecondaryLabel||void 0,referralSecondaryUrl:e.referralSecondaryUrl||void 0,divisionLogos:Array.isArray(e.divisionLogos)?e.divisionLogos:[],focusPages:Array.isArray(e.focusPages)?e.focusPages:[],headerLogoSize:["small","medium","large","xl"].includes(e.headerLogoSize)?e.headerLogoSize:"medium"}}const CHt=[{value:"small",label:"Small",hint:"Discreet — about 36px tall"},{value:"medium",label:"Standard",hint:"Default — about 48px tall"},{value:"large",label:"Large",hint:"Prominent — about 60px tall"},{value:"xl",label:"Extra large",hint:"Fills the header — about 68px tall"}],HRt={small:"h-8 sm:h-9 max-w-[140px]",medium:"h-10 sm:h-12 max-w-[180px]",large:"h-12 sm:h-[60px] max-w-[240px]",xl:"h-14 sm:h-[68px] max-w-[320px]"},WRt={small:"h-10 max-w-[160px]",medium:"h-12 max-w-[200px]",large:"h-16 max-w-[260px]",xl:"h-20 max-w-[320px]"};function yK(t){return t==="small"||t==="large"||t==="xl"?t:"medium"}function KRt(t){return HRt[yK(t)]}function YRt(t){return WRt[yK(t)]}const ZRt=new Set(["localhost","tile-portal.lovable.app","id-preview--b4ed24ae-0b44-4f4d-8676-c620f649ed8a.lovable.app","dashboard.relevelup.com","guestbook.relevelup.com","pages.relevelup.com","listings.relevelup.com"]);function XRt(t){const e=t.toLowerCase().replace(/:\d+$/,"");return!!(ZRt.has(e)||e.endsWith(".lovable.app")||e.endsWith(".lovableproject.com")||e.endsWith(".lovable.dev"))}function Yje(){return new URLSearchParams(window.location.search).get("previewSlug")}function QRt(){const t=Yje();if(t)return t;const r=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return r?r[1]:null}function JRt(){const t=QRt(),e=!!Yje(),r=window.location.hostname,n=t?null:Pfe(r),i=!t&&!XRt(r)&&r.includes(".")&&!Ife(r),o=t||n||(i?r:null),{data:c,isLoading:a,error:f}=mr({queryKey:["lead-site",o,i,e],queryFn:async()=>{var G;if(!o)return null;const y=Re.from("lead_sites").select("*"),v=e?y:y.eq("is_active",!0);let T;if(t)T=await v.eq("subdomain_slug",t).maybeSingle();else if(n)T=await v.ilike("custom_domain",n).maybeSingle();else if(i)T=await v.ilike("custom_domain",r).maybeSingle();else return null;const{data:E,error:k}=T;if(k)throw k;if(!E)return null;const{data:P}=await Re.from("profiles").select("id, name, avatar_url, email, phone, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url, google_business_url, zillow_profile_url, realtor_profile_url, specialties").eq("id",E.agent_id).single();let R=null;if(E.show_team_logo)if(E.team_logo_url)R=E.team_logo_url;else{const{data:W}=await Re.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",E.agent_id).limit(1).maybeSingle();W&&((G=W.teams)!=null&&G.avatar_url)&&(R=W.teams.avatar_url)}const D=E.theme_config||{},M=W=>typeof W=="string"&&W.trim()?W.trim():null,B={id:E.id,agentId:E.agent_id,subdomainSlug:E.subdomain_slug,customDomain:E.custom_domain||null,mlsProviderId:E.mls_provider_id,siteTitle:E.site_title,siteTagline:E.site_tagline,leadRegistrationMode:E.lead_registration_mode||"disabled",registrationTriggerCount:E.registration_trigger_count??1,themeConfig:E.theme_config||{},themeTier:E.theme_tier||"basic",planTier:E.plan_tier||"paid",ownerType:E.owner_type||"agent",orgTier:E.org_tier||"essential",brokerageId:E.brokerage_id||null,teamId:E.team_id||null,orgName:E.org_name||null,orgLogoUrl:E.org_logo_url||null,orgLogoDarkUrl:E.org_logo_dark_url||null,orgProfile:E.org_profile||{},brandColor:E.brand_color||void 0,accentColor:E.accent_color||void 0,mlsServiceCities:Array.isArray(E.mls_service_cities)?E.mls_service_cities:[],isActive:E.is_active,brokerageLegalName:E.brokerage_legal_name||null,brokerageLicenseNumber:E.brokerage_license_number||null,agentLicenseNumber:E.agent_license_number||null,licenseState:E.license_state||null,mlsDisclaimerText:E.mls_disclaimer_text||null,mlsLogoUrl:E.mls_logo_url||null,equalHousingEnabled:E.equal_housing_enabled??!0,faviconUrl:E.favicon_url||null,ogImageUrl:E.og_image_url||null,showTeamLogo:E.show_team_logo??!1,teamLogoUrl:R,headerLogoSize:yK(D.headerLogoSize),valuationLabel:M(D.valuationLabel),noMlsMode:E.no_mls_mode===!0,bookingUrl:E.booking_url||null,pageSubtitles:E.page_subtitles||{},agent:P?{id:P.id,full_name:P.name||"",avatar_url:M(D.agentHeadshotUrl)||P.avatar_url,email:P.email,phone:P.phone,title:M(D.agentTitle)||P.title,bio:M(D.agentBio)||P.bio,areas_served:P.areas_served||null,years_experience:P.years_experience??null,instagram_url:P.instagram_url||null,facebook_url:P.facebook_url||null,linkedin_url:P.linkedin_url||null,google_business_url:P.google_business_url||null,zillow_profile_url:P.zillow_profile_url||null,realtor_profile_url:P.realtor_profile_url||null,specialties:P.specialties||null}:void 0,testimonials:Array.isArray(E.testimonials)?E.testimonials.filter(W=>W&&typeof W=="object"&&W.text).map(W=>({name:String(W.name||"Client"),text:String(W.text),rating:typeof W.rating=="number"?W.rating:5,location:W.location?String(W.location):void 0})):[],seoMetaTitle:E.seo_meta_title||null,seoMetaDescription:E.seo_meta_description||null,googleSearchConsoleVerification:E.google_search_console_verification||null},V=GRt(E);return{siteConfig:B,themeConfig:V}},enabled:!!o,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1}),p=n||(i?r:null);return{siteConfig:(c==null?void 0:c.siteConfig)??null,themeConfig:(c==null?void 0:c.themeConfig)??null,isLoading:a,error:f,slug:t??(c==null?void 0:c.siteConfig.subdomainSlug)??null,customDomain:p}}async function c5(t,e){try{await Re.functions.invoke("lead-site-notify",{body:{lead:e,lead_site_id:t}})}catch(r){console.warn("Lead notification failed:",r)}}function xK(t){const e=`ls_identity_${t}`;try{const r=localStorage.getItem(e);if(r&&/^[0-9a-f-]{36}$/i.test(r))return r;const n=crypto.randomUUID();return localStorage.setItem(e,n),n}catch{return crypto.randomUUID()}}const eLt=mg({lead_site_id:Ai().uuid(),name:Ai().trim().min(1).max(160),email:Ai().trim().email().max(255),phone:Ai().max(40).nullable().optional(),message:Ai().max(5e3).nullable().optional(),source_page:Ai().max(2e3).nullable().optional(),lead_type:Ai().max(100),metadata:u7e(Ai(),LV()).nullable().optional()});async function lg(t){const e=eLt.safeParse(t);if(!e.success)return{error:new Error("Please check your name, email, and message.")};const{error:r}=await Re.rpc("submit_identified_website_lead",{_site_id:e.data.lead_site_id,_token:xK(e.data.lead_site_id),_lead:e.data});return{error:r}}async function NHt(t,e,r){const{error:n}=await Re.rpc("record_identified_property_view",{_site_id:t,_token:xK(t),_mls_number:e,_address:(r==null?void 0:r.propertyAddress)||null,_photo:(r==null?void 0:r.photoUrl)||null});n&&console.warn("Property activity could not be recorded:",n.message)}function IHt(t,e,r,n,i){return t!=="disabled"&&!e&&!r&&n>i}const Zje=C.createContext(null);function Hx(){const t=C.useContext(Zje);if(!t)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return t}function A2({siteConfig:t,children:e}){const[r,n]=C.useState(null),[i,o]=C.useState(null),[c,a]=C.useState(!0);C.useEffect(()=>{let v=!0,T=0;const E=async R=>{const D=++T;let{data:M}=await Re.from("lead_site_consumer_profiles").select("id, name, phone, contact_id").eq("user_id",R.id).eq("lead_site_id",t.id).maybeSingle();if(!M||!M.contact_id){const{data:B}=await Re.from("lead_site_consumer_profiles").upsert({user_id:R.id,lead_site_id:t.id,name:(M==null?void 0:M.name)||R.user_metadata.full_name||"Website visitor",phone:(M==null?void 0:M.phone)||R.user_metadata.consumer_phone||null},{onConflict:"user_id,lead_site_id"}).select("id,name,phone").single();M=B}!v||D!==T||(o(M?{...M,email:R.email||""}:null),a(!1))},{data:{subscription:k}}=Re.auth.onAuthStateChange((R,D)=>{const M=(D==null?void 0:D.user)??null;n(M),M?window.setTimeout(()=>void E(M),0):(T+=1,o(null),a(!1))}),P=window.setTimeout(()=>{v&&(console.warn("Lead site auth initialization timed out."),a(!1))},8e3);return()=>{v=!1,window.clearTimeout(P),k.unsubscribe()}},[t.id]),C.useEffect(()=>{const v=new URL(window.location.href),T=v.searchParams.get("signin");T&&(v.searchParams.delete("signin"),window.history.replaceState({},"",v.pathname+v.search+v.hash),Re.auth.verifyOtp({type:"email",token_hash:T}).then(({error:E})=>{E&&console.warn("Sign-in link could not be used (it may already be used or expired).",E.message)}))},[]);const f=C.useCallback(async v=>{const T=v.email.toLowerCase().trim(),{data:E,error:k}=await Re.functions.invoke("consumer-auth-link",{body:{site_id:t.id,email:T,name:v.name.trim(),phone:v.phone.trim(),mode:"signup",redirect_to:window.location.href}});if(k)throw k;let P=!1;if(E!=null&&E.token_hash){const{error:R}=await Re.auth.verifyOtp({type:"email",token_hash:E.token_hash});R?console.error("Instant sign-in after registration failed:",R):P=!0}{const{error:R}=await lg({lead_site_id:t.id,name:v.name.trim(),email:T,phone:v.phone.trim(),message:P?"Created a website account (signed in)":"Requested a website account; email verification pending",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,verification_pending:!P}});if(R)throw R;c5(t.id,{name:v.name.trim(),email:T,phone:v.phone.trim(),lead_type:"website_registration",message:"Created account on website",source_page:window.location.pathname})}return{instant:P,existing:(E==null?void 0:E.new_account)===!1}},[t.id]),p=C.useCallback(async(v,T)=>{const E=v.toLowerCase().trim(),{data:k,error:P}=await Re.functions.invoke("consumer-auth-link",{body:{site_id:t.id,email:E,mode:"signin",redirect_to:window.location.href}});if(P)throw P;let R=!1;if(k!=null&&k.token_hash){const{error:D}=await Re.auth.verifyOtp({type:"email",token_hash:k.token_hash});D||(R=!0,lg({lead_site_id:t.id,email:E,message:"Created a website account (signed in)",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,verification_pending:!1}}).catch(()=>{}))}return{instant:R}},[t.id]),y=C.useCallback(async()=>{await Re.auth.signOut(),n(null),o(null)},[]);return s.jsx(Zje.Provider,{value:{user:r,profile:i,isLoading:c,signUp:f,signIn:p,signOut:y},children:e})}const Xje=new Set(["7605cc2e-ce21-4f4f-8bb1-4c0f217b1109"]),Qje=new Set(["tomlois"]);function wx(t,e){var r;return t?(e==null?void 0:e.referralMode)===!0||((r=t.themeConfig)==null?void 0:r.referralMode)===!0||t.noMlsMode===!0||Xje.has(t.id||"")||Qje.has((t.subdomainSlug||"").toLowerCase())||!t.mlsProviderId:!1}function tLt(t,e){var r;return t?((r=t.themeConfig)==null?void 0:r.referralMode)===!0||Xje.has(t.id||"")||Qje.has((t.subdomainSlug||"").toLowerCase()):!1}function PHt(t,e){return tLt(t)?"referral":wx(t,e)?"direct":"idx"}function RHt(t){return`Contact ${t.split(" ")[0]||"Me"}`}const rLt="free_luxury",nLt="free_beta";function Jje(t){const e=t==null?void 0:t.planTier;return e===rLt||e===nLt}const LHt={idx_search:{title:"MLS / IDX Home Search",description:"Let visitors search every active MLS listing in your market, with saved searches and instant alerts."},mls_listings:{title:"MLS Listing Feeds",description:"Automatically feature live MLS listings, new listings and sold comps on your homepage and city pages."},cma_reports:{title:"Professional Home Value Reports",description:"Build branded home value reports (CMAs) with live MLS comps and share them with sellers."},custom_domain:{title:"Custom Branded Domain",description:"Point your own web address at your site instead of the free subdomain."},ai_content:{title:"AI Content Creation",description:"Auto-written blog posts, city guides and monthly market updates published to your site."}},RT="#c9a96e",iLt="Schedule a Free Consultation",sLt={sm:"px-5 py-2.5 text-[11px]",md:"px-7 py-3.5 text-xs",lg:"px-9 py-4 text-xs"};function Gp({bookingUrl:t,label:e=iLt,className:r="",variant:n="solid",color:i=RT,size:o="md",onDark:c=!0,source:a}){if(!t)return null;const f=`inline-flex items-center justify-center gap-2.5 font-semibold tracking-[0.18em] uppercase rounded-full transition-all duration-300 ${sLt[o]}`,p=n==="solid"?{backgroundColor:i,color:"#0d0b0a",boxShadow:`0 10px 30px -12px ${i}`}:{borderColor:i,color:i,borderWidth:1};return s.jsxs("a",{href:t,target:"_blank",rel:"noopener noreferrer","data-schedule-source":a,className:`${f} ${n==="solid"?"hover:brightness-110":`border hover:bg-[${i}]/10`} ${n==="outline"&&!c?"bg-white/0":""} ${r}`,style:p,children:[s.jsx(S9,{className:"h-4 w-4 flex-shrink-0"}),s.jsx("span",{children:e})]})}function DHt({bookingUrl:t,agentName:e,accentColor:r=RT,config:n={},luxury:i=!0}){const o=n.bookingUrl||t;if(!o)return null;const c=n.eyebrow||"No Cost. No Obligation.",a=n.sectionTitle||"Schedule a Free Consultation",f=n.subtitle||`Pick a time that works for you and ${e.split(" ")[0]} will personally call you for a free 30-minute real estate consultation.`,p=n.buttonLabel||"Book My Free Consultation",y=[{icon:Dl,title:n.point1Title||"30 Minutes",text:n.point1Text||"A focused conversation about your goals, timeline, and options."},{icon:XDe,title:n.point2Title||"A Personal Call",text:n.point2Text||`${e.split(" ")[0]} calls you at the time you choose — no phone tag.`},{icon:oc,title:n.point3Title||"Real Answers",text:n.point3Text||"Pricing, strategy, and next steps for buying or selling — free of charge."}],v=i?"bg-[#12100e]":"bg-gray-950";return s.jsxs("section",{className:`relative py-24 ${v} overflow-hidden`,children:[s.jsx("div",{className:"absolute inset-0 opacity-[0.07] pointer-events-none",style:{background:`radial-gradient(circle at 50% 0%, ${r}, transparent 60%)`}}),s.jsx("div",{className:"relative max-w-5xl mx-auto px-6 text-center",children:s.jsxs(fr.div,{initial:{opacity:0,y:24},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{duration:.7},children:[s.jsxs("div",{className:"flex items-center justify-center gap-4 mb-5",children:[s.jsx("div",{className:"h-px w-12 bg-white/10"}),s.jsx("span",{className:"text-[11px] tracking-[0.4em] uppercase",style:{color:r},children:c}),s.jsx("div",{className:"h-px w-12 bg-white/10"})]}),s.jsx("h2",{className:"text-3xl md:text-5xl text-white tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:a}),s.jsx("p",{className:"text-white/50 mt-5 text-lg max-w-2xl mx-auto leading-relaxed",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:f}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mt-14 text-left",children:y.map((T,E)=>s.jsxs("div",{className:"border border-white/10 bg-white/[0.03] p-6",children:[s.jsx(T.icon,{className:"h-5 w-5 mb-4",style:{color:r}}),s.jsx("p",{className:"text-white text-sm tracking-[0.15em] uppercase mb-2",children:T.title}),s.jsx("p",{className:"text-white/45 text-sm leading-relaxed",children:T.text})]},E))}),s.jsxs("div",{className:"mt-12 flex flex-col items-center gap-4",children:[s.jsx(Gp,{bookingUrl:o,label:p,size:"lg",color:r,source:"home_section"}),s.jsx("p",{className:"text-white/30 text-xs tracking-[0.2em] uppercase",children:"Opens in a new tab · Free 30-minute consultation"})]})]})})]})}function MHt({bookingUrl:t,accentColor:e=RT,headline:r="Prefer to talk it through?",subtext:n="Book a free 30-minute consultation at a time that works for you.",dark:i=!0,className:o="",source:c}){return t?s.jsxs("div",{className:`flex flex-col sm:flex-row sm:items-center sm:justify-between gap-5 p-6 md:p-8 border ${i?"border-white/10 bg-white/[0.03]":"border-gray-200 bg-gray-50 rounded-2xl"} ${o}`,children:[s.jsxs("div",{children:[s.jsx("p",{className:`text-lg ${i?"text-white":"text-gray-900"}`,style:{fontFamily:"'Playfair Display', Georgia, serif"},children:r}),s.jsx("p",{className:`text-sm mt-1 ${i?"text-white/45":"text-gray-600"}`,children:n})]}),s.jsx(Gp,{bookingUrl:t,label:"Schedule Now",color:e,size:"sm",className:"flex-shrink-0",source:c})]}):null}function aLt({bookingUrl:t,accentColor:e=RT}){const[r,n]=C.useState(!1),[i,o]=C.useState(!1);if(C.useEffect(()=>{sessionStorage.getItem("schedule-cta-dismissed")==="1"&&o(!0);const a=()=>n(window.scrollY>260);return a(),window.addEventListener("scroll",a,{passive:!0}),()=>window.removeEventListener("scroll",a)},[]),!t||i)return null;const c=()=>{sessionStorage.setItem("schedule-cta-dismissed","1"),o(!0)};return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`md:hidden fixed inset-x-0 bottom-0 z-[60] transition-transform duration-300 ${r?"translate-y-0":"translate-y-full"}`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:s.jsxs("div",{className:"bg-[#0d0b0a]/95 backdrop-blur-lg border-t border-white/10 px-4 py-3 flex items-center gap-3",children:[s.jsxs("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"flex-1 inline-flex items-center justify-center gap-2 rounded-full py-3 text-[11px] font-semibold tracking-[0.18em] uppercase",style:{backgroundColor:e,color:"#0d0b0a"},children:[s.jsx(S9,{className:"h-4 w-4"}),"Schedule Free Consultation"]}),s.jsx("button",{onClick:c,"aria-label":"Dismiss",className:"p-2 text-white/40 hover:text-white",children:s.jsx(Os,{className:"h-4 w-4"})})]})}),s.jsx("div",{className:`hidden md:flex fixed bottom-6 left-6 z-[60] items-center gap-2 transition-all duration-300 ${r?"opacity-100 translate-y-0":"opacity-0 translate-y-4 pointer-events-none"}`,children:s.jsx(Gp,{bookingUrl:t,label:"Schedule a Free Consultation",size:"sm",color:e,source:"sticky"})})]})}function oLt({bookingUrl:t,agentName:e}){return C.useEffect(()=>{if(t){const r=setTimeout(()=>window.location.replace(t),400);return()=>clearTimeout(r)}},[t]),s.jsx("div",{className:"min-h-[70vh] flex items-center justify-center bg-[#0d0b0a] px-6 text-center",children:s.jsxs("div",{children:[s.jsx(S9,{className:"h-8 w-8 mx-auto mb-6",style:{color:RT}}),s.jsx("h1",{className:"text-3xl md:text-4xl text-white tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:"Free 30-Minute Real Estate Consultation"}),s.jsx("p",{className:"text-white/45 mt-4",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:t?`Taking you to ${e}'s booking calendar…`:"Online booking is not available yet — please use the contact page."}),t&&s.jsx("div",{className:"mt-8",children:s.jsx(Gp,{bookingUrl:t,label:"Open Booking Calendar",size:"lg",source:"schedule_page"})})]})})}const vK=` id, slug, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, description, video_link, mls_link, co_agent_name, co_agent_brokerage, co_agent_phone, co_agent_email, co_agent_photo_url, photos:listing_photos(id, photo_url, is_primary, sort_order) `;function u5(t){return mr({queryKey:["lead-site-exchange-listings",t],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:e,error:r}=await Re.from("listings").select(vK).eq("agent_id",t).eq("show_on_lead_site",!0).eq("is_approved",!0).not("status","in","(sold,temp_off_market,withdrawn)").order("created_at",{ascending:!1});if(r)throw r;return e||[]}})}function _K(t){return mr({queryKey:["lead-site-sold-listings",t],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:e,error:r}=await Re.from("listings").select(vK).eq("agent_id",t).eq("show_on_lead_site",!0).eq("is_approved",!0).eq("status","sold").order("created_at",{ascending:!1});if(r)throw r;return e||[]}})}function OHt(t,e){return mr({queryKey:["lead-site-exchange-listing",t,e],enabled:!!t&&!!e,queryFn:async()=>{const r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e);let n=Re.from("listings").select(vK).eq("agent_id",t).eq("show_on_lead_site",!0).eq("is_approved",!0);n=r?n.eq("id",e):n.eq("slug",e);const{data:i,error:o}=await n.maybeSingle();if(o)throw o;return i??null}})}function FHt(t){var e;return(e=t==null?void 0:t.photos)!=null&&e.length?[...t.photos].sort((r,n)=>Number(n.is_primary)-Number(r.is_primary)||(r.sort_order??0)-(n.sort_order??0)).map(r=>r.photo_url):[]}function BHt(t){return t?`$${t.toLocaleString()}`:"Price upon request"}const lLt="b4e0faa0-5246-4b05-8545-18596e7ff784",cLt=mg({name:Ai().trim().min(1,"Please enter your name.").max(160),email:Ai().trim().email("Please enter a valid email.").max(255),phone:Ai().trim().max(40),interest:cS(["Buying a home","Selling a home","Buying and selling","eXp Ready program","Other"]),preferredTime:Ai().trim().max(200),message:Ai().trim().max(4e3)});async function $Ht(t,e){const r=cLt.parse(e),n={name:r.name,email:r.email,phone:r.phone||null,message:[`Interested in: ${r.interest}`,`Preferred contact time: ${r.preferredTime||"Not specified"}`,r.message&&`Message: ${r.message}`].filter(Boolean).join(` `),lead_type:"consultation",source_page:"/schedule"},{error:i}=await lg({lead_site_id:t,...n,metadata:{interest:r.interest,preferred_contact_time:r.preferredTime}});if(i)throw i;try{const{data:o,error:c}=await Re.functions.invoke("lead-site-notify",{body:{lead_site_id:t,lead:n}});return{emailSent:!c&&(o==null?void 0:o.success)===!0&&(o==null?void 0:o.sent)===1}}catch{return{emailSent:!1}}}const Jle="ls_visitor_geo",uLt=1e3*60*60,o6="lu_lc_attrib_v1",dLt=1e3*60*60*24*90;function hLt(t){return t==="/"?"home":t==="/search"?"search":t==="/sell"?"sell":t==="/blog"?"blog":t.startsWith("/listing/")?"listing":t.startsWith("/homes-for-sale-in-")?"city":t.startsWith("/homes-in-")?"subdivision":t==="/dashboard"?"dashboard":"other"}function fLt(t,e){switch(e){case"home":return"Home";case"search":return"Search";case"sell":return"Sell Your Home";case"blog":return"Blog";case"listing":return`Listing ${t.split("/listing/")[1]||""}`;case"city":return t.replace("/homes-for-sale-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"subdivision":return t.replace("/homes-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"dashboard":return"My Dashboard";default:return t}}async function mLt(){try{const t=localStorage.getItem(Jle);if(t){const e=JSON.parse(t);if(Date.now()-e.ts{o.current||(o.current=!0,mLt().then(c=>{i.current=c}))},[]),C.useEffect(()=>{if(!(t!=null&&t.id))return;const c=r.pathname;if(c===n.current)return;n.current=c;const a=hLt(c),f=fLt(c,a),p=localStorage.getItem(`ls_visitor_fp_${t.id}`)||null,y=i.current;(async()=>{const T=new URLSearchParams(r.search),E=T.get("luc");if(E&&/^[0-9a-f-]{36}$/i.test(E)){try{localStorage.setItem(o6,JSON.stringify({contact_id:E,ts:Date.now()}))}catch{}return E}const k=T.get("lc");if(k&&/^[0-9a-f-]{36}$/i.test(k)){const{data:P}=await Re.from("listing_email_recipients").select("contact_id").eq("id",k).maybeSingle(),R=P==null?void 0:P.contact_id;if(R){try{localStorage.setItem(o6,JSON.stringify({contact_id:R,ts:Date.now()}))}catch{}return R}}try{const P=localStorage.getItem(o6);if(P){const R=JSON.parse(P);if(R!=null&&R.contact_id&&Date.now()-(R.ts||0){Re.from("lead_site_page_views").insert({lead_site_id:t.id,page_type:a,page_path:c,page_title:f,visitor_fingerprint:p,auth_user_id:e||null,contact_id:T,visitor_city:(y==null?void 0:y.city)||null,visitor_region:(y==null?void 0:y.region)||null,visitor_country:(y==null?void 0:y.country)||null,visitor_lat:(y==null?void 0:y.lat)||null,visitor_lng:(y==null?void 0:y.lng)||null}).then(({error:E})=>{E&&console.error("[PageTracking] insert failed:",E.message)})})},[r.pathname,r.search,t==null?void 0:t.id,e])}const pLt=3e4;function h5(t,e){const r=ki(),n=C.useRef(null),i=C.useRef(null),o=C.useRef(0),c=r.pathname,a=gLt(c),f=yLt(c,a),p=a==="listing"&&c.split("/listing/")[1]||null;C.useEffect(()=>{if(!(t!=null&&t.id))return;a==="listing"&&(o.current+=1);const y=xK(t.id),v=e||y,T=async()=>{const{data:E,error:k}=await Re.rpc("lead_site_presence_heartbeat",{_site_id:t.id,_session_key:v,_fingerprint:y,_path:c,_title:f,_mls:p,_listing_views:o.current});!k&&E&&(n.current=E.id,e&&o.current>=2&&!E.notified_agent&&Re.functions.invoke("lead-site-presence-notify",{body:{visitor_id:E.id,lead_site_id:t.id}}).catch(()=>{}))};return T(),i.current&&clearInterval(i.current),i.current=setInterval(T,pLt),()=>{i.current&&clearInterval(i.current)}},[t==null?void 0:t.id,e,c]),C.useEffect(()=>{if(!(t!=null&&t.id))return;const y=()=>{n.current&&Re.from("lead_site_active_visitors").delete().eq("id",n.current).then(()=>{})};return window.addEventListener("beforeunload",y),()=>window.removeEventListener("beforeunload",y)},[t==null?void 0:t.id,e])}function gLt(t){return t==="/"?"home":t==="/search"?"search":t.startsWith("/listing/")?"listing":t.startsWith("/homes-for-sale-in-")?"city":t.startsWith("/homes-in-")?"subdivision":"other"}function yLt(t,e){switch(e){case"home":return"Home";case"search":return"Search";case"listing":return`Listing ${t.split("/listing/")[1]||""}`;case"city":return t.replace("/homes-for-sale-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"subdivision":return t.replace("/homes-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");default:return t}}function f5({open:t,mode:e,siteConfig:r,onComplete:n,onSkip:i,theme:o="default",accentColor:c}){var Te;const{signUp:a,signIn:f}=Hx(),[p,y]=C.useState(!1),[v,T]=C.useState(""),[E,k]=C.useState(""),[P,R]=C.useState(""),[D,M]=C.useState(!1),[B,V]=C.useState(""),[G,W]=C.useState(!1),[Y,J]=C.useState(!1),[Q,ee]=C.useState(!1),le=e==="required",pe=o==="luxury",Se=c||(pe?"#c9a96e":"#2563eb"),je=((Te=r.agent)==null?void 0:Te.full_name)||"the agent",Le={borderColor:`${Se}66`,"--tw-ring-color":`${Se}66`},Ae=async Ne=>{if(Ne.preventDefault(),V(""),!E.trim()||!p&&!P.trim()){V("Email and phone number are required.");return}if(!p&&!v.trim()){V("Name is required.");return}const Ee=P.replace(/\D/g,"");if(!p&&Ee.length<7){V("Please enter a valid phone number.");return}M(!0);try{const we=p?await f(E,P):await a({name:v,email:E,phone:P});we!=null&&we.instant?J(!0):(ee(!p&&!!(we!=null&&we.existing)),W(!0))}catch(we){const He=String((we==null?void 0:we.message)||"").toLowerCase();He.includes("rate")||He.includes("429")||He.includes("too many")?V("We just sent you a link — please check your inbox (and spam) or try again in a minute."):He.includes("email")&&He.includes("valid")?V("Please double-check your email address and try again."):V("We couldn't complete that just now. Please check your email address and try again.")}finally{M(!1)}},be="w-full",me=pe?Le:void 0;return s.jsx(lo,{open:t,onOpenChange:le?void 0:Ne=>{Ne||i()},children:s.jsxs(qa,{className:"sm:max-w-md bg-background text-foreground",onPointerDownOutside:le?Ne=>Ne.preventDefault():void 0,onEscapeKeyDown:le?Ne=>Ne.preventDefault():void 0,children:[s.jsxs(xl,{children:[s.jsx(Xo,{className:"text-xl",style:pe?{fontFamily:"'Playfair Display', Georgia, serif"}:void 0,children:p?"Welcome Back":le?"Create a Free Account to Continue":"Save Your Search & Get Updates"}),s.jsx(wd,{children:p?"Receive a secure sign-in link by email. No password needed.":`Create a free account to save favorites, get alerts, and connect with ${je}.`})]}),Y?s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("p",{className:"text-sm text-foreground",children:["You're all set",v.trim()?`, ${v.trim().split(" ")[0]}`:"","! Your account is active and you're signed in — everything you view and save is now connected to your account."]}),s.jsx(Bt,{className:"w-full",onClick:n,children:"Start browsing"})]}):G?s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsx("p",{className:"text-sm text-foreground",children:Q?"Welcome back! Looks like you already have an account with us. We've sent a secure sign-in link to your inbox so you can jump right back in.":"Check your email for a secure sign-in link to finish. Your property activity stays connected on this browser."}),s.jsx(Bt,{className:"w-full",onClick:n,children:"Continue browsing"})]}):s.jsxs("form",{onSubmit:Ae,className:"space-y-3 mt-2",children:[!p&&s.jsx(Br,{type:"text",required:!0,placeholder:"Your name",value:v,onChange:Ne=>T(Ne.target.value),className:be,style:me}),s.jsx(Br,{type:"email",required:!0,placeholder:"Email address",value:E,onChange:Ne=>k(Ne.target.value),className:be,style:me}),!p&&s.jsx("div",{children:s.jsx(Br,{type:"tel",required:!0,placeholder:"Phone number",value:P,onChange:Ne=>R(Ne.target.value),className:be,style:me})}),B&&s.jsx("p",{className:"text-destructive text-sm",children:B}),s.jsx(Bt,{type:"submit",disabled:D,className:"w-full",children:D?p?"Sending link...":"Creating account...":p?"Email Sign-In Link":"Create Account"}),s.jsx(Bt,{variant:"ghost",type:"button",onClick:()=>{y(!p),V("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",children:p?"Don't have an account? Sign up":"Already have an account? Sign in"}),!le&&!p&&s.jsx(Bt,{variant:"ghost",type:"button",onClick:i,className:"w-full text-muted-foreground",children:"Skip for now"})]}),s.jsx("p",{className:"text-xs text-center mt-1 text-muted-foreground",children:"By registering you agree to receive property updates. You can unsubscribe anytime."})]})})}const e2e=[{tab:"saved",label:"Saved Homes",icon:bm},{tab:"searches",label:"Saved Searches & Alerts",icon:xd},{tab:"viewed",label:"Recently Viewed",icon:KO},{tab:"profile",label:"Profile & Preferences",icon:A9}];function t2e(t,e){const r=t!=null&&t.name&&t.name!=="Website visitor"?t.name:"",n=(t==null?void 0:t.email)||e||"",i=r.split(" ")[0]||n.split("@")[0]||"Account",o=(r?r.split(" ").map(c=>c[0]).slice(0,2).join(""):n[0]||"A").toUpperCase();return{name:r||i,first:i,email:n,initials:o}}function m5({triggerClassName:t,avatarClassName:e,showSaved:r=!0,savedClassName:n}){const{user:i,profile:o,signOut:c}=Hx(),a=Hs();if(!i)return null;const f=t2e(o,i.email);return s.jsxs("div",{className:"flex items-center gap-1",children:[r&&s.jsxs(Wr,{to:"/account?tab=saved",className:n,"aria-label":"Saved homes",children:[s.jsx(bm,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),s.jsxs(FC,{modal:!1,children:[s.jsxs(BC,{className:t,"aria-label":"Your account",children:[s.jsx("span",{className:e??"flex h-7 w-7 items-center justify-center rounded-full bg-primary text-xs font-semibold text-primary-foreground",children:f.initials}),s.jsx("span",{className:"hidden max-w-[8rem] truncate lg:inline",children:f.first}),s.jsx(yl,{className:"h-3.5 w-3.5 opacity-70"})]}),s.jsxs(dT,{align:"end",className:"z-[80] w-64",children:[s.jsxs(pxe,{className:"font-normal",children:[s.jsx("p",{className:"text-xs text-muted-foreground",children:"Signed in as"}),s.jsx("p",{className:"truncate text-sm font-semibold",children:f.name}),f.email&&s.jsx("p",{className:"truncate text-xs text-muted-foreground",children:f.email})]}),s.jsx(sk,{}),e2e.map(({tab:p,label:y,icon:v})=>s.jsxs(Nu,{onSelect:()=>a(`/account?tab=${p}`),className:"cursor-pointer gap-2",children:[s.jsx(v,{className:"h-4 w-4"}),y]},p)),s.jsx(sk,{}),s.jsxs(Nu,{onSelect:async()=>{await c(),a("/")},className:"cursor-pointer gap-2",children:[s.jsx(ZO,{className:"h-4 w-4"}),"Sign Out"]})]})]})]})}function p5({onNavigate:t,dark:e}){const{user:r,profile:n,signOut:i}=Hx(),o=Hs();if(!r)return null;const c=t2e(n,r.email),a=`flex w-full items-center gap-2 rounded-lg px-3 py-2.5 text-left text-sm font-medium ${e?"text-white/80 hover:bg-white/10":"text-gray-600 hover:bg-gray-50"}`;return s.jsxs("div",{className:`mt-3 rounded-xl border p-2 ${e?"border-white/15":"border-gray-200"}`,children:[s.jsxs("div",{className:"flex items-center gap-3 px-2 py-2",children:[s.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-full bg-primary text-sm font-semibold text-primary-foreground",children:c.initials}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:`truncate text-sm font-semibold ${e?"text-white":"text-gray-900"}`,children:c.name}),c.email&&s.jsx("p",{className:`truncate text-xs ${e?"text-white/50":"text-gray-500"}`,children:c.email})]})]}),e2e.map(({tab:f,label:p,icon:y})=>s.jsxs("button",{className:a,onClick:()=>{o(`/account?tab=${f}`),t()},children:[s.jsx(y,{className:"h-4 w-4"}),p]},f)),s.jsxs("button",{className:a,onClick:async()=>{await i(),t(),o("/")},children:[s.jsx(ZO,{className:"h-4 w-4"}),"Sign Out"]})]})}function yO({siteConfig:t,variant:e,buttonClassName:r,onNavigate:n}){const{user:i}=Hx(),[o,c]=C.useState(!1);if(C.useEffect(()=>{new URLSearchParams(window.location.search).get("join")==="1"&&c(!0)},[]),!t)return null;const a=t.leadRegistrationMode!=="disabled";return i?e==="desktop"?s.jsx(m5,{showSaved:!1,triggerClassName:"flex items-center gap-1.5 rounded-full border border-current/30 py-1 pl-1 pr-2.5 text-sm font-semibold outline-none opacity-90 hover:opacity-100",avatarClassName:"flex h-7 w-7 items-center justify-center rounded-full bg-white text-xs font-bold text-slate-900"}):s.jsx(p5,{dark:!0,onNavigate:()=>n==null?void 0:n()}):a?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",onClick:()=>{c(!0),n==null||n()},className:r??"flex items-center gap-2 text-sm font-semibold opacity-90 hover:opacity-100",children:[s.jsx(Ml,{className:"h-4 w-4"}),"Sign In"]}),o&&s.jsx(f5,{open:o,mode:"optional",siteConfig:t,onComplete:()=>c(!1),onSkip:()=>c(!1)})]}):null}function r2e(t){const{user:e}=Hx();d5(t??null,e==null?void 0:e.id),h5(t??null,e==null?void 0:e.id)}const xLt="7605cc2e-ce21-4f4f-8bb1-4c0f217b1109",n2e=mg({firstName:Ai().trim().min(1,"Enter your first name.").max(80),lastName:Ai().trim().min(1,"Enter your last name.").max(80),email:Ai().trim().email("Enter a valid email address.").max(255),phone:Ai().trim().max(40),message:Ai().trim().max(2e3)}),vLt=n2e.extend({location:Ai().trim().min(2,"Enter the location where you need help.").max(200),situation:cS(["Buying","Selling","Both","Helping someone else","Not sure"]),contactMethod:cS(["Phone","Text","Email"]),message:Ai().trim().min(5,"Tell Tom a little about what is happening.").max(3e3)});function _Lt({config:t,leadSiteId:e,sourcePage:r}){const[n,i]=C.useState({firstName:"",lastName:"",email:"",phone:"",message:""}),[o,c]=C.useState(!1),[a,f]=C.useState(!1),p=T=>E=>i(k=>({...k,[T]:E.target.value})),y=async T=>{var R;if(T.preventDefault(),!e||o)return;const E=n2e.safeParse(n);if(!E.success){Vt.error(((R=E.error.issues[0])==null?void 0:R.message)||"Check the form and try again.");return}const k=`${E.data.firstName} ${E.data.lastName}`.trim();c(!0);const{error:P}=await lg({lead_site_id:e,name:k,email:E.data.email,phone:E.data.phone||null,message:E.data.message||null,source_page:r||null,lead_type:"contact",metadata:{form:t.headline||"Contact form"}});if(P){Vt.error("Your message could not be sent. Please try again."),c(!1);return}c5(e,{name:k,email:E.data.email,phone:E.data.phone||null,message:E.data.message||null,lead_type:"contact",source_page:r||null}),f(!0),c(!1)};if(a)return s.jsx("section",{className:"px-6 py-16 bg-gray-50",children:s.jsx("p",{className:"mx-auto max-w-lg text-center text-lg text-gray-800",children:t.successMessage||"Thank you. Your message has been sent."})});const v="w-full px-4 py-3 rounded-lg border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900";return s.jsx("section",{className:"px-6 py-16 bg-gray-50",children:s.jsxs("div",{className:"max-w-lg mx-auto",children:[t.headline&&s.jsx("h2",{className:"text-3xl font-bold text-gray-900 text-center mb-2",children:t.headline}),t.subtitle&&s.jsx("p",{className:"text-gray-500 text-center mb-8",children:t.subtitle}),s.jsxs("form",{className:"space-y-4",onSubmit:y,children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsx("input",{required:!0,maxLength:80,className:v,value:n.firstName,onChange:p("firstName"),placeholder:"First Name",autoComplete:"given-name"}),s.jsx("input",{required:!0,maxLength:80,className:v,value:n.lastName,onChange:p("lastName"),placeholder:"Last Name",autoComplete:"family-name"})]}),s.jsx("input",{required:!0,maxLength:255,className:v,value:n.email,onChange:p("email"),placeholder:"Email",type:"email",autoComplete:"email"}),t.showPhone&&s.jsx("input",{maxLength:40,className:v,value:n.phone,onChange:p("phone"),placeholder:"Phone (optional)",type:"tel",autoComplete:"tel"}),t.showMessage&&s.jsx("textarea",{maxLength:2e3,className:`${v} resize-none`,value:n.message,onChange:p("message"),rows:4,placeholder:"Message"}),s.jsx("button",{disabled:o,className:"w-full py-3 bg-gray-900 text-white rounded-lg font-semibold hover:bg-gray-800 transition-colors disabled:opacity-60",children:o?"Sending…":t.buttonText||"Send Message"})]})]})})}function zHt({leadSiteId:t,sourcePage:e}){const[r,n]=C.useState({firstName:"",lastName:"",email:"",phone:"",location:"",situation:"Not sure",message:"",contactMethod:"Phone"}),[i,o]=C.useState(!1),[c,a]=C.useState(!1),f=v=>T=>n(E=>({...E,[v]:T.target.value})),p=async v=>{var R;if(v.preventDefault(),t!==xLt||i)return;const T=vLt.safeParse(r);if(!T.success){Vt.error(((R=T.error.issues[0])==null?void 0:R.message)||"Check the form and try again.");return}const E=`${T.data.firstName} ${T.data.lastName}`.trim(),k=`Location: ${T.data.location} Need: ${T.data.situation} Preferred contact: ${T.data.contactMethod} ${T.data.message}`;o(!0);const{error:P}=await lg({lead_site_id:t,name:E,email:T.data.email,phone:T.data.phone||null,message:k,source_page:e||"/p/tell-tom",lead_type:"referral",metadata:{location:T.data.location,situation:T.data.situation,preferred_contact_method:T.data.contactMethod,form:"Tell Tom What You Need"}});if(P){Vt.error("Your message could not be sent. Please try again."),o(!1);return}c5(t,{name:E,email:T.data.email,phone:T.data.phone||null,message:k,lead_type:"referral",source_page:e||"/p/tell-tom"}),a(!0),o(!1)};if(c)return s.jsx("section",{className:"px-6 py-20 bg-gray-50",children:s.jsxs("div",{className:"mx-auto max-w-2xl text-center",children:[s.jsx("h1",{className:"text-4xl font-bold text-gray-900 mb-6",children:"I’ve Got It."}),s.jsxs("div",{className:"space-y-4 text-lg text-gray-600",children:[s.jsx("p",{children:"Thanks for reaching out."}),s.jsx("p",{children:"I’ll review what you’ve sent and contact you so we can talk about what’s going on."}),s.jsx("p",{children:"You don’t need to do anything else right now."}),s.jsx("p",{className:"font-semibold text-gray-900",children:"—Tom"}),s.jsxs("p",{children:["Need to reach me sooner? ",s.jsx("a",{className:"font-semibold underline",href:"tel:+15202712716",children:"Call 520-271-2716."})]})]})]})});const y="w-full rounded-md border border-gray-300 bg-white px-4 py-3 text-gray-900 focus:outline-none focus:ring-2 focus:ring-teal-700";return s.jsx("section",{className:"px-6 py-16 bg-gray-50",children:s.jsxs("div",{className:"mx-auto max-w-2xl",children:[s.jsx("h1",{className:"text-4xl font-bold text-gray-900 text-center",children:"Tell Tom What You Need"}),s.jsx("p",{className:"mt-4 mb-10 text-center text-gray-600",children:"Share a few details. Tom will review them personally and contact you."}),s.jsxs("form",{className:"space-y-5",onSubmit:p,children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("label",{className:"text-sm font-medium text-gray-800",children:["First name",s.jsx("input",{required:!0,maxLength:80,autoComplete:"given-name",className:`${y} mt-1`,value:r.firstName,onChange:f("firstName")})]}),s.jsxs("label",{className:"text-sm font-medium text-gray-800",children:["Last name",s.jsx("input",{required:!0,maxLength:80,autoComplete:"family-name",className:`${y} mt-1`,value:r.lastName,onChange:f("lastName")})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("label",{className:"text-sm font-medium text-gray-800",children:["Email",s.jsx("input",{required:!0,type:"email",maxLength:255,autoComplete:"email",className:`${y} mt-1`,value:r.email,onChange:f("email")})]}),s.jsxs("label",{className:"text-sm font-medium text-gray-800",children:["Phone",s.jsx("input",{type:"tel",maxLength:40,autoComplete:"tel",className:`${y} mt-1`,value:r.phone,onChange:f("phone")})]})]}),s.jsxs("label",{className:"block text-sm font-medium text-gray-800",children:["Where do you need real-estate help?",s.jsx("input",{required:!0,maxLength:200,className:`${y} mt-1`,value:r.location,onChange:f("location"),placeholder:"City, state, or area"})]}),s.jsxs("label",{className:"block text-sm font-medium text-gray-800",children:["What best describes your situation?",s.jsx("select",{className:`${y} mt-1`,value:r.situation,onChange:f("situation"),children:["Buying","Selling","Both","Helping someone else","Not sure"].map(v=>s.jsx("option",{children:v},v))})]}),s.jsxs("label",{className:"block text-sm font-medium text-gray-800",children:["What’s happening?",s.jsx("textarea",{required:!0,maxLength:3e3,rows:6,className:`${y} mt-1 resize-y`,value:r.message,onChange:f("message")})]}),s.jsxs("fieldset",{children:[s.jsx("legend",{className:"text-sm font-medium text-gray-800 mb-2",children:"How would you prefer Tom contact you?"}),s.jsx("div",{className:"flex flex-wrap gap-4",children:["Phone","Text","Email"].map(v=>s.jsxs("label",{className:"flex items-center gap-2 text-gray-700",children:[s.jsx("input",{type:"radio",name:"contactMethod",value:v,checked:r.contactMethod===v,onChange:f("contactMethod")}),v]},v))})]}),s.jsx("button",{disabled:i,className:"w-full rounded-md bg-teal-800 px-6 py-4 font-semibold text-white hover:bg-teal-900 focus:outline-none focus:ring-2 focus:ring-teal-700 focus:ring-offset-2 disabled:opacity-60",children:i?"Sending…":"Send to Tom"}),s.jsx("p",{className:"text-center text-sm text-gray-500",children:"Your information goes directly to Tom and is not automatically distributed to another agent."})]})]})})}function bLt({blocks:t,leadSiteId:e,sourcePage:r}){return s.jsx("div",{className:"w-full",children:t.map(n=>s.jsx(SLt,{block:n,leadSiteId:e,sourcePage:r},n.id))})}function wLt({config:t,accent:e,leadSiteId:r,sourcePage:n}){const[i,o]=C.useState({firstName:"",lastName:"",email:"",phone:"",address:""}),[c,a]=C.useState(!1),f=T=>E=>o(k=>({...k,[T]:E.target.value})),p="w-full px-4 py-3 rounded-lg bg-white/95 text-neutral-900 placeholder:text-neutral-400 text-sm md:text-base outline-none focus:ring-2 focus:ring-white/60 border-0",y="block text-[11px] font-semibold tracking-wider uppercase text-white/70 mb-1.5",v=async T=>{if(T.preventDefault(),c)return;const E=t.buttonLink||"/contact",k=`${i.firstName} ${i.lastName}`.trim();a(!0);try{if(r){const{error:P}=await lg({lead_site_id:r,name:k,email:i.email,phone:i.phone||null,message:i.address?`Property Address: ${i.address}`:null,source_page:n||null,lead_type:"seller",metadata:{first_name:i.firstName,last_name:i.lastName,address:i.address,form:t.formTitle||t.eyebrow||"Premium Hero"}});if(P)throw P;c5(r,{name:k,email:i.email,phone:i.phone||null,message:`${t.formTitle||"Landing page request"} Property Address: ${i.address||"Not provided"}`,lead_type:"seller",source_page:n||null})}typeof window<"u"&&(/^https?:\/\//i.test(E)?window.location.href=E:window.location.assign(E))}catch(P){console.error("Premium hero submission failed:",P),Vt.error("Something went wrong. Please try again."),a(!1)}};return s.jsxs("form",{className:"space-y-3",onSubmit:v,children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:y,children:"First Name"}),s.jsx("input",{required:!0,type:"text",value:i.firstName,onChange:f("firstName"),placeholder:"First name",className:p})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:y,children:"Last Name"}),s.jsx("input",{required:!0,type:"text",value:i.lastName,onChange:f("lastName"),placeholder:"Last name",className:p})]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:y,children:"Email"}),s.jsx("input",{required:!0,type:"email",value:i.email,onChange:f("email"),placeholder:"you@email.com",className:p})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:y,children:"Phone"}),s.jsx("input",{required:!0,type:"tel",value:i.phone,onChange:f("phone"),placeholder:"(555) 555-5555",className:p})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:y,children:"Property Address"}),s.jsx("input",{required:!0,type:"text",value:i.address,onChange:f("address"),placeholder:t.addressPlaceholder||"Enter your home's address",className:p})]}),s.jsxs("button",{type:"submit",disabled:c,className:"w-full px-6 py-3.5 rounded-lg font-bold text-neutral-900 text-base md:text-lg shadow-lg hover:brightness-110 active:brightness-95 transition-all disabled:opacity-70 flex items-center justify-center gap-2",style:{backgroundColor:e},children:[c&&s.jsx(su,{className:"h-4 w-4 animate-spin"}),c?"Sending…":t.buttonText||"Submit"]})]})}function SLt({block:t,leadSiteId:e,sourcePage:r}){const n=t.config;switch(t.type){case"premium-hero":{const o={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"}[n.fontStyle||"playfair"],c=n.accentColor||"#E8B84A",a=n.heightMode==="screen"?"min-h-screen":n.heightMode==="medium"?"min-h-[520px]":"min-h-[640px] md:min-h-[720px]",f=n.align==="center"?"items-center text-center":"items-start text-left",p=Array.isArray(n.trustPills)?n.trustPills:[];return s.jsxs("section",{className:`relative w-full ${a} overflow-hidden bg-neutral-900`,children:[n.backgroundImageUrl?s.jsx("img",{src:n.backgroundImageUrl,alt:"",className:"absolute inset-0 w-full h-full object-cover",loading:"eager"}):s.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-800 via-slate-900 to-black"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/85 via-black/60 to-black/30"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/20"}),s.jsx("div",{className:`relative z-10 mx-auto w-full max-w-7xl px-6 md:px-10 py-16 md:py-24 min-h-inherit flex flex-col justify-center ${f}`,children:s.jsxs("div",{className:`w-full ${n.align==="center"?"max-w-3xl mx-auto":"max-w-2xl"}`,children:[n.eyebrow&&s.jsx("p",{className:"text-xs md:text-sm font-semibold tracking-[0.2em] text-white/80 mb-4 uppercase",children:n.eyebrow}),s.jsxs("h1",{className:"text-white font-bold leading-[1.05] mb-5 text-4xl sm:text-5xl md:text-6xl lg:text-7xl",style:{fontFamily:o,letterSpacing:"-0.01em"},children:[n.headline,n.headlineAccent&&s.jsxs(s.Fragment,{children:[" ",s.jsx("span",{style:{color:c,fontStyle:"italic"},children:n.headlineAccent})]})]}),n.subtitle&&s.jsx("p",{className:"text-base md:text-lg text-white/85 leading-relaxed mb-8 max-w-xl",children:n.subtitle}),s.jsxs("div",{className:"rounded-2xl border border-white/15 bg-white/10 backdrop-blur-xl shadow-2xl p-5 md:p-6 max-w-xl",children:[n.formTitle&&s.jsx("p",{className:"text-white/90 text-sm font-semibold mb-3",children:n.formTitle}),s.jsx(wLt,{config:n,accent:c,leadSiteId:e,sourcePage:r}),p.length>0&&s.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4 pt-1",children:p.map((y,v)=>s.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] md:text-xs text-white/75 font-medium",children:[s.jsx("span",{className:"h-1 w-1 rounded-full",style:{backgroundColor:c}}),y]},v))})]})]})})]})}case"hero-banner":return s.jsxs("section",{className:"relative flex items-center justify-center min-h-[400px] bg-gray-900 text-white overflow-hidden",style:{backgroundImage:n.backgroundImageUrl?`url(${n.backgroundImageUrl})`:void 0,backgroundSize:"cover",backgroundPosition:"center"},children:[s.jsx("div",{className:"absolute inset-0 bg-black",style:{opacity:(n.overlayOpacity??50)/100}}),s.jsxs("div",{className:`relative z-10 px-6 py-16 max-w-3xl w-full ${n.alignment==="left"?"text-left":n.alignment==="right"?"text-right":"text-center mx-auto"}`,children:[s.jsx("h1",{className:"text-4xl md:text-5xl font-bold mb-4",children:n.headline}),n.subtitle&&s.jsx("p",{className:"text-lg md:text-xl text-white/80 mb-6",children:n.subtitle}),n.showButton&&n.buttonText&&s.jsx(Wr,{to:n.buttonLink||"/contact",className:"inline-block px-6 py-3 bg-white text-gray-900 font-semibold rounded-lg hover:bg-gray-100 transition-colors",children:n.buttonText})]})]});case"rich-text":return s.jsx("section",{className:"max-w-3xl mx-auto px-6 py-12",children:s.jsx("div",{className:"prose prose-gray max-w-none",dangerouslySetInnerHTML:{__html:n.content||""}})});case"image-text":{const i=n.imagePosition!=="right";return s.jsx("section",{className:"max-w-6xl mx-auto px-6 py-16",children:s.jsxs("div",{className:`grid grid-cols-1 md:grid-cols-2 gap-10 items-center ${i?"":"md:[direction:rtl] *:md:[direction:ltr]"}`,children:[s.jsx("div",{className:"rounded-2xl overflow-hidden aspect-[4/3] bg-gray-100",children:n.imageUrl?s.jsx("img",{src:n.imageUrl,alt:n.imageAlt||"",className:"w-full h-full object-cover"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-400 text-sm",children:"No image"})}),s.jsxs("div",{children:[s.jsx("h2",{className:"text-3xl font-bold text-gray-900 mb-4",children:n.headline}),s.jsx("p",{className:"text-gray-600 leading-relaxed mb-6",children:n.text}),n.showButton&&n.buttonText&&s.jsx(Wr,{to:n.buttonLink||"#",className:"inline-block px-5 py-2.5 bg-gray-900 text-white rounded-lg font-medium hover:bg-gray-800 transition-colors",children:n.buttonText})]})]})})}case"cta-button":return s.jsx("section",{className:"bg-gray-50 px-6 py-16",children:s.jsxs("div",{className:`max-w-2xl mx-auto text-${n.alignment||"center"}`,children:[s.jsx("h2",{className:"text-3xl font-bold text-gray-900 mb-3",children:n.headline}),n.subtitle&&s.jsx("p",{className:"text-gray-500 text-lg mb-6",children:n.subtitle}),s.jsx(Wr,{to:n.buttonLink||"/contact",className:`inline-block px-8 py-3 rounded-lg font-semibold text-lg transition-colors ${n.style==="outline"?"border-2 border-gray-900 text-gray-900 hover:bg-gray-900 hover:text-white":"bg-gray-900 text-white hover:bg-gray-800"}`,children:n.buttonText})]})});case"testimonials":return s.jsx("section",{className:"px-6 py-16 bg-white",children:s.jsxs("div",{className:"max-w-6xl mx-auto",children:[n.headline&&s.jsx("h2",{className:"text-3xl font-bold text-gray-900 text-center mb-10",children:n.headline}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:(n.items||[]).map((i,o)=>s.jsxs("div",{className:"bg-gray-50 rounded-2xl p-6 border border-gray-100",children:[s.jsx("div",{className:"flex gap-0.5 mb-3",children:Array.from({length:i.rating||5}).map((c,a)=>s.jsx(lc,{className:"h-4 w-4 fill-amber-400 text-amber-400"},a))}),s.jsxs("p",{className:"text-gray-700 text-sm leading-relaxed mb-4",children:['"',i.text,'"']}),s.jsxs("p",{className:"text-sm font-semibold text-gray-900",children:["— ",i.name]})]},o))})]})});case"faq-accordion":return s.jsxs("section",{className:"px-6 py-16 max-w-3xl mx-auto",children:[n.headline&&s.jsx("h2",{className:"text-3xl font-bold text-gray-900 text-center mb-10",children:n.headline}),s.jsx("div",{className:"space-y-3",children:(n.items||[]).map((i,o)=>s.jsx(TLt,{question:i.question,answer:i.answer},o))})]});case"photo-gallery":return s.jsxs("section",{className:"px-6 py-16 max-w-6xl mx-auto",children:[n.headline&&s.jsx("h2",{className:"text-3xl font-bold text-gray-900 text-center mb-10",children:n.headline}),s.jsx("div",{className:`grid grid-cols-2 md:grid-cols-${n.columns||3} gap-4`,children:(n.images||[]).map((i,o)=>s.jsxs("div",{className:"rounded-xl overflow-hidden bg-gray-100 aspect-square",children:[s.jsx("img",{src:i.url,alt:i.caption||"",className:"w-full h-full object-cover"}),i.caption&&s.jsx("p",{className:"text-xs text-gray-500 text-center mt-1 pb-1",children:i.caption})]},o))})]});case"video-embed":{const i=ELt(n.videoUrl||"");return s.jsxs("section",{className:"px-6 py-16 max-w-4xl mx-auto",children:[n.headline&&s.jsx("h2",{className:"text-3xl font-bold text-gray-900 text-center mb-8",children:n.headline}),i?s.jsx("div",{className:"relative w-full aspect-video rounded-2xl overflow-hidden bg-gray-900",children:s.jsx("iframe",{src:i,className:"absolute inset-0 w-full h-full",allowFullScreen:!0,allow:"autoplay; encrypted-media"})}):s.jsx("div",{className:"aspect-video bg-gray-100 rounded-2xl flex items-center justify-center text-gray-400",children:"Paste a YouTube or Vimeo URL"})]})}case"contact-form":return s.jsx(_Lt,{config:n,leadSiteId:e,sourcePage:r});case"stats-row":return s.jsx("section",{className:"px-6 py-16 bg-gray-900 text-white",children:s.jsx("div",{className:"max-w-5xl mx-auto grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-8 text-center",children:(n.items||[]).map((i,o)=>s.jsxs("div",{children:[s.jsx("p",{className:"text-4xl font-bold mb-1",children:i.value}),s.jsx("p",{className:"text-sm text-gray-400 uppercase tracking-wider",children:i.label})]},o))})});case"divider":return s.jsxs("div",{style:{height:n.height||40},className:"flex items-center justify-center px-6",children:[n.style==="line"&&s.jsx("hr",{className:"w-full max-w-4xl border-gray-200"}),n.style==="dots"&&s.jsx("div",{className:"flex gap-2",children:[1,2,3].map(i=>s.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-300"},i))})]});case"card-grid":return s.jsxs("section",{className:"px-6 py-16 max-w-6xl mx-auto",children:[n.headline&&s.jsx("h2",{className:"text-3xl font-bold text-gray-900 text-center mb-10",children:n.headline}),s.jsx("div",{className:`grid grid-cols-1 md:grid-cols-${n.columns||3} gap-6`,children:(n.cards||[]).map((i,o)=>s.jsxs("div",{className:"bg-white rounded-2xl border border-gray-100 overflow-hidden hover:shadow-lg transition-shadow",children:[i.imageUrl&&s.jsx("div",{className:"aspect-[16/10] bg-gray-100",children:s.jsx("img",{src:i.imageUrl,alt:i.title,className:"w-full h-full object-cover"})}),s.jsxs("div",{className:"p-6",children:[s.jsx("h3",{className:"text-lg font-bold text-gray-900 mb-2",children:i.title}),s.jsx("p",{className:"text-sm text-gray-500",children:i.description})]})]},o))})]});case"html-code":return n.code?s.jsx("section",{className:"px-6 py-8 max-w-6xl mx-auto",children:s.jsx("div",{dangerouslySetInnerHTML:{__html:n.code}})}):null;default:return null}}function TLt({question:t,answer:e}){const[r,n]=C.useState(!1);return s.jsxs("div",{className:"border border-gray-200 rounded-xl overflow-hidden",children:[s.jsxs("button",{onClick:()=>n(!r),className:"w-full flex items-center justify-between px-5 py-4 text-left hover:bg-gray-50 transition-colors",children:[s.jsx("span",{className:"font-medium text-gray-900",children:t}),s.jsx(yl,{className:`h-4 w-4 text-gray-400 transition-transform ${r?"rotate-180":""}`})]}),r&&s.jsx("div",{className:"px-5 pb-4 text-sm text-gray-600 leading-relaxed",children:e})]})}function ELt(t){if(!t)return null;const e=t.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]+)/);if(e)return`https://www.youtube.com/embed/${e[1]}`;const r=t.match(/vimeo\.com\/(\d+)/);return r?`https://player.vimeo.com/video/${r[1]}`:null}const jLt=1,ALt="7e98e197-8135-428c-969f-07023434dec8",kLt="b4ed24ae-0b44-4f4d-8676-c620f649ed8a",CLt="/__l5e/assets-v1/7e98e197-8135-428c-969f-07023434dec8/btb-emblem-white.webp",NLt="a/v1/b4ed24ae-0b44-4f4d-8676-c620f649ed8a/7e98e197-8135-428c-969f-07023434dec8/btb-emblem-white.webp",ILt="btb-emblem-white.webp",PLt=141720,RLt="image/webp",LLt="2026-10-30T05:18:02Z",DLt={version:jLt,asset_id:ALt,project_id:kLt,url:CLt,r2_key:NLt,original_filename:ILt,size:PLt,content_type:RLt,created_at:LLt},MLt="/assets/hero-Bp0n5rUQ.jpg",OLt="/assets/construction-DRPJW-Zl.jpg",FLt="/assets/design-DQodobBx.jpg",BLt="/assets/realestate-C0vC4CaI.jpg",$Lt="/assets/lexington-BXiMdbEn.jpg",za={hero:MLt,construction:OLt,design:FLt,realestate:BLt,lexington:$Lt},No={name:"Building The Bluegrass",legal:"Building The Bluegrass Realty",phone:"(859) 201-2101",phoneHref:"tel:+18592012101",address:"3320 Clay Mills Rd",cityLine:"Lexington, KY 40503",logoWhite:`https://tile-portal.lovable.app${DLt.url}`,facebook:"https://www.facebook.com/buildingthebluegrass",instagram:"https://www.instagram.com/buildingthebluegrass"},Xa="https://www.buildingthebluegrass.com/wp-content/uploads/",zLt={"Joey Svec":"joeysvec","Maria Gillette":"mariagillette","Kristi White":"kristiwhite","Mary Grenet":"marygrenet","Jim Cottle":"jamescottle","Allison Haas":"allisonhaas","Randi Mjos":"randimjos","Cindi Baston":"cindibatson","Joshua Cromwell":"joshuacromwell","Monica Suetholz":"monicasuetholz","Angela Piech":"angelapiech","Shannon Foster":"shannonfoster","Chris Haas":"chrishaas","Valeria Kaidanov":"valeriakaidanov","Hampton Johnson":"hamptonjohnson"};function ULt(t){const e=zLt[t];return e?`https://${e}.thelocalmove.com`:null}const tC=[{name:"Joey Svec",role:"CEO & Principal Broker",photo:Xa+"fx-gs.jpeg",group:"Leadership",licensed:!0},{name:"Maria Gillette",role:"Principal of Real Estate & REALTOR®",photo:Xa+"maria.jpeg",group:"Leadership",licensed:!0},{name:"Brad Boaz",role:"Landscape Architect & Planner",photo:Xa+"BradBoaz.jpeg",group:"Construction & Design"},{name:"Elizabeth Powell",role:"Senior Associate Designer",photo:Xa+"Elizabeth-headshot.jpg",group:"Construction & Design"},{name:"Jeff Moore",role:"Project Manager",photo:Xa+"Jeff_Moore_Headshot_BW_Square-400x400.jpg",group:"Construction & Design"},{name:"Michael Wilbanks",role:"Project Manager",photo:Xa+"Mike-headshot.jpg",group:"Construction & Design"},{name:"Noah Storkson",role:"Foreman",photo:Xa+"Noah-headshot.jpg",group:"Construction & Design"},{name:"Jane Carter",role:"Estimator & Procurement Specialist",photo:Xa+"Jane-Headshot.jpg",group:"Construction & Design"},{name:"Kristi White",role:"REALTOR®",photo:Xa+"White_Kristi_BW-scaled-e1725038078208.jpg",group:"Real Estate",licensed:!0},{name:"Mary Grenet",role:"REALTOR®",photo:Xa+"Grenet_Mary_BW-scaled-e1725037952355.jpg",group:"Real Estate",licensed:!0},{name:"Jim Cottle",role:"REALTOR®",photo:Xa+"rsz_1jim-e1695063749369.jpg",group:"Real Estate",licensed:!0},{name:"Allison Haas",role:"REALTOR®",photo:Xa+"allison.jpeg",group:"Real Estate",licensed:!0},{name:"Chris Haas",role:"REALTOR®",photo:Xa+"chris.jpeg",group:"Real Estate",licensed:!0},{name:"Randi Mjos",role:"REALTOR®",photo:Xa+"LMP_8523-scaled-e1695063828144.jpg",group:"Real Estate",licensed:!0},{name:"Cindi Baston",role:"REALTOR®",photo:Xa+"Cindi-Baston-BW-scaled-e1725038818587.jpg",group:"Real Estate",licensed:!0},{name:"Valeria Kaidanov",role:"REALTOR®",photo:Xa+"Valeria-headshot-.jpg",group:"Real Estate",licensed:!0},{name:"Joshua Cromwell",role:"REALTOR®",photo:Xa+"Joshua-Cromwell_BW-scaled-e1725038396105.jpg",group:"Real Estate",licensed:!0},{name:"Monica Suetholz",role:"REALTOR®",photo:Xa+"fx-gs5.jpeg",group:"Real Estate",licensed:!0},{name:"Angela Piech",role:"REALTOR®",photo:Xa+"Angela-Piech-headshot.jpeg",group:"Real Estate",licensed:!0},{name:"Shannon Foster",role:"REALTOR®",photo:Xa+"Shannon-headshot.jpg",group:"Real Estate",licensed:!0},{name:"Hampton Johnson",role:"REALTOR®",photo:Xa+"Hampton-Johnson-BW.webp",group:"Real Estate",licensed:!0},{name:"Jodie Fite",role:"Accounting",photo:Xa+"jodie-e1695063894957.png",group:"Operations"},{name:"Samantha Elliot",role:"Executive Assistant & Bookkeeper",photo:Xa+"Sam-headshot.jpg",group:"Operations"}],VLt=[{slug:"mid-century-modern-ranch",title:"Mid-Century Modern Ranch",type:"Construction",location:"Shadeland East, Lexington",image:"construction",story:"A sprawling ranch fully renovated with new additions — a primary suite with therapy room, a family room with indoor/outdoor living and a den. A reworked kitchen becomes the heart of the home as it grows from 2,200 to 3,500 sq ft."},{slug:"infill-and-redevelopment",title:"Infill & Redevelopment",type:"Design",location:"Montclair, Lexington",image:"design",story:"A beautifully appointed craftsman-style home, built in 2019 as an infill and redevelopment project in the Montclair neighborhood."},{slug:"renovated-ranch",title:"Renovated Ranch",type:"Real Estate",location:"Nicholasville",image:"realestate",story:"A beautifully renovated property our team helped list and bring under contract."},{slug:"rich-road-land",title:"Land With Possibility",type:"Real Estate",location:"Morning View",image:"lexington",story:"Acreage with endless possibilities — agricultural enterprise, recreational land, or simply room to get out of the city."}],qLt=[["Remodels & Fixer-Uppers","Breathing new life into outdated interiors and neglected spaces — turning existing structures into modern, functional, beautiful homes."],["Historic Home Remodeling","Good stewards of each home’s history and architectural heritage, balancing restoration with the amenities today’s families need."],["Kitchen Remodeling","The kitchen is the heart of every home. We create spaces where you gather, cook, laugh and live your best life."],["Bathroom Remodeling","Style and function blended into calm, lasting spaces that reflect your taste."],["Additions","More room for the life you are living now — designed to feel like it was always there."],["Custom Homes","From the first sketch to the final walkthrough, a home built around how you want to live."]],Wx=[{name:"Lexington",county:"Fayette County",blurb:"The heart of the Bluegrass — historic neighborhoods, a lively downtown, the University of Kentucky and horse country minutes away."},{name:"Nicholasville",county:"Jessamine County",blurb:"Just south of Lexington in Jessamine County, with established neighborhoods and new construction."},{name:"Georgetown",county:"Scott County",blurb:"A historic downtown in Scott County with easy access to I-75 and Lexington."},{name:"Versailles",county:"Woodford County",blurb:"Woodford County charm surrounded by farmland and the Kentucky River."},{name:"Winchester",county:"Clark County",blurb:"Clark County’s small-town character east of Lexington."},{name:"Richmond",county:"Madison County",blurb:"Madison County, home to Eastern Kentucky University."}],cg=t=>`/homes-for-sale-in-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,ece=[{key:"buy",label:"Buy a home"},{key:"sell",label:"Sell my home"},{key:"value",label:"What’s my home worth?"},{key:"construction",label:"Build or renovate"},{key:"cabinets",label:"Cabinets"},{key:"relocate",label:"Relocating to the Bluegrass"},{key:"explore",label:"Just exploring"}],bK="We are more than a real estate brokerage; we are a relationship-driven property company serving our clients for life.",GLt=[["Annual Brokerage Branded Photoshoot","Fresh, professional photography every year so your brand always looks its best."],["250 Business Cards / Annually","Brokerage-branded cards in your hand, on us, every year."],["Monthly Educational Brokerage Meeting","Market updates, skill-building and shared wins with the whole office."],["Brokerage-Wide Client Events","Quarterly events that let you thank your clients and grow your sphere."],["Annual Business Development Session","A yearly plan for your business, with quarterly follow-up meetings to keep it on track."],["Business Growth Coaching","One-on-one coaching meetings every two weeks."],["Personality DISC Assessment & Training","Understand how you communicate — and how your clients do."],["LevelUp CRM & Marketing","A full CRM with marketing tools, including listing landing pages."],["Agent Website With Lead Capture","Your own website that captures leads, with weekly training workshops."],["Open House Lead Capture & Community Giving","Digital open house sign-in plus office-led community giving every quarter."],["24/7 Office Access","The office is yours anytime — printer, beverage bar and conference room included."]],HLt=[["Kitchens","Cabinetry designed around how you cook, gather and store — from classic shaker to clean modern lines."],["Baths & Vanities","Furniture-quality vanities and linen storage that make everyday routines feel calm."],["Built-ins","Bookcases, mudroom lockers, window seats and media walls that feel original to the home."],["Storage Solutions","Pull-outs, organizers and pantry systems that put every inch to work."]],WLt=[["Consult","We visit, measure and talk through how you use the space."],["Design","Layouts, door styles, finishes and hardware chosen together."],["Build","Cabinetry crafted and finished to your plan."],["Install","Careful installation and a final walkthrough."]],KLt=[["Strategy session","We talk through your goals, timing, neighborhoods and must-haves."],["Pre-approval & budget","Get pre-approved so you know your number and can move quickly."],["Curated search & tours","Live MLS alerts, saved favorites and private showings."],["Offer & negotiation","A strong, well-priced offer backed by local market data."],["Under contract","Inspections, appraisal and every deadline tracked for you."],["Closing day","Final walkthrough, signatures — and the keys are yours."]],YLt=[["How much do I need for a down payment?","It depends on the loan. Some programs allow as little as 0–3.5% down, while conventional loans often start at 3–5%. A lender can show you the options that fit."],["How long does it take to buy a home?","Many buyers go from first tour to closing in 60–90 days. Closing itself usually takes 30–45 days once you are under contract."],["Can I buy a home that needs work?","Yes. With our construction team and renovation loan options, a dated home can become exactly what you want."],["Do I need to sell before I buy?","Not always. We can talk through timing, contingencies and financing options that let you move with confidence."]],ZLt=[["Conventional","Flexible terms with as little as 3–5% down for qualified buyers."],["FHA","Lower down payment and more flexible credit guidelines."],["VA","For eligible veterans and service members — often with no down payment."],["USDA","Zero-down options for eligible homes in many areas around Central Kentucky."],["Construction & Renovation","Finance the purchase and improvements together — a natural fit with BTB Construction."]],XLt=["Photo ID","Last two years of W-2s or tax returns","Recent pay stubs (30 days)","Two months of bank statements","Information on any current debts","Gift letter, if using gift funds"],QLt=[["Local market valuation","A clear, honest price based on what is actually selling near you."],["Staging & preparation","Practical advice on what is worth fixing — and our construction team when it is."],["Photography & video","Professional photos and video that make buyers want to visit."],["Negotiation to closing","Offers, inspections and closing, handled steadily for you."]],JLt=[["Personal attention","You may be one of dozens of listings","Boutique service — treated like our only client"],["Pre-sale improvements","You find and manage contractors","In-house construction & cabinet teams"],["Marketing","MLS listing and a few photos","Professional photo, video and a dedicated listing website"],["Relationship","Ends at closing","Serving you for life"]],Uh=t=>typeof t=="string"&&t.trim()?t.trim():null;function eDt(t){const e=(t||"").replace(/\D/g,""),r=e.length===11&&e.startsWith("1")?e.slice(1):e;return r.length!==10?null:{phone:`(${r.slice(0,3)}) ${r.slice(3,6)}-${r.slice(6)}`,phoneHref:`tel:+1${r}`}}function tDt(t){var r,n;const e=(r=t.trim().split(/\s+/).pop())==null?void 0:r.toLowerCase();return e&&((n=tC.find(i=>i.name.split(/\s+/).pop().toLowerCase()===e))==null?void 0:n.photo)||null}function rDt(t){const e=t.themeConfig||{},r=t.agent||{},n=Uh(r.full_name)||Uh((t.siteTitle||"").split("|")[0])||"Your Agent",i=n.split(/\s+/)[0],o=eDt(Uh(e.agentPhone)||r.phone)||{phone:No.phone,phoneHref:No.phoneHref};return{name:n,first:i,...o,email:Uh(e.agentEmail)||Uh(r.email),photo:Uh(e.agentHeadshotUrl)||Uh(r.avatar_url)||tDt(n),title:Uh(e.agentTitle)||Uh(r.title)||"REALTOR®",bio:Uh(e.agentBio)||Uh(r.bio)||`${n} is a REALTOR® with Building The Bluegrass Realty in Lexington, Kentucky. ${i} helps buyers and sellers across Central Kentucky with honest advice, thoughtful pricing and steady guidance from the first conversation to the closing table — the relationship-first way our whole office works.`}}const i2e="https://wsrv.nl/",nDt=["cdn.photos.sparkplatform.com","images.unsplash.com","cdn.repliers.io","cdn.repliers.com","relzejiswnotikjgvjhz.supabase.co","supabase.co"],iDt={thumb:200,card:600,hero:1200,full:1920},sDt={thumb:70,card:75,hero:80,full:82};function UHt(t,e={}){return""}function aDt(t){if(!t||t.startsWith("data:")||t.startsWith("blob:")||t.startsWith(i2e)||t.includes("/functions/v1/mlsgrid-media")||t.includes("/functions/v1/trestle-media"))return!1;try{const e=new URL(t);return nDt.some(r=>e.hostname===r||e.hostname.endsWith("."+r))}catch{return!1}}function oDt(t,e={}){if(!t)return"";if(!aDt(t))return t;const r=e.variant??"card",n=e.width??iDt[r],i=e.quality??sDt[r],o=t.replace(/^https?:\/\//,""),c=new URLSearchParams({url:o,w:String(n),q:String(i),output:"webp"});return e.height&&c.set("h",String(e.height)),e.fit&&c.set("fit",e.fit),`${i2e}?${c.toString()}`}function Hp({siteConfig:t,accentColor:e,sectionTitle:r,cities:n,count:i=12,mode:o,luxuryMode:c=!1}){const a=Hs(),f=C.useRef(null),[p,y]=C.useState(!1),[v,T]=C.useState(!1),{data:E=[],isLoading:k}=mr({queryKey:["lead-site-carousel",t.id,o,n,i,t.agentId],queryFn:async()=>{const B="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/lead-site-search",V={leadSiteId:t.id,pageSize:i,propertyType:"Residential"},G=J=>{const Q=(J.propertyType||"").toLowerCase().replace(/\s+/g,"");return Q?Q.startsWith("residential")||Q.startsWith("singlefamily")||Q.startsWith("condo")||Q.startsWith("townhouse")||Q.startsWith("townhome")||Q.startsWith("multifamily")||Q.startsWith("manufactured"):!0},W=async J=>{const Q=await fetch(B,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify(J),signal:AbortSignal.timeout(15e3)});return Q.ok?((await Q.json()).listings||[]).filter(G).slice(0,i):[]};if(n){const J=n.split(",").map(Q=>Q.trim()).filter(Boolean);J.length>0&&(V.filterCities=J)}return o==="open_houses"&&(V.openHousesOnly=!0),o==="my_listings"&&(V.agentListings=!0,V.agentId=t.agentId),o==="new_listings"&&(V.sortBy="newest"),await W(V)},staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1,refetchOnMount:!1}),P=()=>{const B=f.current;B&&(y(B.scrollLeft>10),T(B.scrollLeft{const B=f.current;if(B)return P(),B.addEventListener("scroll",P,{passive:!0}),window.addEventListener("resize",P),()=>{B.removeEventListener("scroll",P),window.removeEventListener("resize",P)}},[E]);const R=B=>{const V=f.current;if(!V)return;const G=340;V.scrollBy({left:B==="left"?-G*2:G*2,behavior:"smooth"})},D={new_listings:"New on the Market",open_houses:"Open Houses",my_listings:"My Active Listings"},M={new_listings:"The latest properties just listed",open_houses:"Tour these homes in person",my_listings:"Properties I'm currently representing"};return k?s.jsx("section",{className:`py-16 md:py-20 overflow-hidden ${c?"bg-[#0d0b0a]":""}`,children:s.jsxs("div",{className:"max-w-[1400px] mx-auto px-6",children:[s.jsxs("div",{className:"text-center mb-10",children:[s.jsx("div",{className:`h-4 w-20 rounded mx-auto mb-3 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`}),s.jsx("div",{className:`h-8 w-72 rounded mx-auto mb-2 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`}),s.jsx("div",{className:`h-4 w-56 rounded mx-auto animate-pulse ${c?"bg-white/5":"bg-gray-200"}`})]}),s.jsx("div",{className:"flex gap-5",children:[1,2,3,4].map(B=>s.jsxs("div",{className:`min-w-[320px] rounded-2xl overflow-hidden ${c?"bg-white/5":"bg-gray-100"}`,children:[s.jsx("div",{className:`h-56 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`}),s.jsxs("div",{className:"p-5 space-y-3",children:[s.jsx("div",{className:`h-5 rounded w-24 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`}),s.jsx("div",{className:`h-4 rounded w-40 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`})]})]},B))})]})}):E.length?s.jsx("section",{className:`py-16 md:py-20 overflow-hidden ${c?"bg-[#0d0b0a]":""}`,children:s.jsxs("div",{className:"max-w-[1400px] mx-auto px-6",children:[s.jsxs("div",{className:"flex items-end justify-between mb-10",children:[s.jsxs("div",{children:[s.jsx(fr.p,{initial:{opacity:0,y:10},whileInView:{opacity:1,y:0},viewport:{once:!0},className:`text-sm tracking-[0.2em] uppercase font-semibold mb-2 ${c?"tracking-[0.4em]":""}`,style:{color:e},children:o==="open_houses"?"Open Houses":o==="my_listings"?"My Listings":"Just Listed"}),s.jsx(fr.h2,{initial:{opacity:0,y:15},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{delay:.05},className:`text-3xl md:text-4xl tracking-tight ${c?"text-white":"text-gray-900 font-bold"}`,style:c?{fontFamily:"'Playfair Display', Georgia, serif"}:{},children:r||D[o]}),s.jsx(fr.p,{initial:{opacity:0},whileInView:{opacity:1},viewport:{once:!0},transition:{delay:.1},className:`mt-1.5 ${c?"text-white/40":"text-gray-500"}`,children:M[o]})]}),s.jsxs("div",{className:"hidden md:flex items-center gap-2",children:[s.jsx("button",{onClick:()=>R("left"),disabled:!p,className:`p-3 rounded-full border transition-all disabled:opacity-30 disabled:cursor-not-allowed ${c?"border-white/10 text-white/50 hover:border-white/30":"border-gray-200 text-gray-600 hover:bg-gray-50 hover:border-gray-300"}`,children:s.jsx(Cm,{className:"h-5 w-5"})}),s.jsx("button",{onClick:()=>R("right"),disabled:!v,className:`p-3 rounded-full border transition-all disabled:opacity-30 disabled:cursor-not-allowed ${c?"border-white/10 text-white/50 hover:border-white/30":"border-gray-200 text-gray-600 hover:bg-gray-50 hover:border-gray-300"}`,children:s.jsx(jd,{className:"h-5 w-5"})})]})]}),s.jsxs("div",{className:"relative -mx-6",children:[s.jsxs("div",{ref:f,className:"flex gap-5 overflow-x-auto scrollbar-hide px-6 snap-x snap-mandatory",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:[E.map((B,V)=>{var G,W,Y,J;return s.jsx(fr.div,{initial:{opacity:0,y:20},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{duration:.4,delay:V*.05},onClick:()=>a(`/listing/${B.mlsNumber}`),className:"group min-w-[300px] sm:min-w-[320px] max-w-[340px] flex-shrink-0 snap-start cursor-pointer",children:s.jsxs("div",{className:`overflow-hidden h-full flex flex-col ${c?"bg-[#161312] hover:bg-[#1a1715] transition-all duration-500":"bg-white rounded-2xl shadow-[0_2px_20px_-4px_rgba(0,0,0,0.08)] hover:shadow-[0_8px_40px_-8px_rgba(0,0,0,0.15)] transition-all duration-500"}`,children:[s.jsxs("div",{className:"relative h-56 overflow-hidden",children:[s.jsx("img",{src:oDt(((G=B.photos)==null?void 0:G[0])||"https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?w=600&q=75",{variant:"card"}),alt:B.address,className:"w-full h-full object-cover group-hover:scale-[1.06] transition-transform duration-700 ease-out",loading:"lazy",decoding:"async"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/50 via-transparent to-transparent"}),s.jsx("div",{className:"absolute top-3 left-3 px-3 py-1 rounded-full text-[11px] font-bold tracking-wide uppercase text-white backdrop-blur-md",style:{backgroundColor:`${e}cc`},children:o==="open_houses"?"Open House":B.status||"Active"}),s.jsx("div",{className:"absolute bottom-3 left-3",children:s.jsxs("p",{className:"text-2xl font-bold text-white drop-shadow-lg",children:["$",(W=B.price)==null?void 0:W.toLocaleString()]})}),((Y=B.photos)==null?void 0:Y.length)>1&&s.jsxs("div",{className:"absolute bottom-3 right-3 px-2.5 py-1 bg-black/40 backdrop-blur-sm rounded-full text-[11px] text-white font-medium",children:[B.photos.length," photos"]})]}),s.jsxs("div",{className:"p-4 flex-1 flex flex-col",children:[s.jsx("p",{className:`font-semibold text-[15px] leading-snug mb-1 truncate ${c?"text-white/80":"text-gray-900"}`,children:B.address}),s.jsxs("p",{className:`text-sm mb-3 truncate ${c?"text-white/30":"text-gray-500"}`,children:[B.city,", ",B.state," ",B.zip]}),s.jsxs("div",{className:`flex items-center gap-4 mt-auto pt-3 border-t ${c?"border-white/5":"border-gray-100"}`,children:[s.jsxs("div",{className:`flex items-center gap-1.5 ${c?"text-white/30":"text-gray-600"}`,children:[s.jsx(XS,{className:"h-3.5 w-3.5"}),s.jsx("span",{className:"text-sm font-medium",children:B.bedrooms})]}),s.jsxs("div",{className:`flex items-center gap-1.5 ${c?"text-white/30":"text-gray-600"}`,children:[s.jsx(__,{className:"h-3.5 w-3.5"}),s.jsx("span",{className:"text-sm font-medium",children:B.bathrooms})]}),s.jsxs("div",{className:`flex items-center gap-1.5 ${c?"text-white/30":"text-gray-600"}`,children:[s.jsx(qDe,{className:"h-3.5 w-3.5"}),s.jsxs("span",{className:"text-sm font-medium",children:[(J=B.sqft)==null?void 0:J.toLocaleString()," sqft"]})]})]})]})]})},B.mlsNumber)}),s.jsx(fr.div,{initial:{opacity:0},whileInView:{opacity:1},viewport:{once:!0},onClick:()=>a(o==="open_houses"?"/search?openHouses=1":"/search"),className:"min-w-[200px] flex-shrink-0 snap-start cursor-pointer flex items-center justify-center",children:s.jsxs("div",{className:"text-center group",children:[s.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center mx-auto mb-3 transition-transform group-hover:scale-110",style:{backgroundColor:`${e}15`},children:s.jsx(Ds,{className:"h-6 w-6",style:{color:e}})}),s.jsx("p",{className:`text-sm font-semibold transition-colors ${c?"text-white/50 group-hover:text-white":"text-gray-700 group-hover:text-gray-900"}`,children:"View All"})]})})]}),s.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-12 bg-gradient-to-l pointer-events-none md:hidden ${c?"from-[#0d0b0a]":"from-white"} to-transparent`})]})]})}):null}const s2e=C.createContext(void 0),a2e=C.createContext(null),LT=()=>C.useContext(a2e);function hN(t){var f;const e=C.useContext(s2e),{pathname:r}=ki(),n=t||r.replace(/^\/+|\/+$/g,""),{data:i}=mr({queryKey:["btb-editable",e,n],enabled:!!e&&!!n,staleTime:6e4,queryFn:async()=>{const{data:p}=await Re.from("lead_site_pages").select("page_blocks").eq("site_id",e).eq("slug",n).eq("is_published",!0).maybeSingle();return(p==null?void 0:p.page_blocks)||[]}}),o=i||[],c=((f=o[0])==null?void 0:f.type)==="hero-banner"?o[0].config||{}:null,a=c?o.slice(1):o;return{hero:c,rest:a,siteId:e,slug:n}}function g5({blocks:t,siteId:e,slug:r}){return!t.length||!e?null:s.jsx("div",{className:"btb-bg-paper",children:s.jsx(bLt,{blocks:t,leadSiteId:e,sourcePage:`/${r}`})})}function cu(){C.useEffect(()=>{const t=document.querySelectorAll(".btb-reveal:not(.is-in)"),e=new IntersectionObserver(r=>r.forEach(n=>{n.isIntersecting&&(n.target.classList.add("is-in"),e.unobserve(n.target))}),{threshold:.12});return t.forEach(r=>e.observe(r)),()=>e.disconnect()})}const tce=[{label:"Who We Are",to:"/about",children:[{label:"About Us",to:"/about"},{label:"Our Agents",to:"/team"},{label:"BTB Construction",to:"/construction"},{label:"BTB Cabinets",to:"/cabinets"}]},{label:"Selling",to:"/sell",children:[{label:"Sell Your Home",to:"/sell"},{label:"What’s My Home Worth?",to:"/home-value"}]},{label:"Buying",to:"/buying-process",children:[{label:"The Buying Process",to:"/buying-process"},{label:"Financing",to:"/financing"},{label:"Find a Home",to:"/search"},{label:"My Saved Homes",to:"/account?tab=saved"},{label:"Saved Searches & Alerts",to:"/account?tab=searches"}]},{label:"Top Areas",to:"/communities",children:[...Wx.map(t=>({label:t.name,to:cg(t.name)})),{label:"All Areas",to:"/communities"}]},{label:"Reviews",to:"/reviews"},{label:"Blog",to:"/blog"},{label:"Careers",to:"/careers"},{label:"Connect",to:"/contact"}];function lDt(t){const[e,r]=C.useState(tce);return C.useEffect(()=>{if(!t)return;let n=!1;return(async()=>{const[{data:i},{data:o}]=await Promise.all([Re.from("lead_site_menu_items").select("id,label,item_type,target_url,page_id,parent_id,sort_order,is_visible").eq("site_id",t).order("sort_order"),Re.from("lead_site_pages").select("id,slug").eq("site_id",t)]);if(n||!(i!=null&&i.length))return;const c=new Map((o||[]).map(y=>[y.id,y.slug])),a=y=>y.page_id&&c.get(y.page_id)?`/p/${c.get(y.page_id)}`:y.target_url||"/",f=i.filter(y=>y.is_visible!==!1),p=f.filter(y=>!y.parent_id&&y.item_type!=="cities"&&(y.item_type==="dropdown"||a(y)!=="/")).map(y=>{var E,k;let v=f.filter(P=>P.parent_id===y.id).map(P=>({label:P.label,to:a(P)}));const T=y.item_type==="dropdown"?((E=v[0])==null?void 0:E.to)||"/":a(y);return!v.length&&T==="/communities"&&(v=((k=tce.find(P=>P.to==="/communities"))==null?void 0:k.children)||[]),{label:y.label,to:T,children:v.length?v:void 0}});p.length&&r(p)})(),()=>{n=!0}},[t]),e}const cDt=[{label:"About Me",to:"/about"},{label:"Selling",to:"/sell",children:[{label:"Sell Your Home",to:"/sell"},{label:"What’s My Home Worth?",to:"/home-value"}]},{label:"Buying",to:"/buying-process",children:[{label:"The Buying Process",to:"/buying-process"},{label:"Financing",to:"/financing"},{label:"Find a Home",to:"/search"},{label:"My Saved Homes",to:"/account?tab=saved"},{label:"Saved Searches & Alerts",to:"/account?tab=searches"}]},{label:"Top Areas",to:"/communities",children:[...Wx.map(t=>({label:t.name,to:cg(t.name)})),{label:"All Areas",to:"/communities"}]},{label:"Reviews",to:"/reviews"},{label:"Blog",to:"/blog"},{label:"Contact",to:"/contact"}];function rce({children:t,siteId:e,agent:r=null,siteConfig:n=null}){return s.jsx(s2e.Provider,{value:e,children:s.jsx(a2e.Provider,{value:r,children:s.jsx(uDt,{siteId:e,siteConfig:n,children:t})})})}function uDt({children:t,siteId:e,siteConfig:r}){r2e(r);const n=LT(),i=lDt(n?void 0:e),o=n?cDt:i,{pathname:c}=ki(),a=c==="/",[f,p]=C.useState(!1),[y,v]=C.useState(!1);C.useEffect(()=>{const E=()=>p(window.scrollY>40);return E(),window.addEventListener("scroll",E,{passive:!0}),()=>window.removeEventListener("scroll",E)},[]),C.useEffect(()=>v(!1),[c]);const T=a&&!f&&!y;return s.jsxs("div",{className:"btb-site min-h-screen",children:[s.jsxs("header",{className:`fixed inset-x-0 top-0 z-50 transition-colors duration-300 ${T?"btb-light":"btb-bg-ink shadow-sm"}`,children:[s.jsxs("div",{className:`mx-auto flex max-w-[1400px] items-center justify-between px-5 lg:px-10 ${T?"h-24":"h-[72px]"} transition-all`,children:[s.jsxs(Wr,{to:"/",className:"flex items-center gap-3","aria-label":n?`${n.name} home`:"Building The Bluegrass home",children:[s.jsx("img",{src:No.logoWhite,alt:"",className:"h-11 w-11 object-contain"}),n?s.jsxs("span",{className:"leading-none",children:[s.jsx("span",{className:"btb-serif text-xl block",children:n.name}),s.jsx("span",{className:"btb-eyebrow opacity-70 !text-[0.6rem] hidden sm:block mt-1",children:"Building The Bluegrass Realty"})]}):s.jsx("span",{className:"btb-serif text-xl leading-none hidden sm:block",children:"Building The Bluegrass"})]}),s.jsx("nav",{className:"hidden xl:flex items-center gap-6","aria-label":"Main",children:o.map(E=>s.jsxs("div",{className:"group relative",children:[s.jsxs(Wr,{to:E.to,className:"flex items-center gap-1 text-[0.74rem] tracking-[0.12em] uppercase py-6 whitespace-nowrap opacity-90 hover:opacity-100",children:[E.label,E.children&&s.jsx(yl,{className:"h-3 w-3"})]}),E.children&&s.jsx("div",{className:"invisible opacity-0 group-hover:visible group-hover:opacity-100 group-focus-within:visible group-focus-within:opacity-100 transition absolute left-0 top-full min-w-[220px] btb-bg-paper btb-ink border btb-line py-3",children:E.children.map(k=>s.jsx(Wr,{to:k.to,className:"block px-5 py-2.5 text-sm hover:btb-accent",children:k.label},k.label))})]},E.label))}),s.jsxs("div",{className:"flex items-center gap-3",children:[n&&s.jsx("a",{href:n.phoneHref,className:"hidden 2xl:inline text-sm opacity-90 hover:opacity-100",children:n.phone}),s.jsx("span",{className:"hidden md:inline-flex",children:s.jsx(yO,{siteConfig:r,variant:"desktop"})}),s.jsxs(Wr,{to:"/search",className:"btb-btn btb-btn-light !py-3 !px-4",children:[s.jsx(xd,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden sm:inline",children:"Search Homes"})]}),s.jsx("button",{className:"xl:hidden p-2",onClick:()=>v(!y),"aria-label":y?"Close menu":"Open menu","aria-expanded":y,children:y?s.jsx(Os,{className:"h-6 w-6"}):s.jsx(QS,{className:"h-6 w-6"})})]})]}),y&&s.jsxs("div",{className:"xl:hidden btb-bg-ink border-t btb-line-light max-h-[80vh] overflow-y-auto px-6 py-6 space-y-5",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsx(Wr,{to:"/search",className:"btb-btn btb-btn-light justify-center",children:"Search Homes"}),s.jsx(Wr,{to:"/contact",className:"btb-btn btb-btn-ghost justify-center",children:"Contact"})]}),s.jsx(yO,{siteConfig:r,variant:"mobile",onNavigate:()=>v(!1)}),o.map(E=>s.jsxs("div",{children:[s.jsx(Wr,{to:E.to,className:"btb-serif text-2xl block",children:E.label}),E.children&&s.jsx("div",{className:"mt-2 pl-1 space-y-1.5",children:E.children.map(k=>s.jsx(Wr,{to:k.to,className:"block text-sm opacity-75",children:k.label},k.label))})]},E.label))]})]}),s.jsx("main",{className:a?"":"pt-[72px]",children:t}),s.jsx(dDt,{})]})}function dDt(){const t=LT();return t?s.jsx(hDt,{agent:t}):s.jsxs("footer",{className:"btb-bg-ink",children:[s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-20 grid gap-12 md:grid-cols-12",children:[s.jsxs("div",{className:"md:col-span-5",children:[s.jsx("img",{src:No.logoWhite,alt:"Building The Bluegrass",className:"h-16 w-16 object-contain mb-6"}),s.jsx("p",{className:"btb-serif text-3xl leading-tight max-w-sm",children:"Home, the Bluegrass way."}),s.jsxs("p",{className:"mt-6 text-sm opacity-70 leading-relaxed",children:[No.address,s.jsx("br",{}),No.cityLine,s.jsx("br",{})]})]}),[["Real Estate",[["Find a Home","/search"],["Buying Process","/buying-process"],["Financing","/financing"],["Sell Your Home","/sell"],["Home Value","/home-value"]]],["Explore",[...Wx.slice(0,3).map(e=>[e.name,cg(e.name)]),["All Areas","/communities"],["Reviews","/reviews"],["Blog","/blog"]]],["Company",[["About Us","/about"],["Our Agents","/team"],["BTB Construction","/construction"],["BTB Cabinets","/cabinets"],["Careers","/careers"],["Connect","/contact"]]]].map(([e,r])=>s.jsxs("div",{className:"md:col-span-2",children:[s.jsx("p",{className:"btb-eyebrow opacity-60 mb-5",children:e}),s.jsx("ul",{className:"space-y-3 text-sm",children:r.map(([n,i])=>s.jsx("li",{children:s.jsx(Wr,{to:i,className:"opacity-85 hover:opacity-100",children:n})},n))})]},e)),s.jsxs("div",{className:"md:col-span-1",children:[s.jsx("p",{className:"btb-eyebrow opacity-60 mb-5",children:"Follow"}),s.jsxs("ul",{className:"space-y-3 text-sm",children:[s.jsx("li",{children:s.jsx("a",{href:No.facebook,target:"_blank",rel:"noreferrer",children:"Facebook"})}),s.jsx("li",{children:s.jsx("a",{href:No.instagram,target:"_blank",rel:"noreferrer",children:"Instagram"})})]})]})]}),s.jsx("div",{className:"border-t btb-line-light",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-6 text-xs opacity-60 flex flex-col md:flex-row gap-3 justify-between",children:[s.jsxs("p",{children:["© ",new Date().getFullYear()," ",No.legal,". All rights reserved. Equal Housing Opportunity."]}),s.jsx("p",{children:"Listing data provided courtesy of Imagine MLS. Information deemed reliable but not guaranteed."})]})})]})}function hDt({agent:t}){return s.jsxs("footer",{className:"btb-bg-ink",children:[s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-20 grid gap-12 md:grid-cols-12",children:[s.jsxs("div",{className:"md:col-span-5 flex gap-6 items-start",children:[t.photo&&s.jsx("img",{src:t.photo,alt:t.name,className:"h-28 w-24 object-cover object-top grayscale"}),s.jsxs("div",{children:[s.jsx("p",{className:"btb-serif text-3xl leading-tight",children:t.name}),s.jsxs("p",{className:"text-sm opacity-70 mt-1",children:[t.title," · Building The Bluegrass Realty"]}),s.jsxs("p",{className:"mt-5 text-sm leading-relaxed",children:[s.jsx("a",{href:t.phoneHref,className:"hover:underline",children:t.phone}),t.email&&s.jsxs(s.Fragment,{children:[s.jsx("br",{}),s.jsx("a",{href:`mailto:${t.email}`,className:"hover:underline",children:t.email})]})]}),s.jsxs("p",{className:"mt-4 text-sm opacity-70 leading-relaxed",children:[No.address,s.jsx("br",{}),No.cityLine]})]})]}),[["Real Estate",[["Find a Home","/search"],["Buying Process","/buying-process"],["Financing","/financing"],["Sell Your Home","/sell"],["Home Value","/home-value"]]],["Explore",[...Wx.slice(0,3).map(e=>[e.name,cg(e.name)]),["All Areas","/communities"],["Reviews","/reviews"],["Blog","/blog"]]],["Me",[["About Me","/about"],["Contact","/contact"],["My Saved Homes","/dashboard"]]]].map(([e,r])=>s.jsxs("div",{className:"md:col-span-2",children:[s.jsx("p",{className:"btb-eyebrow opacity-60 mb-5",children:e}),s.jsx("ul",{className:"space-y-3 text-sm",children:r.map(([n,i])=>s.jsx("li",{children:s.jsx(Wr,{to:i,className:"opacity-85 hover:opacity-100",children:n})},n))})]},e)),s.jsx("div",{className:"md:col-span-1",children:s.jsx("img",{src:No.logoWhite,alt:"Building The Bluegrass Realty",className:"h-14 w-14 object-contain"})})]}),s.jsx("div",{className:"border-t btb-line-light",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-6 text-xs opacity-60 flex flex-col md:flex-row gap-3 justify-between",children:[s.jsxs("p",{children:["© ",new Date().getFullYear()," ",t.name," · ",No.legal,". Equal Housing Opportunity."]}),s.jsx("p",{children:"Listing data provided courtesy of Imagine MLS. Information deemed reliable but not guaranteed."})]})})]})}function A1({compact:t=!1}){const e=Hs(),[r,n]=C.useState(""),[i,o]=C.useState(""),[c,a]=C.useState(""),f=p=>{p.preventDefault();const y=new URLSearchParams;r.trim()&&y.set("q",r.trim()),i&&y.set("maxPrice",i),c&&y.set("beds",c),e(`/search?${y.toString()}`)};return s.jsxs("form",{onSubmit:f,className:`btb-bg-paper btb-ink grid gap-0 md:grid-cols-[1fr_180px_140px_auto] ${t?"":"shadow-2xl"}`,role:"search",children:[s.jsxs("label",{className:"px-6 py-4 border-b md:border-b-0 md:border-r btb-line",children:[s.jsx("span",{className:"btb-eyebrow btb-soft block mb-1",children:"Location"}),s.jsx("input",{value:r,onChange:p=>n(p.target.value),placeholder:"City, neighborhood, address or MLS #",className:"w-full bg-transparent outline-none text-base"})]}),s.jsxs("label",{className:"px-6 py-4 border-b md:border-b-0 md:border-r btb-line",children:[s.jsx("span",{className:"btb-eyebrow btb-soft block mb-1",children:"Max price"}),s.jsxs("select",{value:i,onChange:p=>o(p.target.value),className:"w-full bg-transparent outline-none",children:[s.jsx("option",{value:"",children:"Any"}),[3e5,45e4,6e5,8e5,1e6,15e5].map(p=>s.jsxs("option",{value:p,children:["$",(p/1e3).toLocaleString(),"k"]},p))]})]}),s.jsxs("label",{className:"px-6 py-4 border-b md:border-b-0 md:border-r btb-line",children:[s.jsx("span",{className:"btb-eyebrow btb-soft block mb-1",children:"Beds"}),s.jsxs("select",{value:c,onChange:p=>a(p.target.value),className:"w-full bg-transparent outline-none",children:[s.jsx("option",{value:"",children:"Any"}),[1,2,3,4,5].map(p=>s.jsxs("option",{value:p,children:[p,"+"]},p))]})]}),s.jsxs("button",{type:"submit",className:"btb-btn justify-center !py-5",children:[s.jsx(xd,{className:"h-4 w-4"}),"Search"]})]})}function vg(t){const{hero:e,rest:r,siteId:n,slug:i}=hN(),o=(e==null?void 0:e.eyebrow)||t.eyebrow,c=(e==null?void 0:e.headline)||t.title,a=(e==null?void 0:e.subtitle)??t.intro,f=(e==null?void 0:e.backgroundImageUrl)||t.image;return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"relative h-[62vh] min-h-[440px] overflow-hidden btb-light",children:[s.jsx("img",{src:f,alt:"",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 btb-hero-shade"}),s.jsxs("div",{className:"relative mx-auto flex h-full max-w-[1400px] flex-col justify-end px-5 lg:px-10 pb-16",children:[s.jsx("p",{className:"btb-eyebrow mb-5 opacity-90",children:o}),s.jsx("h1",{className:"btb-serif text-5xl md:text-7xl max-w-4xl leading-[1.02]",children:c}),s.jsx("p",{className:"mt-6 max-w-xl text-lg opacity-90",children:a})]})]}),s.jsx(g5,{blocks:r,siteId:n,slug:i})]})}function Ac({title:t,description:e}){return s.jsxs(Zo,{children:[s.jsx("title",{children:t}),s.jsx("meta",{name:"description",content:e}),s.jsx("meta",{property:"og:title",content:t}),s.jsx("meta",{property:"og:description",content:e})]})}function uu({siteConfig:t,defaultIntent:e="explore",heading:r="What are you imagining?"}){var P;const{pathname:n}=ki(),i=LT(),[o,c]=C.useState(e),[a,f]=C.useState({name:"",email:"",phone:"",message:""}),[p,y]=C.useState("idle"),[v,T]=C.useState(""),E=((P=ece.find(R=>R.key===o))==null?void 0:P.label)||"Explore my options",k=async R=>{if(R.preventDefault(),T(""),!a.name.trim()||!a.email.trim()){T("Please add your name and email.");return}y("sending");const{error:D}=await lg({lead_site_id:t.id,name:a.name.trim(),email:a.email.trim(),phone:a.phone.trim()||null,message:`[${E}] ${a.message.trim()}`.trim(),source_page:n,lead_type:o==="sell"||o==="value"?"seller":o==="buy"?"buyer":"contact",metadata:{intent:o,intent_label:E,division:"real_estate"}});if(D){y("error"),T(D.message||"Something went wrong. Please try again or call us.");return}y("sent")};return s.jsx("section",{id:"inquire",className:"btb-bg-stone",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-32 grid gap-14 lg:grid-cols-2",children:[s.jsxs("div",{className:"btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Start a conversation"}),s.jsx("h2",{className:"btb-serif text-5xl md:text-6xl leading-[1.05]",children:r}),s.jsxs("p",{className:"mt-6 btb-soft text-lg max-w-md",children:["Tell us where you are in the journey. ",i?`${i.first} will follow up with you personally`:"A Building The Bluegrass agent will follow up personally"," — no pressure, just good advice."]}),s.jsx("div",{className:"mt-10 flex flex-wrap gap-2",role:"radiogroup","aria-label":"What can we help with?",children:ece.map(R=>s.jsx("button",{type:"button",role:"radio","aria-checked":o===R.key,onClick:()=>c(R.key),className:`px-4 py-2.5 text-sm border transition ${o===R.key?"btb-bg-ink border-transparent":"btb-line hover:btb-bg-paper"}`,children:R.label},R.key))})]}),p==="sent"?s.jsxs("div",{className:"btb-bg-paper p-10 md:p-14 flex flex-col justify-center",role:"status",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-4",children:"Received"}),s.jsxs("p",{className:"btb-serif text-4xl",children:["Thank you, ",a.name.split(" ")[0],"."]}),s.jsxs("p",{className:"mt-4 btb-soft",children:["Your note about “",E.toLowerCase(),"” is with ",i?i.first:"our team",". We’ll be in touch soon."]})]}):s.jsxs("form",{onSubmit:k,className:"btb-bg-paper p-8 md:p-12 space-y-6",noValidate:!0,children:[s.jsxs("div",{className:"grid gap-6 sm:grid-cols-2",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Name *"}),s.jsx("input",{className:"btb-input",value:a.name,onChange:R=>f({...a,name:R.target.value}),autoComplete:"name",required:!0})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Phone"}),s.jsx("input",{className:"btb-input",value:a.phone,onChange:R=>f({...a,phone:R.target.value}),autoComplete:"tel",type:"tel"})]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Email *"}),s.jsx("input",{className:"btb-input",type:"email",value:a.email,onChange:R=>f({...a,email:R.target.value}),autoComplete:"email",required:!0})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Tell us a little more"}),s.jsx("textarea",{className:"btb-input min-h-[110px] resize-none",value:a.message,onChange:R=>f({...a,message:R.target.value}),placeholder:o==="sell"||o==="value"?"Property address and timing…":"Neighborhoods, price range, timing…"})]}),v&&s.jsx("p",{className:"text-sm text-destructive",role:"alert",children:v}),s.jsx("button",{type:"submit",disabled:p==="sending",className:"btb-btn w-full justify-center",children:p==="sending"?"Sending…":s.jsxs(s.Fragment,{children:[i?`Send to ${i.first}`:"Send to our team"," ",s.jsx(Ds,{className:"h-4 w-4"})]})})]})]})})}function fDt({siteConfig:t}){cu();const[e,r]=C.useState(0),n=tC.filter(o=>o.group==="Leadership"),i=tC.filter(o=>o.group==="Real Estate").slice(0,6);return s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:"Building The Bluegrass Realty | Lexington, KY Homes for Sale",description:"Search every home for sale in Lexington and Central Kentucky. Boutique real estate service for buyers and sellers from Building The Bluegrass Realty."}),s.jsxs("section",{className:"relative h-[92svh] md:h-[100svh] min-h-[600px] overflow-hidden btb-light",children:[s.jsx("img",{src:za.hero,alt:"Kentucky farmhouse at sunset (temporary placeholder image)",width:1920,height:1088,fetchPriority:"high",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 btb-hero-shade"}),s.jsxs("div",{className:"relative mx-auto flex h-full max-w-[1400px] flex-col justify-end px-5 lg:px-10 pb-10 md:pb-14",children:[s.jsx("p",{className:"btb-eyebrow mb-6 opacity-90",children:"Building The Bluegrass Realty · Lexington, Kentucky"}),s.jsxs("h1",{className:"btb-serif text-[2.9rem] leading-[0.98] sm:text-7xl lg:text-[7.5rem] max-w-5xl",children:["Find your place",s.jsx("br",{}),s.jsx("em",{className:"font-normal",children:"in the Bluegrass."})]}),s.jsx("p",{className:"mt-7 max-w-xl text-lg opacity-90",children:"Boutique real estate for Lexington and Central Kentucky — every home on the market, and agents who know these communities by heart."}),s.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[s.jsx(Wr,{to:"/search",className:"btb-btn btb-btn-light",children:"Search Homes"}),s.jsx(Wr,{to:"/home-value",className:"btb-btn btb-btn-ghost",children:"What’s My Home Worth?"})]}),s.jsx("div",{className:"mt-14 hidden md:block",children:s.jsx(A1,{})}),s.jsxs("div",{className:"mt-4 hidden md:flex flex-wrap gap-x-6 gap-y-2 text-sm opacity-85",children:[["Lexington","Nicholasville","Georgetown","Versailles"].map(o=>s.jsx(Wr,{to:cg(o),className:"hover:underline",children:o},o)),s.jsx(Wr,{to:"/search?propertyType=Land",className:"hover:underline",children:"Land & Lots"})]})]})]}),s.jsx("section",{className:"md:hidden px-5 py-8 btb-bg-ink",children:s.jsx(A1,{compact:!0})}),s.jsx("section",{className:"btb-bg-stone",children:s.jsxs("div",{className:"mx-auto max-w-5xl px-5 lg:px-10 py-24 md:py-32 text-center btb-reveal",children:[s.jsx("img",{src:No.logoWhite,alt:"",className:"mx-auto h-14 w-14 object-contain mb-8 rounded-full btb-bg-ink p-2"}),s.jsx("p",{className:"btb-eyebrow btb-accent mb-8",children:"Our mission"}),s.jsxs("blockquote",{className:"btb-serif text-4xl md:text-6xl leading-[1.1]",children:["“",bK,"”"]}),s.jsx("p",{className:"mt-10 btb-eyebrow btb-soft",children:"Joey Svec & Maria Gillette · Building The Bluegrass"})]})}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-36 grid gap-12 lg:grid-cols-12 items-center",children:[s.jsx("div",{className:"lg:col-span-6 btb-reveal btb-img-zoom overflow-hidden aspect-[4/5]",children:s.jsx("img",{src:za.design,alt:"Warm, light-filled kitchen (temporary placeholder image)",loading:"lazy",width:1200,height:1504,className:"h-full w-full object-cover"})}),s.jsxs("div",{className:"lg:col-span-5 lg:col-start-8 btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-6",children:"A boutique brokerage"}),s.jsxs("h2",{className:"btb-serif text-5xl md:text-6xl leading-[1.04]",children:["Local knowledge.",s.jsx("br",{}),"A more personal experience."]}),s.jsx("p",{className:"mt-8 btb-soft text-lg leading-relaxed",children:"With more than 100 years of combined experience, our REALTORS® treat every client as if they are our only client — thoughtful pricing, honest guidance and steady negotiation from the first showing to the closing table."}),s.jsx(Wr,{to:"/about",className:"btb-link mt-10 inline-block",children:"Our story"})]})]}),s.jsxs("section",{id:"paths",className:"btb-bg-ink",children:[s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pt-24 pb-10",children:[s.jsx("p",{className:"btb-eyebrow opacity-60 mb-5",children:"How we can help"}),s.jsx("h2",{className:"btb-serif text-5xl md:text-6xl max-w-3xl leading-[1.05]",children:"Wherever you are in the move, start here."})]}),s.jsx("div",{className:"grid md:grid-cols-2 xl:grid-cols-4",children:[{k:"Buy",h:"Find the place for your next chapter.",b:"Search every listing across Central Kentucky, save favorites, get alerts and tour with an agent who knows the neighborhood.",to:"/buying-process",img:za.realestate,cta:"Start your search"},{k:"Sell",h:"Present your home at its best.",b:"Thoughtful pricing, strong presentation and a marketing plan built to bring the right buyer to your door.",to:"/sell",img:za.design,cta:"Talk about selling"},{k:"Build & Renovate",h:"Make a house exactly yours.",b:"BTB Construction and BTB Cabinets help you renovate, add on or build — under the same roof as your agent.",to:"/construction",img:za.construction,cta:"Explore construction"},{k:"Top Areas",h:"Get to know the Bluegrass.",b:"Local guides and live homes for sale in Lexington and the towns around it.",to:"/communities",img:za.lexington,cta:"Explore areas"}].map((o,c)=>s.jsxs(Wr,{to:o.to,className:"group relative block h-[78vh] min-h-[520px] overflow-hidden btb-img-zoom btb-light",children:[s.jsx("img",{src:o.img,alt:"",loading:"lazy",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 btb-hero-shade"}),s.jsxs("div",{className:"relative flex h-full flex-col justify-between p-8 md:p-10",children:[s.jsxs("span",{className:"btb-eyebrow opacity-80",children:["0",c+1," — ",o.k]}),s.jsxs("div",{children:[s.jsx("h3",{className:"btb-serif text-3xl lg:text-4xl leading-tight",children:o.h}),s.jsx("p",{className:"mt-4 opacity-85 max-w-sm",children:o.b}),s.jsxs("span",{className:"btb-link mt-8 inline-flex items-center gap-2",children:[o.cta," ",s.jsx(GA,{className:"h-4 w-4"})]})]})]})]},o.k))})]}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-32 grid gap-10 md:grid-cols-12 items-end",children:[s.jsxs("div",{className:"md:col-span-7 btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"The Journal"}),s.jsx("h2",{className:"btb-serif text-5xl md:text-6xl leading-[1.05]",children:"Market notes, neighborhood stories and advice from our agents."})]}),s.jsxs("div",{className:"md:col-span-4 md:col-start-9 btb-reveal",children:[s.jsx("p",{className:"btb-soft text-lg",children:"What’s selling, where prices are heading and what to know before you make a move in Central Kentucky."}),s.jsx(Wr,{to:"/blog",className:"btb-link mt-8 inline-block",children:"Read the Journal"})]})]}),s.jsx("section",{className:"btb-bg-paper border-y btb-line",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-10 lg:grid-cols-12 items-center",children:[s.jsxs("div",{className:"lg:col-span-5 btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Homes across the Bluegrass"}),s.jsx("h2",{className:"btb-serif text-5xl leading-[1.05]",children:"Explore every home on the market."}),s.jsx("p",{className:"mt-6 btb-soft text-lg",children:"Search live listings from Lexington to the surrounding counties — save favorites, set alerts, and request a showing with our agents."}),s.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[s.jsx(Wr,{to:"/search",className:"btb-btn",children:"Explore all homes"}),s.jsx(Wr,{to:"/search?propertyType=Land",className:"btb-btn btb-btn-ghost",children:"Land & Lots"})]})]}),s.jsx("div",{className:"lg:col-span-6 lg:col-start-7 btb-reveal",children:s.jsx(A1,{compact:!0})})]})}),s.jsx("section",{className:"btb-bg-paper py-6",children:s.jsxs("div",{children:[s.jsx(Hp,{siteConfig:t,accentColor:"#406E71",mode:"new_listings",sectionTitle:"Just Listed in the Bluegrass",count:12}),s.jsx(Hp,{siteConfig:t,accentColor:"#406E71",mode:"open_houses",sectionTitle:"Upcoming Open Houses",count:12})]})}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-36 grid gap-12 lg:grid-cols-12",children:[s.jsxs("div",{className:"lg:col-span-5 btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Discover the Bluegrass"}),s.jsx("h2",{className:"btb-serif text-5xl leading-[1.05]",children:"Places we know by heart."}),s.jsx("div",{className:"mt-10 border-t btb-line",children:Wx.map((o,c)=>s.jsxs("div",{className:"border-b btb-line",children:[s.jsxs("button",{className:"flex w-full items-center justify-between py-5 text-left",onClick:()=>r(c),"aria-expanded":e===c,children:[s.jsx("span",{className:"btb-serif text-3xl",children:o.name}),s.jsx(yl,{className:`h-5 w-5 transition ${e===c?"rotate-180":""}`})]}),e===c&&s.jsxs("div",{className:"pb-6",children:[s.jsx("p",{className:"btb-soft",children:o.blurb}),s.jsxs("div",{className:"mt-4 flex gap-6",children:[s.jsxs(Wr,{to:cg(o.name),className:"btb-link",children:["Homes in ",o.name]}),s.jsx("a",{href:"#inquire",className:"btb-link",children:"Ask an agent"})]})]})]},o.name))})]}),s.jsx("div",{className:"lg:col-span-6 lg:col-start-7 overflow-hidden min-h-[420px] btb-reveal",children:s.jsx("img",{src:za.lexington,alt:"Bluegrass horse farm (temporary placeholder image)",loading:"lazy",className:"h-full w-full object-cover"})})]}),s.jsx("section",{className:"btb-bg-green",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-32",children:[s.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-6 mb-14",children:[s.jsxs("div",{children:[s.jsx("p",{className:"btb-eyebrow opacity-70 mb-5",children:"The people behind the possibilities"}),s.jsx("h2",{className:"btb-serif text-5xl md:text-6xl max-w-2xl leading-[1.05]",children:"REALTORS® who know the Bluegrass."})]}),s.jsx(Wr,{to:"/team",className:"btb-link",children:"Meet our agents"})]}),s.jsx("div",{className:"grid gap-10 md:grid-cols-2 mb-14",children:n.map(o=>s.jsxs("div",{className:"flex gap-6 items-end btb-reveal",children:[s.jsx("img",{src:o.photo,alt:o.name,loading:"lazy",className:"w-40 h-52 object-cover object-top grayscale"}),s.jsxs("div",{children:[s.jsx("p",{className:"btb-serif text-3xl",children:o.name}),s.jsx("p",{className:"opacity-75 text-sm mt-1",children:o.role}),s.jsx("p",{className:"btb-eyebrow mt-3 opacity-60",children:"Brokerage leadership"})]})]},o.name))}),s.jsx("div",{className:"grid grid-cols-3 md:grid-cols-6 gap-4",children:i.map(o=>s.jsxs("div",{children:[s.jsx("img",{src:o.photo,alt:o.name,loading:"lazy",className:"aspect-[3/4] w-full object-cover object-top grayscale"}),s.jsx("p",{className:"mt-2 text-sm",children:o.name}),s.jsx("p",{className:"text-xs opacity-65",children:o.role})]},o.name))})]})}),s.jsx(uu,{siteConfig:t})]})}function wK({steps:t}){return s.jsx("div",{className:`grid gap-px md:grid-cols-2 ${t.length%3===0?"lg:grid-cols-3":"lg:grid-cols-4"} btb-bg-stone`,children:t.map(([e,r],n)=>s.jsxs("div",{className:"btb-bg p-8 btb-reveal",children:[s.jsx("p",{className:"btb-serif text-5xl btb-accent",children:n+1}),s.jsx("p",{className:"mt-4 btb-serif text-2xl",children:e}),s.jsx("p",{className:"mt-2 btb-soft text-sm",children:r})]},e))})}function mDt(){return s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pb-24",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-8",children:"Popular communities"}),s.jsx("div",{className:"flex flex-wrap gap-3",children:Wx.map(t=>s.jsx(Wr,{to:cg(t.name),className:"px-5 py-3 border btb-line hover:btb-bg-paper btb-serif text-xl",children:t.name},t.name))})]})}function nce({siteConfig:t}){return cu(),s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:"Buy a Home in Lexington, KY | Building The Bluegrass Realty",description:"Search homes, land and new construction in Lexington and Central Kentucky with a boutique team of local REALTORS®."}),s.jsx(vg,{eyebrow:"Buy",title:"Find the place for your next chapter.",intro:"Every home on the market across Central Kentucky, and an agent who will tell you honestly what each one is — and isn’t.",image:za.realestate}),s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 -mt-10 relative z-10",children:s.jsx(A1,{})}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-8",children:"How buying with us works"}),s.jsx(wK,{steps:[["Plan","Your goals, budget, timing and must-haves."],["Search","Live MLS listings, saved favorites and instant alerts."],["Tour & offer","Private showings and a strong, well-priced offer."],["Close","Inspections, appraisal and closing day, handled."]]})]}),s.jsx(mDt,{}),s.jsx(uu,{siteConfig:t,defaultIntent:"buy",heading:"Let’s find your place."})]})}function ice({siteConfig:t}){return cu(),s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:"Sell Your Home in Lexington, KY | Building The Bluegrass Realty",description:"Pricing, presentation and marketing that bring the right buyer. Request a free home value from Building The Bluegrass Realty."}),s.jsx(vg,{eyebrow:"Selling",title:"Present your home at its best.",intro:"Thoughtful pricing, beautiful presentation and steady negotiation — with a boutique team that treats your sale like it’s our only one.",image:za.design}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-4",children:"The seller roadmap"}),s.jsx("h2",{className:"btb-serif text-5xl leading-[1.05] max-w-3xl mb-12",children:"Four steps from “thinking about it” to sold."}),s.jsx(wK,{steps:QLt})]}),s.jsx("section",{className:"btb-bg-ink",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsx("p",{className:"btb-eyebrow opacity-60 mb-4",children:"Why list with BTB"}),s.jsx("h2",{className:"btb-serif text-5xl leading-[1.05] max-w-3xl",children:"The boutique advantage."}),s.jsxs("div",{className:"mt-12 border-t btb-line-light",children:[s.jsxs("div",{className:"hidden md:grid grid-cols-3 gap-6 py-4 btb-eyebrow opacity-60",children:[s.jsx("span",{}),s.jsx("span",{children:"Typical brokerage"}),s.jsx("span",{children:"Building The Bluegrass"})]}),JLt.map(([e,r,n])=>s.jsxs("div",{className:"grid md:grid-cols-3 gap-2 md:gap-6 py-6 border-b btb-line-light btb-reveal",children:[s.jsx("p",{className:"btb-serif text-2xl",children:e}),s.jsx("p",{className:"opacity-55 line-through decoration-1",children:r}),s.jsx("p",{className:"text-lg",children:n})]},e))]}),s.jsxs(Wr,{to:"/home-value",className:"btb-btn btb-btn-light mt-12",children:["What’s my home worth? ",s.jsx(Ds,{className:"h-4 w-4"})]})]})}),s.jsx("div",{id:"value",className:"scroll-mt-24",children:s.jsx(uu,{siteConfig:t,defaultIntent:"sell",heading:"Let’s talk about your sale."})})]})}function pDt({siteConfig:t}){return cu(),s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:"Our Story | Building The Bluegrass",description:"A Lexington real estate brokerage built on relationships, service and faith — giving 10% of all profits to charity."}),s.jsx(vg,{eyebrow:"Our story",title:"To be your trusted property professional.",intro:"A Lexington brokerage built to be the local expert through relationships, with excellence in service to our clients.",image:za.lexington}),s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-px md:grid-cols-3 btb-bg-stone",children:[["We Connect","Passions and gifts to serve clients through a trustworthy, fulfilling and educational experience."],["We Believe","Leadership provides the opportunity to serve others; whoever brings blessings will be enriched."],["We Give","Time and resources to others, giving 10% of all profits to charities."]].map(([e,r])=>s.jsxs("div",{className:"btb-bg p-10 btb-reveal",children:[s.jsx("p",{className:"btb-serif text-4xl",children:e}),s.jsx("p",{className:"mt-4 btb-soft leading-relaxed",children:r})]},e))}),s.jsxs("section",{className:"mx-auto max-w-3xl px-5 pb-24 btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-6",children:"Foundational principles"}),s.jsx("div",{className:"space-y-10",children:[["Relationship","Matthew 6:28–34","A vertical relationship needs to be established before we can make a horizontal impact — serving clients and having true relationships with others."],["Worth","Genesis 1:27 & Ephesians 3:6","Rather than chasing a leaderboard, we ask where you find your worth — made in God’s image, with Him all things are possible."],["Revenue","Malachi 3:8–12","Finances are a tool to strengthen the Kingdom. We give a 10 percent tithe first, and stay faithful to that principle."],["Generational","Exodus 20:5–6","Building a stable, influential company for the community, meant to last for generations to come."]].map(([e,r,n])=>s.jsxs("div",{className:"border-t btb-line pt-6",children:[s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("h3",{className:"btb-serif text-3xl",children:e}),s.jsx("span",{className:"btb-soft text-sm italic",children:r})]}),s.jsx("p",{className:"mt-3 btb-soft leading-relaxed",children:n})]},e))})]}),s.jsx(uu,{siteConfig:t})]})}function gDt({siteConfig:t}){cu();const e=["Leadership","Real Estate","Operations"];return s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:"Our Team | Building The Bluegrass",description:"Meet the REALTORS® and staff of Building The Bluegrass in Lexington, KY."}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pt-20 pb-6",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Our team"}),s.jsx("h1",{className:"btb-serif text-6xl md:text-7xl max-w-3xl leading-[1.02]",children:"The people behind the possibilities."})]}),e.map(r=>s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-14",children:[s.jsxs("div",{className:"flex items-baseline justify-between border-b btb-line pb-4 mb-10",children:[s.jsx("h2",{className:"btb-serif text-4xl",children:r}),r==="Real Estate"&&s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Licensed REALTORS®"})]}),s.jsx("div",{className:`grid gap-8 ${r==="Leadership"?"sm:grid-cols-2 lg:grid-cols-3":"grid-cols-2 sm:grid-cols-3 lg:grid-cols-5"}`,children:tC.filter(n=>n.group===r).map(n=>{const i=ULt(n.name),o=s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"relative overflow-hidden aspect-[3/4]",children:[s.jsx("img",{src:n.photo,alt:n.name,loading:"lazy",className:"h-full w-full object-cover object-top grayscale group-hover:grayscale-0 group-hover:scale-105 group-focus-visible:grayscale-0 transition duration-700"}),i&&s.jsxs("span",{className:"btb-light absolute inset-x-0 bottom-0 flex items-center justify-between gap-2 px-4 py-3 text-[0.68rem] tracking-[0.16em] uppercase bg-[linear-gradient(to_top,hsl(var(--btb-ink)/0.85),transparent)] opacity-0 translate-y-2 group-hover:opacity-100 group-hover:translate-y-0 group-focus-visible:opacity-100 transition duration-500",children:["Visit ",n.name.split(" ")[0],"’s site ",s.jsx(GA,{className:"h-4 w-4"})]})]}),s.jsx("p",{className:`btb-serif mt-4 ${r==="Leadership"?"text-3xl":"text-2xl"}`,children:n.name}),s.jsx("p",{className:"btb-soft text-sm",children:n.role}),i&&s.jsxs("p",{className:"mt-2 inline-flex items-center gap-1 text-[0.68rem] tracking-[0.16em] uppercase btb-accent",children:["View website ",s.jsx(GA,{className:"h-3 w-3 transition-transform group-hover:translate-x-0.5 group-hover:-translate-y-0.5"})]})]});return i?s.jsx("a",{href:i,target:"_blank",rel:"noopener","aria-label":`Visit ${n.name}’s website`,className:"group block btb-reveal outline-none",children:o},n.name):s.jsx("div",{className:"group btb-reveal",children:o},n.name)})})]},r)),s.jsx(uu,{siteConfig:t})]})}function sce({siteConfig:t}){return cu(),s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:"Central Kentucky Communities | Building The Bluegrass",description:"Local guides to Lexington, Nicholasville, Georgetown, Versailles, Winchester and Richmond with live homes for sale."}),s.jsx(vg,{eyebrow:"Communities",title:"Discover the Bluegrass.",intro:"Guides to the places our agents know and serve — market snapshots, local favorites and live homes for sale.",image:za.lexington}),s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-px md:grid-cols-3 btb-bg-stone",children:Wx.map(e=>s.jsxs("div",{className:"btb-bg p-10 btb-reveal",children:[s.jsx("h2",{className:"btb-serif text-4xl",children:e.name}),s.jsx("p",{className:"mt-4 btb-soft",children:e.blurb}),s.jsx("p",{className:"btb-eyebrow btb-soft mt-2",children:e.county}),s.jsxs(Wr,{to:cg(e.name),className:"btb-link mt-6 inline-block",children:["Homes in ",e.name]})]},e.name))}),s.jsx(uu,{siteConfig:t,defaultIntent:"buy"})]})}function Kd({children:t}){const e=C.useRef(null);return s.jsx("div",{ref:e,className:"btb-bg-paper min-h-[70vh]",children:t})}const Tc="mx-auto max-w-[1400px] px-5 lg:px-10";function US({eyebrow:t,title:e,body:r}){return s.jsxs("div",{className:"max-w-3xl btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-4",children:t}),s.jsx("h2",{className:"btb-serif text-5xl md:text-6xl leading-[1.05]",children:e}),r&&s.jsx("p",{className:"mt-6 btb-soft text-lg leading-relaxed",children:r})]})}function SK({items:t,cols:e=3}){return s.jsx("div",{className:`mt-14 grid gap-px btb-bg-stone sm:grid-cols-2 ${e===3?"lg:grid-cols-3":""}`,children:t.map(([r,n],i)=>s.jsxs("div",{className:"btb-bg p-8 md:p-10 btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent",children:String(i+1).padStart(2,"0")}),s.jsx("h3",{className:"mt-4 btb-serif text-3xl leading-tight",children:r}),s.jsx("p",{className:"mt-3 btb-soft leading-relaxed",children:n})]},r))})}function ace({siteConfig:t}){cu();const e=tC.filter(n=>n.group==="Construction & Design"),r=VLt.filter(n=>n.type!=="Real Estate");return s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:"BTB Construction | Remodels, Additions & Custom Homes in Lexington, KY",description:"Design-build renovations, additions, historic remodels and custom homes from Building The Bluegrass Construction."}),s.jsx(vg,{eyebrow:"Who we are · BTB Construction",title:"Build the home you actually want.",intro:"Remodels, additions, historic renovations and custom homes — from a design-build team that works hand in hand with your real estate agent.",image:za.construction}),s.jsxs("section",{className:`${Tc} py-24`,children:[s.jsx(US,{eyebrow:"What we build",title:"One team from first sketch to final walkthrough.",body:"Buying a home that needs work, or getting yours ready to sell? Our construction team sits under the same roof as our agents, so plans, budgets and timelines all line up."}),s.jsx(SK,{items:qLt})]}),s.jsx("section",{className:"btb-bg-ink",children:s.jsxs("div",{className:`${Tc} py-24`,children:[s.jsx("p",{className:"btb-eyebrow opacity-60 mb-4",children:"Project spotlights"}),s.jsx("h2",{className:"btb-serif text-5xl leading-[1.05] max-w-3xl",children:"Recent work around Lexington."}),s.jsx("div",{className:"mt-14 grid gap-10 md:grid-cols-2",children:r.map(n=>s.jsxs("article",{className:"btb-reveal",children:[s.jsx("div",{className:"overflow-hidden aspect-[4/3] btb-img-zoom",children:s.jsx("img",{src:za[n.image],alt:"",loading:"lazy",className:"h-full w-full object-cover"})}),s.jsxs("p",{className:"btb-eyebrow opacity-60 mt-6 flex items-center gap-2",children:[s.jsx(Es,{className:"h-3.5 w-3.5"}),n.location]}),s.jsx("h3",{className:"btb-serif text-3xl mt-2",children:n.title}),s.jsx("p",{className:"mt-3 opacity-80 leading-relaxed max-w-xl",children:n.story})]},n.slug))})]})}),s.jsxs("section",{className:`${Tc} py-24`,children:[s.jsx(US,{eyebrow:"The crew",title:"The people who build it."}),s.jsx("div",{className:"mt-12 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-6",children:e.map(n=>s.jsxs("div",{className:"btb-reveal",children:[s.jsx("div",{className:"overflow-hidden aspect-[3/4]",children:s.jsx("img",{src:n.photo,alt:n.name,loading:"lazy",className:"h-full w-full object-cover object-top grayscale"})}),s.jsx("p",{className:"btb-serif text-xl mt-3",children:n.name}),s.jsx("p",{className:"btb-soft text-sm",children:n.role})]},n.name))})]}),s.jsx(uu,{siteConfig:t,defaultIntent:"construction",heading:"Tell us about your project."})]})}function oce({siteConfig:t}){return cu(),s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:"BTB Cabinets | Custom Kitchen & Bath Cabinetry in Lexington, KY",description:"Custom and semi-custom cabinetry for kitchens, baths and built-ins from Building The Bluegrass."}),s.jsx(vg,{eyebrow:"Who we are · BTB Cabinets",title:"Cabinetry made for the way you live.",intro:"Kitchens, baths and built-ins designed with care and installed by the same team that builds and renovates our homes.",image:za.design}),s.jsxs("section",{className:`${Tc} py-24`,children:[s.jsx(US,{eyebrow:"What we make",title:"Beautiful storage, room by room."}),s.jsx(SK,{items:HLt,cols:2})]}),s.jsx("section",{className:"btb-bg-green",children:s.jsxs("div",{className:`${Tc} py-24 grid gap-12 lg:grid-cols-2 items-center`,children:[s.jsxs("div",{className:"btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow opacity-70 mb-4",children:"Craftsmanship"}),s.jsx("h2",{className:"btb-serif text-5xl leading-[1.05]",children:"Details you notice every day."}),s.jsx("ul",{className:"mt-10 space-y-4 text-lg",children:["Door styles from classic shaker to slab","Painted, stained and natural wood finishes","Soft-close hardware and organized interiors","Coordinated with your remodel or new build"].map(e=>s.jsxs("li",{className:"flex gap-3",children:[s.jsx(no,{className:"h-5 w-5 mt-1 shrink-0"}),e]},e))})]}),s.jsx("div",{className:"overflow-hidden aspect-[4/5] btb-reveal",children:s.jsx("img",{src:za.design,alt:"",loading:"lazy",className:"h-full w-full object-cover"})})]})}),s.jsxs("section",{className:`${Tc} py-24`,children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-8",children:"How it works"}),s.jsx(wK,{steps:WLt})]}),s.jsx(uu,{siteConfig:t,defaultIntent:"cabinets",heading:"Let’s design your cabinets."})]})}function lce({siteConfig:t}){cu();const[e,r]=C.useState(0);return s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:"The Home Buying Process | Building The Bluegrass Realty",description:"A step-by-step guide to buying a home in Lexington and Central Kentucky."}),s.jsx(vg,{eyebrow:"Buying · The process",title:"Six steps to the keys.",intro:"Buying a home is a big decision. Here is exactly how we walk you through it, from the first conversation to closing day.",image:za.realestate}),s.jsxs("section",{className:`${Tc} py-24`,children:[s.jsx("ol",{className:"relative border-l btb-line ml-3 space-y-14",children:KLt.map(([n,i],o)=>s.jsxs("li",{className:"pl-10 relative btb-reveal",children:[s.jsx("span",{className:"absolute -left-[22px] top-0 h-11 w-11 rounded-full btb-bg-ink flex items-center justify-center btb-serif text-xl",children:o+1}),s.jsx("h3",{className:"btb-serif text-4xl",children:n}),s.jsx("p",{className:"mt-2 btb-soft text-lg max-w-2xl",children:i})]},n))}),s.jsxs("div",{className:"mt-16 flex flex-wrap gap-3",children:[s.jsx(Wr,{to:"/search",className:"btb-btn",children:"Find a home"}),s.jsx(Wr,{to:"/financing",className:"btb-btn btb-btn-ghost",children:"Financing options"})]})]}),s.jsx("section",{className:"btb-bg-stone",children:s.jsxs("div",{className:`${Tc} py-24 grid gap-12 lg:grid-cols-12`,children:[s.jsx("div",{className:"lg:col-span-4",children:s.jsx(US,{eyebrow:"Buyer questions",title:"Good to know."})}),s.jsx("div",{className:"lg:col-span-7 lg:col-start-6 border-t btb-line",children:YLt.map(([n,i],o)=>s.jsxs("div",{className:"border-b btb-line",children:[s.jsxs("button",{className:"w-full text-left py-6 flex justify-between gap-6 btb-serif text-2xl",onClick:()=>r(e===o?-1:o),"aria-expanded":e===o,children:[n,s.jsx("span",{className:"btb-accent",children:e===o?"–":"+"})]}),e===o&&s.jsx("p",{className:"pb-6 btb-soft text-lg",children:i})]},n))})]})}),s.jsx(uu,{siteConfig:t,defaultIntent:"buy",heading:"Let’s find your place."})]})}const l6=t=>t.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});function yDt(t,e,r){const n=r*12,i=e/100/12;return t<=0||n<=0?0:i===0?t/n:t*i/(1-Math.pow(1+i,-n))}function cce({siteConfig:t}){cu();const[e,r]=C.useState({price:35e4,down:10,rate:6.5,years:30,tax:2800,ins:1500}),n=C.useMemo(()=>{const o=e.price*(1-e.down/100),c=yDt(o,e.rate,e.years);return{loan:o,pi:c,total:c+e.tax/12+e.ins/12}},[e]),i=(o,c,a=1)=>s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:c}),s.jsx("input",{type:"number",inputMode:"decimal",step:a,min:0,className:"btb-input",value:e[o],onChange:f=>r({...e,[o]:Number(f.target.value)||0})})]});return s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:"Home Financing & Mortgage Calculator | Building The Bluegrass Realty",description:"Loan options including construction and renovation loans, a mortgage calculator and a pre-approval checklist."}),s.jsx(vg,{eyebrow:"Buying · Financing",title:"Know your number before you fall in love.",intro:"Loan options, an easy payment calculator and everything you need to get pre-approved.",image:za.lexington}),s.jsxs("section",{className:`${Tc} py-24`,children:[s.jsx(US,{eyebrow:"Loan options",title:"The right loan for the right home."}),s.jsx(SK,{items:ZLt})]}),s.jsx("section",{className:"btb-bg-ink",children:s.jsxs("div",{className:`${Tc} py-24 grid gap-12 lg:grid-cols-2`,children:[s.jsxs("div",{children:[s.jsx("p",{className:"btb-eyebrow opacity-60 mb-4",children:"Payment calculator"}),s.jsx("h2",{className:"btb-serif text-5xl leading-[1.05]",children:"Estimate your monthly payment."}),s.jsx("p",{className:"mt-6 opacity-75 max-w-md",children:"An estimate only — your lender will give you exact numbers."}),s.jsx("p",{className:"mt-12 btb-eyebrow opacity-60",children:"Estimated monthly"}),s.jsx("p",{className:"btb-serif text-7xl mt-2","aria-live":"polite",children:l6(n.total)}),s.jsxs("p",{className:"mt-4 opacity-75 text-sm",children:["Principal & interest ",l6(n.pi)," · Loan amount ",l6(n.loan)]})]}),s.jsxs("div",{className:"btb-bg-paper btb-ink p-8 md:p-12 grid gap-6 sm:grid-cols-2",children:[i("price","Home price ($)",1e3),i("down","Down payment (%)",.5),i("rate","Interest rate (%)",.125),i("years","Term (years)"),i("tax","Property tax ($/yr)",100),i("ins","Insurance ($/yr)",100)]})]})}),s.jsxs("section",{className:`${Tc} py-24 grid gap-12 lg:grid-cols-2`,children:[s.jsx(US,{eyebrow:"Pre-approval checklist",title:"What to gather.",body:"Have these ready and pre-approval goes quickly."}),s.jsx("ul",{className:"grid gap-4 sm:grid-cols-2 content-start",children:XLt.map(o=>s.jsxs("li",{className:"flex gap-3 border btb-line p-5 btb-reveal",children:[s.jsx(no,{className:"h-5 w-5 btb-accent shrink-0"}),o]},o))})]}),s.jsx(uu,{siteConfig:t,defaultIntent:"buy",heading:"Want a lender introduction?"})]})}function uce({siteConfig:t}){var v,T,E,k;const{pathname:e}=ki(),[r,n]=C.useState({address:"",beds:"",baths:"",sqft:"",condition:"Good",timing:"0-3 months",name:"",email:"",phone:""}),i=hN(),[o,c]=C.useState("idle"),[a,f]=C.useState(""),p=P=>R=>n({...r,[P]:R.target.value}),y=async P=>{if(P.preventDefault(),f(""),!r.address.trim()||!r.name.trim()||!r.email.trim()){f("Please add the address, your name and email.");return}c("sending");const R=[`Address: ${r.address.trim()}`,r.beds&&`Beds: ${r.beds}`,r.baths&&`Baths: ${r.baths}`,r.sqft&&`Sq ft: ${r.sqft}`,`Condition: ${r.condition}`,`Timing: ${r.timing}`].filter(Boolean).join(" · "),{error:D}=await lg({lead_site_id:t.id,name:r.name.trim(),email:r.email.trim(),phone:r.phone.trim()||null,message:`[What’s my home worth?] ${R}`,source_page:e,lead_type:"seller",metadata:{intent:"value",intent_label:"What’s my home worth?",division:"real_estate",property_address:r.address.trim(),beds:r.beds,baths:r.baths,sqft:r.sqft,condition:r.condition,timing:r.timing}});if(D){c("error"),f(D.message||"Something went wrong. Please try again.");return}c("sent")};return s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:"What’s My Home Worth? | Free Home Value | Building The Bluegrass Realty",description:"Get a free, personal home value from a Building The Bluegrass REALTOR® in Lexington and Central Kentucky."}),s.jsxs("section",{className:"relative min-h-[100svh] overflow-hidden btb-light",children:[s.jsx("img",{src:((v=i.hero)==null?void 0:v.backgroundImageUrl)||za.hero,alt:"",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 btb-hero-shade"}),s.jsxs("div",{className:`relative ${Tc} py-20 grid gap-12 lg:grid-cols-2 items-center min-h-[100svh]`,children:[s.jsxs("div",{children:[s.jsx("p",{className:"btb-eyebrow mb-5 opacity-90",children:((T=i.hero)==null?void 0:T.eyebrow)||"Selling · Home value"}),s.jsx("h1",{className:"btb-serif text-5xl md:text-7xl leading-[1.02]",children:((E=i.hero)==null?void 0:E.headline)||"What’s your home really worth?"}),s.jsx("p",{className:"mt-6 text-lg opacity-90 max-w-md",children:((k=i.hero)==null?void 0:k.subtitle)||"Not a robot estimate. A local REALTOR® reviews your home and recent sales nearby, then sends you a personal valuation — free, with no obligation."})]}),o==="sent"?s.jsxs("div",{className:"btb-bg-paper btb-ink p-10 md:p-14",role:"status",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-4",children:"Request received"}),s.jsxs("p",{className:"btb-serif text-4xl",children:["Thank you, ",r.name.split(" ")[0],"."]}),s.jsxs("p",{className:"mt-4 btb-soft",children:["We’re preparing a valuation for ",r.address,". An agent will reach out soon."]})]}):s.jsxs("form",{onSubmit:y,className:"btb-bg-paper btb-ink p-8 md:p-10 space-y-5 shadow-2xl",noValidate:!0,children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Property address *"}),s.jsx("input",{className:"btb-input",value:r.address,onChange:p("address"),autoComplete:"street-address",placeholder:"123 Main St, Lexington, KY"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Beds"}),s.jsx("input",{className:"btb-input",inputMode:"numeric",value:r.beds,onChange:p("beds")})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Baths"}),s.jsx("input",{className:"btb-input",inputMode:"decimal",value:r.baths,onChange:p("baths")})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Sq ft"}),s.jsx("input",{className:"btb-input",inputMode:"numeric",value:r.sqft,onChange:p("sqft")})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Condition"}),s.jsx("select",{className:"btb-input",value:r.condition,onChange:p("condition"),children:["Excellent","Good","Needs some work","Needs a lot of work"].map(P=>s.jsx("option",{children:P},P))})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Timing"}),s.jsx("select",{className:"btb-input",value:r.timing,onChange:p("timing"),children:["0-3 months","3-6 months","6-12 months","Just curious"].map(P=>s.jsx("option",{children:P},P))})]})]}),s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Name *"}),s.jsx("input",{className:"btb-input",value:r.name,onChange:p("name"),autoComplete:"name"})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Phone"}),s.jsx("input",{className:"btb-input",type:"tel",value:r.phone,onChange:p("phone"),autoComplete:"tel"})]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Email *"}),s.jsx("input",{className:"btb-input",type:"email",value:r.email,onChange:p("email"),autoComplete:"email"})]}),a&&s.jsx("p",{className:"text-sm text-destructive",role:"alert",children:a}),s.jsx("button",{type:"submit",disabled:o==="sending",className:"btb-btn w-full justify-center",children:o==="sending"?"Sending…":s.jsxs(s.Fragment,{children:["Get my home value ",s.jsx(Ds,{className:"h-4 w-4"})]})})]})]})]}),s.jsx(g5,{blocks:i.rest,siteId:i.siteId,slug:i.slug})]})}function xDt({siteConfig:t}){return cu(),s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:"Career Opportunities | Building The Bluegrass Realty",description:"Join Building The Bluegrass — coaching, marketing, technology and a real estate, design and construction platform for agents in Lexington, KY."}),s.jsx(vg,{eyebrow:"Career opportunities",title:"An atmosphere that is fun, exciting, and full of learning opportunities.",intro:"Build a business around real estate — not just transaction to transaction.",image:za.construction}),s.jsxs("section",{className:`${Tc} py-24 grid gap-12 lg:grid-cols-12 items-start`,children:[s.jsxs("div",{className:"lg:col-span-4 btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-4",children:"Why BTB?"}),s.jsx("h2",{className:"btb-serif text-5xl leading-[1.05]",children:"Real estate is just the beginning."})]}),s.jsxs("div",{className:"lg:col-span-7 lg:col-start-6 btb-reveal",children:[s.jsx("p",{className:"btb-serif text-3xl leading-snug",children:"At BTB, we believe real estate is just the beginning. We provide our agents with the platform, resources, relationships and opportunities to build a business around real estate — not simply work transactions to transactions."}),s.jsx("p",{className:"mt-6 btb-soft text-lg leading-relaxed",children:"By connecting real estate, design and construction we help our agents create more value for their clients, expand their opportunities, and build a business designed for long term success."})]})]}),s.jsx("section",{className:"btb-bg-ink",children:s.jsxs("div",{className:`${Tc} py-24`,children:[s.jsx("p",{className:"btb-eyebrow opacity-60 mb-4",children:"What you get"}),s.jsx("h2",{className:"btb-serif text-5xl leading-[1.05] max-w-3xl",children:"Everything you need to grow."}),s.jsxs("div",{className:"mt-14 grid gap-px sm:grid-cols-2 lg:grid-cols-3",style:{background:"hsl(var(--btb-ivory) / 0.15)"},children:[GLt.map(([e,r],n)=>s.jsxs("div",{className:"btb-bg-ink p-8 btb-reveal",children:[s.jsx("p",{className:"btb-serif text-4xl opacity-40",children:String(n+1).padStart(2,"0")}),s.jsx("h3",{className:"mt-4 btb-serif text-2xl leading-tight",children:e}),s.jsx("p",{className:"mt-2 opacity-70 text-sm leading-relaxed",children:r})]},e)),s.jsxs("div",{className:"btb-bg-green p-8 flex flex-col justify-between",children:[s.jsx("p",{className:"btb-serif text-3xl leading-tight",children:"Ready to talk?"}),s.jsx("a",{href:"#inquire",className:"btb-link mt-6 self-start",children:"Schedule a confidential coffee"})]})]})]})}),s.jsx(uu,{siteConfig:t,defaultIntent:"explore",heading:"Grab a confidential coffee with Joey or Maria."})]})}function vDt({siteConfig:t}){var i,o;cu();const[e]=Px(),r=hN(),n=`${No.address}, ${No.cityLine}`;return s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:"Connect | Building The Bluegrass",description:`Visit Building The Bluegrass at ${n}.`}),s.jsxs("section",{className:`${Tc} pt-20 pb-16 grid gap-12 lg:grid-cols-2 items-end`,children:[s.jsxs("div",{children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Connect"}),s.jsx("h1",{className:"btb-serif text-6xl md:text-8xl leading-[1.0]",children:((i=r.hero)==null?void 0:i.headline)||"Come say hello."}),s.jsx("p",{className:"mt-6 btb-soft text-lg max-w-md",children:((o=r.hero)==null?void 0:o.subtitle)||bK})]}),s.jsxs("div",{className:"btb-soft text-lg space-y-1",children:[s.jsx("p",{className:"btb-eyebrow mb-2",children:"Our office"}),s.jsx("p",{className:"btb-serif text-3xl btb-ink",children:No.address}),s.jsx("p",{children:No.cityLine}),s.jsx("a",{className:"btb-link mt-5 inline-block btb-ink",href:`https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(n)}`,target:"_blank",rel:"noreferrer",children:"Get directions"})]})]}),s.jsxs("section",{className:`${Tc} pb-24 grid gap-6 lg:grid-cols-2`,children:[s.jsx("div",{className:"overflow-hidden aspect-[4/3] btb-bg-stone",children:s.jsx("img",{src:za.lexington,alt:"",loading:"lazy",className:"h-full w-full object-cover"})}),s.jsx("div",{className:"aspect-[4/3] border btb-line overflow-hidden",children:s.jsx("iframe",{title:"Map to Building The Bluegrass",className:"h-full w-full",loading:"lazy",src:`https://www.google.com/maps?q=${encodeURIComponent(n)}&output=embed`})})]}),s.jsx(uu,{siteConfig:t,defaultIntent:e.get("intent")||"explore",heading:"How can we help?"}),s.jsx(g5,{blocks:r.rest,siteId:r.siteId,slug:r.slug})]})}function rG({agent:t,className:e=""}){return t.photo?s.jsx("img",{src:t.photo,alt:t.name,className:`object-cover object-top ${e}`}):s.jsx("div",{className:`btb-bg-green flex items-center justify-center ${e}`,children:s.jsx("span",{className:"btb-serif text-7xl opacity-80",children:t.name.split(/\s+/).map(r=>r[0]).slice(0,2).join("")})})}function _Dt({siteConfig:t}){cu();const e=LT(),{hero:r}=hN("home");return s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:`${e.name} | REALTOR® in Lexington, KY | Building The Bluegrass Realty`,description:`Search every home for sale in Lexington and Central Kentucky with ${e.name} of Building The Bluegrass Realty.`}),s.jsxs("section",{className:"relative min-h-[100svh] overflow-hidden btb-light",children:[s.jsx("img",{src:(r==null?void 0:r.backgroundImageUrl)||za.hero,alt:"",fetchPriority:"high",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 btb-hero-shade"}),s.jsxs("div",{className:"relative mx-auto grid min-h-[100svh] max-w-[1400px] items-end gap-10 px-5 lg:px-10 pb-12 pt-32 lg:grid-cols-12",children:[s.jsxs("div",{className:"lg:col-span-7",children:[s.jsx("p",{className:"btb-eyebrow mb-6 opacity-90",children:(r==null?void 0:r.eyebrow)||`${e.title} · Building The Bluegrass Realty`}),s.jsx("h1",{className:"btb-serif text-[2.9rem] leading-[0.98] sm:text-7xl lg:text-[5.5rem]",children:(r==null?void 0:r.headline)||s.jsxs(s.Fragment,{children:[e.first," will help you",s.jsx("br",{}),s.jsx("em",{className:"font-normal",children:"find your place."})]})}),s.jsx("p",{className:"mt-7 max-w-xl text-lg opacity-90",children:(r==null?void 0:r.subtitle)||"Lexington and Central Kentucky real estate — every home on the market, honest advice and someone in your corner from first showing to closing day."}),s.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[s.jsx(Wr,{to:"/search",className:"btb-btn btb-btn-light",children:"Search Homes"}),s.jsx(Wr,{to:"/home-value",className:"btb-btn btb-btn-ghost",children:"What’s My Home Worth?"}),s.jsxs("a",{href:e.phoneHref,className:"btb-btn btb-btn-ghost",children:[s.jsx(ri,{className:"h-4 w-4"}),e.phone]})]}),s.jsx("div",{className:"mt-12 hidden md:block",children:s.jsx(A1,{})})]}),s.jsx("div",{className:"hidden lg:block lg:col-span-4 lg:col-start-9 btb-reveal",children:s.jsxs("div",{className:"relative",children:[s.jsx(rG,{agent:e,className:"aspect-[4/5] w-full shadow-2xl"}),s.jsxs("div",{className:"absolute -bottom-6 -left-6 btb-bg-paper btb-ink px-6 py-4 shadow-xl",children:[s.jsx("p",{className:"btb-serif text-2xl leading-none",children:e.name}),s.jsx("p",{className:"btb-eyebrow btb-soft mt-2",children:e.title})]})]})})]})]}),s.jsx("section",{className:"md:hidden px-5 py-8 btb-bg-ink",children:s.jsx(A1,{compact:!0})}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-36 grid gap-12 lg:grid-cols-12 items-center",children:[s.jsx("div",{className:"lg:col-span-5 btb-reveal overflow-hidden lg:hidden",children:s.jsx(rG,{agent:e,className:"aspect-[4/5] w-full"})}),s.jsxs("div",{className:"lg:col-span-7 btb-reveal",children:[s.jsxs("p",{className:"btb-eyebrow btb-accent mb-6",children:["Meet ",e.first]}),s.jsxs("h2",{className:"btb-serif text-5xl md:text-6xl leading-[1.04]",children:["Local knowledge.",s.jsx("br",{}),"A personal experience."]}),s.jsx("p",{className:"mt-8 btb-soft text-lg leading-relaxed whitespace-pre-line line-clamp-[8]",children:e.bio}),s.jsxs("div",{className:"mt-10 flex flex-wrap gap-8",children:[s.jsxs(Wr,{to:"/about",className:"btb-link",children:["More about ",e.first]}),s.jsx(Wr,{to:"/contact",className:"btb-link",children:"Get in touch"})]})]}),s.jsxs("div",{className:"lg:col-span-4 lg:col-start-9 btb-reveal btb-bg-stone p-10",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Our mission"}),s.jsxs("blockquote",{className:"btb-serif text-3xl leading-[1.15]",children:["“",bK,"”"]}),s.jsx("p",{className:"mt-6 btb-eyebrow btb-soft",children:"Building The Bluegrass Realty"})]})]}),s.jsxs("section",{className:"btb-bg-ink",children:[s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pt-24 pb-10",children:[s.jsxs("p",{className:"btb-eyebrow opacity-60 mb-5",children:["How ",e.first," can help"]}),s.jsx("h2",{className:"btb-serif text-5xl md:text-6xl max-w-3xl leading-[1.05]",children:"Wherever you are in the move, start here."})]}),s.jsx("div",{className:"grid md:grid-cols-3",children:[{k:"Buy",h:"Find the place for your next chapter.",b:"Live listings across Central Kentucky, saved favorites, instant alerts and private tours.",to:"/buying-process",img:za.realestate,cta:"Start your search"},{k:"Sell",h:"Present your home at its best.",b:"Thoughtful pricing, strong presentation and a marketing plan built to bring the right buyer.",to:"/sell",img:za.design,cta:"Talk about selling"},{k:"Top Areas",h:"Get to know the Bluegrass.",b:"Local guides and homes for sale in Lexington and the towns around it.",to:"/communities",img:za.lexington,cta:"Explore areas"}].map((n,i)=>s.jsxs(Wr,{to:n.to,className:"group relative block h-[70vh] min-h-[480px] overflow-hidden btb-img-zoom btb-light",children:[s.jsx("img",{src:n.img,alt:"",loading:"lazy",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 btb-hero-shade"}),s.jsxs("div",{className:"relative flex h-full flex-col justify-between p-8 md:p-10",children:[s.jsxs("span",{className:"btb-eyebrow opacity-80",children:["0",i+1," — ",n.k]}),s.jsxs("div",{children:[s.jsx("h3",{className:"btb-serif text-3xl lg:text-4xl leading-tight",children:n.h}),s.jsx("p",{className:"mt-4 opacity-85 max-w-sm",children:n.b}),s.jsxs("span",{className:"btb-link mt-8 inline-flex items-center gap-2",children:[n.cta," ",s.jsx(GA,{className:"h-4 w-4"})]})]})]})]},n.k))})]}),s.jsxs("section",{className:"btb-bg-paper py-10",children:[s.jsx(Hp,{siteConfig:t,accentColor:"#406E71",mode:"my_listings",sectionTitle:`${e.first}’s Listings`,count:12}),s.jsx(Hp,{siteConfig:t,accentColor:"#406E71",mode:"new_listings",sectionTitle:"Just Listed in the Bluegrass",count:12}),s.jsx(Hp,{siteConfig:t,accentColor:"#406E71",mode:"open_houses",sectionTitle:"Upcoming Open Houses",count:12})]}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-32",children:[s.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-6 mb-12 btb-reveal",children:[s.jsxs("div",{children:[s.jsxs("p",{className:"btb-eyebrow btb-accent mb-5",children:["Areas ",e.first," serves"]}),s.jsx("h2",{className:"btb-serif text-5xl leading-[1.05]",children:"Places I know by heart."})]}),s.jsx(Wr,{to:"/communities",className:"btb-link",children:"All areas"})]}),s.jsx("div",{className:"grid gap-px md:grid-cols-3 btb-bg-stone",children:Wx.map(n=>s.jsxs(Wr,{to:cg(n.name),className:"btb-bg p-8 group btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-soft",children:n.county}),s.jsxs("p",{className:"btb-serif text-3xl mt-2 flex items-center justify-between",children:[n.name,s.jsx(Ds,{className:"h-5 w-5 opacity-0 group-hover:opacity-100 transition"})]}),s.jsx("p",{className:"mt-3 btb-soft text-sm",children:n.blurb})]},n.name))})]}),s.jsx(uu,{siteConfig:t,heading:`Let’s talk — I’m ${e.first}.`})]})}function bDt({siteConfig:t}){cu();const e=LT(),{rest:r,siteId:n,slug:i}=hN("about");return s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:`About ${e.name} | Building The Bluegrass Realty`,description:`${e.name} is a ${e.title} with Building The Bluegrass Realty in Lexington, Kentucky.`}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pt-20 pb-24 grid gap-14 lg:grid-cols-12 items-start",children:[s.jsx("div",{className:"lg:col-span-5 btb-reveal",children:s.jsx(rG,{agent:e,className:"aspect-[4/5] w-full"})}),s.jsxs("div",{className:"lg:col-span-6 lg:col-start-7 btb-reveal",children:[s.jsxs("p",{className:"btb-eyebrow btb-accent mb-5",children:[e.title," · Building The Bluegrass Realty"]}),s.jsx("h1",{className:"btb-serif text-6xl md:text-7xl leading-[1.02]",children:e.name}),s.jsx("p",{className:"mt-10 btb-soft text-lg leading-relaxed whitespace-pre-line",children:e.bio}),s.jsxs("div",{className:"mt-10 flex flex-wrap gap-3",children:[s.jsxs("a",{href:e.phoneHref,className:"btb-btn",children:[s.jsx(ri,{className:"h-4 w-4"}),e.phone]}),e.email&&s.jsxs("a",{href:`mailto:${e.email}`,className:"btb-link inline-flex items-center gap-2 self-center ml-4",children:[s.jsx(mi,{className:"h-4 w-4"}),"Email ",e.first]})]})]})]}),s.jsx(g5,{blocks:r,siteId:n,slug:i}),s.jsx("section",{className:"btb-bg-ink",children:s.jsx("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-px md:grid-cols-3",children:[["We Connect","Passions and gifts to serve clients through a trustworthy, fulfilling and educational experience."],["We Believe","Leadership provides the opportunity to serve others; whoever brings blessings will be enriched."],["We Give","Time and resources to others — Building The Bluegrass gives 10% of all profits to charity."]].map(([o,c])=>s.jsxs("div",{className:"p-10 btb-reveal",children:[s.jsx("p",{className:"btb-serif text-4xl",children:o}),s.jsx("p",{className:"mt-4 opacity-75 leading-relaxed",children:c})]},o))})}),s.jsx(uu,{siteConfig:t})]})}function wDt({siteConfig:t}){cu();const e=LT();return s.jsxs(s.Fragment,{children:[s.jsx(Ac,{title:`Contact ${e.name} | Building The Bluegrass Realty`,description:`Call, email or send a note to ${e.name}, REALTOR® with Building The Bluegrass Realty in Lexington, KY.`}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pt-20 pb-10 grid gap-10 md:grid-cols-12 items-end",children:[s.jsxs("div",{className:"md:col-span-7",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Connect"}),s.jsx("h1",{className:"btb-serif text-6xl md:text-7xl leading-[1.02]",children:"Let’s talk about your move."})]}),s.jsxs("div",{className:"md:col-span-4 md:col-start-9 space-y-3 text-lg",children:[s.jsxs("a",{href:e.phoneHref,className:"flex items-center gap-3 btb-link",children:[s.jsx(ri,{className:"h-4 w-4"}),e.phone]}),e.email&&s.jsxs("a",{href:`mailto:${e.email}`,className:"flex items-center gap-3 btb-link break-all",children:[s.jsx(mi,{className:"h-4 w-4"}),e.email]}),s.jsxs("p",{className:"btb-soft text-base pt-2",children:[No.legal,s.jsx("br",{}),No.address,", ",No.cityLine]})]})]}),s.jsx(uu,{siteConfig:t,heading:`Send ${e.first} a note.`})]})}function TK(t){return mr({queryKey:["org-site-roster",t],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:e,error:r}=await Re.rpc("get_org_site_roster",{p_site_id:t});if(r)throw r;return e||[]}})}function VHt(t,e=!1){return mr({queryKey:["org-site-listings",t,e],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:r,error:n}=await Re.rpc("get_org_site_listings",{p_site_id:t,p_sold:e});if(n)throw n;return r||[]}})}function qHt(t){return t?`$${Math.round(t).toLocaleString()}`:"Price upon request"}const SDt="/assets/hero-kv4I0DLE.jpg",TDt="/assets/lexington-DDS8S5Ti.jpg",EDt="/assets/georgetown-CDefc5Gd.jpg",jDt="/assets/winchester-BRay9GI-.jpg",ADt="/assets/interior-BGPkmSFt.jpg",kDt="/assets/hero-generic-DIIV7gLP.jpg",Yf={hero:SDt,lexington:TDt,georgetown:EDt,winchester:jDt,interior:ADt},Tw={name:"RE/MAX Creative Realty",phone:"(859) 422-2000",phoneHref:"tel:+18594222000",tollFree:"(800) 860-7468",founded:1987,broker:"Sarith “Sari” Lawrence, Principal Broker"},c6=t=>`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(t)}`,CDt=[{key:"lexington",name:"Lexington",address:"2808 Palumbo Dr, Unit 100",cityLine:"Lexington, KY 40509",hours:"Mon–Fri · 8:30am–5:30pm",image:"lexington",note:"Our main office on the corner of Man o’ War and Palumbo, just off I-75 at exit 108.",map:c6("2808 Palumbo Dr Unit 100, Lexington, KY 40509")},{key:"georgetown",name:"Georgetown",address:"128 Edwards Ave",cityLine:"Georgetown, KY 40324",hours:"Flexible hours — call ahead",image:"georgetown",note:"Serving Scott County and the I-75 corridor north of Lexington.",map:c6("128 Edwards Ave, Georgetown, KY 40324")},{key:"winchester",name:"Winchester",address:"804 Bypass Rd",cityLine:"Winchester, KY 40391",hours:"By appointment — call ahead",image:"winchester",note:"Home base for Clark County and the eastern Bluegrass.",map:c6("804 Bypass Rd, Winchester, KY 40391")}],NDt=[{name:"Lexington",county:"Fayette County",image:"lexington",blurb:"Historic neighborhoods, a lively downtown, the University of Kentucky and horse farms minutes away."},{name:"Georgetown",county:"Scott County",image:"georgetown",blurb:"A walkable historic downtown, Georgetown College and an easy I-75 commute."},{name:"Winchester",county:"Clark County",image:"winchester",blurb:"Small-town character, rolling farmland and room to breathe east of Lexington."},{name:"Nicholasville",county:"Jessamine County",image:"interior",blurb:"Established neighborhoods and new construction just south of Lexington."},{name:"Versailles",county:"Woodford County",image:"hero",blurb:"Horse country charm along the Kentucky River."},{name:"Richmond",county:"Madison County",image:"winchester",blurb:"Home to Eastern Kentucky University and growing neighborhoods."},{name:"Frankfort",county:"Franklin County",image:"georgetown",blurb:"Kentucky’s capital city, with historic homes and river views."},{name:"Lawrenceburg",county:"Anderson County",image:"hero",blurb:"Bourbon country living with a close-knit feel."}],rC=t=>`/homes-for-sale-in-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,IDt=[{key:"buy",label:"Buy a home"},{key:"sell",label:"Sell my home"},{key:"value",label:"What’s my home worth?"},{key:"relocate",label:"Moving to Kentucky"},{key:"join",label:"Join RE/MAX Creative"}];function EK(t){const e=(t||"").replace(/\D/g,""),r=e.length===11&&e.startsWith("1")?e.slice(1):e;return r.length!==10?null:{phone:`(${r.slice(0,3)}) ${r.slice(3,6)}-${r.slice(6)}`,phoneHref:`tel:+1${r}`}}const Yd=t=>typeof t=="string"&&t.trim()?t.trim():null;function o2e(t){const e=t.ownerType==="brokerage"?"brokerage":t.ownerType==="team"?"team":"agent",r=t.brand||VS;if(e==="brokerage")return{mode:e,name:r.name,first:r.name,phone:r.phone,phoneHref:r.phoneHref,email:null,photo:null,title:"Real estate brokerage",bio:null};const n=t.themeConfig||{},i=t.agent||{},o=Yd((t.siteTitle||"").split("|")[0]),c=e==="team"?Yd(t.orgName)||o||"Our Team":Yd(i.full_name)||o||"Your Agent",a=EK(Yd(n.agentPhone)||i.phone)||{phone:r.phone,phoneHref:r.phoneHref};return{mode:e,name:c,first:e==="agent"?c.split(/\s+/)[0]:c,...a,email:Yd(n.agentEmail)||Yd(i.email),photo:Yd(n.agentHeadshotUrl)||Yd(i.avatar_url),title:Yd(n.agentTitle)||Yd(i.title)||(e==="team"?"Real estate team":"REALTOR®"),bio:Yd(n.agentBio)||Yd(i.bio)}}const VS={name:Tw.name,shortName:"Creative Realty",phone:Tw.phone,phoneHref:Tw.phoneHref,tollFree:Tw.tollFree,founded:Tw.founded,broker:Tw.broker,region:"Central Kentucky",regionNick:"the Bluegrass",heroWord:"Bluegrass",state:"Kentucky",mls:"Imagine MLS",agentCount:"70+",countyCount:"8+",images:{hero:Yf.hero,buy:Yf.interior,sell:Yf.winchester,team:Yf.lexington,offices:Yf.georgetown,careers:Yf.georgetown,contact:Yf.lexington},heroAlt:"Kentucky horse farm at sunrise",offices:CDt.map(t=>({...t,image:Yf[t.image]})),communities:NDt.map(t=>({...t,image:Yf[t.image]})),cities:"Lexington, Georgetown, Winchester, Nicholasville, Versailles, Richmond"},PDt=t=>`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(t)}`,Ls=t=>typeof t=="string"&&t.trim()?t.trim():"";function RDt(t){const e=t||{};if(e.orgPreset!=="remax")return VS;const r=e.remaxBrand||{},n=Ls(r.name)||"RE/MAX",i=n.replace(/^RE\/?MAX\s*/i,"").trim(),o=EK(r.phone)||{phone:Ls(r.phone),phoneHref:Ls(r.phone)?`tel:${Ls(r.phone).replace(/[^\d+]/g,"")}`:""},c=Ls(r.heroImageUrl)||kDt,a=Ls(r.cityImageUrl)||c,f=Ls(r.region)||"your area",p=(r.offices||[]).filter(T=>Ls(T.name)).map((T,E)=>({key:`office-${E}`,name:Ls(T.name),address:Ls(T.address),cityLine:Ls(T.cityLine),hours:Ls(T.hours)||"Call for hours",note:Ls(T.note),image:Ls(T.image)||(E===0?c:a),map:PDt(`${Ls(T.address)}, ${Ls(T.cityLine)}`)})),y=(r.communities||[]).filter(T=>Ls(T.name)).map(T=>({name:Ls(T.name),county:Ls(T.county),blurb:Ls(T.blurb),image:Ls(T.image)||a})),v=Number(r.founded);return{name:n,shortName:i||"Real Estate",...o,tollFree:Ls(r.tollFree)||null,founded:Number.isFinite(v)&&v>1900?v:null,broker:Ls(r.broker),region:f,regionNick:Ls(r.regionNick)||f,heroWord:Ls(r.heroWord),state:Ls(r.state),mls:Ls(r.mls)||"the local MLS",agentCount:Ls(r.agentCount),countyCount:Ls(r.countyCount),images:{hero:c,buy:Yf.interior,sell:a,team:a,offices:a,careers:a,contact:a},heroAlt:Ls(r.heroAlt)||`Homes in ${f}`,offices:p,communities:y,cities:y.slice(0,6).map(T=>T.name).join(", ")}}const LDt=1,DDt="46dc71ce-4743-4cc2-b8f2-7899c82a15ba",MDt="b4ed24ae-0b44-4f4d-8676-c620f649ed8a",ODt="/__l5e/assets-v1/46dc71ce-4743-4cc2-b8f2-7899c82a15ba/remax-balloon-mark.webp",FDt="a/v1/b4ed24ae-0b44-4f4d-8676-c620f649ed8a/46dc71ce-4743-4cc2-b8f2-7899c82a15ba/remax-balloon-mark.webp",BDt="remax-balloon-mark.webp",$Dt=23912,zDt="image/webp",UDt="2026-10-31T00:58:57Z",k1={version:LDt,asset_id:DDt,project_id:MDt,url:ODt,r2_key:FDt,original_filename:BDt,size:$Dt,content_type:zDt,created_at:UDt};function y5(){C.useEffect(()=>{const t=document.querySelectorAll(".rmc-reveal:not(.is-in)"),e=new IntersectionObserver(r=>r.forEach(n=>{n.isIntersecting&&(n.target.classList.add("is-in"),e.unobserve(n.target))}),{threshold:.1});return t.forEach(r=>e.observe(r)),()=>e.disconnect()})}function Sx({title:t,description:e}){return s.jsxs(Zo,{children:[s.jsx("title",{children:t}),s.jsx("meta",{name:"description",content:e}),s.jsx("meta",{property:"og:title",content:t}),s.jsx("meta",{property:"og:description",content:e})]})}const l2e=C.createContext(o2e({ownerType:"brokerage"})),Om=()=>C.useContext(l2e),c2e=C.createContext(VS),zu=()=>C.useContext(c2e);function u2e({light:t=!0}){const e=Om(),r=zu();return e.mode!=="brokerage"?s.jsxs("span",{className:"flex items-center gap-3",children:[s.jsx("img",{src:k1.url,alt:"","aria-hidden":!0,className:"block h-10 w-auto shrink-0 drop-shadow"}),s.jsxs("span",{className:"leading-none",children:[s.jsx("span",{className:`block text-lg md:text-xl font-bold tracking-tight ${t?"":"rmc-blue"}`,children:e.name}),s.jsxs("span",{className:"block text-[0.6rem] tracking-[0.28em] uppercase opacity-80 mt-1",children:["RE",s.jsx("span",{className:"rmc-red",children:"/"}),"MAX ",r.shortName]})]})]}):s.jsxs("span",{className:"flex items-center gap-3",children:[s.jsx("img",{src:k1.url,alt:"","aria-hidden":!0,className:"block h-10 w-auto shrink-0 drop-shadow"}),s.jsxs("span",{className:"leading-none",children:[s.jsxs("span",{className:`block text-xl font-bold tracking-tight ${t?"":"rmc-blue"}`,children:["RE",s.jsx("span",{className:"rmc-red",children:"/"}),"MAX"]}),s.jsx("span",{className:"block text-[0.62rem] tracking-[0.32em] uppercase opacity-80 mt-1",children:r.shortName})]})]})}const VDt=t=>[{label:"Buy",to:"/buy",children:[{label:"Search All Homes",to:"/search"},{label:"Buying With Us",to:"/buy"},{label:"Farms & Land",to:"/search?propertyType=Land"},{label:"My Saved Homes",to:"/account?tab=saved"},{label:"Saved Searches & Alerts",to:"/account?tab=searches"}]},{label:"Sell",to:"/sell",children:[{label:"Selling With Us",to:"/sell"},{label:"What’s My Home Worth?",to:"/sell#inquire"}]},{label:"Communities",to:"/communities",children:[...t.communities.slice(0,6).map(e=>({label:e.name,to:rC(e.name)})),{label:"All Communities",to:"/communities"}]},{label:"Agents",to:"/agents"},{label:"Offices",to:"/offices"},{label:"About",to:"/about",children:[{label:"Our Story",to:"/about"},{label:"Join Our Team",to:"/join"},{label:"Market Blog",to:"/blog"},{label:"Contact",to:"/contact"}]}];function qDt(t,e){const r=VDt(e).filter(n=>e.offices.length||n.label!=="Offices");return t==="brokerage"?r:r.map(n=>n.label==="About"?{...n,children:n.children.filter(i=>i.to!=="/join")}:n).filter(n=>t==="team"||n.label!=="Agents").map(n=>n.label==="Agents"?{...n,label:"Our Team"}:n)}function GDt({children:t,siteConfig:e}){r2e(e);const r=C.useMemo(()=>RDt(e.themeConfig),[e]),n=C.useMemo(()=>o2e({...e,brand:r}),[e,r]),i=qDt(n.mode,r),{pathname:o}=ki(),c=o==="/",[a,f]=C.useState(!1),[p,y]=C.useState(!1);C.useEffect(()=>{const T=()=>f(window.scrollY>40);return T(),window.addEventListener("scroll",T,{passive:!0}),()=>window.removeEventListener("scroll",T)},[]),C.useEffect(()=>y(!1),[o]);const v=c&&!a&&!p;return s.jsx(c2e.Provider,{value:r,children:s.jsx(l2e.Provider,{value:n,children:s.jsxs("div",{className:"rmc-site min-h-screen",children:[s.jsxs("header",{className:`fixed inset-x-0 top-0 z-50 transition-all duration-300 ${v?"rmc-light":"rmc-bg-navy shadow-lg"}`,children:[!v&&s.jsx("div",{className:"rmc-stripe"}),s.jsxs("div",{className:`mx-auto flex max-w-[1400px] items-center justify-between px-5 lg:px-10 ${v?"h-24":"h-[72px]"} transition-all`,children:[s.jsx(Wr,{to:"/","aria-label":`${n.name} home`,children:s.jsx(u2e,{})}),s.jsx("nav",{className:"hidden xl:flex items-center gap-7","aria-label":"Main",children:i.map(T=>s.jsxs("div",{className:"group relative",children:[s.jsxs(Wr,{to:T.to,className:"flex items-center gap-1 text-[0.8rem] font-semibold tracking-[0.12em] uppercase py-6 opacity-90 hover:opacity-100",children:[T.label,T.children&&s.jsx(yl,{className:"h-3 w-3"})]}),T.children&&s.jsx("div",{className:"invisible opacity-0 group-hover:visible group-hover:opacity-100 group-focus-within:visible group-focus-within:opacity-100 transition absolute left-0 top-full min-w-[230px] rmc-card py-3 text-[hsl(var(--rmc-ink))]",children:T.children.map(E=>s.jsx(Wr,{to:E.to,className:"block px-5 py-2.5 text-sm hover:rmc-red",children:E.label},E.label))})]},T.label))}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("a",{href:n.phoneHref,className:"hidden md:flex items-center gap-2 text-sm font-semibold",children:[s.jsx(ri,{className:"h-4 w-4"}),n.phone]}),s.jsx("span",{className:"hidden md:inline-flex",children:s.jsx(yO,{siteConfig:e,variant:"desktop"})}),s.jsxs(Wr,{to:"/search",className:"rmc-btn !py-3 !px-4",children:[s.jsx(xd,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden sm:inline",children:"Search"})]}),s.jsx("button",{className:"xl:hidden p-2",onClick:()=>y(!p),"aria-label":p?"Close menu":"Open menu","aria-expanded":p,children:p?s.jsx(Os,{className:"h-6 w-6"}):s.jsx(QS,{className:"h-6 w-6"})})]})]}),p&&s.jsxs("div",{className:"xl:hidden rmc-bg-navy border-t rmc-line-light max-h-[80vh] overflow-y-auto px-6 py-6 space-y-5",children:[i.map(T=>s.jsxs("div",{children:[s.jsx(Wr,{to:T.to,className:"rmc-display text-2xl block",children:T.label}),T.children&&s.jsx("div",{className:"mt-2 space-y-1.5",children:T.children.map(E=>s.jsx(Wr,{to:E.to,className:"block text-sm opacity-75",children:E.label},E.label))})]},T.label)),s.jsxs("a",{href:n.phoneHref,className:"flex items-center gap-2 text-sm",children:[s.jsx(ri,{className:"h-4 w-4"}),n.phone]}),s.jsx(yO,{siteConfig:e,variant:"mobile",onNavigate:()=>y(!1)})]})]}),s.jsx("main",{className:c?"":"pt-[76px]",children:t}),s.jsx(HDt,{})]})})})}function HDt(){const t=Om(),e=zu();return s.jsxs("footer",{className:"rmc-bg-navy",children:[s.jsx("div",{className:"rmc-stripe"}),s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-16 grid gap-12 lg:grid-cols-12",children:[s.jsxs("div",{className:"lg:col-span-4",children:[s.jsx(u2e,{}),s.jsx("p",{className:"rmc-display text-3xl mt-6 max-w-xs leading-tight",children:t.mode==="brokerage"?s.jsxs(s.Fragment,{children:[e.region,"’s RE/MAX",e.founded?s.jsxs(s.Fragment,{children:[" — since ",e.founded]}):null,"."]}):s.jsxs(s.Fragment,{children:["Your ",e.heroWord?`${e.heroWord} `:"","home, handled with care."]})}),t.email&&s.jsxs("a",{href:`mailto:${t.email}`,className:"mt-3 flex items-center gap-2 text-sm opacity-85",children:[s.jsx(mi,{className:"h-4 w-4"}),t.email]}),s.jsxs("a",{href:t.phoneHref,className:"mt-6 inline-flex items-center gap-2 font-semibold",children:[s.jsx(ri,{className:"h-4 w-4"}),t.phone]})]}),s.jsx("div",{className:"lg:col-span-5 grid gap-8 sm:grid-cols-3",children:e.offices.map(r=>s.jsxs("div",{className:"text-sm",children:[s.jsx("p",{className:"rmc-eyebrow opacity-60 mb-3",children:r.name}),s.jsxs("p",{className:"opacity-85 leading-relaxed",children:[r.address,s.jsx("br",{}),r.cityLine]}),s.jsx("a",{href:r.map,target:"_blank",rel:"noreferrer",className:"mt-2 inline-block text-xs underline opacity-70",children:"Directions"})]},r.key))}),s.jsxs("div",{className:"lg:col-span-3 grid grid-cols-2 gap-6 text-sm",children:[s.jsx("ul",{className:"space-y-2.5",children:[["Search Homes","/search"],["Buy","/buy"],["Sell","/sell"],["Communities","/communities"]].map(([r,n])=>s.jsx("li",{children:s.jsx(Wr,{to:n,className:"opacity-85 hover:opacity-100",children:r})},r))}),s.jsx("ul",{className:"space-y-2.5",children:(t.mode==="brokerage"?[["Our Agents","/agents"],["Offices","/offices"],["Join Us","/join"],["Contact","/contact"]]:[[t.mode==="team"?"Our Team":"About",t.mode==="team"?"/agents":"/about"],["Offices","/offices"],["Blog","/blog"],["Contact","/contact"]]).map(([r,n])=>s.jsx("li",{children:s.jsx(Wr,{to:n,className:"opacity-85 hover:opacity-100",children:r})},r))})]})]}),s.jsx("div",{className:"border-t rmc-line-light",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-6 text-xs opacity-60 space-y-1.5",children:[s.jsxs("p",{children:["© ",new Date().getFullYear()," ",t.mode==="brokerage"?"":`${t.name} · `,e.name,". Each office independently owned and operated.",e.broker?` ${e.broker}.`:""," Equal Housing Opportunity."]}),s.jsxs("p",{children:["Listing data courtesy of ",e.mls,". Information deemed reliable but not guaranteed."]})]})})]})}function WDt(){const t=Hs(),[e,r]=C.useState(""),[n,i]=C.useState(""),[o,c]=C.useState(""),a=f=>{f.preventDefault();const p=new URLSearchParams;e.trim()&&p.set("q",e.trim()),n&&p.set("maxPrice",n),o&&p.set("beds",o),t(`/search?${p.toString()}`)};return s.jsxs("form",{onSubmit:a,role:"search",className:"rmc-card text-[hsl(var(--rmc-ink))] p-2 grid gap-1 md:grid-cols-[1fr_170px_120px_auto] md:rounded-full",children:[s.jsxs("label",{className:"px-5 py-2.5",children:[s.jsx("span",{className:"rmc-eyebrow rmc-soft block !text-[0.62rem]",children:"Where"}),s.jsx("input",{value:e,onChange:f=>r(f.target.value),placeholder:"City, ZIP, address or MLS #",className:"w-full bg-transparent outline-none"})]}),s.jsxs("label",{className:"px-5 py-2.5 md:border-l rmc-line",children:[s.jsx("span",{className:"rmc-eyebrow rmc-soft block !text-[0.62rem]",children:"Max price"}),s.jsxs("select",{value:n,onChange:f=>i(f.target.value),className:"w-full bg-transparent outline-none",children:[s.jsx("option",{value:"",children:"Any"}),[25e4,4e5,6e5,8e5,1e6,2e6].map(f=>s.jsxs("option",{value:f,children:["$",(f/1e3).toLocaleString(),"k"]},f))]})]}),s.jsxs("label",{className:"px-5 py-2.5 md:border-l rmc-line",children:[s.jsx("span",{className:"rmc-eyebrow rmc-soft block !text-[0.62rem]",children:"Beds"}),s.jsxs("select",{value:o,onChange:f=>c(f.target.value),className:"w-full bg-transparent outline-none",children:[s.jsx("option",{value:"",children:"Any"}),[1,2,3,4,5].map(f=>s.jsxs("option",{value:f,children:[f,"+"]},f))]})]}),s.jsxs("button",{type:"submit",className:"rmc-btn justify-center",children:[s.jsx(xd,{className:"h-4 w-4"}),"Search"]})]})}function p_({eyebrow:t,title:e,intro:r,image:n}){return s.jsxs("section",{className:"relative h-[56vh] min-h-[420px] overflow-hidden rmc-light",children:[s.jsx("img",{src:n,alt:"",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 rmc-hero-shade"}),s.jsxs("div",{className:"relative mx-auto flex h-full max-w-[1400px] flex-col justify-end px-5 lg:px-10 pb-14",children:[s.jsx("p",{className:"rmc-eyebrow mb-4",children:t}),s.jsx("h1",{className:"rmc-display text-5xl md:text-7xl max-w-4xl leading-[1.02]",children:e}),s.jsx("p",{className:"mt-5 max-w-xl text-lg opacity-90",children:r})]})]})}function WL({eyebrow:t,title:e,intro:r,center:n=!1}){return s.jsxs("div",{className:`rmc-reveal mb-12 ${n?"text-center mx-auto max-w-2xl":"max-w-2xl"}`,children:[s.jsx("p",{className:"rmc-eyebrow rmc-red mb-4",children:t}),s.jsx("h2",{className:"rmc-display text-4xl md:text-6xl leading-[1.05]",children:e}),r&&s.jsx("p",{className:"mt-5 rmc-soft text-lg",children:r})]})}function Tx({siteConfig:t,defaultIntent:e="buy",heading:r="How can we help you move?"}){var V,G;const n=Om(),i=zu(),o=IDt.map(W=>W.key==="relocate"&&i!==VS?{...W,label:`Moving to ${i.state||i.region}`}:W.key==="join"&&i!==VS?{...W,label:`Join ${i.name}`}:W),c=n.mode==="brokerage"?o:o.filter(W=>W.key!=="join"),{pathname:a}=ki(),[f,p]=C.useState(e),[y,v]=C.useState(((V=i.offices[0])==null?void 0:V.key)||""),[T,E]=C.useState({name:"",email:"",phone:"",message:""}),[k,P]=C.useState("idle"),[R,D]=C.useState(""),M=((G=o.find(W=>W.key===f))==null?void 0:G.label)||"General question",B=async W=>{var Q;if(W.preventDefault(),D(""),!T.name.trim()||!T.email.trim()){D("Please add your name and email.");return}P("sending");const Y=(Q=i.offices.find(ee=>ee.key===y))==null?void 0:Q.name,{error:J}=await lg({lead_site_id:t.id,name:T.name.trim(),email:T.email.trim(),phone:T.phone.trim()||null,message:`[${M}${n.mode==="brokerage"?` · ${Y} office`:""}] ${T.message.trim()}`.trim(),source_page:a,lead_type:f==="sell"||f==="value"?"seller":f==="buy"||f==="relocate"?"buyer":"contact",metadata:{intent:f,intent_label:M,office:y}});if(J){P("error"),D(J.message||`Something went wrong. Please call ${n.phone}.`);return}P("sent")};return s.jsx("section",{id:"inquire",className:"rmc-bg-mist",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-14 lg:grid-cols-2 items-center",children:[s.jsxs("div",{className:"rmc-reveal",children:[s.jsx("p",{className:"rmc-eyebrow rmc-red mb-4",children:"Talk to a local expert"}),s.jsx("h2",{className:"rmc-display text-5xl md:text-6xl leading-[1.05]",children:r}),s.jsx("p",{className:"mt-5 rmc-soft text-lg max-w-md",children:n.mode==="agent"?"Tell me what you need and I’ll reach out personally — usually the same day.":n.mode==="team"?"Tell us what you need and someone from our team will reach out — usually the same day.":"Tell us what you need and the right agent from the nearest office will reach out — usually the same day."}),s.jsx("div",{className:"mt-8 flex flex-wrap gap-2",role:"radiogroup","aria-label":"What can we help with?",children:c.map(W=>s.jsx("button",{type:"button",role:"radio","aria-checked":f===W.key,onClick:()=>p(W.key),className:`px-4 py-2.5 rounded-full text-sm font-medium border transition ${f===W.key?"rmc-bg-blue border-transparent":"rmc-line rmc-bg-paper"}`,children:W.label},W.key))})]}),k==="sent"?s.jsxs("div",{className:"rmc-card p-12",role:"status",children:[s.jsx("p",{className:"rmc-eyebrow rmc-red mb-3",children:"Got it"}),s.jsxs("p",{className:"rmc-display text-4xl",children:["Thank you, ",T.name.split(" ")[0],"!"]}),s.jsxs("p",{className:"mt-4 rmc-soft",children:[n.mode==="brokerage"?`A ${i.name} agent`:n.mode==="agent"?n.first:"Our team"," will follow up shortly. Need us now? Call ",n.phone,"."]})]}):s.jsxs("form",{onSubmit:B,className:"rmc-card p-8 md:p-10 space-y-4",noValidate:!0,children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsx("input",{className:"rmc-input",placeholder:"Name *","aria-label":"Name",value:T.name,onChange:W=>E({...T,name:W.target.value}),autoComplete:"name"}),s.jsx("input",{className:"rmc-input",placeholder:"Phone","aria-label":"Phone",type:"tel",value:T.phone,onChange:W=>E({...T,phone:W.target.value}),autoComplete:"tel"})]}),s.jsx("input",{className:"rmc-input",placeholder:"Email *","aria-label":"Email",type:"email",value:T.email,onChange:W=>E({...T,email:W.target.value}),autoComplete:"email"}),n.mode==="brokerage"&&i.offices.length>0&&s.jsx("select",{className:"rmc-input","aria-label":"Nearest office",value:y,onChange:W=>v(W.target.value),children:i.offices.map(W=>s.jsxs("option",{value:W.key,children:[W.name," office"]},W.key))}),s.jsx("textarea",{className:"rmc-input min-h-[110px] resize-none",placeholder:f==="sell"||f==="value"?"Property address and timing…":"Areas, price range, timing…","aria-label":"Message",value:T.message,onChange:W=>E({...T,message:W.target.value})}),R&&s.jsx("p",{className:"text-sm text-destructive",role:"alert",children:R}),s.jsx("button",{type:"submit",disabled:k==="sending",className:"rmc-btn w-full justify-center",children:k==="sending"?"Sending…":s.jsxs(s.Fragment,{children:["Send message ",s.jsx(Ds,{className:"h-4 w-4"})]})})]})]})})}function d2e(t){return(t||"?").split(/\s+/).map(e=>e[0]).slice(0,2).join("").toUpperCase()}function xO({a:t}){var r;const e=t.agent_site_slug?`https://${t.agent_site_slug}.thelocalmove.com`:null;return s.jsxs("div",{className:"rmc-card overflow-hidden group flex flex-col",children:[s.jsxs("div",{className:"aspect-[4/5] rmc-bg-mist overflow-hidden rmc-zoom relative",children:[t.avatar_url?s.jsx("img",{src:t.avatar_url,alt:t.full_name||"",loading:"lazy",className:"h-full w-full object-cover"}):s.jsx("div",{className:"h-full w-full flex items-center justify-center rmc-display text-5xl rmc-blue",children:d2e(t.full_name)}),t.team_name&&s.jsx("span",{className:"absolute left-3 top-3 rounded-full rmc-bg-navy px-3 py-1 text-[0.65rem] font-semibold uppercase tracking-wider",children:t.team_name})]}),s.jsxs("div",{className:"p-5 flex-1 flex flex-col",children:[s.jsx("p",{className:"font-semibold text-lg leading-tight",children:t.full_name}),s.jsx("p",{className:"text-sm rmc-soft mt-0.5",children:t.title||"REALTOR®"}),s.jsxs("div",{className:"mt-4 space-y-1.5 text-sm",children:[t.phone&&s.jsxs("a",{href:`tel:${t.phone.replace(/[^\d+]/g,"")}`,className:"flex items-center gap-2 hover:rmc-red",children:[s.jsx(ri,{className:"h-3.5 w-3.5"}),((r=EK(t.phone))==null?void 0:r.phone)||t.phone]}),t.email&&s.jsxs("a",{href:`mailto:${t.email}`,className:"flex items-center gap-2 hover:rmc-red truncate",children:[s.jsx(mi,{className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"truncate",children:t.email})]})]}),e&&s.jsxs("a",{href:e,target:"_blank",rel:"noreferrer",className:"mt-auto pt-4 inline-flex items-center gap-1 text-xs font-semibold uppercase tracking-wider rmc-blue",children:["Visit website ",s.jsx(GA,{className:"h-3.5 w-3.5"})]})]})]})}function h2e({roster:t}){const e=Om(),r=zu(),n=(e.bio||"").split(/\n\s*\n/).map(i=>i.trim()).filter(Boolean);return e.mode==="team"?s.jsx("section",{className:"rmc-bg-paper",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-6",children:[s.jsx(WL,{eyebrow:"Meet the team",title:`The ${e.name}.`,intro:n[0]||"Local experts who share the work — so you always have someone ready to help."}),s.jsxs(Wr,{to:"/agents",className:"rmc-btn mb-12",children:["Meet everyone ",s.jsx(Ds,{className:"h-4 w-4"})]})]}),t.length>0&&s.jsx("div",{className:"grid gap-5 grid-cols-2 md:grid-cols-4",children:t.slice(0,8).map(i=>s.jsx(xO,{a:i},i.user_id))})]})}):s.jsx("section",{className:"rmc-bg-paper",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-12 lg:grid-cols-[minmax(0,5fr)_minmax(0,7fr)] items-center",children:[s.jsxs("div",{className:"rmc-reveal relative",children:[s.jsx("div",{className:"aspect-[4/5] overflow-hidden rounded-[1.5rem] rmc-bg-mist",children:e.photo?s.jsx("img",{src:e.photo,alt:e.name,loading:"lazy",className:"h-full w-full object-cover"}):s.jsx("div",{className:"h-full w-full flex items-center justify-center rmc-display text-7xl rmc-blue",children:d2e(e.name)})}),s.jsx("img",{src:k1.url,alt:"","aria-hidden":!0,className:"absolute -right-4 -bottom-6 h-24 w-auto drop-shadow-lg"})]}),s.jsxs("div",{className:"rmc-reveal",children:[s.jsxs("p",{className:"rmc-eyebrow rmc-red mb-4",children:["Meet ",e.first]}),s.jsx("h2",{className:"rmc-display text-4xl md:text-6xl leading-[1.05]",children:e.name}),s.jsxs("p",{className:"mt-2 rmc-soft",children:[e.title," · ",r.name]}),s.jsx("div",{className:"mt-6 space-y-4 text-lg rmc-soft max-w-2xl",children:(n.length?n.slice(0,2):[`I help ${r.region} buyers and sellers move with clarity and confidence — with local market knowledge and the reach of RE/MAX behind every move.`]).map((i,o)=>s.jsx("p",{children:i},o))}),s.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[s.jsxs("a",{href:e.phoneHref,className:"rmc-btn",children:[s.jsx(ri,{className:"h-4 w-4"}),e.phone]}),e.email&&s.jsxs("a",{href:`mailto:${e.email}`,className:"rmc-btn rmc-btn-blue",children:[s.jsx(mi,{className:"h-4 w-4"}),"Email ",e.first]}),s.jsxs(Wr,{to:"/about",className:"rmc-btn rmc-btn-ghost",children:["My story ",s.jsx(Ds,{className:"h-4 w-4"})]})]})]})]})})}function KDt({siteConfig:t}){var a;y5();const e=Om(),r=zu(),n=e.mode==="brokerage",{data:i=[]}=TK(e.mode==="agent"?null:t.id),o=(n?i.filter(f=>f.avatar_url):i).slice(0,8),c=((a=t.themeConfig)==null?void 0:a.heroImageUrl)||r.images.hero;return s.jsxs(s.Fragment,{children:[s.jsx(Sx,{title:n?`${r.name} | ${r.region} Homes for Sale`:`${e.name} | ${r.name} | ${r.region} Homes for Sale`,description:n?`Search every ${r.region} home for sale with ${r.name}${r.offices.length?` — offices in ${r.offices.map(f=>f.name).join(", ")}`:""}.`:`Search every ${r.region} home for sale with ${e.name} of ${r.name}.`}),s.jsxs("section",{className:"relative min-h-[100svh] md:h-[100svh] md:min-h-[640px] overflow-hidden rmc-light",children:[s.jsx("img",{src:n?r.images.hero:c,alt:r.heroAlt,width:1920,height:1088,fetchPriority:"high",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 rmc-hero-shade"}),s.jsx("img",{src:k1.url,alt:"","aria-hidden":!0,className:"rmc-balloon hidden md:block right-[9%] top-[22%] h-28 w-auto drop-shadow-lg"}),s.jsx("img",{src:k1.url,alt:"","aria-hidden":!0,className:"rmc-balloon hidden md:block right-[21%] top-[36%] h-14 w-auto opacity-80 drop-shadow",style:{animationDelay:"-3s"}}),s.jsxs("div",{className:"relative mx-auto flex min-h-[100svh] md:min-h-0 md:h-full max-w-[1400px] flex-col justify-end px-5 lg:px-10 pt-28 md:pt-0 pb-10 md:pb-16",children:[s.jsx("p",{className:"rmc-eyebrow mb-4 md:mb-5",children:n?r.offices.length?r.offices.map(f=>f.name).join(" · "):r.region:`${e.name} · ${r.name}`}),s.jsxs("h1",{className:"rmc-display text-[2.4rem] leading-[1] sm:text-7xl lg:text-[7rem] max-w-5xl",children:["Your ",r.heroWord?`${r.heroWord} `:"","home ",s.jsx("em",{className:"rmc-red not-italic",children:"starts here."})]}),s.jsx("p",{className:"mt-4 md:mt-6 max-w-xl text-base md:text-lg opacity-90",children:n?r===VS?"Central Kentucky’s original RE/MAX. Three offices, 70+ local REALTORS®, and every home on the market — searchable right here.":`${r.name}${r.agentCount?` — ${r.agentCount} local REALTORS®`:""} and every home on the market in ${r.region}, searchable right here.`:e.mode==="team"?"Local REALTORS® who work together for you — and every home on the market, searchable right here.":`Local guidance from ${e.first}, backed by ${r.name} — and every home on the market, searchable right here.`}),s.jsx("div",{className:"mt-6 md:mt-10 max-w-4xl",children:s.jsx(WDt,{})}),s.jsx("div",{className:"mt-5 flex flex-wrap gap-x-5 gap-y-2 text-sm opacity-90",children:r.communities.slice(0,6).map(f=>s.jsx(Wr,{to:rC(f.name),className:"hover:underline",children:f.name},f.name))})]})]}),n&&s.jsx("section",{className:"rmc-bg-blue",children:s.jsx("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-12 grid grid-cols-2 md:grid-cols-4 gap-8",children:[[f1,r.founded?`Since ${r.founded}`:"Local",`Serving ${r.region}`],[fl,i.length?`${i.length}+`:r.agentCount||"Local","Local REALTORS®"],[_o,String(r.offices.length||1),`Office${r.offices.length===1?"":"s"} in ${r.regionNick}`],[va,r.countyCount||String(r.communities.length||"—"),r.countyCount?"Counties we cover":"Communities we serve"]].map(([f,p,y])=>s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx(f,{className:"h-8 w-8 opacity-80 shrink-0"}),s.jsxs("div",{children:[s.jsx("p",{className:"rmc-display text-4xl leading-none",children:p}),s.jsx("p",{className:"text-sm opacity-80 mt-1",children:y})]})]},y))})}),!n&&s.jsx(h2e,{siteConfig:t,roster:i}),t.mlsProviderId&&s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsx(WL,{eyebrow:"Fresh on the market",title:`Just listed in ${r.region}.`,intro:`Live from ${r.mls} — updated throughout the day.`}),s.jsxs("div",{className:"space-y-6",children:[e.mode==="agent"&&s.jsx(Hp,{siteConfig:t,accentColor:"#003DA5",mode:"my_listings",sectionTitle:`${e.first}’s Listings`,count:12}),s.jsx(Hp,{siteConfig:t,accentColor:"#DC1C2E",cities:r.cities||void 0,mode:"new_listings",sectionTitle:"Newest Listings",count:12}),s.jsx(Hp,{siteConfig:t,accentColor:"#003DA5",cities:r.cities||void 0,mode:"open_houses",sectionTitle:"Open Houses This Week",count:12})]}),s.jsx("div",{className:"mt-10",children:s.jsxs(Wr,{to:"/search",className:"rmc-btn rmc-btn-blue",children:["See every home ",s.jsx(Ds,{className:"h-4 w-4"})]})})]}),s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pb-24 grid gap-6 md:grid-cols-2",children:[{to:"/buy",img:r.images.buy,eyebrow:"Buying",title:"Find the one.",copy:"Search like an insider with saved searches, instant alerts and an agent who knows every street."},{to:"/sell",img:r.images.sell,eyebrow:"Selling",title:"Sell for more.",copy:"Pricing backed by live MLS data, marketing with the reach of the RE/MAX network."}].map(f=>s.jsxs(Wr,{to:f.to,className:"rmc-reveal relative overflow-hidden rounded-[1.5rem] h-[440px] rmc-zoom rmc-light group",children:[s.jsx("img",{src:f.img,alt:"",loading:"lazy",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 rmc-hero-shade"}),s.jsxs("div",{className:"absolute bottom-0 p-8 md:p-10",children:[s.jsx("p",{className:"rmc-eyebrow mb-3",children:f.eyebrow}),s.jsx("p",{className:"rmc-display text-5xl",children:f.title}),s.jsx("p",{className:"mt-3 max-w-sm opacity-90",children:f.copy}),s.jsxs("span",{className:"mt-5 inline-flex items-center gap-2 text-sm font-semibold uppercase tracking-wider",children:["Learn more ",s.jsx(Ds,{className:"h-4 w-4 transition group-hover:translate-x-1"})]})]})]},f.to))}),r.offices.length>0&&s.jsx("section",{className:"rmc-bg-navy",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsxs("div",{className:"rmc-reveal mb-12 max-w-2xl",children:[s.jsx("p",{className:"rmc-eyebrow rmc-red mb-4",children:n?`${r.offices.length} office${r.offices.length===1?"":"s"}`:`${r.name} offices`}),s.jsx("h2",{className:"rmc-display text-4xl md:text-6xl",children:"Close to home, wherever home is."})]}),s.jsx("div",{className:"grid gap-6 md:grid-cols-3",children:r.offices.map(f=>s.jsxs("div",{className:"rmc-reveal rounded-[1.25rem] overflow-hidden bg-[hsl(var(--rmc-cream)/0.06)] border rmc-line-light",children:[s.jsx("div",{className:"h-48 overflow-hidden rmc-zoom",children:s.jsx("img",{src:f.image,alt:"",loading:"lazy",className:"h-full w-full object-cover"})}),s.jsxs("div",{className:"p-6",children:[s.jsx("p",{className:"rmc-display text-3xl",children:f.name}),s.jsxs("p",{className:"mt-3 text-sm opacity-85 flex gap-2",children:[s.jsx(Es,{className:"h-4 w-4 shrink-0 mt-0.5"}),f.address,", ",f.cityLine]}),s.jsxs("p",{className:"mt-2 text-sm opacity-70 flex gap-2",children:[s.jsx(Dl,{className:"h-4 w-4 shrink-0 mt-0.5"}),f.hours]}),s.jsxs("div",{className:"mt-5 flex gap-3",children:[s.jsx("a",{href:f.map,target:"_blank",rel:"noreferrer",className:"rmc-btn !py-2.5 !px-4 !text-[0.7rem]",children:"Directions"}),s.jsx("a",{href:r.phoneHref,className:"rmc-btn rmc-btn-ghost !py-2.5 !px-4 !text-[0.7rem]",children:"Call"})]})]})]},f.key))})]})}),r.communities.length>0&&s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsx(WL,{eyebrow:`Explore ${r.regionNick}`,title:"Communities we call home."}),s.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-4",children:r.communities.slice(0,4).map((f,p)=>s.jsxs(Wr,{to:rC(f.name),className:`rmc-reveal relative overflow-hidden rounded-[1.25rem] rmc-zoom rmc-light ${p===0?"lg:col-span-2 lg:row-span-2 h-[300px] lg:h-full min-h-[300px]":"h-[300px]"}`,children:[s.jsx("img",{src:f.image,alt:"",loading:"lazy",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 rmc-hero-shade"}),s.jsxs("div",{className:"absolute bottom-0 p-6",children:[s.jsx("p",{className:"rmc-eyebrow opacity-80",children:f.county}),s.jsx("p",{className:"rmc-display text-4xl",children:f.name})]})]},f.name))}),s.jsx("div",{className:"mt-8",children:s.jsxs(Wr,{to:"/communities",className:"rmc-btn rmc-btn-blue",children:["All communities ",s.jsx(Ds,{className:"h-4 w-4"})]})})]}),n&&o.length>0&&s.jsx("section",{className:"rmc-bg-paper",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-6",children:[s.jsx(WL,{eyebrow:"Our people",title:"Meet a few of our agents."}),s.jsxs(Wr,{to:"/agents",className:"rmc-btn mb-12",children:["All ",i.length," agents ",s.jsx(Ds,{className:"h-4 w-4"})]})]}),s.jsx("div",{className:"grid gap-5 grid-cols-2 md:grid-cols-4",children:o.map(f=>s.jsx(xO,{a:f},f.user_id))})]})}),n&&s.jsxs("section",{className:"relative overflow-hidden rmc-bg-blue",children:[s.jsx("img",{src:k1.url,alt:"","aria-hidden":!0,className:"rmc-balloon left-[6%] top-10 h-32 w-auto opacity-30"}),s.jsxs("div",{className:"relative mx-auto max-w-[1400px] px-5 lg:px-10 py-20 grid gap-8 md:grid-cols-[1fr_auto] items-center",children:[s.jsxs("div",{children:[s.jsx("p",{className:"rmc-eyebrow mb-3 opacity-80",children:"Careers"}),s.jsx("p",{className:"rmc-display text-4xl md:text-5xl max-w-2xl",children:"Grow your business with the most recognized name in real estate."})]}),s.jsxs(Wr,{to:"/join",className:"rmc-btn",children:["Join our team ",s.jsx(Ds,{className:"h-4 w-4"})]})]})]}),s.jsx(Tx,{siteConfig:t})]})}function YDt({siteConfig:t}){const e=Om(),r=zu(),{data:n=[],isLoading:i}=TK(e.mode==="agent"?null:t.id),[o,c]=C.useState(""),[a,f]=C.useState(""),p=C.useMemo(()=>n.filter(y=>{const v=(y.full_name||"").toLowerCase();return!(o&&!v.includes(o.toLowerCase())&&!(y.team_name||"").toLowerCase().includes(o.toLowerCase())||a&&!(v.split(" ").pop()||"").startsWith(a.toLowerCase()))}),[n,o,a]);return e.mode==="agent"?s.jsx(ci,{to:"/about",replace:!0}):e.mode==="team"?s.jsxs(s.Fragment,{children:[s.jsx(Sx,{title:`Our Team | ${e.name}`,description:`Meet the REALTORS® of ${e.name}, ${r.name}.`}),s.jsx(p_,{eyebrow:"Our team",title:`Meet the ${e.name}.`,intro:"Local REALTORS® who work together for you.",image:r.images.team}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-14",children:[s.jsx("p",{className:"text-sm rmc-soft",children:i?"Loading team…":`${n.length} team member${n.length===1?"":"s"}`}),s.jsx("div",{className:"mt-6 grid gap-5 grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:n.map(y=>s.jsx(xO,{a:y},y.user_id))})]}),s.jsx(Tx,{siteConfig:t,heading:"Talk to our team."})]}):s.jsxs(s.Fragment,{children:[s.jsx(Sx,{title:`Our Agents | ${r.name}`,description:`Find a ${r.name} REALTOR® in ${r.region}.`}),s.jsx(p_,{eyebrow:"Agent directory",title:"Find your agent.",intro:`${n.length||r.agentCount||"Local"} REALTORS® across ${r.region}.`,image:r.images.team}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-14",children:[s.jsxs("div",{className:"rmc-card p-4 flex flex-col md:flex-row gap-4 md:items-center",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(xd,{className:"h-4 w-4 absolute left-4 top-1/2 -translate-y-1/2 rmc-soft"}),s.jsx("input",{className:"rmc-input !pl-11",placeholder:"Search by name or team",value:o,onChange:y=>c(y.target.value),"aria-label":"Search agents"})]}),s.jsx("div",{className:"flex flex-wrap gap-1","aria-label":"Filter by last name",children:["",..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")].map(y=>s.jsx("button",{onClick:()=>f(y),className:`h-8 min-w-8 px-2 rounded-full text-xs font-semibold ${a===y?"rmc-bg-blue":"hover:rmc-bg-mist"}`,children:y||"All"},y||"all"))})]}),s.jsx("p",{className:"mt-6 text-sm rmc-soft",children:i?"Loading agents…":`${p.length} agent${p.length===1?"":"s"}`}),s.jsx("div",{className:"mt-6 grid gap-5 grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:p.map(y=>s.jsx(xO,{a:y},y.user_id))})]}),s.jsx(Tx,{siteConfig:t,heading:"Not sure who to call?"})]})}function ZDt({siteConfig:t}){const e=zu();return s.jsxs(s.Fragment,{children:[s.jsx(Sx,{title:`Offices | ${e.name}`,description:`Visit ${e.name} in ${e.region}.`}),s.jsx(p_,{eyebrow:"Visit us",title:e.offices.length>1?`${e.offices.length} offices. One team.`:"Come see us.",intro:e.phone?`Call any office at ${e.phone}.`:`Serving ${e.region}.`,image:e.images.offices}),s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-20 space-y-10",children:e.offices.map((r,n)=>s.jsxs("div",{className:`rmc-card overflow-hidden grid md:grid-cols-2 ${n%2?"md:[&>*:first-child]:order-2":""}`,children:[s.jsx("div",{className:"h-72 md:h-auto overflow-hidden",children:s.jsx("img",{src:r.image,alt:"",loading:"lazy",className:"h-full w-full object-cover"})}),s.jsxs("div",{className:"p-10 md:p-14",children:[s.jsx("p",{className:"rmc-eyebrow rmc-red mb-3",children:n===0?"Main office":"Branch office"}),s.jsx("h2",{className:"rmc-display text-5xl",children:r.name}),s.jsx("p",{className:"mt-4 rmc-soft",children:r.note}),s.jsxs("div",{className:"mt-6 space-y-2 text-sm",children:[s.jsxs("p",{className:"flex gap-2",children:[s.jsx(Es,{className:"h-4 w-4 rmc-blue mt-0.5"}),r.address,", ",r.cityLine]}),s.jsxs("p",{className:"flex gap-2",children:[s.jsx(Dl,{className:"h-4 w-4 rmc-blue mt-0.5"}),r.hours]}),s.jsxs("p",{className:"flex gap-2",children:[s.jsx(ri,{className:"h-4 w-4 rmc-blue mt-0.5"}),s.jsx("a",{href:e.phoneHref,children:e.phone})]})]}),s.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[s.jsx("a",{href:r.map,target:"_blank",rel:"noreferrer",className:"rmc-btn",children:"Get directions"}),s.jsxs(Wr,{to:rC(r.name),className:"rmc-btn rmc-btn-blue",children:["Homes in ",r.name]})]})]})]},r.key))}),s.jsx(Tx,{siteConfig:t})]})}function XDt({siteConfig:t}){y5();const e=zu();return s.jsxs(s.Fragment,{children:[s.jsx(Sx,{title:`${e.region} Communities | ${e.name}`,description:`Explore homes for sale in ${e.communities.map(r=>r.name).join(", ")||e.region}.`}),s.jsx(p_,{eyebrow:"Communities",title:`Explore ${e.regionNick}.`,intro:"Neighborhood guides, market snapshots and every listing in the towns we serve.",image:e.images.hero}),s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-20 grid gap-6 sm:grid-cols-2 lg:grid-cols-3",children:e.communities.map(r=>s.jsxs(Wr,{to:rC(r.name),className:"rmc-reveal rmc-card overflow-hidden group",children:[s.jsx("div",{className:"h-56 overflow-hidden rmc-zoom",children:s.jsx("img",{src:r.image,alt:"",loading:"lazy",className:"h-full w-full object-cover"})}),s.jsxs("div",{className:"p-6",children:[s.jsx("p",{className:"rmc-eyebrow rmc-red",children:r.county}),s.jsx("p",{className:"rmc-display text-3xl mt-1",children:r.name}),s.jsx("p",{className:"mt-2 text-sm rmc-soft",children:r.blurb}),s.jsxs("span",{className:"mt-4 inline-flex items-center gap-1 text-xs font-semibold uppercase tracking-wider rmc-blue",children:["Homes for sale ",s.jsx(Ds,{className:"h-3.5 w-3.5 transition group-hover:translate-x-1"})]})]})]},r.name))}),s.jsx(Tx,{siteConfig:t,defaultIntent:"relocate",heading:`Moving to ${e.region}?`})]})}function x5({siteConfig:t,seo:e,hero:r,points:n,intent:i,heading:o,children:c}){y5();const a=Om(),f=zu(),p=a.mode==="brokerage"?f.name:`${a.name} | ${f.name}`;return s.jsxs(s.Fragment,{children:[s.jsx(Sx,{title:e[0].replace(f.name,p),description:e[1]}),s.jsx(p_,{...r}),s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-20 grid gap-6 md:grid-cols-3",children:n.map(([y,v],T)=>s.jsxs("div",{className:"rmc-reveal rmc-card p-8",children:[s.jsx("span",{className:`inline-flex h-10 w-10 items-center justify-center rounded-full text-sm font-bold ${T%2?"rmc-bg-blue":"bg-[hsl(var(--rmc-red))] text-[hsl(var(--rmc-paper))]"}`,children:T+1}),s.jsx("p",{className:"rmc-display text-2xl mt-5",children:y}),s.jsx("p",{className:"mt-2 rmc-soft text-sm leading-relaxed",children:v})]},y))}),c,s.jsx(Tx,{siteConfig:t,defaultIntent:i,heading:o})]})}function QDt({siteConfig:t}){const e=zu();return s.jsx(x5,{siteConfig:t,intent:"buy",heading:"Ready to start looking?",seo:[`Buy a Home in ${e.region} | ${e.name}`,`Search every ${e.region} listing and buy with a local ${e.name} agent.`],hero:{eyebrow:"Buying",title:"Find the one.",intro:"Every MLS listing, instant alerts and an agent who knows the neighborhood.",image:e.images.buy},points:[["Search everything",`Every home listed in ${e.mls}, updated throughout the day, with saved searches and alerts.`],["Local guidance","Schools, commutes, farms and neighborhoods — from agents who live here."],["Negotiate with confidence","Offer strategy and a QSC service guarantee from the first showing to closing."]],children:s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pb-20",children:s.jsx(Hp,{siteConfig:t,accentColor:"#DC1C2E",cities:e.cities||void 0,mode:"new_listings",sectionTitle:"Newest Listings",count:12})})})}function JDt({siteConfig:t}){const e=zu();return s.jsx(x5,{siteConfig:t,intent:"value",heading:"What’s your home worth?",seo:[`Sell Your Home in ${e.region} | ${e.name}`,`Get a free home value and sell with ${e.name}.`],hero:{eyebrow:"Selling",title:"Sell smarter. Net more.",intro:"Pricing from live MLS data, and marketing with the reach of the RE/MAX network.",image:e.images.sell},points:[["Price it right","A comparative market analysis built on today’s sales, not last quarter’s headlines."],["Market it everywhere","Professional photography, MLS syndication and the global RE/MAX network."],["Close with care","Offer review, negotiation and a team that sees every detail through to closing."]]})}function eMt({siteConfig:t}){var i;const e=Om(),r=zu(),{data:n=[]}=TK(e.mode==="team"?t.id:null);if(y5(),e.mode!=="brokerage"){const o=(e.bio||"").split(/\n\s*\n/).map(c=>c.trim()).filter(Boolean);return s.jsxs(s.Fragment,{children:[s.jsx(Sx,{title:`About ${e.name} | ${r.name}`,description:`Get to know ${e.name} of ${r.name}, serving ${r.region}.`}),s.jsx(p_,{eyebrow:e.mode==="team"?"About the team":`About ${e.first}`,title:e.name,intro:`${e.title} · ${r.name}`,image:((i=t.themeConfig)==null?void 0:i.heroImageUrl)||r.images.hero}),s.jsx(h2e,{siteConfig:t,roster:n}),o.length>2&&e.mode==="agent"&&s.jsx("section",{className:"mx-auto max-w-3xl px-5 lg:px-10 pb-20 space-y-4 text-lg rmc-soft",children:o.slice(2).map((c,a)=>s.jsx("p",{children:c},a))}),s.jsx(Tx,{siteConfig:t,heading:"Let’s talk."})]})}return s.jsx(x5,{siteConfig:t,intent:"buy",heading:"Let’s talk.",seo:[`About ${r.name} | ${r.region}`,`${r.name}, serving ${r.regionNick}${r.founded?` since ${r.founded}`:""}.`],hero:{eyebrow:"Our story",title:r.founded?`Rooted in ${r.regionNick} since ${r.founded}.`:`Rooted in ${r.regionNick}.`,intro:`${r.name}${r.agentCount?` — ${r.agentCount} REALTORS®`:""} ready to work for you across ${r.region}.`,image:r.images.hero},points:[[r.founded?`Local since ${r.founded}`:"Truly local",`We help families buy, sell and invest across ${r.region}.`],["Quality Service Certified","Our agents earn the QSC designation and put their service guarantee in writing."],["Giving back","Our agents support Children’s Miracle Network, Habitat for Humanity, CASA and many more causes close to home."]]})}function tMt({siteConfig:t}){const e=zu();return Om().mode!=="brokerage"?s.jsx(ci,{to:"/contact",replace:!0}):s.jsx(x5,{siteConfig:t,intent:"join",heading:"Let’s talk about your career.",seo:[`Join ${e.name} | Real Estate Careers in ${e.state||e.region}`,`Grow your real estate career with ${e.name} in ${e.region}.`],hero:{eyebrow:"Careers",title:"Build your business here.",intro:"The most recognized brand in real estate, with local leadership in your corner.",image:e.images.careers},points:[["A global brand","The RE/MAX balloon opens doors — and referrals — around the world."],[e.offices.length>1?`${e.offices.length} offices`:"Local support",e.offices.length?`Work from ${e.offices.map(r=>r.name).join(", ")} with real support staff.`:"Local leadership and real support staff in your corner."],["Modern tools","Your own IDX website, CRM, marketing and video tools through LevelUp."]]})}function rMt({siteConfig:t}){const e=Om(),r=zu(),n=e.mode==="brokerage";return s.jsxs(s.Fragment,{children:[s.jsx(Sx,{title:`Contact ${e.name}`,description:`Call ${e.phone} or send a message to ${e.name}.`}),s.jsx(p_,{eyebrow:"Contact",title:e.mode==="agent"?"Let’s talk.":"We’re here to help.",intro:n?`Call ${e.phone}${r.tollFree?` · toll-free ${r.tollFree}`:""}`:`Call ${e.phone}${e.email?` · ${e.email}`:""}`,image:r.images.contact}),s.jsx(Tx,{siteConfig:t,heading:"Send us a message."})]})}function nMt({children:t}){return s.jsx("div",{className:"rmc-bg-paper min-h-[70vh]",children:t})}function jK(t,e){const r=(e||"").trim(),n=(t||"").trim(),i=n.split(/\s+[|–—-]\s+/)[0].trim();return i&&i.length<=40?r&&i.toLowerCase()===r.toLowerCase()?`${r} Real Estate`:i:r?`${r} Real Estate`:n||"Real Estate"}function iMt(t,e){const r=jK(t,e),n=(e||"").trim(),i=[n,n?`${n} Realtor`:"",(t||"").trim()].map(o=>o.trim()).filter(o=>o&&o.toLowerCase()!==r.toLowerCase());return Array.from(new Set(i))}function AK({siteConfig:t,pagePath:e}){const r=t.agent;if(!r)return null;const n=t.customDomain?`https://${t.customDomain}`:`https://${t.subdomainSlug}.thelocalmove.com`,i=t.id==="7605cc2e-ce21-4f4f-8bb1-4c0f217b1109",o=!wx(t),a=(r.areas_served||"").split(/,|;|\|/).map(J=>J.trim()).filter(Boolean),f=a[0]||"",[p,y]=f.split(/,\s*/),v=(r.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],T=[...new Set(v.map(J=>J.toUpperCase()))],E=t.testimonials||[],k=E.length?{"@type":"AggregateRating",ratingValue:(E.reduce((J,Q)=>J+(Q.rating||5),0)/E.length).toFixed(1),reviewCount:E.length,bestRating:5,worstRating:1}:void 0,P=[r.google_business_url,r.zillow_profile_url,r.realtor_profile_url,r.linkedin_url,r.facebook_url,r.instagram_url].filter(Boolean),R=(r.specialties||"").split(/,|;|\n/).map(J=>J.trim()).filter(Boolean),D={"@context":"https://schema.org","@type":["RealEstateAgent","LocalBusiness"],"@id":`${n}/#agent`,name:r.full_name,url:n,image:r.avatar_url||t.ogImageUrl||void 0,logo:t.ogImageUrl||r.avatar_url||void 0,email:r.email,telephone:r.phone||void 0,jobTitle:i?"Personal Real Estate Advisor":r.title||"Real Estate Agent",description:r.bio||`${r.full_name} is a trusted local real estate professional${f?` serving ${f}`:""}.`,priceRange:"$$",...P.length&&{sameAs:P},...t.brokerageLegalName&&{worksFor:{"@type":"RealEstateAgent",name:t.brokerageLegalName,...t.brokerageLicenseNumber&&{identifier:t.brokerageLicenseNumber}}},...t.agentLicenseNumber&&{identifier:t.agentLicenseNumber},...p&&{address:{"@type":"PostalAddress",addressLocality:p,...y&&{addressRegion:y},addressCountry:"US"}},...a.length&&{areaServed:a.map(J=>{const[Q,ee]=J.split(/,\s*/);return{"@type":"City",name:Q,...ee&&{containedInPlace:{"@type":"State",name:ee}}}})},...k&&{aggregateRating:k},...E.length&&{review:E.slice(0,10).map(J=>({"@type":"Review",author:{"@type":"Person",name:J.name},reviewBody:J.text,reviewRating:{"@type":"Rating",ratingValue:J.rating||5,bestRating:5,worstRating:1},...J.location&&{locationCreated:{"@type":"Place",name:J.location}}}))}},M={"@context":"https://schema.org","@type":"Person","@id":`${n}/#person`,name:r.full_name,jobTitle:i?"Personal Real Estate Advisor":r.title||"Real Estate Agent",description:r.bio||void 0,image:r.avatar_url||void 0,url:n,email:r.email,telephone:r.phone||void 0,...i&&{email:"Tom@TomLois.com",telephone:"520-271-2716",address:{"@type":"PostalAddress",addressLocality:"Columbia",addressRegion:"Missouri",addressCountry:"US"}},...P.length&&{sameAs:P},knowsAbout:[...new Set([...R,"Residential Real Estate","Home Buying","Home Selling",...a.map(J=>`${J} Real Estate`)])].filter(Boolean).slice(0,25),...R.length&&{makesOffer:R.slice(0,12).map(J=>({"@type":"Offer",itemOffered:{"@type":"Service",name:J,serviceType:"Real Estate Service"}}))},...T.length&&{hasCredential:T.map(J=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:J}))},...t.brokerageLegalName&&{worksFor:{"@type":"Organization",name:t.brokerageLegalName}}},B=jK(t.siteTitle,r.full_name),V=iMt(t.siteTitle,r.full_name),G={"@context":"https://schema.org","@type":"WebSite","@id":`${n}/#website`,name:B,...V.length?{alternateName:V}:{},url:n,publisher:{"@id":`${n}/#agent`},...o&&{potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${n}/search?q={search_term_string}`},"query-input":"required name=search_term_string"}}},W=[...o?[{name:"Search Homes",description:`Browse all current MLS listings${f?` in ${f}`:""}.`,path:"/search"}]:[],{name:"Featured Areas",description:"Explore featured neighborhoods, cities, and communities.",path:"/areas"},...o?[{name:"Sold Properties",description:"See recently sold homes and local market activity.",path:"/sold"}]:[],{name:"Home Valuation",description:"Get a free, no-obligation estimate of what your home is worth.",path:"/sell"},{name:"About",description:`Learn more about ${r.full_name}${t.brokerageLegalName?` and ${t.brokerageLegalName}`:""}.`,path:"/about"},{name:"Contact",description:`Get in touch with ${r.full_name} for buying, selling, or relocation help.`,path:"/contact"}],Y={"@context":"https://schema.org","@type":"ItemList","@id":`${n}/#nav`,name:"Main Navigation",itemListElement:W.map((J,Q)=>({"@type":"SiteNavigationElement",position:Q+1,name:J.name,description:J.description,url:`${n}${J.path}`}))};return s.jsxs(Zo,{children:[s.jsx("script",{type:"application/ld+json",children:JSON.stringify(D)}),s.jsx("script",{type:"application/ld+json",children:JSON.stringify(M)}),s.jsx("script",{type:"application/ld+json",children:JSON.stringify(G)}),s.jsx("script",{type:"application/ld+json",children:JSON.stringify(Y)})]})}function GHt({items:t,siteConfig:e}){const r=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug}.thelocalmove.com`,n={"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:t.map((i,o)=>({"@type":"ListItem",position:o+1,name:i.name,item:`${r}${i.path}`}))};return s.jsx(Zo,{children:s.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function HHt({listing:t,siteConfig:e}){var i;const r=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug}.thelocalmove.com`,n={"@context":"https://schema.org","@type":"SingleFamilyResidence",name:`${t.address}, ${t.city}, ${t.state} ${t.zip}`,url:`${r}/listing/${t.mlsNumber}`,image:((i=t.photos)==null?void 0:i[0])||void 0,numberOfRooms:t.bedrooms,numberOfBathroomsTotal:t.bathrooms,floorSize:t.sqft?{"@type":"QuantitativeValue",value:t.sqft,unitCode:"FTK"}:void 0,address:{"@type":"PostalAddress",streetAddress:t.address,addressLocality:t.city,addressRegion:t.state,postalCode:t.zip},...t.latitude&&t.longitude&&{geo:{"@type":"GeoCoordinates",latitude:t.latitude,longitude:t.longitude}},offers:{"@type":"Offer",price:t.price,priceCurrency:"USD",availability:t.status==="Active"?"https://schema.org/InStock":"https://schema.org/SoldOut"},...t.yearBuilt&&{yearBuilt:t.yearBuilt}};return s.jsx(Zo,{children:s.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function sMt({faqs:t}){if(!t.length)return null;const e={"@context":"https://schema.org","@type":"FAQPage",mainEntity:t.map(r=>({"@type":"Question",name:r.question,acceptedAnswer:{"@type":"Answer",text:r.answer}}))};return s.jsx(Zo,{children:s.jsx("script",{type:"application/ld+json",children:JSON.stringify(e)})})}function WHt({title:t,description:e,publishedAt:r,modifiedAt:n,imageUrl:i,slug:o,siteConfig:c}){const a=c.customDomain?`https://${c.customDomain}`:`https://${c.subdomainSlug}.thelocalmove.com`,f=c.agent,p={"@context":"https://schema.org","@type":"Article",headline:t,description:e,url:`${a}/blog/${o}`,datePublished:r,dateModified:n||r,...i&&{image:i},author:f?{"@type":"Person",name:f.full_name,url:a}:void 0,publisher:{"@type":"Organization",name:c.siteTitle||(f==null?void 0:f.full_name)||"Agent",url:a}};return s.jsx(Zo,{children:s.jsx("script",{type:"application/ld+json",children:JSON.stringify(p)})})}function KHt({videoId:t,title:e,description:r,thumbnailUrl:n,uploadDate:i,durationSeconds:o}){const c=o&&o>0?o:null,a=c?`PT${Math.floor(c/3600)?`${Math.floor(c/3600)}H`:""}${Math.floor(c%3600/60)}M${c%60}S`:void 0,f={"@context":"https://schema.org","@type":"VideoObject",name:e,description:r,thumbnailUrl:n||`https://i.ytimg.com/vi/${t}/maxresdefault.jpg`,...i&&{uploadDate:i},...a&&{duration:a},embedUrl:`https://www.youtube.com/embed/${t}`,contentUrl:`https://www.youtube.com/watch?v=${t}`};return s.jsx(Zo,{children:s.jsx("script",{type:"application/ld+json",children:JSON.stringify(f)})})}const aMt="Home Valuation";function oMt(t){return(t.valuationLabel||"").trim()||aMt}function lMt(t){return t.split(" ").map(e=>e.length>1&&e===e.toUpperCase()?e:e.toLowerCase()).join(" ")}function kK({siteConfig:t}){var R;const e=ki(),r=t.agent,n=/faq|frequently-asked/i.test(e.pathname);if(!r||!n)return null;const i=r.full_name,o=t.brokerageLegalName||"their brokerage",c=r.areas_served||"the local market",a=((R=c.split(/,|;|\|/)[0])==null?void 0:R.trim())||"the local area",f=r.years_experience,p=r.phone||"",y=r.email,v=t.agentLicenseNumber,T=!wx(t),E=(r.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],k=[...new Set(E.map(D=>D.toUpperCase()))],P=[{question:`Who is ${i}?`,answer:`${i} is a ${r.title||"REALTOR®"} with ${o}${f?`, with ${f}+ years of local real estate experience`:""} serving ${c}. ${r.bio||""}`.trim()},{question:`What areas does ${i} serve?`,answer:`${i} serves ${c} and surrounding communities. Whether you're buying, selling, relocating, or downsizing, ${i.split(" ")[0]} provides expert local guidance.`},{question:`How can I contact ${i}?`,answer:`You can reach ${i} by ${p?`phone at ${p}, `:""}email at ${y}, or by booking a consultation directly through this website.`},...k.length?[{question:`What real estate designations does ${i} hold?`,answer:`${i} holds the following professional designations: ${k.join(", ")}. These designations represent advanced training in specialized areas of real estate.`}]:[],...v?[{question:`Is ${i} a licensed real estate agent?`,answer:`Yes, ${i} is a fully licensed real estate professional (License #${v}) with ${o}.`}]:[],...T?[{question:`How do I search for homes for sale in ${a}?`,answer:`Use the property search on this site to view current MLS listings in ${a}. You can filter by price, bedrooms, neighborhood, and more, and save searches to receive email alerts when new homes match your criteria.`}]:[],{question:`What is the home buying process like in ${a}?`,answer:T?`${i} guides buyers through every step: getting pre-approved, searching MLS listings, touring homes, writing competitive offers, navigating inspections and appraisals, and closing on schedule. Contact ${i.split(" ")[0]} for a buyer consultation.`:`${i} guides buyers through every step: getting pre-approved, identifying suitable properties, touring homes, writing competitive offers, navigating inspections and appraisals, and closing on schedule. Contact ${i.split(" ")[0]} for a buyer consultation.`},{question:`How do I find out what my home is worth in ${a}?`,answer:`Request a free, no-obligation ${lMt(oMt(t))} from ${i}. ${i.split(" ")[0]} reviews recent local sales and current market conditions in ${a} to give you a realistic picture of your home's value.`}];return s.jsx(sMt,{faqs:P})}const pn=Number.isFinite||function(t){return typeof t=="number"&&isFinite(t)},cMt=Number.isSafeInteger||function(t){return typeof t=="number"&&Math.abs(t)<=uMt},uMt=Number.MAX_SAFE_INTEGER||9007199254740991;let Dn=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),Jt=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.UNKNOWN="unknown",t}({}),Ce=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});var Wi={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Tn={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Ew{constructor(e,r=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=r,this.totalWeight_=n}sample(e,r){const n=Math.pow(this.alpha_,e);this.estimate_=r*(1-n)+n*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class dMt{constructor(e,r,n,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ew(e),this.fast_=new Ew(r),this.defaultTTFB_=i,this.ttfb_=new Ew(e)}update(e,r){const{slow_:n,fast_:i,ttfb_:o}=this;n.halfLife!==e&&(this.slow_=new Ew(e,n.getEstimate(),n.getTotalWeight())),i.halfLife!==r&&(this.fast_=new Ew(r,i.getEstimate(),i.getTotalWeight())),o.halfLife!==e&&(this.ttfb_=new Ew(e,o.getEstimate(),o.getTotalWeight()))}sample(e,r){e=Math.max(e,this.minDelayMs_);const n=8*r,i=e/1e3,o=n/i;this.fast_.sample(i,o),this.slow_.sample(i,o)}sampleTTFB(e){const r=e/1e3,n=Math.sqrt(2)*Math.exp(-Math.pow(r,2)/2);this.ttfb_.sample(n,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function hMt(t,e,r){return(e=mMt(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Js(){return Js=Object.assign?Object.assign.bind():function(t){for(var e=1;e`):Ey}function hce(t,e,r){return e[t]?e[t].bind(e):gMt(t,r)}const iG=nG();function yMt(t,e,r){const n=nG();if(typeof console=="object"&&t===!0||typeof t=="object"){const i=["debug","log","info","warn","error"];i.forEach(o=>{n[o]=hce(o,t,r)});try{n.log(`Debug logs enabled for "${e}" in hls.js version 1.6.16`)}catch{return nG()}i.forEach(o=>{iG[o]=hce(o,t)})}else Js(iG,n);return n}const qs=iG;function Ex(t=!0){return typeof self>"u"?void 0:(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function xMt(t){return typeof self<"u"&&t===self.ManagedMediaSource}function f2e(t,e){const r=Object.keys(t),n=Object.keys(e),i=r.length,o=n.length;return!i||!o||i===o&&!r.some(c=>n.indexOf(c)===-1)}function pd(t,e=!1){if(typeof TextDecoder<"u"){const p=new TextDecoder("utf-8").decode(t);if(e){const y=p.indexOf("\0");return y!==-1?p.substring(0,y):p}return p.replace(/\0/g,"")}const r=t.length;let n,i,o,c="",a=0;for(;a>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:c+=String.fromCharCode(n);break;case 12:case 13:i=t[a++],c+=String.fromCharCode((n&31)<<6|i&63);break;case 14:i=t[a++],o=t[a++],c+=String.fromCharCode((n&15)<<12|(i&63)<<6|(o&63)<<0);break}}return c}function Xl(t){let e="";for(let r=0;r1||i===1&&(r=this.levelkeys[n[0]])!=null&&r.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!pn(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Io(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const r=this.levelkeys;if(r){var n;const i=r[e];i&&!((n=this._decryptdata)!=null&&n.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,r))}}abortRequests(){var e,r;(e=this.loader)==null||e.abort(),(r=this.keyLoader)==null||r.abort()}setElementaryStreamInfo(e,r,n,i,o,c=!1){const{elementaryStreams:a}=this,f=a[e];if(!f){a[e]={startPTS:r,endPTS:n,startDTS:i,endDTS:o,partial:c};return}f.startPTS=Math.min(f.startPTS,r),f.endPTS=Math.max(f.endPTS,n),f.startDTS=Math.min(f.startDTS,i),f.endDTS=Math.max(f.endDTS,o)}}class bMt extends p2e{constructor(e,r,n,i,o){super(n),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=r,this.index=i;const c=e.enumeratedString("BYTERANGE");c&&this.setByteRange(c,o),o&&(this.fragOffset=o.fragOffset+o.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function g2e(t,e){const r=Object.getPrototypeOf(t);if(r){const n=Object.getOwnPropertyDescriptor(r,e);return n||g2e(r,e)}}function wMt(t,e){const r=g2e(t,e);r&&(r.enumerable=!0,Object.defineProperty(t,e,r))}const mce=Math.pow(2,32)-1,SMt=[].push,y2e={video:1,audio:2,id3:3,text:4};function cl(t){return String.fromCharCode.apply(null,t)}function x2e(t,e){const r=t[e]<<8|t[e+1];return r<0?65536+r:r}function xi(t,e){const r=v2e(t,e);return r<0?4294967296+r:r}function pce(t,e){let r=xi(t,e);return r*=Math.pow(2,32),r+=xi(t,e+4),r}function v2e(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function TMt(t){const e=t.byteLength;for(let r=0;r8&&t[r+4]===109&&t[r+5]===111&&t[r+6]===111&&t[r+7]===102)return!0;r=n>1?r+n:e}return!1}function Hi(t,e){const r=[];if(!e.length)return r;const n=t.byteLength;for(let i=0;i1?i+o:n;if(c===e[0])if(e.length===1)r.push(t.subarray(i+8,a));else{const f=Hi(t.subarray(i+8,a),e.slice(1));f.length&&SMt.apply(r,f)}i=a}return r}function EMt(t){const e=[],r=t[0];let n=8;const i=xi(t,n);n+=4;let o=0,c=0;r===0?(o=xi(t,n),c=xi(t,n+4),n+=8):(o=pce(t,n),c=pce(t,n+8),n+=16),n+=2;let a=t.length+c;const f=x2e(t,n);n+=2;for(let p=0;p>>31===1)return qs.warn("SIDX has hierarchical references (not supported)"),null;const k=xi(t,y);y+=4,e.push({referenceSize:T,subsegmentDuration:k,info:{duration:k/i,start:a,end:a+T-1}}),a+=T,y+=4,n=y}return{earliestPresentationTime:o,timescale:i,version:r,referencesCount:f,references:e}}function _2e(t){const e=[],r=Hi(t,["moov","trak"]);for(let i=0;i{const o=xi(i,4),c=e[o];c&&(c.default={duration:xi(i,12),flags:xi(i,20)})}),e}function jMt(t){const e=t.subarray(8),r=e.subarray(86),n=cl(e.subarray(4,8));let i=n,o;const c=n==="enca"||n==="encv";if(c){const p=Hi(e,[n])[0].subarray(n==="enca"?28:78);Hi(p,["sinf"]).forEach(v=>{const T=Hi(v,["schm"])[0];if(T){const E=cl(T.subarray(4,8));if(E==="cbcs"||E==="cenc"){const k=Hi(v,["frma"])[0];k&&(i=cl(k))}}})}const a=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const f=Hi(r,["avcC"])[0];f&&f.length>3&&(i+="."+WR(f[1])+WR(f[2])+WR(f[3]),o=HR(a==="avc1"?"dva1":"dvav",r));break}case"mp4a":{const f=Hi(e,[n])[0],p=Hi(f.subarray(28),["esds"])[0];if(p&&p.length>7){let y=4;if(p[y++]!==3)break;y=h6(p,y),y+=2;const v=p[y++];if(v&128&&(y+=2),v&64&&(y+=p[y++]),p[y++]!==4)break;y=h6(p,y);const T=p[y++];if(T===64)i+="."+WR(T);else break;if(y+=12,p[y++]!==5)break;y=h6(p,y);const E=p[y++];let k=(E&248)>>3;k===31&&(k+=1+((E&7)<<3)+((p[y]&224)>>5)),i+="."+k}break}case"hvc1":case"hev1":{const f=Hi(r,["hvcC"])[0];if(f&&f.length>12){const p=f[1],y=["","A","B","C"][p>>6],v=p&31,T=xi(f,2),E=(p&32)>>5?"H":"L",k=f[12],P=f.subarray(6,12);i+="."+y+v,i+="."+AMt(T).toString(16).toUpperCase(),i+="."+E+k;let R="";for(let D=P.length;D--;){const M=P[D];(M||R)&&(R="."+M.toString(16).toUpperCase()+R)}i+=R}o=HR(a=="hev1"?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=HR(i,r)||i;break}case"vp09":{const f=Hi(r,["vpcC"])[0];if(f&&f.length>6){const p=f[4],y=f[5],v=f[6]>>4&15;i+="."+Qf(p)+"."+Qf(y)+"."+Qf(v)}break}case"av01":{const f=Hi(r,["av1C"])[0];if(f&&f.length>2){const p=f[1]>>>5,y=f[1]&31,v=f[2]>>>7?"H":"M",T=(f[2]&64)>>6,E=(f[2]&32)>>5,k=p===2&&T?E?12:10:T?10:8,P=(f[2]&16)>>4,R=(f[2]&8)>>3,D=(f[2]&4)>>2,M=f[2]&3;i+="."+p+"."+Qf(y)+v+"."+Qf(k)+"."+P+"."+R+D+M+"."+Qf(1)+"."+Qf(1)+"."+Qf(1)+"."+0,o=HR("dav1",r)}break}}return{codec:i,encrypted:c,supplemental:o}}function HR(t,e){const r=Hi(e,["dvvC"]),n=r.length?r[0]:Hi(e,["dvcC"])[0];if(n){const i=n[2]>>1&127,o=n[2]<<5&32|n[3]>>3&31;return t+"."+Qf(i)+"."+Qf(o)}}function AMt(t){let e=0;for(let r=0;r<32;r++)e|=(t>>r&1)<<31-r;return e>>>0}function h6(t,e){const r=e+5;for(;t[e++]&128&&e{const o=n.subarray(8,24);o.some(c=>c!==0)||(qs.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Xl(o)} -> ${Xl(r)}`),n.set(r,8))})}function CMt(t){const e=[];return b2e(t,r=>e.push(r.subarray(8,24))),e}function b2e(t,e){Hi(t,["moov","trak"]).forEach(n=>{const i=Hi(n,["mdia","minf","stbl","stsd"])[0];if(!i)return;const o=i.subarray(8);let c=Hi(o,["enca"]);const a=c.length>0;a||(c=Hi(o,["encv"])),c.forEach(f=>{const p=a?f.subarray(28):f.subarray(78);Hi(p,["sinf"]).forEach(v=>{const T=w2e(v);T&&e(T,a)})})})}function w2e(t){const e=Hi(t,["schm"])[0];if(e){const r=cl(e.subarray(4,8));if(r==="cbcs"||r==="cenc"){const n=Hi(t,["schi","tenc"])[0];if(n)return n}}}function NMt(t,e,r){const n={},i=Hi(t,["moof","traf"]);for(let o=0;on[o].duration)){let o=1/0,c=0;const a=Hi(t,["sidx"]);for(let f=0;fv+T.info.duration||0,0);c=Math.max(c,y+p.earliestPresentationTime/p.timescale)}}c&&pn(c)&&Object.keys(n).forEach(f=>{n[f].duration||(n[f].duration=c*n[f].timescale-n[f].start)})}return n}function IMt(t){const e={valid:null,remainder:null},r=Hi(t,["moof"]);if(r.length<2)return e.remainder=t,e;const n=r[r.length-1];return e.valid=t.slice(0,n.byteOffset-8),e.remainder=t.slice(n.byteOffset-8),e}function ph(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}function gce(t,e){const r=[],n=e.samples,i=e.timescale,o=e.id;let c=!1;return Hi(n,["moof"]).map(f=>{const p=f.byteOffset-8;Hi(f,["traf"]).map(v=>{const T=Hi(v,["tfdt"]).map(E=>{const k=E[0];let P=xi(E,4);return k===1&&(P*=Math.pow(2,32),P+=xi(E,8)),P/i})[0];return T!==void 0&&(t=T),Hi(v,["tfhd"]).map(E=>{const k=xi(E,4),P=xi(E,0)&16777215,R=(P&1)!==0,D=(P&2)!==0,M=(P&8)!==0;let B=0;const V=(P&16)!==0;let G=0;const W=(P&32)!==0;let Y=8;k===o&&(R&&(Y+=8),D&&(Y+=4),M&&(B=xi(E,Y),Y+=4),V&&(G=xi(E,Y),Y+=4),W&&(Y+=4),e.type==="video"&&(c=v5(e.codec)),Hi(v,["trun"]).map(J=>{const Q=J[0],ee=xi(J,0)&16777215,le=(ee&1)!==0;let pe=0;const Se=(ee&4)!==0,je=(ee&256)!==0;let Le=0;const Ae=(ee&512)!==0;let be=0;const me=(ee&1024)!==0,Te=(ee&2048)!==0;let Ne=0;const Ee=xi(J,4);let we=8;le&&(pe=xi(J,we),we+=4),Se&&(we+=4);let He=pe+p;for(let tt=0;tt>1&63;return r===39||r===40}else return(e&31)===6}function IK(t,e,r,n){const i=S2e(t);let o=0;o+=e;let c=0,a=0,f=0;for(;o=i.length)break;f=i[o++],c+=f}while(f===255);a=0;do{if(o>=i.length)break;f=i[o++],a+=f}while(f===255);const p=i.length-o;let y=o;if(ap){qs.error(`Malformed SEI payload. ${a} is too small, only ${p} bytes left to parse.`);break}if(c===4){if(i[y++]===181){const T=x2e(i,y);if(y+=2,T===49){const E=xi(i,y);if(y+=4,E===1195456820){const k=i[y++];if(k===3){const P=i[y++],R=31&P,D=64&P,M=D?2+R*3:0,B=new Uint8Array(M);if(D){B[0]=P;for(let V=1;V16){const v=[];for(let k=0;k<16;k++){const P=i[y++].toString(16);v.push(P.length==1?"0"+P:P),(k===3||k===5||k===7||k===9)&&v.push("-")}const T=a-16,E=new Uint8Array(T);for(let k=0;k>24&255,o[1]=n>>16&255,o[2]=n>>8&255,o[3]=n&255,o.set(t,4),i=0,n=8;i0?(o=new Uint8Array(4),e.length>0&&new DataView(o.buffer).setUint32(0,e.length,!1)):o=new Uint8Array;const c=new Uint8Array(4);return r.byteLength>0&&new DataView(c.buffer).setUint32(0,r.byteLength,!1),LMt([112,115,115,104],new Uint8Array([n,0,0,0]),t,o,i,c,r)}function MMt(t){const e=[];if(t instanceof ArrayBuffer){const r=t.byteLength;let n=0;for(;n+32>>24;if(o!==0&&o!==1)return{offset:r,size:e};const c=t.buffer,a=Xl(new Uint8Array(c,r+12,16));let f=null,p=null,y=0;if(o===0)y=28;else{const T=t.getUint32(28);if(!T||n<32+T*16)return{offset:r,size:e};f=[];for(let E=0;E/\(Windows.+Firefox\//i.test(navigator.userAgent),qS={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function PK(t,e){const r=qS[e];return!!r&&!!r[t.slice(0,4)]}function nC(t,e,r=!0){return!t.split(",").some(n=>!RK(n,e,r))}function RK(t,e,r=!0){var n;const i=Ex(r);return(n=i==null?void 0:i.isTypeSupported(iC(t,e)))!=null?n:!1}function iC(t,e){return`${e}/mp4;codecs=${t}`}function yce(t){if(t){const e=t.substring(0,4);return qS.video[e]}return 2}function vO(t){const e=T2e();return t.split(",").reduce((r,n)=>{const o=e&&v5(n)?9:qS.video[n];return o?(o*2+r)/(r?3:2):(qS.audio[n]+r)/(r?2:1)},0)}const f6={};function FMt(t,e=!0){if(f6[t])return f6[t];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let i=0;iFMt(r.toLowerCase(),e))}function $Mt(t,e){const r=[];if(t){const n=t.split(",");for(let i=0;i4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t)!==-1)&&(xce(t,"audio")||xce(t,"video")))return t;if(e){const r=e.split(",");if(r.length>1){if(t){for(let n=r.length;n--;)if(r[n].substring(0,4)===t.substring(0,4))return r[n]}return r[0]}}return e||t}function xce(t,e){return PK(t,e)&&RK(t,e)}function zMt(t){const e=t.split(",");for(let r=0;r2&&n[0]==="avc1"&&(e[r]=`avc1.${parseInt(n[1]).toString(16)}${("000"+parseInt(n[2]).toString(16)).slice(-4)}`)}return e.join(",")}function UMt(t){if(t.startsWith("av01.")){const e=t.split("."),r=["0","111","01","01","01","0"];for(let n=e.length;n>4&&n<10;n++)e[n]=r[n-4];return e.join(".")}return t}function vce(t){const e=Ex(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function sG(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const VMt={supported:!0,powerEfficient:!0,smooth:!0},qMt={supported:!1,smooth:!1,powerEfficient:!1},E2e={supported:!0,configurations:[],decodingInfoResults:[VMt]};function j2e(t,e){return{supported:!1,configurations:e,decodingInfoResults:[qMt],error:t}}function GMt(t,e,r,n,i,o){const c=t.videoCodec,a=t.audioCodec?t.audioGroups:null,f=o==null?void 0:o.audioCodec,p=o==null?void 0:o.channels,y=p?parseInt(p):f?1/0:2;let v=null;if(a!=null&&a.length)try{a.length===1&&a[0]?v=e.groups[a[0]].channels:v=a.reduce((T,E)=>{if(E){const k=e.groups[E];if(!k)throw new Error(`Audio track group ${E} not found`);Object.keys(k.channels).forEach(P=>{T[P]=(T[P]||0)+k.channels[P]})}return T},{2:0})}catch{return!0}return c!==void 0&&(c.split(",").some(T=>v5(T))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(n,30)||t.videoRange!=="SDR"&&t.videoRange!==r||t.bitrate>Math.max(i,8e6))||!!v&&pn(y)&&Object.keys(v).some(T=>parseInt(T)>y)}function A2e(t,e,r,n={}){const i=t.videoCodec;if(!i&&!t.audioCodec||!r)return Promise.resolve(E2e);const o=[],c=HMt(t),a=c.length,f=WMt(t,e,a>0),p=f.length;for(let y=a||1*p||1;y--;){const v={type:"media-source"};if(a&&(v.video=c[y%a]),p){v.audio=f[y%p];const T=v.audio.bitrate;v.video&&T&&(v.video.bitrate-=T)}o.push(v)}if(i){const y=navigator.userAgent;if(i.split(",").some(v=>v5(v))&&T2e())return Promise.resolve(j2e(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${y})`),o))}return Promise.all(o.map(y=>{const v=YMt(y);return n[v]||(n[v]=r.decodingInfo(y))})).then(y=>({supported:!y.some(v=>!v.supported),configurations:o,decodingInfoResults:y})).catch(y=>({supported:!1,configurations:o,decodingInfoResults:[],error:y}))}function HMt(t){var e;const r=(e=t.videoCodec)==null?void 0:e.split(","),n=k2e(t),i=t.width||640,o=t.height||480,c=t.frameRate||30,a=t.videoRange.toLowerCase();return r?r.map(f=>{const p={contentType:iC(UMt(f),"video"),width:i,height:o,bitrate:n,framerate:c};return a!=="sdr"&&(p.transferFunction=a),p}):[]}function WMt(t,e,r){var n;const i=(n=t.audioCodec)==null?void 0:n.split(","),o=k2e(t);return i&&t.audioGroups?t.audioGroups.reduce((c,a)=>{var f;const p=a?(f=e.groups[a])==null?void 0:f.tracks:null;return p?p.reduce((y,v)=>{if(v.groupId===a){const T=parseFloat(v.channels||"");i.forEach(E=>{const k={contentType:iC(E,"audio"),bitrate:r?KMt(E,o):o};T&&(k.channels=""+T),y.push(k)})}return y},c):c},[]):[]}function KMt(t,e){if(e<=1)return 1;let r=128e3;return t==="ec-3"?r=768e3:t==="ac-3"&&(r=64e4),Math.min(e/2,r)}function k2e(t){return Math.ceil(Math.max(t.bitrate*.9,t.averageBitrate)/1e3)*1e3||1}function YMt(t){let e="";const{audio:r,video:n}=t;if(n){const i=sG(n.contentType);e+=`${i}_r${n.height}x${n.width}f${Math.ceil(n.framerate)}${n.transferFunction||"sd"}_${Math.ceil(n.bitrate/1e5)}`}if(r){const i=sG(r.contentType);e+=`${n?"_":""}${i}_c${r.channels}`}return e}const aG=["NONE","TYPE-0","TYPE-1",null];function ZMt(t){return aG.indexOf(t)>-1}const bO=["SDR","PQ","HLG"];function XMt(t){return!!t&&bO.indexOf(t)>-1}var YL={No:"",Yes:"YES",v2:"v2"};function _ce(t){const{canSkipUntil:e,canSkipDateRanges:r,age:n}=t,i=n!!n).map(n=>n.substring(0,4)).join(","),"supplemental"in e){var r;this.supplemental=e.supplemental;const n=(r=e.supplemental)==null?void 0:r.videoCodec;n&&n!==e.videoCodec&&(this.codecSet+=`,${n.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return wce(this._audioGroups,e)}hasSubtitleGroup(e){return wce(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,r){if(r){if(e==="audio"){let n=this._audioGroups;n||(n=this._audioGroups=[]),n.indexOf(r)===-1&&n.push(r)}else if(e==="text"){let n=this._subtitleGroups;n||(n=this._subtitleGroups=[]),n.indexOf(r)===-1&&n.push(r)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function wce(t,e){return!e||!t?!1:t.indexOf(e)!==-1}function QMt(){if(typeof matchMedia=="function"){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return t.matches===!0}return!1}function JMt(t,e){let r=!1,n=[];if(t&&(r=t!=="SDR",n=[t]),e){n=e.allowedVideoRanges||bO.slice(0);const i=n.join("")!=="SDR"&&!e.videoCodec;r=e.preferHDR!==void 0?e.preferHDR:i&&QMt(),r||(n=["SDR"])}return{preferHDR:r,allowedVideoRanges:n}}const eOt=t=>{const e=new WeakSet;return(r,n)=>{if(t&&(n=t(r,n)),typeof n=="object"&&n!==null){if(e.has(n))return;e.add(n)}return n}},aa=(t,e)=>JSON.stringify(t,eOt(e));function tOt(t,e,r,n,i){const o=Object.keys(t),c=n==null?void 0:n.channels,a=n==null?void 0:n.audioCodec,f=i==null?void 0:i.videoCodec,p=c&&parseInt(c)===2;let y=!1,v=!1,T=1/0,E=1/0,k=1/0,P=1/0,R=0,D=[];const{preferHDR:M,allowedVideoRanges:B}=JMt(e,i);for(let J=o.length;J--;){const Q=t[o[J]];y||(y=Q.channels[2]>0),T=Math.min(T,Q.minHeight),E=Math.min(E,Q.minFramerate),k=Math.min(k,Q.minBitrate),B.filter(le=>Q.videoRanges[le]>0).length>0&&(v=!0)}T=pn(T)?T:0,E=pn(E)?E:0;const V=Math.max(1080,T),G=Math.max(30,E);k=pn(k)?k:r,r=Math.max(k,r),v||(e=void 0);const W=o.length>1;return{codecSet:o.reduce((J,Q)=>{const ee=t[Q];if(Q===J)return J;if(D=v?B.filter(le=>ee.videoRanges[le]>0):[],W){if(ee.minBitrate>r)return qf(Q,`min bitrate of ${ee.minBitrate} > current estimate of ${r}`),J;if(!ee.hasDefaultAudio)return qf(Q,"no renditions with default or auto-select sound found"),J;if(a&&Q.indexOf(a.substring(0,4))%5!==0)return qf(Q,`audio codec preference "${a}" not found`),J;if(c&&!p){if(!ee.channels[c])return qf(Q,`no renditions with ${c} channel sound found (channels options: ${Object.keys(ee.channels)})`),J}else if((!a||p)&&y&&ee.channels[2]===0)return qf(Q,"no renditions with stereo sound found"),J;if(ee.minHeight>V)return qf(Q,`min resolution of ${ee.minHeight} > maximum of ${V}`),J;if(ee.minFramerate>G)return qf(Q,`min framerate of ${ee.minFramerate} > maximum of ${G}`),J;if(!D.some(le=>ee.videoRanges[le]>0))return qf(Q,`no variants with VIDEO-RANGE of ${aa(D)} found`),J;if(f&&Q.indexOf(f.substring(0,4))%5!==0)return qf(Q,`video codec preference "${f}" not found`),J;if(ee.maxScore=vO(J)||ee.fragmentError>t[J].fragmentError)?J:(P=ee.minIndex,R=ee.maxScore,Q)},void 0),videoRanges:D,preferHDR:M,minFramerate:E,minBitrate:k,minIndex:P}}function qf(t,e){qs.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function C2e(t){return t.reduce((e,r)=>{let n=e.groups[r.groupId];n||(n=e.groups[r.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),n.tracks.push(r);const i=r.channels||"2";return n.channels[i]=(n.channels[i]||0)+1,n.hasDefault=n.hasDefault||r.default,n.hasAutoSelect=n.hasAutoSelect||r.autoselect,n.hasDefault&&(e.hasDefaultAudio=!0),n.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function rOt(t,e,r,n){return t.slice(r,n+1).reduce((i,o,c)=>{if(!o.codecSet)return i;const a=o.audioGroups;let f=i[o.codecSet];f||(i[o.codecSet]=f={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:c,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!a,fragmentError:0}),f.minBitrate=Math.min(f.minBitrate,o.bitrate);const p=Math.min(o.height,o.width);return f.minHeight=Math.min(f.minHeight,p),f.minFramerate=Math.min(f.minFramerate,o.frameRate),f.minIndex=Math.min(f.minIndex,c),f.maxScore=Math.max(f.maxScore,o.score),f.fragmentError+=o.fragmentError,f.videoRanges[o.videoRange]=(f.videoRanges[o.videoRange]||0)+1,a&&a.forEach(y=>{if(!y)return;const v=e.groups[y];v&&(f.hasDefaultAudio=f.hasDefaultAudio||e.hasDefaultAudio?v.hasDefault:v.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(v.channels).forEach(T=>{f.channels[T]=(f.channels[T]||0)+v.channels[T]}))}),i},{})}function Sce(t){if(!t)return t;const{lang:e,assocLang:r,characteristics:n,channels:i,audioCodec:o}=t;return{lang:e,assocLang:r,characteristics:n,channels:i,audioCodec:o}}function dm(t,e,r){if("attrs"in t){const n=e.indexOf(t);if(n!==-1)return n}for(let n=0;nn.indexOf(i)===-1)}function vv(t,e){const{audioCodec:r,channels:n}=t;return(r===void 0||(e.audioCodec||"").substring(0,4)===r.substring(0,4))&&(n===void 0||n===(e.channels||"2"))}function sOt(t,e,r,n,i){const o=e[n],a=e.reduce((T,E,k)=>{const P=E.uri;return(T[P]||(T[P]=[])).push(k),T},{})[o.uri];a.length>1&&(n=Math.max.apply(Math,a));const f=o.videoRange,p=o.frameRate,y=o.codecSet.substring(0,4),v=Tce(e,n,T=>{if(T.videoRange!==f||T.frameRate!==p||T.codecSet.substring(0,4)!==y)return!1;const E=T.audioGroups,k=r.filter(P=>!E||E.indexOf(P.groupId)!==-1);return dm(t,k,i)>-1});return v>-1?v:Tce(e,n,T=>{const E=T.audioGroups,k=r.filter(P=>!E||E.indexOf(P.groupId)!==-1);return dm(t,k,i)>-1})}function Tce(t,e,r){for(let n=e;n>-1;n--)if(r(t[n]))return n;for(let n=e+1;n{var n;const{fragCurrent:i,partCurrent:o,hls:c}=this,{autoLevelEnabled:a,media:f}=c;if(!i||!f)return;const p=performance.now(),y=o?o.stats:i.stats,v=o?o.duration:i.duration,T=p-y.loading.start,E=c.minAutoLevel,k=i.level,P=this._nextAutoLevel;if(y.aborted||y.loaded&&y.loaded===y.total||k<=E){this.clearTimer(),this._nextAutoLevel=-1;return}if(!a)return;const R=P>-1&&P!==k,D=!!r||R;if(!D&&(f.paused||!f.playbackRate||!f.readyState))return;const M=c.mainForwardBufferInfo;if(!D&&M===null)return;const B=this.bwEstimator.getEstimateTTFB(),V=Math.abs(f.playbackRate);if(T<=Math.max(B,1e3*(v/(V*2))))return;const G=M?M.len/V:0,W=y.loading.first?y.loading.first-y.loading.start:-1,Y=y.loaded&&W>-1,J=this.getBwEstimate(),Q=c.levels,ee=Q[k],le=Math.max(y.loaded,Math.round(v*(i.bitrate||ee.averageBitrate)/8));let pe=Y?T-W:T;pe<1&&Y&&(pe=Math.min(T,y.loaded*8/J));const Se=Y?y.loaded*1e3/pe:0,je=B/1e3,Le=Se?(le-y.loaded)/Se:le*8/J+je;if(Le<=G)return;const Ae=Se?Se*8:J,be=((n=(r==null?void 0:r.details)||this.hls.latestLevelDetails)==null?void 0:n.live)===!0,me=this.hls.config.abrBandWidthUpFactor;let Te=Number.POSITIVE_INFINITY,Ne;for(Ne=k-1;Ne>E;Ne--){const tt=Q[Ne].maxBitrate,at=!Q[Ne].details||be;if(Te=this.getTimeToLoadFrag(je,Ae,v*tt,at),Te=Le||Te>v*10)return;Y?this.bwEstimator.sample(T-Math.min(B,W),y.loaded):this.bwEstimator.sampleTTFB(T);const Ee=Q[Ne].maxBitrate;this.getBwEstimate()*me>Ee&&this.resetEstimator(Ee);const we=this.findBestLevel(Ee,E,Ne,0,G,1,1);we>-1&&(Ne=we),this.warn(`Fragment ${i.sn}${o?" part "+o.index:""} of level ${k} is loading too slowly; Fragment duration: ${i.duration.toFixed(3)} Time to underbuffer: ${G.toFixed(3)} s Estimated load time for current fragment: ${Le.toFixed(3)} s Estimated load time for down switch fragment: ${Te.toFixed(3)} s TTFB estimate: ${W|0} ms Current BW estimate: ${pn(J)?J|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${Ne} @ ${Ee|0} bps`),c.nextLoadLevel=c.nextAutoLevel=Ne,this.clearTimer();const He=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===Ne&&Ne>0){const tt=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${Ne>0?"and switching down":""} Fragment duration: ${i.duration.toFixed(3)} s Time to underbuffer: ${tt.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,Ne>E){let at=this.findBestLevel(this.hls.levels[E].bitrate,E,Ne,0,tt,1,1);at===-1&&(at=E),this.hls.nextLoadLevel=this.hls.nextAutoLevel=at,this.resetEstimator(this.hls.levels[at].bitrate)}}};R||Le>Te*2?He():this.timer=self.setInterval(He,Te*1e3),c.trigger(Ce.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:o,stats:y})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new dMt(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ce.FRAG_LOADING,this.onFragLoading,this),e.on(Ce.FRAG_LOADED,this.onFragLoaded,this),e.on(Ce.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Ce.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Ce.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Ce.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Ce.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(Ce.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ce.FRAG_LOADING,this.onFragLoading,this),e.off(Ce.FRAG_LOADED,this.onFragLoaded,this),e.off(Ce.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Ce.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Ce.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Ce.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Ce.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(Ce.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,r){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,r){const n=r.frag;if(!this.ignoreFragment(n)){if(!n.bitrateTest){var i;this.fragCurrent=n,this.partCurrent=(i=r.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,r){this.clearTimer()}onError(e,r){if(!r.fatal)switch(r.details){case Jt.BUFFER_ADD_CODEC_ERROR:case Jt.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Jt.FRAG_LOAD_TIMEOUT:{const n=r.frag,{fragCurrent:i,partCurrent:o}=this;if(n&&i&&n.sn===i.sn&&n.level===i.level){const c=performance.now(),a=o?o.stats:n.stats,f=c-a.loading.start,p=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&p>-1){const v=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(f-Math.min(v,p),a.loaded)}else this.bwEstimator.sampleTTFB(f)}break}}}getTimeToLoadFrag(e,r,n,i){const o=e+n/r,c=i?e+this.lastLevelLoadSec:0;return o+c}onLevelLoaded(e,r){const n=this.hls.config,{loading:i}=r.stats,o=i.end-i.first;pn(o)&&(this.lastLevelLoadSec=o/1e3),r.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(r.levelInfo)}onFragLoaded(e,{frag:r,part:n}){const i=n?n.stats:r.stats;if(r.type===Tn.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const o=n?n.duration:r.duration,c=this.hls.levels[r.level],a=(c.loaded?c.loaded.bytes:0)+i.loaded,f=(c.loaded?c.loaded.duration:0)+o;c.loaded={bytes:a,duration:f},c.realBitrate=Math.round(8*a/f)}if(r.bitrateTest){const o={stats:i,frag:r,part:n,id:r.type};this.onFragBuffered(Ce.FRAG_BUFFERED,o),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}}onFragBuffered(e,r){const{frag:n,part:i}=r,o=i!=null&&i.stats.loaded?i.stats:n.stats;if(o.aborted||this.ignoreFragment(n))return;const c=o.parsing.end-o.loading.start-Math.min(o.loading.first-o.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(c,o.loaded),o.bwEstimate=this.getBwEstimate(),n.bitrateTest?this.bitrateTestDelay=c/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Tn.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:r}=this.hls,n=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,o=this.findBestLevel(n,r,e,0,i,1,1);if(o>-1)return o;const c=this.hls.firstLevel,a=Math.min(Math.max(c,r),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${c} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,n=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!n||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const o=n&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const c=this.hls.levels;if(c.length>Math.max(e,o)&&c[e].loadError<=c[o].loadError)return e}return this._nextAutoLevel=o,this.nextAutoLevelKey=this.getAutoLevelKey(),o}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:r,hls:n}=this;if(n.levels.length<=1)return n.loadLevel;const{maxAutoLevel:i,config:o,minAutoLevel:c}=n,a=r?r.duration:e?e.duration:0,f=this.getBwEstimate(),p=this.getStarvationDelay();let y=o.abrBandWidthFactor,v=o.abrBandWidthUpFactor;if(p){const R=this.findBestLevel(f,c,i,p,0,y,v);if(R>=0)return this.rebufferNotice=-1,R}let T=a?Math.min(a,o.maxStarvationDelay):o.maxStarvationDelay;if(!p){const R=this.bitrateTestDelay;R&&(T=(a?Math.min(a,o.maxLoadingDelay):o.maxLoadingDelay)-R,this.info(`bitrate test took ${Math.round(1e3*R)}ms, set first fragment max fetchDuration to ${Math.round(1e3*T)} ms`),y=v=1)}const E=this.findBestLevel(f,c,i,p,T,y,v);if(this.rebufferNotice!==E&&(this.rebufferNotice=E,this.info(`${p?"rebuffering expected":"buffer is empty"}, optimal quality level ${E}`)),E>-1)return E;const k=n.levels[c],P=n.loadLevelObj;return P&&(k==null?void 0:k.bitrate)=r;Ae--){var Le;const be=k[Ae],me=Ae>v;if(!be)continue;if(D.useMediaCapabilities&&!be.supportedResult&&!be.supportedPromise){const at=navigator.mediaCapabilities;typeof(at==null?void 0:at.decodingInfo)=="function"&&GMt(be,ee,W,Y,e,J)?(be.supportedPromise=A2e(be,ee,at,this.supportedCache),be.supportedPromise.then(Et=>{if(!this.hls)return;be.supportedResult=Et;const vt=this.hls.levels,Gt=vt.indexOf(be);Et.error?this.warn(`MediaCapabilities decodingInfo error: "${Et.error}" for level ${Gt} ${aa(Et)}`):Et.supported?Et.decodingInfoResults.some(pt=>pt.smooth===!1||pt.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Gt} not smooth or powerEfficient: ${aa(Et)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Gt} ${aa(Et)}`),Gt>-1&&vt.length>1&&(this.log(`Removing unsupported level ${Gt}`),this.hls.removeLevel(Gt),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Et=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Et}`)})):be.supportedResult=E2e}if((G&&be.codecSet!==G||W&&be.videoRange!==W||me&&Y>be.frameRate||!me&&Y>0&&Yat.smooth===!1))&&(!V||Ae!==le)){je.push(Ae);continue}const Te=be.details,Ne=(E?Te==null?void 0:Te.partTarget:Te==null?void 0:Te.averagetargetduration)||pe;let Ee;me?Ee=a*e:Ee=c*e;const we=pe&&i>=pe*2&&o===0?be.averageBitrate:be.maxBitrate,He=this.getTimeToLoadFrag(Se,Ee,we*Ne,Te===void 0);if(Ee>=we&&(Ae===y||be.loadError===0&&be.fragmentError===0)&&(He<=Se||!pn(He)||B&&!this.bitrateTestDelay||He${Ae} adjustedbw(${Math.round(Ee)})-bitrate=${Math.round(Ee-we)} ttfb:${Se.toFixed(1)} avgDuration:${Ne.toFixed(1)} maxFetchDuration:${p.toFixed(1)} fetchDuration:${He.toFixed(1)} firstSelection:${V} codecSet:${be.codecSet} videoRange:${be.videoRange} hls.loadLevel:${R}`)),V&&(this.firstSelection=Ae),Ae}}return-1}set nextAutoLevel(e){const r=this.deriveNextAutoLevel(e);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}deriveNextAutoLevel(e){const{maxAutoLevel:r,minAutoLevel:n}=this.hls;return Math.min(Math.max(e,n),r)}}const N2e={search:function(t,e){let r=0,n=t.length-1,i=null,o=null;for(;r<=n;){i=(r+n)/2|0,o=t[i];const c=e(o);if(c>0)r=i+1;else if(c<0)n=i-1;else return o}return null}};function oOt(t,e,r){if(e===null||!Array.isArray(t)||!t.length||!pn(e))return null;const n=t[0].programDateTime;if(e<(n||0))return null;const i=t[t.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let o=0;o0&&a<15e-7&&(r+=15e-7),o&&t.level!==o.level&&o.end<=t.end&&(o=e[2+t.sn-e[0].sn]||null)}else r===0&&e[0].start===0&&(o=e[0]);if(o&&((!t||t.level===o.level)&&Ece(r,n,o)===0||lOt(o,t,Math.min(i,n))))return o;const c=N2e.search(e,Ece.bind(null,r,n));return c&&(c!==t||!o)?c:o}function lOt(t,e,r){if(e&&e.start===0&&e.level0){const n=e.tagList.reduce((i,o)=>(o[0]==="INF"&&(i+=parseFloat(o[1])),i),r);return t.start<=n}return!1}function Ece(t=0,e=0,r){if(r.start<=t&&r.start+r.duration>t)return 0;const n=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=t?1:r.start-n>t&&r.start?-1:0}function cOt(t,e,r){const n=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0))*1e3;return(r.endProgramDateTime||0)-n>t}function I2e(t,e,r){if(t&&t.startCC<=e&&t.endCC>=e){let n=t.fragments;const{fragmentHint:i}=t;i&&(n=n.concat(i));let o;return N2e.search(n,c=>c.cce?-1:(o=c,c.end<=r?1:c.start>r?-1:0)),o||null}return null}function SO(t){switch(t.details){case Jt.FRAG_LOAD_TIMEOUT:case Jt.KEY_LOAD_TIMEOUT:case Jt.LEVEL_LOAD_TIMEOUT:case Jt.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function P2e(t){return t.details.startsWith("key")}function R2e(t){return P2e(t)&&!!t.frag&&!t.frag.decryptdata}function jce(t,e){const r=SO(e);return t.default[`${r?"timeout":"error"}Retry`]}function LK(t,e){const r=t.backoff==="linear"?1:Math.pow(2,e);return Math.min(r*t.retryDelayMs,t.maxRetryDelayMs)}function Ace(t){return Us(Us({},t),{errorRetry:null,timeoutRetry:null})}function TO(t,e,r,n){if(!t)return!1;const i=n==null?void 0:n.code,o=e499)}function oG(t){return t===0&&navigator.onLine===!1}var Kl={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},td={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class dOt extends _h{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(Ce.ERROR,this.onError,this),e.on(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ce.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Ce.ERROR,this.onError,this),e.off(Ce.ERROR,this.onErrorOut,this),e.off(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ce.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===Tn.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const r=this.hls,n=r.currentLevel;return(e=r.loadLevelObj)!=null&&e.details||n===-1?r.loadLevel:n}variantHasKey(e,r){if(e){var n;if((n=e.details)!=null&&n.hasKey(r))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(c=>i.indexOf(c.groupId)>=0).some(c=>{var a;return(a=c.details)==null?void 0:a.hasKey(r)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,r){var n;if(r.fatal)return;const i=this.hls,o=r.context;switch(r.details){case Jt.FRAG_LOAD_ERROR:case Jt.FRAG_LOAD_TIMEOUT:case Jt.KEY_LOAD_ERROR:case Jt.KEY_LOAD_TIMEOUT:r.errorAction=this.getFragRetryOrSwitchAction(r);return;case Jt.FRAG_PARSING_ERROR:if((n=r.frag)!=null&&n.gap){r.errorAction=C1();return}case Jt.FRAG_GAP:case Jt.FRAG_DECRYPT_ERROR:{r.errorAction=this.getFragRetryOrSwitchAction(r),r.errorAction.action=Kl.SendAlternateToPenaltyBox;return}case Jt.LEVEL_EMPTY_ERROR:case Jt.LEVEL_PARSING_ERROR:{var c;const f=r.parent===Tn.MAIN?r.level:i.loadLevel;r.details===Jt.LEVEL_EMPTY_ERROR&&((c=r.context)!=null&&(c=c.levelDetails)!=null&&c.live)?r.errorAction=this.getPlaylistRetryOrSwitchAction(r,f):(r.levelRetry=!1,r.errorAction=this.getLevelSwitchAction(r,f))}return;case Jt.LEVEL_LOAD_ERROR:case Jt.LEVEL_LOAD_TIMEOUT:typeof(o==null?void 0:o.level)=="number"&&(r.errorAction=this.getPlaylistRetryOrSwitchAction(r,o.level));return;case Jt.AUDIO_TRACK_LOAD_ERROR:case Jt.AUDIO_TRACK_LOAD_TIMEOUT:case Jt.SUBTITLE_LOAD_ERROR:case Jt.SUBTITLE_TRACK_LOAD_TIMEOUT:if(o){const f=i.loadLevelObj;if(f&&(o.type===Wi.AUDIO_TRACK&&f.hasAudioGroup(o.groupId)||o.type===Wi.SUBTITLE_TRACK&&f.hasSubtitleGroup(o.groupId))){r.errorAction=this.getPlaylistRetryOrSwitchAction(r,i.loadLevel),r.errorAction.action=Kl.SendAlternateToPenaltyBox,r.errorAction.flags=td.MoveAllAlternatesMatchingHost;return}}return;case Jt.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:r.errorAction={action:Kl.SendAlternateToPenaltyBox,flags:td.MoveAllAlternatesMatchingHDCP};return;case Jt.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Jt.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Jt.KEY_SYSTEM_NO_SESSION:r.errorAction={action:Kl.SendAlternateToPenaltyBox,flags:td.MoveAllAlternatesMatchingKey};return;case Jt.BUFFER_ADD_CODEC_ERROR:case Jt.REMUX_ALLOC_ERROR:case Jt.BUFFER_APPEND_ERROR:if(!r.errorAction){var a;r.errorAction=this.getLevelSwitchAction(r,(a=r.level)!=null?a:i.loadLevel)}return;case Jt.INTERNAL_EXCEPTION:case Jt.BUFFER_APPENDING_ERROR:case Jt.BUFFER_FULL_ERROR:case Jt.LEVEL_SWITCH_ERROR:case Jt.BUFFER_STALLED_ERROR:case Jt.BUFFER_SEEK_OVER_HOLE:case Jt.BUFFER_NUDGE_ON_STALL:r.errorAction=C1();return}r.type===Dn.KEY_SYSTEM_ERROR&&(r.levelRetry=!1,r.errorAction=C1())}getPlaylistRetryOrSwitchAction(e,r){const n=this.hls,i=jce(n.config.playlistLoadPolicy,e),o=this.playlistError++;if(TO(i,o,SO(e),e.response))return{action:Kl.RetryRequest,flags:td.None,retryConfig:i,retryCount:o};const a=this.getLevelSwitchAction(e,r);return i&&(a.retryConfig=i,a.retryCount=o),a}getFragRetryOrSwitchAction(e){const r=this.hls,n=this.getVariantLevelIndex(e.frag),i=r.levels[n],{fragLoadPolicy:o,keyLoadPolicy:c}=r.config,a=jce(P2e(e)?c:o,e),f=r.levels.reduce((y,v)=>y+v.fragmentError,0);if(i&&(e.details!==Jt.FRAG_GAP&&i.fragmentError++,!R2e(e)&&TO(a,f,SO(e),e.response)))return{action:Kl.RetryRequest,flags:td.None,retryConfig:a,retryCount:f};const p=this.getLevelSwitchAction(e,n);return a&&(p.retryConfig=a,p.retryCount=f),p}getLevelSwitchAction(e,r){const n=this.hls;r==null&&(r=n.loadLevel);const i=this.hls.levels[r];if(i){var o,c;const p=e.details;i.loadError++,p===Jt.BUFFER_APPEND_ERROR&&i.fragmentError++;let y=-1;const{levels:v,loadLevel:T,minAutoLevel:E,maxAutoLevel:k}=n;!n.autoLevelEnabled&&!n.config.preserveManualLevelOnError&&(n.loadLevel=-1);const P=(o=e.frag)==null?void 0:o.type,D=(P===Tn.AUDIO&&p===Jt.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(p===Jt.BUFFER_ADD_CODEC_ERROR||p===Jt.BUFFER_APPEND_ERROR))&&v.some(({audioCodec:W})=>i.audioCodec!==W),B=e.sourceBufferName==="video"&&(p===Jt.BUFFER_ADD_CODEC_ERROR||p===Jt.BUFFER_APPEND_ERROR)&&v.some(({codecSet:W,audioCodec:Y})=>i.codecSet!==W&&i.audioCodec===Y),{type:V,groupId:G}=(c=e.context)!=null?c:{};for(let W=v.length;W--;){const Y=(W+T)%v.length;if(Y!==T&&Y>=E&&Y<=k&&v[Y].loadError===0){var a,f;const J=v[Y];if(p===Jt.FRAG_GAP&&P===Tn.MAIN&&e.frag){const Q=v[Y].details;if(Q){const ee=g_(e.frag,Q.fragments,e.frag.start);if(ee!=null&&ee.gap)continue}}else{if(V===Wi.AUDIO_TRACK&&J.hasAudioGroup(G)||V===Wi.SUBTITLE_TRACK&&J.hasSubtitleGroup(G))continue;if(P===Tn.AUDIO&&(a=i.audioGroups)!=null&&a.some(Q=>J.hasAudioGroup(Q))||P===Tn.SUBTITLE&&(f=i.subtitleGroups)!=null&&f.some(Q=>J.hasSubtitleGroup(Q))||D&&i.audioCodec===J.audioCodec||B&&i.codecSet===J.codecSet||!D&&i.codecSet!==J.codecSet)continue}y=Y;break}}if(y>-1&&n.loadLevel!==y)return e.levelRetry=!0,this.playlistError=0,{action:Kl.SendAlternateToPenaltyBox,flags:td.None,nextAutoLevel:y}}return{action:Kl.SendAlternateToPenaltyBox,flags:td.MoveAllAlternatesMatchingHost}}onErrorOut(e,r){var n;switch((n=r.errorAction)==null?void 0:n.action){case Kl.DoNothing:break;case Kl.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(r),!r.errorAction.resolved&&r.details!==Jt.FRAG_GAP?r.fatal=!0:/MediaSource readyState: ended/.test(r.error.message)&&(this.warn(`MediaSource ended after "${r.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(r.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const r=this.hls,n=e.errorAction;if(!n)return;const{flags:i}=n,o=n.nextAutoLevel;switch(i){case td.None:this.switchLevel(e,o);break;case td.MoveAllAlternatesMatchingHDCP:{const f=this.getVariantLevelIndex(e.frag),p=r.levels[f],y=p==null?void 0:p.attrs["HDCP-LEVEL"];if(n.hdcpLevel=y,y==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(y){r.maxHdcpLevel=aG[aG.indexOf(y)-1],n.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${r.maxHdcpLevel}" or lower`);break}}case td.MoveAllAlternatesMatchingKey:{const f=e.decryptdata;if(f){const p=this.hls.levels,y=p.length;for(let T=y;T--;)if(this.variantHasKey(p[T],f)){var c,a;this.log(`Banned key found in level ${T} (${p[T].bitrate}bps) or audio group "${(c=p[T].audioGroups)==null?void 0:c.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${Xl(f.keyId||[])}`),p[T].fragmentError++,p[T].loadError++,this.log(`Removing level ${T} with key error (${e.error})`),this.hls.removeLevel(T)}const v=e.frag;if(this.hls.levels.length{const f=this.fragments[a];if(!f||c>=f.body.sn)return;if(!f.buffered&&(!f.loaded||o)){f.body.type===n&&this.removeFragment(f.body);return}const p=f.range[e];if(p){if(p.time.length===0){this.removeFragment(f.body);return}p.time.some(y=>{const v=!this.isTimeBuffered(y.startPTS,y.endPTS,r);return v&&this.removeFragment(f.body),v})}})}detectPartialFragments(e){const r=this.timeRanges;if(!r||e.frag.sn==="initSegment")return;const n=e.frag,i=jw(n),o=this.fragments[i];if(!o||o.buffered&&n.gap)return;const c=!n.relurl;Object.keys(r).forEach(a=>{const f=n.elementaryStreams[a];if(!f)return;const p=r[a],y=c||f.partial===!0;o.range[a]=this.getBufferedTimes(n,e.part,y,p)}),o.loaded=null,Object.keys(o.range).length?(this.bufferedEnd(o,n),KR(o)||this.removeParts(n.sn-1,n.type)):this.removeFragment(o.body)}bufferedEnd(e,r){e.buffered=!0,(e.body.endList=r.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,r){const n=this.activePartLists[r];n&&(this.activePartLists[r]=kce(n,i=>i.fragment.sn>=e))}fragBuffered(e,r){const n=jw(e);let i=this.fragments[n];!i&&r&&(i=this.fragments[n]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,r,n,i){const o={time:[],partial:n},c=e.start,a=e.end,f=e.minEndPTS||a,p=e.maxStartPTS||c;for(let y=0;y=v&&f<=T){o.time.push({startPTS:Math.max(c,i.start(y)),endPTS:Math.min(a,i.end(y))});break}else if(cv){const E=Math.max(c,i.start(y)),k=Math.min(a,i.end(y));k>E&&(o.partial=!0,o.time.push({startPTS:E,endPTS:k}))}else if(a<=v)break}return o}getPartialFragment(e){let r=null,n,i,o,c=0;const{bufferPadding:a,fragments:f}=this;return Object.keys(f).forEach(p=>{const y=f[p];y&&KR(y)&&(i=y.body.start-a,o=y.body.end+a,e>=i&&e<=o&&(n=Math.min(e-i,o-e),c<=n&&(r=y.body,c=n)))}),r}isEndListAppended(e){const r=this.endListFragments[e];return r!==void 0&&(r.buffered||KR(r))}getState(e){const r=jw(e),n=this.fragments[r];return n?n.buffered?KR(n)?dl.PARTIAL:dl.OK:dl.APPENDING:dl.NOT_LOADED}isTimeBuffered(e,r,n){let i,o;for(let c=0;c=i&&r<=o)return!0;if(r<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,r){if(r.frag.sn==="initSegment"||r.frag.bitrateTest)return;const n=r.frag,i=r.part?null:r,o=jw(n);this.fragments[o]={body:n,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,r){const{frag:n,part:i,timeRanges:o,type:c}=r;if(n.sn==="initSegment")return;const a=n.type;if(i){let p=this.activePartLists[a];p||(this.activePartLists[a]=p=[]),p.push(i)}this.timeRanges=o;const f=o[c];this.detectEvictedFragments(c,f,a,i)}onFragBuffered(e,r){this.detectPartialFragments(r)}hasFragment(e){const r=jw(e);return!!this.fragments[r]}hasFragments(e){const{fragments:r}=this,n=Object.keys(r);if(!e)return n.length>0;for(let i=n.length;i--;){const o=r[n[i]];if((o==null?void 0:o.body.type)===e)return!0}return!1}hasParts(e){var r;return!!((r=this.activePartLists[e])!=null&&r.length)}removeFragmentsInRange(e,r,n,i,o){i&&!this.hasGaps||Object.keys(this.fragments).forEach(c=>{const a=this.fragments[c];if(!a)return;const f=a.body;f.type!==n||i&&!f.gap||f.starte&&(a.buffered||o)&&this.removeFragment(f)})}removeFragment(e){const r=jw(e);e.clearElementaryStreamInfo();const n=this.activePartLists[e.type];if(n){const i=e.sn;this.activePartLists[e.type]=kce(n,o=>o.fragment.sn!==i)}delete this.fragments[r],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const r=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;r&&r.forEach(n=>n.clearElementaryStreamInfo())}}function KR(t){var e,r,n;return t.buffered&&!!(t.body.gap||(e=t.range.video)!=null&&e.partial||(r=t.range.audio)!=null&&r.partial||(n=t.range.audiovideo)!=null&&n.partial)}function jw(t){return`${t.type}_${t.level}_${t.sn}`}function kce(t,e){return t.filter(r=>{const n=e(r);return n||r.clearElementaryStreamInfo(),n})}var jx={cbc:0,ctr:1};class fOt{constructor(e,r,n){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=r,this.aesMode=n}decrypt(e,r){switch(this.aesMode){case jx.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},r,e);case jx.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},r,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function mOt(t){const e=t.byteLength,r=e&&new DataView(t.buffer).getUint8(e-1);return r?t.slice(0,e-r):t}class pOt{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const r=new DataView(e),n=new Uint32Array(4);for(let i=0;i<4;i++)n[i]=r.getUint32(i*4);return n}initTable(){const e=this.sBox,r=this.invSBox,n=this.subMix,i=n[0],o=n[1],c=n[2],a=n[3],f=this.invSubMix,p=f[0],y=f[1],v=f[2],T=f[3],E=new Uint32Array(256);let k=0,P=0,R=0;for(R=0;R<256;R++)R<128?E[R]=R<<1:E[R]=R<<1^283;for(R=0;R<256;R++){let D=P^P<<1^P<<2^P<<3^P<<4;D=D>>>8^D&255^99,e[k]=D,r[D]=k;const M=E[k],B=E[M],V=E[B];let G=E[D]*257^D*16843008;i[k]=G<<24|G>>>8,o[k]=G<<16|G>>>16,c[k]=G<<8|G>>>24,a[k]=G,G=V*16843009^B*65537^M*257^k*16843008,p[D]=G<<24|G>>>8,y[D]=G<<16|G>>>16,v[D]=G<<8|G>>>24,T[D]=G,k?(k=M^E[E[E[V^M]]],P^=E[E[P]]):k=P=1}}expandKey(e){const r=this.uint8ArrayToUint32Array_(e);let n=!0,i=0;for(;i{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,r,n,i);const f=this.flush();f?o(f.buffer):c(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),r,n,i)}softwareDecrypt(e,r,n,i){const{currentIV:o,currentResult:c,remainderData:a}=this;if(i!==jx.cbc||r.byteLength!==16)return qs.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=ph(a,e),this.remainderData=null);const f=this.getValidChunk(e);if(!f.length)return null;o&&(n=o);let p=this.softwareDecrypter;p||(p=this.softwareDecrypter=new pOt),p.expandKey(r);const y=c;return this.currentResult=p.decrypt(f.buffer,0,n),this.currentIV=f.slice(-16).buffer,y||null}webCryptoDecrypt(e,r,n,i){if(this.key!==r||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,r,n,i));this.key=r,this.fastAesKey=new gOt(this.subtle,r,i)}return this.fastAesKey.expandKey().then(o=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new fOt(this.subtle,new Uint8Array(n),i).decrypt(e.buffer,o)):Promise.reject(new Error("web crypto not initialized"))).catch(o=>(qs.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${o.name}: ${o.message}`),this.onWebCryptoError(e,r,n,i)))}onWebCryptoError(e,r,n,i){const o=this.enableSoftwareAES;if(o){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,r,n,i);const c=this.flush();if(c)return c.buffer}throw new Error("WebCrypto"+(o?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let r=e;const n=e.length-e.length%xOt;return n!==e.length&&(r=e.slice(0,n),this.remainderData=e.slice(n)),r}logOnce(e){this.logEnabled&&(qs.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Cce=Math.pow(2,17);class vOt{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,r){const n=e.url;if(!n)return Promise.reject(new Ap({type:Dn.NETWORK_ERROR,details:Jt.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${n?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,o=i.fLoader,c=i.loader;return new Promise((a,f)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(k=>k[0]==="GAP")){f(Ice(e));return}else e.gap=!1;const p=this.loader=o?new o(i):new c(i),y=Nce(e);e.loader=p;const v=Ace(i.fragLoadPolicy.default),T={loadPolicy:v,timeout:v.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Cce};e.stats=p.stats;const E={onSuccess:(k,P,R,D)=>{this.resetLoader(e,p);let M=k.data;R.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(M.slice(0,16)),M=M.slice(16)),a({frag:e,part:null,payload:M,networkDetails:D})},onError:(k,P,R,D)=>{this.resetLoader(e,p),f(new Ap({type:Dn.NETWORK_ERROR,details:Jt.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Us({url:n,data:void 0},k),error:new Error(`HTTP Error ${k.code} ${k.text}`),networkDetails:R,stats:D}))},onAbort:(k,P,R)=>{this.resetLoader(e,p),f(new Ap({type:Dn.NETWORK_ERROR,details:Jt.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:R,stats:k}))},onTimeout:(k,P,R)=>{this.resetLoader(e,p),f(new Ap({type:Dn.NETWORK_ERROR,details:Jt.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${T.timeout}ms`),networkDetails:R,stats:k}))}};r&&(E.onProgress=(k,P,R,D)=>r({frag:e,part:null,payload:R,networkDetails:D})),p.load(y,T,E)})}loadPart(e,r,n){this.abort();const i=this.config,o=i.fLoader,c=i.loader;return new Promise((a,f)=>{if(this.loader&&this.loader.destroy(),e.gap||r.gap){f(Ice(e,r));return}const p=this.loader=o?new o(i):new c(i),y=Nce(e,r);e.loader=p;const v=Ace(i.fragLoadPolicy.default),T={loadPolicy:v,timeout:v.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Cce};r.stats=p.stats,p.load(y,T,{onSuccess:(E,k,P,R)=>{this.resetLoader(e,p),this.updateStatsFromPart(e,r);const D={frag:e,part:r,payload:E.data,networkDetails:R};n(D),a(D)},onError:(E,k,P,R)=>{this.resetLoader(e,p),f(new Ap({type:Dn.NETWORK_ERROR,details:Jt.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:r,response:Us({url:y.url,data:void 0},E),error:new Error(`HTTP Error ${E.code} ${E.text}`),networkDetails:P,stats:R}))},onAbort:(E,k,P)=>{e.stats.aborted=r.stats.aborted,this.resetLoader(e,p),f(new Ap({type:Dn.NETWORK_ERROR,details:Jt.INTERNAL_ABORTED,fatal:!1,frag:e,part:r,error:new Error("Aborted"),networkDetails:P,stats:E}))},onTimeout:(E,k,P)=>{this.resetLoader(e,p),f(new Ap({type:Dn.NETWORK_ERROR,details:Jt.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:r,error:new Error(`Timeout after ${T.timeout}ms`),networkDetails:P,stats:E}))}})})}updateStatsFromPart(e,r){const n=e.stats,i=r.stats,o=i.total;if(n.loaded+=i.loaded,o){const f=Math.round(e.duration/r.duration),p=Math.min(Math.round(n.loaded/o),f),v=(f-p)*Math.round(n.loaded/p);n.total=n.loaded+v}else n.total=Math.max(n.loaded,n.total);const c=n.loading,a=i.loading;c.start?c.first+=a.first-a.start:(c.start=a.start,c.first=a.first),c.end=a.end}resetLoader(e,r){e.loader=null,this.loader===r&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),r.destroy()}}function Nce(t,e=null){const r=e||t,n={frag:t,part:e,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},i=r.byteRangeStartOffset,o=r.byteRangeEndOffset;if(pn(i)&&pn(o)){var c;let a=i,f=o;if(t.sn==="initSegment"&&_Ot((c=t.decryptdata)==null?void 0:c.method)){const p=o-i;p%16&&(f=o+(16-p%16)),i!==0&&(n.resetIV=!0,a=i-16)}n.rangeStart=a,n.rangeEnd=f}return n}function Ice(t,e){const r=new Error(`GAP ${t.gap?"tag":"attribute"} found`),n={type:Dn.MEDIA_ERROR,details:Jt.FRAG_GAP,fatal:!1,frag:t,error:r,networkDetails:null};return e&&(n.part=e),(e||t).stats.aborted=!0,new Ap(n)}function _Ot(t){return t==="AES-128"||t==="AES-256"}class Ap extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class L2e extends _h{constructor(e,r){super(e,r),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class MK{constructor(e,r,n,i=0,o=-1,c=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=YR(),this.buffering={audio:YR(),video:YR(),audiovideo:YR()},this.level=e,this.sn=r,this.id=n,this.size=i,this.part=o,this.partial=c}}function YR(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Pce={length:0,start:()=>0,end:()=>0};class Ti{static isBuffered(e,r){if(e){const n=Ti.getBuffered(e);for(let i=n.length;i--;)if(r>=n.start(i)&&r<=n.end(i))return!0}return!1}static bufferedRanges(e){if(e){const r=Ti.getBuffered(e);return Ti.timeRangesToArray(r)}return[]}static timeRangesToArray(e){const r=[];for(let n=0;n1&&e.sort((y,v)=>y.start-v.start||v.end-y.end);let i=-1,o=[];if(n)for(let y=0;y=e[y].start&&r<=e[y].end&&(i=y);const v=o.length;if(v){const T=o[v-1].end;e[y].start-TT&&(o[v-1].end=e[y].end):o.push(e[y])}else o.push(e[y])}else o=e;let c=0,a,f=r,p=r;for(let y=0;y=v&&r<=T&&(i=y),r+n>=v&&r{const i=n.substring(2,n.length-1),o=r==null?void 0:r[i];return o===void 0?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),n):o})}return e}function Lce(t,e,r){let n=t.variableList;n||(t.variableList=n={});let i,o;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const c=new self.URL(r).searchParams;if(c.has(i))o=c.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${r}"`)}catch(c){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${c.message}`))}}else i=e.NAME,o=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=o||""}function bOt(t,e,r){const n=e.IMPORT;if(r&&n in r){let i=t.variableList;i||(t.variableList=i={}),i[n]=r[n]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}const wOt=/^(\d+)x(\d+)$/,Dce=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Qa{constructor(e,r){typeof e=="string"&&(e=Qa.parseAttrList(e,r)),Js(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const r=parseInt(this[e],10);return r>Number.MAX_SAFE_INTEGER?1/0:r}hexadecimalInteger(e){if(this[e]){let r=(this[e]||"0x").slice(2);r=(r.length&1?"0":"")+r;const n=new Uint8Array(r.length/2);for(let i=0;iNumber.MAX_SAFE_INTEGER?1/0:r}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,r){const n=this[e];return n?parseFloat(n):r}enumeratedString(e){return this[e]}enumeratedStringList(e,r){const n=this[e];return(n?n.split(/[ ,]+/):[]).reduce((i,o)=>(i[o.toLowerCase()]=!0,i),r)}bool(e){return this[e]==="YES"}decimalResolution(e){const r=wOt.exec(this[e]);if(r!==null)return{width:parseInt(r[1],10),height:parseInt(r[2],10)}}static parseAttrList(e,r){let n;const i={},o='"';for(Dce.lastIndex=0;(n=Dce.exec(e))!==null;){const c=n[1].trim();let a=n[2];const f=a.indexOf(o)===0&&a.lastIndexOf(o)===a.length-1;let p=!1;if(f)a=a.slice(1,-1);else switch(c){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":p=!0}if(r&&(f||p))a=lG(r,a);else if(!p&&!f)switch(c){case"CLOSED-CAPTIONS":if(a==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":qs.warn(`${e}: attribute ${c} is missing quotes`)}i[c]=a}return i}}const SOt="com.apple.hls.interstitial";function TOt(t){return t!=="ID"&&t!=="CLASS"&&t!=="CUE"&&t!=="START-DATE"&&t!=="DURATION"&&t!=="END-DATE"&&t!=="END-ON-NEXT"}function EOt(t){return t==="SCTE35-OUT"||t==="SCTE35-IN"||t==="SCTE35-CMD"}class M2e{constructor(e,r,n=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(r==null?void 0:r.tagAnchor)||null,this.tagOrder=(i=r==null?void 0:r.tagOrder)!=null?i:n,r){const o=r.attr;for(const c in o)if(Object.prototype.hasOwnProperty.call(e,c)&&e[c]!==o[c]){qs.warn(`DATERANGE tag attribute: "${c}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=c;break}e=Js(new Qa({}),o,e)}if(this.attr=e,r?(this._startDate=r._startDate,this._cue=r._cue,this._endDate=r._endDate,this._dateAtEnd=r._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const o=(r==null?void 0:r.endDate)||new Date(this.attr["END-DATE"]);pn(o.getTime())&&(this._endDate=o)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(qs.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const r=this.duration;return r!==null?this._dateAtEnd=new Date(this._startDate.getTime()+r*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(pn(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===SOt}get isValid(){return!!this.id&&!this._badValueForSameId&&pn(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const jOt=10;class AOt{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const r=this.lastPartSn-e.lastPartSn,n=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!n||!!r||!this.live,this.advanced=this.endSN>e.endSN||r>0||r===0&&n>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(r=>{let n=r.decryptdata;return n||(r.setKeyFormat(e.keyFormat),n=r.decryptdata),!!n&&e.matches(n)})}get hasProgramDateTime(){return this.fragments.length?pn(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||jOt}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const r=this.lastPartIndex;if(r!==-1){for(let n=e.length;n--;)if(e[n].index>r)return e[n].index;return r}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function EO(t,e){return t.length===e.length?!t.some((r,n)=>r!==e[n]):!1}function Mce(t,e){return!t&&!e?!0:!t||!e?!1:EO(t,e)}function N1(t){return t==="AES-128"||t==="AES-256"||t==="AES-256-CTR"}function OK(t){switch(t){case"AES-128":case"AES-256":return jx.cbc;case"AES-256-CTR":return jx.ctr;default:throw new Error(`invalid full segment method ${t}`)}}function FK(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}function cG(t){return Uint8Array.from(unescape(encodeURIComponent(t)),e=>e.charCodeAt(0))}function kOt(t){const e=cG(t).subarray(0,16),r=new Uint8Array(16);return r.set(e,16-e.length),r}function O2e(t){const e=function(n,i,o){const c=n[i];n[i]=n[o],n[o]=c};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function F2e(t){const e=t.split(":");let r=null;if(e[0]==="data"&&e.length===2){const n=e[1].split(";"),i=n[n.length-1].split(",");if(i.length===2){const o=i[0]==="base64",c=i[1];o?(n.splice(-1,1),r=FK(c)):r=kOt(c)}}return r}const jO=typeof self<"u"?self:void 0;var to={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ql={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function ZL(t){switch(t){case Ql.FAIRPLAY:return to.FAIRPLAY;case Ql.PLAYREADY:return to.PLAYREADY;case Ql.WIDEVINE:return to.WIDEVINE;case Ql.CLEARKEY:return to.CLEARKEY}}function m6(t){switch(t){case to.FAIRPLAY:return Ql.FAIRPLAY;case to.PLAYREADY:return Ql.PLAYREADY;case to.WIDEVINE:return Ql.WIDEVINE;case to.CLEARKEY:return Ql.CLEARKEY}}function W2(t){const{drmSystems:e,widevineLicenseUrl:r}=t,n=e?[to.FAIRPLAY,to.WIDEVINE,to.PLAYREADY,to.CLEARKEY].filter(i=>!!e[i]):[];return!n[to.WIDEVINE]&&r&&n.push(to.WIDEVINE),n}const B2e=function(t){return jO!=null&&(t=jO.navigator)!=null&&t.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function COt(t,e,r,n){let i;switch(t){case to.FAIRPLAY:i=["cenc","sinf"];break;case to.WIDEVINE:case to.PLAYREADY:i=["cenc"];break;case to.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return NOt(i,e,r,n)}function NOt(t,e,r,n){return[{initDataTypes:t,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:e.map(o=>({contentType:`audio/mp4; codecs=${o}`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null})),videoCapabilities:r.map(o=>({contentType:`video/mp4; codecs=${o}`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}))}]}function IOt(t){var e;return!!t&&(t.sessionType==="persistent-license"||!!((e=t.sessionTypes)!=null&&e.some(r=>r==="persistent-license")))}function $2e(t){const e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),r=String.fromCharCode.apply(null,Array.from(e)),n=r.substring(r.indexOf("<"),r.length),c=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(c){const a=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(a){const f=FK(a).subarray(0,16);return O2e(f),f}}return null}let Aw={};class ox{static clearKeyUriToKeyIdMap(){Aw={}}static setKeyIdForUri(e,r){Aw[e]=r}static addKeyIdForUri(e){const r=Object.keys(Aw).length%Number.MAX_SAFE_INTEGER,n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,r),Aw[e]=n,n}constructor(e,r,n,i=[1],o=null,c){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=r,this.keyFormat=n,this.keyFormatVersions=i,this.iv=o,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!N1(e),c!=null&&c.startsWith("0x")&&(this.keyId=new Uint8Array(m2e(c)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&EO(e.keyFormatVersions,this.keyFormatVersions)&&Mce(e.iv,this.iv)&&Mce(e.keyId,this.keyId)}isSupported(){if(this.method){if(N1(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ql.FAIRPLAY:case Ql.WIDEVINE:case Ql.PLAYREADY:case Ql.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,r){if(!this.encrypted||!this.uri)return null;if(N1(this.method)){let o=this.iv;return o||(typeof e!="number"&&(qs.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),o=ROt(e)),new ox(this.method,this.uri,"identity",this.keyFormatVersions,o)}if(this.keyId){const o=Aw[this.uri];if(o&&!EO(this.keyId,o)&&ox.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const n=F2e(this.uri);if(n)switch(this.keyFormat){case Ql.WIDEVINE:if(this.pssh=n,!this.keyId){const o=MMt(n.buffer);if(o.length){var i;const c=o[0];this.keyId=(i=c.kids)!=null&&i.length?c.kids[0]:null}}this.keyId||(this.keyId=Oce(r));break;case Ql.PLAYREADY:{const o=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=DMt(o,null,n),this.keyId=$2e(n);break}default:{let o=n.subarray(0,16);if(o.length!==16){const c=new Uint8Array(16);c.set(o,16-o.length),o=c}this.keyId=o;break}}if(!this.keyId||this.keyId.byteLength!==16){let o;o=POt(r),o||(o=Oce(r),o||(o=Aw[this.uri])),o&&(this.keyId=o,ox.setKeyIdForUri(this.uri,o))}return this}}function POt(t){const e=t==null?void 0:t[Ql.WIDEVINE];return e?e.keyId:null}function Oce(t){const e=t==null?void 0:t[Ql.PLAYREADY];if(e){const r=F2e(e.uri);if(r)return $2e(r)}return null}function ROt(t){const e=new Uint8Array(16);for(let r=12;r<16;r++)e[r]=t>>8*(15-r)&255;return e}const Fce=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Bce=/#EXT-X-MEDIA:(.*)/g,LOt=/^#EXT(?:INF|-X-TARGETDURATION):/m,p6=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),DOt=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class hm{static findGroup(e,r){for(let n=0;n0&&o.length({id:p.attrs.AUDIO,audioCodec:p.audioCodec})),SUBTITLES:c.map(p=>({id:p.attrs.SUBTITLES,textCodec:p.textCodec})),"CLOSED-CAPTIONS":[]};let f=0;for(Bce.lastIndex=0;(i=Bce.exec(e))!==null;){const p=new Qa(i[1],n),y=p.TYPE;if(y){const v=a[y],T=o[y]||[];o[y]=T;const E=p.LANGUAGE,k=p["ASSOC-LANGUAGE"],P=p.CHANNELS,R=p.CHARACTERISTICS,D=p["INSTREAM-ID"],M={attrs:p,bitrate:0,id:f++,groupId:p["GROUP-ID"]||"",name:p.NAME||E||"",type:y,default:p.bool("DEFAULT"),autoselect:p.bool("AUTOSELECT"),forced:p.bool("FORCED"),lang:E,url:p.URI?hm.resolve(p.URI,r):""};if(k&&(M.assocLang=k),P&&(M.channels=P),R&&(M.characteristics=R),D&&(M.instreamId=D),v!=null&&v.length){const B=hm.findGroup(v,M.groupId)||v[0];Vce(M,B,"audioCodec"),Vce(M,B,"textCodec")}T.push(M)}}return o}static parseLevelPlaylist(e,r,n,i,o,c){var a;const f={url:r},p=new AOt(r),y=p.fragments,v=[];let T=null,E=0,k=0,P=0,R=0,D=0,M=null,B=new d6(i,f),V,G,W,Y=-1,J=!1,Q=null,ee;if(p6.lastIndex=0,p.m3u8=e,p.hasVariableRefs=Rce(e),((a=p6.exec(e))==null?void 0:a[0])!=="#EXTM3U")return p.playlistParsingError=new Error("Missing format identifier #EXTM3U"),p;for(;(V=p6.exec(e))!==null;){J&&(J=!1,B=new d6(i,f),B.playlistOffset=P,B.setStart(P),B.sn=E,B.cc=R,D&&(B.bitrate=D),B.level=n,T&&(B.initSegment=T,T.rawProgramDateTime&&(B.rawProgramDateTime=T.rawProgramDateTime,T.rawProgramDateTime=null),Q&&(B.setByteRange(Q),Q=null)));const je=V[1];if(je){B.duration=parseFloat(je);const Le=(" "+V[2]).slice(1);B.title=Le||null,B.tagList.push(Le?["INF",je,Le]:["INF",je])}else if(V[3]){if(pn(B.duration)){B.playlistOffset=P,B.setStart(P),W&&Gce(B,W,p),B.sn=E,B.level=n,B.cc=R,y.push(B);const Le=(" "+V[3]).slice(1);B.relurl=lG(p,Le),uG(B,M,v),M=B,P+=B.duration,E++,k=0,J=!0}}else{if(V=V[0].match(DOt),!V){qs.warn("No matches on slow regex match for level playlist!");continue}for(G=1;G0&&Hce(p,Le,V),E=p.startSN=parseInt(Ae);break;case"SKIP":{p.skippedSegments&&vp(p,Le,V);const me=new Qa(Ae,p),Te=me.decimalInteger("SKIPPED-SEGMENTS");if(pn(Te)){p.skippedSegments+=Te;for(let Ee=Te;Ee--;)y.push(null);E+=Te}const Ne=me.enumeratedString("RECENTLY-REMOVED-DATERANGES");Ne&&(p.recentlyRemovedDateranges=(p.recentlyRemovedDateranges||[]).concat(Ne.split(" ")));break}case"TARGETDURATION":p.targetduration!==0&&vp(p,Le,V),p.targetduration=Math.max(parseInt(Ae),1);break;case"VERSION":p.version!==null&&vp(p,Le,V),p.version=parseInt(Ae);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":p.live||vp(p,Le,V),p.live=!1;break;case"#":(Ae||be)&&B.tagList.push(be?[Ae,be]:[Ae]);break;case"DISCONTINUITY":R++,B.tagList.push(["DIS"]);break;case"GAP":B.gap=!0,B.tagList.push([Le]);break;case"BITRATE":B.tagList.push([Le,Ae]),D=parseInt(Ae)*1e3,pn(D)?B.bitrate=D:D=0;break;case"DATERANGE":{const me=new Qa(Ae,p),Te=new M2e(me,p.dateRanges[me.ID],p.dateRangeTagCount);p.dateRangeTagCount++,Te.isValid||p.skippedSegments?p.dateRanges[Te.id]=Te:qs.warn(`Ignoring invalid DATERANGE tag: "${Ae}"`),B.tagList.push(["EXT-X-DATERANGE",Ae]);break}case"DEFINE":{{const me=new Qa(Ae,p);"IMPORT"in me?bOt(p,me,c):Lce(p,me,r)}break}case"DISCONTINUITY-SEQUENCE":p.startCC!==0?vp(p,Le,V):y.length>0&&Hce(p,Le,V),p.startCC=R=parseInt(Ae);break;case"KEY":{const me=$ce(Ae,r,p);if(me.isSupported()){if(me.method==="NONE"){W=void 0;break}W||(W={});const Te=W[me.keyFormat];Te!=null&&Te.matches(me)||(Te&&(W=Js({},W)),W[me.keyFormat]=me)}else qs.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${Ae}"`);break}case"START":p.startTimeOffset=zce(Ae);break;case"MAP":{const me=new Qa(Ae,p);if(B.duration){const Te=new d6(i,f);qce(Te,me,n,W),T=Te,B.initSegment=T,T.rawProgramDateTime&&!B.rawProgramDateTime&&(B.rawProgramDateTime=T.rawProgramDateTime)}else{const Te=B.byteRangeEndOffset;if(Te){const Ne=B.byteRangeStartOffset;Q=`${Te-Ne}@${Ne}`}else Q=null;qce(B,me,n,W),T=B,J=!0}T.cc=R;break}case"SERVER-CONTROL":{ee&&vp(p,Le,V),ee=new Qa(Ae),p.canBlockReload=ee.bool("CAN-BLOCK-RELOAD"),p.canSkipUntil=ee.optionalFloat("CAN-SKIP-UNTIL",0),p.canSkipDateRanges=p.canSkipUntil>0&&ee.bool("CAN-SKIP-DATERANGES"),p.partHoldBack=ee.optionalFloat("PART-HOLD-BACK",0),p.holdBack=ee.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{p.partTarget&&vp(p,Le,V);const me=new Qa(Ae);p.partTarget=me.decimalFloatingPoint("PART-TARGET");break}case"PART":{let me=p.partList;me||(me=p.partList=[]);const Te=k>0?me[me.length-1]:void 0,Ne=k++,Ee=new Qa(Ae,p),we=new bMt(Ee,B,f,Ne,Te);me.push(we),B.duration+=we.duration;break}case"PRELOAD-HINT":{const me=new Qa(Ae,p);p.preloadHint=me;break}case"RENDITION-REPORT":{const me=new Qa(Ae,p);p.renditionReports=p.renditionReports||[],p.renditionReports.push(me);break}default:qs.warn(`line parsed but not handled: ${V}`);break}}}M&&!M.relurl?(y.pop(),P-=M.duration,p.partList&&(p.fragmentHint=M)):p.partList&&(uG(B,M,v),B.cc=R,p.fragmentHint=B,W&&Gce(B,W,p)),p.targetduration||(p.playlistParsingError=new Error("Missing Target Duration"));const le=y.length,pe=y[0],Se=y[le-1];if(P+=p.skippedSegments*p.targetduration,P>0&&le&&Se){p.averagetargetduration=P/le;const je=Se.sn;p.endSN=je!=="initSegment"?je:0,p.live||(Se.endList=!0),Y>0&&(OOt(y,Y),pe&&v.unshift(pe))}return p.fragmentHint&&(P+=p.fragmentHint.duration),p.totalduration=P,v.length&&p.dateRangeTagCount&&pe&&z2e(v,p),p.endCC=R,p}}function z2e(t,e){let r=t.length;if(!r)if(e.hasProgramDateTime){const a=e.fragments[e.fragments.length-1];t.push(a),r++}else return;const n=t[r-1],i=e.live?1/0:e.totalduration,o=Object.keys(e.dateRanges);for(let a=o.length;a--;){const f=e.dateRanges[o[a]],p=f.startDate.getTime();f.tagAnchor=n.ref;for(let y=r;y--;){var c;if(((c=t[y])==null?void 0:c.sn)=a||n===0){var c;const f=(((c=r[n+1])==null?void 0:c.start)||i)-o.start;if(e<=a+f*1e3){const p=r[n].sn-t.startSN;if(p<0)return-1;const y=t.fragments;if(y.length>r.length){const T=(r[n+1]||y[y.length-1]).sn-t.startSN;for(let E=T;E>p;E--){const k=y[E].programDateTime;if(e>=k&&en);["video","audio","text"].forEach(n=>{const i=r.filter(o=>PK(o,n));i.length&&(e[`${n}Codec`]=i.map(o=>o.split("/")[0]).join(","),r=r.filter(o=>i.indexOf(o)===-1))}),e.unknownCodecs=r}function Vce(t,e,r){const n=e[r];n&&(t[r]=n)}function OOt(t,e){let r=t[e];for(let n=e;n--;){const i=t[n];if(!i)return;i.programDateTime=r.programDateTime-i.duration*1e3,r=i}}function uG(t,e,r){t.rawProgramDateTime?r.push(t):e!=null&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function qce(t,e,r,n){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=r,t.sn="initSegment",n&&(t.levelkeys=n),t.initSegment=null}function Gce(t,e,r){t.levelkeys=e;const{encryptedFragments:n}=r;(!n.length||n[n.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&n.push(t)}function vp(t,e,r){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${r[0]})`)}function Hce(t,e,r){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${r[0]})`)}function g6(t,e){const r=e.startPTS;if(pn(r)){let n=0,i;e.sn>t.sn?(n=r-t.start,i=t):(n=t.start-r,i=e),i.duration!==n&&i.setDuration(n)}else e.sn>t.sn?t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration):e.setStart(Math.max(t.start-e.duration,0))}function U2e(t,e,r,n,i,o,c){n-r<=0&&(c.warn("Fragment should have a positive duration",e),n=r+e.duration,o=i+e.duration);let f=r,p=n;const y=e.startPTS,v=e.endPTS;if(pn(y)){const D=Math.abs(y-r);t&&D>t.totalduration?c.warn(`media timestamps and playlist times differ by ${D}s for level ${e.level} ${t.url}`):pn(e.deltaPTS)?e.deltaPTS=Math.max(D,e.deltaPTS):e.deltaPTS=D,f=Math.max(r,y),r=Math.min(r,y),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,p=Math.min(n,v),n=Math.max(n,v),o=e.endDTS!==void 0?Math.max(o,e.endDTS):o}const T=r-e.start;e.start!==0&&e.setStart(r),e.setDuration(n-e.start),e.startPTS=r,e.maxStartPTS=f,e.startDTS=i,e.endPTS=n,e.minEndPTS=p,e.endDTS=o;const E=e.sn;if(!t||Et.endSN)return 0;let k;const P=E-t.startSN,R=t.fragments;for(R[P]=e,k=P;k>0;k--)g6(R[k],R[k-1]);for(k=P;k=0;y--){const v=i[y].initSegment;if(v){n=v;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let o;zOt(t,e,(y,v,T,E)=>{if((!e.startCC||e.skippedSegments)&&v.cc!==y.cc){const k=y.cc-v.cc;for(let P=T;P{var v;y&&(!y.initSegment||y.initSegment.relurl===((v=n)==null?void 0:v.relurl))&&(y.initSegment=n)}),e.skippedSegments){if(e.deltaUpdateFailed=c.some(y=>!y),e.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let y=e.skippedSegments;y--;)c.shift();e.startSN=c[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=BOt(t.dateRanges,e,r));const y=t.fragments.filter(v=>v.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let v=1;v{v.elementaryStreams=y.elementaryStreams,v.stats=y.stats}),o?U2e(e,o,o.startPTS,o.endPTS,o.startDTS,o.endDTS,r):V2e(t,e),c.length&&(e.totalduration=e.edge-c[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const p=e.advancedDateTime;if(e.advanced&&p){const y=e.edge;e.driftStart||(e.driftStartTime=p,e.driftStart=y),e.driftEndTime=p,e.driftEnd=y}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=t.requestScheduled)}function BOt(t,e,r){const{dateRanges:n,recentlyRemovedDateranges:i}=e,o=Js({},t);i&&i.forEach(f=>{delete o[f]});const a=Object.keys(o).length;return a?(Object.keys(n).forEach(f=>{const p=o[f],y=new M2e(n[f].attr,p);y.isValid?(o[f]=y,p||(y.tagOrder+=a)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${aa(n[f].attr)}"`)}),o):n}function $Ot(t,e,r){if(t&&e){let n=0;for(let i=0,o=t.length;i<=o;i++){const c=t[i],a=e[i+n];c&&a&&c.index===a.index&&c.fragment.sn===a.fragment.sn?r(c,a):n--}}}function zOt(t,e,r){const n=e.skippedSegments,i=Math.max(t.startSN,e.startSN)-e.startSN,o=(t.fragmentHint?1:0)+(n?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,c=e.startSN-t.startSN,a=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,f=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let p=i;p<=o;p++){const y=f[c+p];let v=a[p];if(n&&!v&&y&&(v=e.fragments[p]=y),y&&v){r(y,v,p,a);const T=y.relurl,E=v.relurl;if(T&&UOt(T,E)){e.playlistParsingError=Wce(`media sequence mismatch ${v.sn}:`,t,e,y,v);return}else if(y.cc!==v.cc){e.playlistParsingError=Wce(`discontinuity sequence mismatch (${y.cc}!=${v.cc})`,t,e,y,v);return}}}}function Wce(t,e,r,n,i){return new Error(`${t} ${i.url} Playlist starting @${e.startSN} ${e.m3u8} Playlist starting @${r.startSN} ${r.m3u8}`)}function V2e(t,e,r=!0){const n=e.startSN+e.skippedSegments-t.startSN,i=t.fragments,o=n>=0;let c=0;if(o&&ne){const o=n[n.length-1].duration*1e3;o{var n;(n=e.details)==null||n.fragments.forEach(i=>{i.level=r,i.initSegment&&(i.initSegment.level=r)})})}function UOt(t,e){return t!==e&&e?Yce(t)!==Yce(e):!1}function Yce(t){return t.replace(/\?[^?]*$/,"")}function EA(t,e){for(let n=0,i=t.length;nt.startCC)}function Zce(t,e){const r=t.start+e;t.startPTS=r,t.setStart(r),t.endPTS=r+t.duration}function K2e(t,e){const r=e.fragments;for(let n=0,i=r.length;n{const{config:c,fragCurrent:a,media:f,mediaBuffer:p,state:y}=this,v=f?f.currentTime:0,T=Ti.bufferInfo(p||f,v,c.maxBufferHole),E=!T.len;if(this.log(`Media seeking to ${pn(v)?v.toFixed(3):v}, state: ${y}, ${E?"out of":"in"} buffer`),this.state===wr.ENDED)this.resetLoadingState();else if(a){const k=c.maxFragLookUpTolerance,P=a.start-k,R=a.start+a.duration+k;if(E||RT.end){const D=v>R;(vk&&(this.lastCurrentTime=v),!this.loadingParts){const P=Math.max(T.end,v),R=this.shouldLoadParts(this.getLevelDetails(),P);R&&(this.log(`LL-Part loading ON after seeking to ${v.toFixed(2)} with buffer @${P.toFixed(2)}`),this.loadingParts=R)}}this.hls.hasEnoughToStart||(this.log(`Setting ${E?"startPosition":"nextLoadPosition"} to ${v} for seek without enough to start`),this.nextLoadPosition=v,E&&(this.startPosition=v)),E&&this.state===wr.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=o,this.hls=e,this.fragmentLoader=new vOt(e.config),this.keyLoader=n,this.fragmentTracker=r,this.config=e.config,this.decrypter=new DK(e.config)}registerListeners(){const{hls:e}=this;e.on(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ce.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Ce.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ce.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Ce.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===wr.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=wr.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:r}=this;return r===-1&&e?e:r}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,r){if(r.live||!this.media)return!1;const n=e.end||0,i=this.config.timelineOffset||0;if(n<=i)return!1;const o=e.buffered;this.config.maxBufferHole&&o&&o.length>1&&(e=Ti.bufferedInfo(o,e.start,0));const c=e.nextStart;if(c&&c>i&&c{const c=o.frag;if(this.fragContextChanged(c)){this.warn(`${c.type} sn: ${c.sn}${o.part?" part: "+o.part.index:""} of ${this.fragInfo(c,!1,o.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(c);return}c.stats.chunkCount++,this._handleFragmentLoadProgress(o)};this._doFragLoad(e,r,n,i).then(o=>{if(!o)return;const c=this.state,a=o.frag;if(this.fragContextChanged(a)){(c===wr.FRAG_LOADING||!this.fragCurrent&&c===wr.PARSING)&&(this.fragmentTracker.removeFragment(a),this.state=wr.IDLE);return}"payload"in o&&(this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level}`),this.hls.trigger(Ce.FRAG_LOADED,o)),this._handleFragmentLoadComplete(o)}).catch(o=>{this.state===wr.STOPPED||this.state===wr.ERROR||(this.warn(`Frag error: ${(o==null?void 0:o.message)||o}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var r;const{fragmentTracker:n}=this;if(n.getState(e)===dl.APPENDING){const o=e.type,c=this.getFwdBufferInfo(this.mediaBuffer,o),a=Math.max(e.duration,c?c.len:this.config.maxBufferLength),f=this.backtrackFragment;((f?e.sn-f.sn:0)===1||this.reduceMaxBufferLength(a,e.duration))&&n.removeFragment(e)}else((r=this.mediaBuffer)==null?void 0:r.buffered.length)===0?n.removeAllFragments():n.hasParts(e.type)&&(n.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),n.getState(e)===dl.PARTIAL&&n.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const r=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const r=e.details;return(r==null?void 0:r.live)&&r.type!=="EVENT"&&(this.levelLastLoaded!==e||r.expired)}flushMainBuffer(e,r,n=null){if(!(e-r))return;const i={startOffset:e,endOffset:r,type:n};this.hls.trigger(Ce.BUFFER_FLUSHING,i)}_loadInitSegment(e,r){this._doFragLoad(e,r).then(n=>{const i=n==null?void 0:n.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return n}).then(n=>{const{hls:i}=this,{frag:o,payload:c}=n,a=o.decryptdata;if(c&&c.byteLength>0&&a!=null&&a.key&&a.iv&&N1(a.method)){const f=self.performance.now();return this.decrypter.decrypt(new Uint8Array(c),a.key.buffer,a.iv.buffer,OK(a.method)).catch(p=>{throw i.trigger(Ce.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.FRAG_DECRYPT_ERROR,fatal:!1,error:p,reason:p.message,frag:o}),p}).then(p=>{const y=self.performance.now();return i.trigger(Ce.FRAG_DECRYPTED,{frag:o,payload:p,stats:{tstart:f,tdecrypt:y}}),n.payload=p,this.completeInitSegmentLoad(n)})}return this.completeInitSegmentLoad(n)}).catch(n=>{this.state===wr.STOPPED||this.state===wr.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:r}=this;if(!r)throw new Error("init load aborted, missing levels");const n=e.frag.stats;this.state!==wr.STOPPED&&(this.state=wr.IDLE),e.frag.data=new Uint8Array(e.payload),n.parsing.start=n.buffering.start=self.performance.now(),n.parsing.end=n.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,r){var n,i;const o=e.tracks;if(o&&!r.encrypted&&((n=o.audio)!=null&&n.encrypted||(i=o.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const c=this.media,a=new Error(`Encrypted track with no key in ${this.fragInfo(r)} (media ${c?"attached mediaKeys: "+c.mediaKeys:"detached"})`);return this.warn(a.message),!c||c.mediaKeys?!1:(this.hls.trigger(Ce.ERROR,{type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_NO_KEYS,fatal:!1,error:a,frag:r}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:r}=this;return!e||!r||e.sn!==r.sn||e.level!==r.level}fragBufferedComplete(e,r){const n=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${r?" part: "+r.index:""} of ${this.fragInfo(e,!1,r)} > buffer:${n?GOt.toString(Ti.getBuffered(n)):"(detached)"})`),Io(e)){var i;if(e.type!==Tn.SUBTITLE){const c=e.elementaryStreams;if(!Object.keys(c).some(a=>!!c[a])){this.state=wr.IDLE;return}}const o=(i=this.levels)==null?void 0:i[e.level];o!=null&&o.fragmentError&&(this.log(`Resetting level fragment error count of ${o.fragmentError} on frag buffered`),o.fragmentError=0)}this.state=wr.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:r}=this;if(!r)return;const{frag:n,part:i,partsLoaded:o}=e,c=!o||o.length===0||o.some(f=>!f),a=new MK(n.level,n.sn,n.stats.chunkCount+1,0,i?i.index:-1,!c);r.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,r,n=null,i){var o;this.fragCurrent=e;const c=r.details;if(!this.levels||!c)throw new Error(`frag load aborted, missing level${c?"":" detail"}s`);let a=null;if(e.encrypted&&!((o=e.decryptdata)!=null&&o.key)){if(this.log(`Loading key for ${e.sn} of [${c.startSN}-${c.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=wr.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then(T=>{if(!this.fragContextChanged(T.frag))return this.hls.trigger(Ce.KEY_LOADED,T),this.state===wr.KEY_LOADING&&(this.state=wr.IDLE),T}),this.hls.trigger(Ce.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(a=this.keyLoader.loadClear(e,c.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));const f=this.fragPrevious;if(Io(e)&&(!f||e.sn!==f.sn)){const T=this.shouldLoadParts(r.details,e.end);T!==this.loadingParts&&(this.log(`LL-Part loading ${T?"ON":"OFF"} loading sn ${f==null?void 0:f.sn}->${e.sn}`),this.loadingParts=T)}if(n=Math.max(e.start,n||0),this.loadingParts&&Io(e)){const T=c.partList;if(T&&i){n>c.fragmentEnd&&c.fragmentHint&&(e=c.fragmentHint);const E=this.getNextPart(T,e,n);if(E>-1){const k=T[E];e=this.fragCurrent=k.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${k.index} (${E}/${T.length-1}) of ${this.fragInfo(e,!1,k)}) cc: ${e.cc} [${c.startSN}-${c.endSN}], target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=k.start+k.duration,this.state=wr.FRAG_LOADING;let P;return a?P=a.then(R=>!R||this.fragContextChanged(R.frag)?null:this.doFragPartsLoad(e,k,r,i)).catch(R=>this.handleFragLoadError(R)):P=this.doFragPartsLoad(e,k,r,i).catch(R=>this.handleFragLoadError(R)),this.hls.trigger(Ce.FRAG_LOADING,{frag:e,part:k,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):P}else if(!e.url||this.loadedEndOfParts(T,n))return Promise.resolve(null)}}if(Io(e)&&this.loadingParts){var p;this.log(`LL-Part loading OFF after next part miss @${n.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(p=c.partList)==null?void 0:p.filter(T=>T.loaded).map(T=>`[${T.start}-${T.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+c.startSN+"-"+c.endSN+"]"}, target: ${parseFloat(n.toFixed(3))}`),pn(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=wr.FRAG_LOADING;const y=this.config.progressive&&e.type!==Tn.SUBTITLE;let v;return y&&a?v=a.then(T=>!T||this.fragContextChanged(T.frag)?null:this.fragmentLoader.load(e,i)).catch(T=>this.handleFragLoadError(T)):v=Promise.all([this.fragmentLoader.load(e,y?i:void 0),a]).then(([T])=>(!y&&i&&i(T),T)).catch(T=>this.handleFragLoadError(T)),this.hls.trigger(Ce.FRAG_LOADING,{frag:e,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):v}doFragPartsLoad(e,r,n,i){return new Promise((o,c)=>{var a;const f=[],p=(a=n.details)==null?void 0:a.partList,y=v=>{this.fragmentLoader.loadPart(e,v,i).then(T=>{f[v.index]=T;const E=T.part;this.hls.trigger(Ce.FRAG_LOADED,T);const k=Kce(n.details,e.sn,v.index+1)||H2e(p,e.sn,v.index+1);if(k)y(k);else return o({frag:e,part:E,partsLoaded:f})}).catch(c)};y(r)})}handleFragLoadError(e){if("data"in e){const r=e.data;r.frag&&r.details===Jt.INTERNAL_ABORTED?this.handleFragLoadAborted(r.frag,r.part):r.frag&&r.type===Dn.KEY_SYSTEM_ERROR?(r.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(r.frag)):this.hls.trigger(Ce.ERROR,r)}else this.hls.trigger(Ce.ERROR,{type:Dn.OTHER_ERROR,details:Jt.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const r=this.getCurrentContext(e);if(!r||this.state!==wr.PARSING){!this.fragCurrent&&this.state!==wr.STOPPED&&this.state!==wr.ERROR&&(this.state=wr.IDLE);return}const{frag:n,part:i,level:o}=r,c=self.performance.now();n.stats.parsing.end=c,i&&(i.stats.parsing.end=c);const a=this.getLevelDetails(),p=a&&n.sn>a.endSN||this.shouldLoadParts(a,n.end);p!==this.loadingParts&&(this.log(`LL-Part loading ${p?"ON":"OFF"} after parsing segment ending @${n.end.toFixed(2)}`),this.loadingParts=p),this.updateLevelTiming(n,i,o,e.partial)}shouldLoadParts(e,r){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var n;const o=e.partList[0];if(o.fragment.type===Tn.SUBTITLE)return!1;const c=o.end+(((n=e.fragmentHint)==null?void 0:n.duration)||0);if(r>=c){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>o.start-o.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:r,fragCurrent:n}=this,{level:i,sn:o,part:c}=e;if(!(r!=null&&r[i]))return this.warn(`Levels object was unset while buffering fragment ${o} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=r[i],f=a.details,p=c>-1?Kce(f,o,c):null,y=p?p.fragment:G2e(f,o,n);return y?(n&&n!==y&&(y.stats=n.stats),{frag:y,part:p,level:a}):null}bufferFragmentData(e,r,n,i,o){if(this.state!==wr.PARSING)return;const{data1:c,data2:a}=e;let f=c;if(a&&(f=ph(c,a)),!f.length)return;const p=this.initPTS[r.cc],y=p?-p.baseTime/p.timescale:void 0,v={type:e.type,frag:r,part:n,chunkMeta:i,offset:y,parent:r.type,data:f};if(this.hls.trigger(Ce.BUFFER_APPENDING,v),e.dropped&&e.independent&&!n){if(o)return;this.flushBufferGap(r)}}flushBufferGap(e){const r=this.media;if(!r)return;if(!Ti.isBuffered(r,r.currentTime)){this.flushMainBuffer(0,e.start);return}const n=r.currentTime,i=Ti.bufferInfo(r,n,0),o=e.duration,c=Math.min(this.config.maxFragLookUpTolerance*2,o*.25),a=Math.max(Math.min(e.start-c,i.end-c),n+c);e.start-a>c&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,r){var n;const i=this.getLoadPosition();if(!pn(i))return null;const c=this.lastCurrentTime>i||(n=this.media)!=null&&n.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,r,c)}getFwdBufferInfoAtPos(e,r,n,i){const o=Ti.bufferInfo(e,r,i);if(o.len===0&&o.nextStart!==void 0){const c=this.fragmentTracker.getBufferedFrag(r,n);if(c&&(o.nextStart<=c.end||c.gap)){const a=Math.max(Math.min(o.nextStart,c.end)-r,i);return Ti.bufferInfo(e,r,a)}}return o}getMaxBufferLength(e){const{config:r}=this;let n;return e?n=Math.max(8*r.maxBufferSize/e,r.maxBufferLength):n=r.maxBufferLength,Math.min(n,r.maxMaxBufferLength)}exceedsMaxBuffer(e,r,n){const i=e.nextStart;if(i&&n.start>i){const o=e.buffered;if(o){let c=e.len;const a=e.bufferedIndex;for(let f=o.length-1;f>a;f--)o[f].start=r}}return!1}reduceMaxBufferLength(e,r){const n=this.config,i=Math.max(Math.min(e-r,n.maxBufferLength),r),o=Math.max(e-r*3,n.maxMaxBufferLength/2,i);return o>=i?(n.maxMaxBufferLength=o,this.warn(`Reduce max buffer length to ${o}s`),!0):!1}getAppendedFrag(e,r=Tn.MAIN){const n=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,r):null;return n&&"fragment"in n?n.fragment:n}getNextFragment(e,r){const n=r.fragments,i=n.length;if(!i)return null;const{config:o}=this,c=r.fragmentStart,a=o.lowLatencyMode&&!!r.partList;let f=null;if(r.live){const v=o.initialLiveManifestSize;if(i=c?(R=E,D=E===T?"config":"next load start"):k!==null?(R=k,D="live edge"):(R=e,D="buffer pos"),R=o){const f=c.sn;return this.loopSn!==f&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${f}`),this.loopSn=f),null}}return this.loopSn=void 0,c}get primaryPrefetch(){if(Xce(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,r){if(!e)return e;if(Xce(this.config)&&e.type!==Tn.SUBTITLE){const n=this.hls.interstitialsManager,i=n==null?void 0:n.bufferingItem;if(i){const c=i.event;if(c){if(c.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&(r==null?void 0:r.live)===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const o=n==null?void 0:n.playerQueue;if(o)for(let c=o.length;c--;){const a=o[c].interstitial;if(a.appendInPlace&&e.start>=a.startTime&&e.end<=a.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,r,n){let i=-1,o=!1,c=!0;for(let a=0,f=e.length;a-1&&nn.start)return!0}return!1}getInitialLiveFragment(e){const r=e.fragments,n=this.fragPrevious;let i=null;if(n){if(e.hasProgramDateTime&&(i=oOt(r,n.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`)),!i){const o=n.sn+1;if(o>=e.startSN&&o<=e.endSN){const c=r[o-e.startSN];n.cc===c.cc&&(i=c,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=I2e(e,n.cc,n.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const o=this.hls.liveSyncPosition;o!==null&&(i=this.getFragmentAtPosition(o,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,r,n){const{config:i}=this;let{fragPrevious:o}=this,{fragments:c,endSN:a}=n;const{fragmentHint:f}=n,{maxFragLookUpTolerance:p}=i,y=n.partList,v=!!(this.loadingParts&&y!=null&&y.length&&f);v&&!this.bitrateTest&&y[y.length-1].fragment.sn===f.sn&&(c=c.concat(f),a=f.sn);let T;if(er-p||(E=this.media)!=null&&E.paused||!this.startFragRequested?0:p;T=g_(o,c,e,P)}else T=c[c.length-1];if(T){const k=T.sn-n.startSN,P=this.fragmentTracker.getState(T);if((P===dl.OK||P===dl.PARTIAL&&T.gap)&&(o=T),o&&T.sn===o.sn&&(!v||y[0].fragment.sn>T.sn||!n.live)&&T.level===o.level){const D=c[k+1];T.sn${e.startSN} fragments: ${i}`),f}return o}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,r){let n=this.startPosition;n=0&&(n=this.nextLoadPosition),n}handleFragLoadAborted(e,r){this.transmuxer&&e.type===this.playlistType&&Io(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${r?" part "+r.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==wr.FRAG_LOADING_WAITING_RETRY)&&(this.state=wr.IDLE)}onFragmentOrKeyLoadError(e,r){var n;if(r.chunkMeta&&!r.frag){const D=this.getCurrentContext(r.chunkMeta);D&&(r.frag=D.frag)}const i=r.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var o;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(o=this.fragCurrent)==null?void 0:o.url}`);return}const c=r.details===Jt.FRAG_GAP;c&&this.fragmentTracker.fragBuffered(i,!0);const a=r.errorAction;if(!a){this.state=wr.ERROR;return}const{action:f,flags:p,retryCount:y=0,retryConfig:v}=a,T=!!v,E=T&&f===Kl.RetryRequest,k=T&&!a.resolved&&p===td.MoveAllAlternatesMatchingHost,P=(n=this.hls.latestLevelDetails)==null?void 0:n.live;if(!E&&k&&Io(i)&&!i.endList&&P&&!R2e(r))this.resetFragmentErrors(e),this.treatAsGap(i),a.resolved=!0;else if((E||k)&&y=r||n&&!oG(0))&&(n&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=wr.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===wr.PARSING||this.state===wr.PARSED){const r=e.frag,n=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,n),o=i&&i.len>.5;o&&this.reduceMaxBufferLength(i.len,(r==null?void 0:r.duration)||10);const c=!o;return c&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${n} buffer`),r&&(this.fragmentTracker.removeFragment(r),this.nextLoadPosition=r.start),this.resetLoadingState(),c}return!1}resetFragmentErrors(e){e===Tn.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==wr.STOPPED&&(this.state=wr.IDLE)}afterBufferFlushed(e,r,n){if(!e)return;const i=Ti.getBuffered(e);this.fragmentTracker.detectEvictedFragments(r,i,n),this.state===wr.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==wr.STOPPED&&(this.state=wr.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,r=e?e.details:null;r!=null&&r.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(r,r.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,r,n,i){const o=n.details;if(!o){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((f,p)=>{const y=e.elementaryStreams[p];if(y){const v=y.endPTS-y.startPTS;if(v<=0)return this.warn(`Could not parse fragment ${e.sn} ${p} duration reliably (${v})`),f||!1;const T=i?0:U2e(o,e,y.startPTS,y.endPTS,y.startDTS,y.endDTS,this);return this.hls.trigger(Ce.LEVEL_PTS_UPDATED,{details:o,level:n,drift:T,type:p,frag:e,start:y.startPTS,end:y.endPTS}),!0}return f},!1)){var a;const f=((a=this.transmuxer)==null?void 0:a.error)===null;if((n.fragmentError===0||f&&(n.fragmentError<2||e.endList))&&this.treatAsGap(e,n),f){const p=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(p.message),this.hls.trigger(Ce.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.FRAG_PARSING_ERROR,fatal:!1,error:p,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=wr.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${r?" part: "+r.index:""} of ${this.fragInfo(e,!1,r)})`),this.hls.trigger(Ce.FRAG_PARSED,{frag:e,part:r})}playlistLabel(){return this.playlistType===Tn.MAIN?"level":"track"}fragInfo(e,r=!0,n){var i,o;return`${this.playlistLabel()} ${e.level} (${n?"part":"frag"}:[${((i=r&&!n?e.startPTS:(n||e).start)!=null?i:NaN).toFixed(3)}-${((o=r&&!n?e.endPTS:(n||e).end)!=null?o:NaN).toFixed(3)}]${n&&e.type==="main"?"INDEPENDENT="+(n.independent?"YES":"NO"):""}`}treatAsGap(e,r){r&&r.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const r=this._state;r!==e&&(this._state=e,this.log(`${r}->${e}`))}get state(){return this._state}}function Xce(t){return!!t.interstitialsController&&t.enableInterstitialPlayback!==!1}class Z2e{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:r}=this;let n;if(e.length)e.length===1?n=e[0]:n=HOt(e,r);else return new Uint8Array(0);return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}}function HOt(t,e){const r=new Uint8Array(e);let n=0;for(let i=0;i0)return t.subarray(r,r+n)}function JOt(t,e,r,n){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],o=e[r+2],c=o>>2&15;if(c>12){const E=new Error(`invalid ADTS sampling index:${c}`);t.emit(Ce.ERROR,Ce.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.FRAG_PARSING_ERROR,fatal:!0,error:E,reason:E.message});return}const a=(o>>6&3)+1,f=e[r+3]>>6&3|(o&1)<<2,p="mp4a.40."+a,y=i[c];let v=c;(a===5||a===29)&&(v-=3);const T=[a<<3|(v&14)>>1,(v&1)<<7|f<<3];return qs.log(`manifest codec:${n}, parsed codec:${p}, channels:${f}, rate:${y} (ADTS object type:${a} sampling index:${c})`),{config:T,samplerate:y,channelCount:f,codec:p,parsedCodec:p,manifestCodec:n}}function Q2e(t,e){return t[e]===255&&(t[e+1]&246)===240}function J2e(t,e){return t[e+1]&1?7:9}function UK(t,e){return(t[e+3]&3)<<11|t[e+4]<<3|(t[e+5]&224)>>>5}function e3t(t,e){return e+5=t.length)return!1;const n=UK(t,e);if(n<=r)return!1;const i=e+n;return i===t.length||kO(t,i)}return!1}function eAe(t,e,r,n,i){if(!t.samplerate){const o=JOt(e,r,n,i);if(!o)return;Js(t,o)}}function tAe(t){return 1024*9e4/t}function n3t(t,e){const r=J2e(t,e);if(e+r<=t.length){const n=UK(t,e)-r;if(n>0)return{headerLength:r,frameLength:n}}}function rAe(t,e,r,n,i){const o=tAe(t.samplerate),c=n+i*o,a=n3t(e,r);let f;if(a){const{frameLength:v,headerLength:T}=a,E=T+v,k=Math.max(0,r+E-e.length);k?(f=new Uint8Array(E-T),f.set(e.subarray(r+T,e.length),0)):f=e.subarray(r+T,r+E);const P={unit:f,pts:c};return k||t.samples.push(P),{sample:P,length:E,missing:k}}const p=e.length-r;return f=new Uint8Array(p),f.set(e.subarray(r,e.length),0),{sample:{unit:f,pts:c},length:p,missing:-1}}function i3t(t,e){return zK(t,e)&&_5(t,e+6)+10<=t.length-e}function s3t(t){return t instanceof ArrayBuffer?t:t.byteOffset==0&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function x6(t,e=0,r=1/0){return a3t(t,e,r,Uint8Array)}function a3t(t,e,r,n){const i=o3t(t);let o=1;"BYTES_PER_ELEMENT"in n&&(o=n.BYTES_PER_ELEMENT);const c=l3t(t)?t.byteOffset:0,a=(c+t.byteLength)/o,f=(c+e)/o,p=Math.floor(Math.max(0,Math.min(f,a))),y=Math.floor(Math.min(p+Math.max(r,0),a));return new n(i,p,y-p)}function o3t(t){return t instanceof ArrayBuffer?t:t.buffer}function l3t(t){return t&&t.buffer instanceof ArrayBuffer&&t.byteLength!==void 0&&t.byteOffset!==void 0}function c3t(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null},r=3;if(t.size<2)return;if(t.data[0]!==r){console.log("Ignore frame with unrecognized character encoding");return}const n=t.data.subarray(1).indexOf(0);if(n===-1)return;const i=pd(x6(t.data,1,n)),o=t.data[2+n],c=t.data.subarray(3+n).indexOf(0);if(c===-1)return;const a=pd(x6(t.data,3+n,c));let f;return i==="-->"?f=pd(x6(t.data,4+n+c)):f=s3t(t.data.subarray(4+n+c)),e.mimeType=i,e.pictureType=o,e.description=a,e.data=f,e}function u3t(t){if(t.size<2)return;const e=pd(t.data,!0),r=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:r.buffer}}function d3t(t){if(t.size<2)return;if(t.type==="TXXX"){let r=1;const n=pd(t.data.subarray(r),!0);r+=n.length+1;const i=pd(t.data.subarray(r));return{key:t.type,info:n,data:i}}const e=pd(t.data.subarray(1));return{key:t.type,info:"",data:e}}function h3t(t){if(t.type==="WXXX"){if(t.size<2)return;let r=1;const n=pd(t.data.subarray(r),!0);r+=n.length+1;const i=pd(t.data.subarray(r));return{key:t.type,info:n,data:i}}const e=pd(t.data);return{key:t.type,info:"",data:e}}function f3t(t){return t.type==="PRIV"?u3t(t):t.type[0]==="W"?h3t(t):t.type==="APIC"?c3t(t):d3t(t)}function m3t(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),r=_5(t,4),n=10;return{type:e,size:r,data:t.subarray(n,n+r)}}const ZR=10,p3t=10;function nAe(t){let e=0;const r=[];for(;zK(t,e);){const n=_5(t,e+6);t[e+5]>>6&1&&(e+=ZR),e+=ZR;const i=e+n;for(;e+p3t0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:od.audioId3,duration:Number.POSITIVE_INFINITY});i{if(pn(t))return t*90;const n=r?r.baseTime*9e4/r.timescale:0;return e*9e4+n};let XR=null;const x3t=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],v3t=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],_3t=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],b3t=[0,1,1,4];function sAe(t,e,r,n,i){if(r+24>e.length)return;const o=aAe(e,r);if(o&&r+o.frameLength<=e.length){const c=o.samplesPerFrame*9e4/o.sampleRate,a=n+i*c,f={unit:e.subarray(r,r+o.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=o.channelCount,t.samplerate=o.sampleRate,t.samples.push(f),{sample:f,length:o.frameLength,missing:0}}}function aAe(t,e){const r=t[e+1]>>3&3,n=t[e+1]>>1&3,i=t[e+2]>>4&15,o=t[e+2]>>2&3;if(r!==1&&i!==0&&i!==15&&o!==3){const c=t[e+2]>>1&1,a=t[e+3]>>6,f=r===3?3-n:n===3?3:4,p=x3t[f*14+i-1]*1e3,v=v3t[(r===3?0:r===2?1:2)*3+o],T=a===3?1:2,E=_3t[r][n],k=b3t[n],P=E*8*k,R=Math.floor(E*p/v+c)*k;if(XR===null){const B=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);XR=B?parseInt(B[1]):0}return!!XR&&XR<=87&&n===2&&p>=224e3&&a===0&&(t[e+3]=t[e+3]|128),{sampleRate:v,channelCount:T,frameLength:R,samplesPerFrame:P}}}function GK(t,e){return t[e]===255&&(t[e+1]&224)===224&&(t[e+1]&6)!==0}function oAe(t,e){return e+1{let r=0,n=5;e+=n;const i=new Uint32Array(1),o=new Uint32Array(1),c=new Uint8Array(1);for(;n>0;){c[0]=t[e];const a=Math.min(n,8),f=8-a;o[0]=4278190080>>>24+f<>f,r=r?r<e.length||e[r]!==11||e[r+1]!==119)return-1;const o=e[r+4]>>6;if(o>=3)return-1;const a=[48e3,44100,32e3][o],f=e[r+4]&63,y=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][f*3+o]*2;if(r+y>e.length)return-1;const v=e[r+6]>>5;let T=0;v===2?T+=2:(v&1&&v!==1&&(T+=2),v&4&&(T+=2));const E=(e[r+6]<<8|e[r+7])>>12-T&1,P=[2,1,2,3,3,4,4,5][v]+E,R=e[r+5]>>3,D=e[r+5]&7,M=new Uint8Array([o<<6|R<<1|D>>2,(D&3)<<6|v<<3|E<<2|f>>4,f<<4&224]),B=1536/a*9e4,V=n+i*B,G=e.subarray(r,r+y);return t.config=M,t.channelCount=P,t.samplerate=a,t.samples.push({unit:G,pts:V}),y}class E3t extends qK{resetInitSegment(e,r,n,i){super.resetInitSegment(e,r,n,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const r=oC(e,0);let n=(r==null?void 0:r.length)||0;if(r&&e[n]===11&&e[n+1]===119&&VK(r)!==void 0&&cAe(e,n)<=16)return!1;for(let i=e.length;n{const c=RMt(o);if(j3t.test(c.schemeIdUri)){const a=Jce(c,r);let f=c.eventDuration===4294967295?Number.POSITIVE_INFINITY:c.eventDuration/c.timeScale;f<=.001&&(f=Number.POSITIVE_INFINITY);const p=c.payload;n.samples.push({data:p,len:p.byteLength,dts:a,pts:a,type:od.emsg,duration:f})}else if(this.config.enableEmsgKLVMetadata&&c.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const a=Jce(c,r);n.samples.push({data:c.payload,len:c.payload.byteLength,dts:a,pts:a,type:od.misbklv,duration:Number.POSITIVE_INFINITY})}})}return n}demuxSampleAes(e,r,n){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function Jce(t,e){return pn(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class k3t{constructor(e,r,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new DK(r,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,jx.cbc)}decryptAacSample(e,r,n){const i=e[r].unit;if(i.length<=16)return;const o=i.subarray(16,i.length-i.length%16),c=o.buffer.slice(o.byteOffset,o.byteOffset+o.length);this.decryptBuffer(c).then(a=>{const f=new Uint8Array(a);i.set(f,16),this.decrypter.isSync()||this.decryptAacSamples(e,r+1,n)}).catch(n)}decryptAacSamples(e,r,n){for(;;r++){if(r>=e.length){n();return}if(!(e[r].unit.length<32)&&(this.decryptAacSample(e,r,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const r=Math.floor((e.length-48)/160)*16+16,n=new Int8Array(r);let i=0;for(let o=32;o{o.data=this.getAvcDecryptedUnit(c,f),this.decrypter.isSync()||this.decryptAvcSamples(e,r,n+1,i)}).catch(i)}decryptAvcSamples(e,r,n,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;r++,n=0){if(r>=e.length){i();return}const o=e[r].units;for(;!(n>=o.length);n++){const c=o[n];if(!(c.data.length<=48||c.type!==1&&c.type!==5)&&(this.decryptAvcSample(e,r,n,i,c),!this.decrypter.isSync()))return}}}}class dAe{constructor(){this.VideoSample=null}createVideoSample(e,r,n){return{key:e,frame:!1,pts:r,dts:n,units:[],length:0}}getLastNalUnit(e){var r;let n=this.VideoSample,i;if((!n||n.units.length===0)&&(n=e[e.length-1]),(r=n)!=null&&r.units){const o=n.units;i=o[o.length-1]}return i}pushAccessUnit(e,r){if(e.units.length&&e.frame){if(e.pts===void 0){const n=r.samples,i=n.length;if(i){const o=n[i-1];e.pts=o.pts,e.dts=o.dts}else{r.dropped++;return}}r.samples.push(e)}}parseNALu(e,r,n){const i=r.byteLength;let o=e.naluState||0;const c=o,a=[];let f=0,p,y,v,T=-1,E=0;for(o===-1&&(T=0,E=this.getNALuType(r,0),o=0,f=1);f=0){const k={data:r.subarray(T,y),type:E};a.push(k)}else{const k=this.getLastNalUnit(e.samples);k&&(c&&f<=4-c&&k.state&&(k.data=k.data.subarray(0,k.data.byteLength-c)),y>0&&(k.data=ph(k.data,r.subarray(0,y)),k.state=0))}f=0&&o>=0){const k={data:r.subarray(T,i),type:E,state:o};a.push(k)}if(a.length===0){const k=this.getLastNalUnit(e.samples);k&&(k.data=ph(k.data,r))}return e.naluState=o,a}}class jA{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,r=this.bytesAvailable,n=e.byteLength-r,i=new Uint8Array(4),o=Math.min(4,r);if(o===0)throw new Error("no bytes available");i.set(e.subarray(n,n+o)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=o*8,this.bytesAvailable-=o}skipBits(e){let r;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,r=e>>3,e-=r<<3,this.bytesAvailable-=r,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let r=Math.min(this.bitsAvailable,e);const n=this.word>>>32-r;if(e>32&&qs.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=r,this.bitsAvailable>0)this.word<<=r;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return r=e-r,r>0&&this.bitsAvailable?n<>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class C3t extends dAe{parsePES(e,r,n,i){const o=this.parseNALu(e,n.data,i);let c=this.VideoSample,a,f=!1;n.data=null,c&&o.length&&!e.audFound&&(this.pushAccessUnit(c,e),c=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),o.forEach(p=>{var y,v;switch(p.type){case 1:{let P=!1;a=!0;const R=p.data;if(f&&R.length>4){const D=this.readSliceType(R);(D===2||D===4||D===7||D===9)&&(P=!0)}if(P){var T;(T=c)!=null&&T.frame&&!c.key&&(this.pushAccessUnit(c,e),c=this.VideoSample=null)}c||(c=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),c.frame=!0,c.key=P;break}case 5:a=!0,(y=c)!=null&&y.frame&&!c.key&&(this.pushAccessUnit(c,e),c=this.VideoSample=null),c||(c=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),c.key=!0,c.frame=!0;break;case 6:{a=!0,IK(p.data,1,n.pts,r.samples);break}case 7:{var E,k;a=!0,f=!0;const P=p.data,R=this.readSPS(P);if(!e.sps||e.width!==R.width||e.height!==R.height||((E=e.pixelRatio)==null?void 0:E[0])!==R.pixelRatio[0]||((k=e.pixelRatio)==null?void 0:k[1])!==R.pixelRatio[1]){e.width=R.width,e.height=R.height,e.pixelRatio=R.pixelRatio,e.sps=[P];const D=P.subarray(1,4);let M="avc1.";for(let B=0;B<3;B++){let V=D[B].toString(16);V.length<2&&(V="0"+V),M+=V}e.codec=M}break}case 8:a=!0,e.pps=[p.data];break;case 9:a=!0,e.audFound=!0,(v=c)!=null&&v.frame&&(this.pushAccessUnit(c,e),c=null),c||(c=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts));break;case 12:a=!0;break;default:a=!1;break}c&&a&&c.units.push(p)}),i&&c&&(this.pushAccessUnit(c,e),this.VideoSample=null)}getNALuType(e,r){return e[r]&31}readSliceType(e){const r=new jA(e);return r.readUByte(),r.readUEG(),r.readUEG()}skipScalingList(e,r){let n=8,i=8,o;for(let c=0;c{var y,v;switch(p.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:c||(c=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),c.frame=!0,a=!0;break;case 16:case 17:case 18:case 21:if(a=!0,f){var T;(T=c)!=null&&T.frame&&!c.key&&(this.pushAccessUnit(c,e),c=this.VideoSample=null)}c||(c=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),c.key=!0,c.frame=!0;break;case 19:case 20:a=!0,(y=c)!=null&&y.frame&&!c.key&&(this.pushAccessUnit(c,e),c=this.VideoSample=null),c||(c=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),c.key=!0,c.frame=!0;break;case 39:a=!0,IK(p.data,2,n.pts,r.samples);break;case 32:a=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Js(e.params,this.readVPS(p.data)),this.initVPS=p.data),e.vps=[p.data];break;case 33:if(a=!0,f=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],p.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const E=this.readSPS(p.data);e.width=E.width,e.height=E.height,e.pixelRatio=E.pixelRatio,e.codec=E.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const k in E.params)e.params[k]=E.params[k]}this.pushParameterSet(e.sps,p.data,e.vps),c||(c=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),c.key=!0;break;case 34:if(a=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const E=this.readPPS(p.data);for(const k in E)e.params[k]=E[k]}this.pushParameterSet(e.pps,p.data,e.vps)}break;case 35:a=!0,e.audFound=!0,(v=c)!=null&&v.frame&&(this.pushAccessUnit(c,e),c=null),c||(c=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts));break;default:a=!1;break}c&&a&&c.units.push(p)}),i&&c&&(this.pushAccessUnit(c,e),this.VideoSample=null)}pushParameterSet(e,r,n){(n&&n[0]===this.initVPS||!n&&!e.length)&&e.push(r)}getNALuType(e,r){return(e[r]&126)>>>1}ebsp2rbsp(e){const r=new Uint8Array(e.byteLength);let n=0;for(let i=0;i=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(r[n]=e[i],n++);return new Uint8Array(r.buffer,0,n)}pushAccessUnit(e,r){super.pushAccessUnit(e,r),this.initVPS&&(this.initVPS=null)}readVPS(e){const r=new jA(e);r.readUByte(),r.readUByte(),r.readBits(4),r.skipBits(2),r.readBits(6);const n=r.readBits(3),i=r.readBoolean();return{numTemporalLayers:n+1,temporalIdNested:i}}readSPS(e){const r=new jA(this.ebsp2rbsp(e));r.readUByte(),r.readUByte(),r.readBits(4);const n=r.readBits(3);r.readBoolean();const i=r.readBits(2),o=r.readBoolean(),c=r.readBits(5),a=r.readUByte(),f=r.readUByte(),p=r.readUByte(),y=r.readUByte(),v=r.readUByte(),T=r.readUByte(),E=r.readUByte(),k=r.readUByte(),P=r.readUByte(),R=r.readUByte(),D=r.readUByte(),M=[],B=[];for(let ur=0;ur0)for(let ur=n;ur<8;ur++)r.readBits(2);for(let ur=0;ur1&&r.readEG();for(let jt=0;jt0&&er<16?(we=Pr[er-1],He=dr[er-1]):er===255&&(we=r.readBits(16),He=r.readBits(16))}if(r.readBoolean()&&r.readBoolean(),r.readBoolean()&&(r.readBits(3),r.readBoolean(),r.readBoolean()&&(r.readUByte(),r.readUByte(),r.readUByte())),r.readBoolean()&&(r.readUEG(),r.readUEG()),r.readBoolean(),r.readBoolean(),r.readBoolean(),vt=r.readBoolean(),vt&&(r.skipUEG(),r.skipUEG(),r.skipUEG(),r.skipUEG()),r.readBoolean()&&(at=r.readBits(32),Et=r.readBits(32),r.readBoolean()&&r.readUEG(),r.readBoolean())){const dr=r.readBoolean(),ar=r.readBoolean();let Nt=!1;(dr||ar)&&(Nt=r.readBoolean(),Nt&&(r.readUByte(),r.readBits(5),r.readBoolean(),r.readBits(5)),r.readBits(4),r.readBits(4),Nt&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let gr=0;gr<=n;gr++){tt=r.readBoolean();const En=tt||r.readBoolean();let ni=!1;En?r.readEG():ni=r.readBoolean();const ii=ni?1:r.readUEG()+1;if(dr)for(let Ui=0;Ui>ur&1)<<31-ur)>>>0;let Tr=cr.toString(16);return c===1&&Tr==="2"&&(Tr="6"),{codecString:`hvc1.${tr}${c}.${Tr}.${o?"H":"L"}${D}.B0`,params:{general_tier_flag:o,general_profile_idc:c,general_profile_space:i,general_profile_compatibility_flags:[a,f,p,y],general_constraint_indicator_flags:[v,T,E,k,P,R],general_level_idc:D,bit_depth:pe+8,bit_depth_luma_minus8:pe,bit_depth_chroma_minus8:Se,min_spatial_segmentation_idc:Ee,chroma_format_idc:V,frame_rate:{fixed:tt,fps:Et/at}},width:pt,height:Pt,pixelRatio:[we,He]}}readPPS(e){const r=new jA(this.ebsp2rbsp(e));r.readUByte(),r.readUByte(),r.skipUEG(),r.skipUEG(),r.skipBits(2),r.skipBits(3),r.skipBits(2),r.skipUEG(),r.skipUEG(),r.skipEG(),r.skipBits(2),r.readBoolean()&&r.skipUEG(),r.skipEG(),r.skipEG(),r.skipBits(4);const i=r.readBoolean(),o=r.readBoolean();let c=1;return o&&i?c=0:o?c=3:i&&(c=2),{parallelismType:c}}matchSPS(e,r){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,r).substr(3)}}const Cl=188;class jy{constructor(e,r,n,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=r,this.typeSupported=n,this.logger=i,this.videoParser=null}static probe(e,r){const n=jy.syncOffset(e);return n>0&&r.warn(`MPEG2-TS detected but first sync word found @ offset ${n}`),n!==-1}static syncOffset(e){const r=e.length;let n=Math.min(Cl*5,r-Cl)+1,i=0;for(;i1&&(c===0&&a>2||f+Cl>n))return c}else{if(a)return-1;break}i++}return-1}static createTrack(e,r){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:y2e[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?r:void 0}}resetInitSegment(e,r,n,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=jy.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=jy.createTrack("audio",i),this._id3Track=jy.createTrack("id3"),this._txtTrack=jy.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=n}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:r,_id3Track:n}=this;e&&(e.pesData=null),r&&(r.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,r,n=!1,i=!1){n||(this.sampleAes=null);let o;const c=this._videoTrack,a=this._audioTrack,f=this._id3Track,p=this._txtTrack;let y=c.pid,v=c.pesData,T=a.pid,E=f.pid,k=a.pesData,P=f.pesData,R=null,D=this.pmtParsed,M=this._pmtId,B=e.length;if(this.remainderData&&(e=ph(this.remainderData,e),B=e.length,this.remainderData=null),B>4;let le;if(ee>1){if(le=Y+5+e[Y+4],le===Y+Cl)continue}else le=Y+4;switch(Q){case y:J&&(v&&(o=kw(v,this.logger))&&(this.readyVideoParser(c.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(c,p,o,!1)),v={data:[],size:0}),v&&(v.data.push(e.subarray(le,Y+Cl)),v.size+=Y+Cl-le);break;case T:if(J){if(k&&(o=kw(k,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,o);break;case"mp3":this.parseMPEGPES(a,o);break;case"ac3":this.parseAC3PES(a,o);break}k={data:[],size:0}}k&&(k.data.push(e.subarray(le,Y+Cl)),k.size+=Y+Cl-le);break;case E:J&&(P&&(o=kw(P,this.logger))&&this.parseID3PES(f,o),P={data:[],size:0}),P&&(P.data.push(e.subarray(le,Y+Cl)),P.size+=Y+Cl-le);break;case 0:J&&(le+=e[le]+1),M=this._pmtId=I3t(e,le);break;case M:{J&&(le+=e[le]+1);const pe=P3t(e,le,this.typeSupported,n,this.observer,this.logger);y=pe.videoPid,y>0&&(c.pid=y,c.segmentCodec=pe.segmentVideoCodec),T=pe.audioPid,T>0&&(a.pid=T,a.segmentCodec=pe.segmentAudioCodec),E=pe.id3Pid,E>0&&(f.pid=E),R!==null&&!D&&(this.logger.warn(`MPEG-TS PMT found at ${Y} after unknown PID '${R}'. Backtracking to sync byte @${V} to parse all TS packets.`),R=null,Y=V-188),D=this.pmtParsed=!0;break}case 17:case 8191:break;default:R=Q;break}}else G++;G>0&&fG(this.observer,new Error(`Found ${G} TS packet/s that do not start with 0x47`),void 0,this.logger),c.pesData=v,a.pesData=k,f.pesData=P;const W={audioTrack:a,videoTrack:c,id3Track:f,textTrack:p};return i&&this.extractRemainingSamples(W),W}flush(){const{remainderData:e}=this;this.remainderData=null;let r;return e?r=this.demux(e,-1,!1,!0):r={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r),this.sampleAes?this.decrypt(r,this.sampleAes):r}extractRemainingSamples(e){const{audioTrack:r,videoTrack:n,id3Track:i,textTrack:o}=e,c=n.pesData,a=r.pesData,f=i.pesData;let p;if(c&&(p=kw(c,this.logger))?(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(n,o,p,!0),n.pesData=null)):n.pesData=c,a&&(p=kw(a,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,p);break;case"mp3":this.parseMPEGPES(r,p);break;case"ac3":this.parseAC3PES(r,p);break}r.pesData=null}else a!=null&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=a;f&&(p=kw(f,this.logger))?(this.parseID3PES(i,p),i.pesData=null):i.pesData=f}demuxSampleAes(e,r,n){const i=this.demux(e,n,!0,!this.config.progressive),o=this.sampleAes=new k3t(this.observer,this.config,r);return this.decrypt(i,o)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new C3t:e==="hevc"&&(this.videoParser=new N3t))}decrypt(e,r){return new Promise(n=>{const{audioTrack:i,videoTrack:o}=e;i.samples&&i.segmentCodec==="aac"?r.decryptAacSamples(i.samples,0,()=>{o.samples?r.decryptAvcSamples(o.samples,0,0,()=>{n(e)}):n(e)}):o.samples&&r.decryptAvcSamples(o.samples,0,0,()=>{n(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,r){let n=0;const i=this.aacOverFlow;let o=r.data;if(i){this.aacOverFlow=null;const v=i.missing,T=i.sample.unit.byteLength;if(v===-1)o=ph(i.sample.unit,o);else{const E=T-v;i.sample.unit.set(o.subarray(0,v),E),e.samples.push(i.sample),n=i.missing}}let c,a;for(c=n,a=o.length;c0;)a+=f}}parseID3PES(e,r){if(r.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const n=Js({},r,{type:this._videoTrack?od.emsg:od.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(n)}}function hG(t,e){return((t[e+1]&31)<<8)+t[e+2]}function I3t(t,e){return(t[e+10]&31)<<8|t[e+11]}function P3t(t,e,r,n,i,o){const c={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(t[e+1]&15)<<8|t[e+2],f=e+3+a-4,p=(t[e+10]&15)<<8|t[e+11];for(e+=12+p;e0){let T=e+5,E=v;for(;E>2;){switch(t[T]){case 106:r.ac3!==!0?o.log("AC-3 audio found, not supported in this browser for now"):(c.audioPid=y,c.segmentAudioCodec="ac3");break}const P=t[T+1]+2;T+=P,E-=P}}break;case 194:case 135:return fG(i,new Error("Unsupported EC-3 in M2TS found"),void 0,o),c;case 36:c.videoPid===-1&&(c.videoPid=y,c.segmentVideoCodec="hevc",o.log("HEVC in M2TS found"));break}e+=v+5}return c}function fG(t,e,r,n){n.warn(`parsing error: ${e.message}`),t.emit(Ce.ERROR,Ce.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:e,reason:e.message})}function v6(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function kw(t,e){let r=0,n,i,o,c,a;const f=t.data;if(!t||t.size===0)return null;for(;f[0].length<19&&f.length>1;)f[0]=ph(f[0],f[1]),f.splice(1,1);if(n=f[0],(n[0]<<16)+(n[1]<<8)+n[2]===1){if(i=(n[4]<<8)+n[5],i&&i>t.size-6)return null;const y=n[7];y&192&&(c=(n[9]&14)*536870912+(n[10]&255)*4194304+(n[11]&254)*16384+(n[12]&255)*128+(n[13]&254)/2,y&64?(a=(n[14]&14)*536870912+(n[15]&255)*4194304+(n[16]&254)*16384+(n[17]&255)*128+(n[18]&254)/2,c-a>60*9e4&&(e.warn(`${Math.round((c-a)/9e4)}s delta between PTS and DTS, align them`),c=a)):a=c),o=n[8];let v=o+9;if(t.size<=v)return null;t.size-=v;const T=new Uint8Array(t.size);for(let E=0,k=f.length;EP){v-=P;continue}else n=n.subarray(v),P-=v,v=0;T.set(n,r),r+=P}return i&&(i-=o+3),{data:T,pts:c,dts:a,len:i}}return null}class R3t{static getSilentFrame(e,r){switch(e){case"mp4a.40.2":if(r===1)return new Uint8Array([0,200,0,128,35,128]);if(r===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(r===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(r===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(r===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(r===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(r===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(r===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(r===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const hy=Math.pow(2,32)-1;class Xt{static init(){Xt.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in Xt.types)Xt.types.hasOwnProperty(e)&&(Xt.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const r=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),n=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Xt.HDLR_TYPES={video:r,audio:n};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),o=new Uint8Array([0,0,0,0,0,0,0,0]);Xt.STTS=Xt.STSC=Xt.STCO=o,Xt.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Xt.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Xt.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Xt.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const c=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),f=new Uint8Array([0,0,0,1]);Xt.FTYP=Xt.box(Xt.types.ftyp,c,f,c,a),Xt.DINF=Xt.box(Xt.types.dinf,Xt.box(Xt.types.dref,i))}static box(e,...r){let n=8,i=r.length;const o=i;for(;i--;)n+=r[i].byteLength;const c=new Uint8Array(n);for(c[0]=n>>24&255,c[1]=n>>16&255,c[2]=n>>8&255,c[3]=n&255,c.set(e,4),i=0,n=8;i>24&255,e>>16&255,e>>8&255,e&255,n>>24,n>>16&255,n>>8&255,n&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return Xt.box(Xt.types.mdia,Xt.mdhd(e.timescale||0,e.duration||0),Xt.hdlr(e.type),Xt.minf(e))}static mfhd(e){return Xt.box(Xt.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?Xt.box(Xt.types.minf,Xt.box(Xt.types.smhd,Xt.SMHD),Xt.DINF,Xt.stbl(e)):Xt.box(Xt.types.minf,Xt.box(Xt.types.vmhd,Xt.VMHD),Xt.DINF,Xt.stbl(e))}static moof(e,r,n){return Xt.box(Xt.types.moof,Xt.mfhd(e),Xt.traf(n,r))}static moov(e){let r=e.length;const n=[];for(;r--;)n[r]=Xt.trak(e[r]);return Xt.box.apply(null,[Xt.types.moov,Xt.mvhd(e[0].timescale||0,e[0].duration||0)].concat(n).concat(Xt.mvex(e)))}static mvex(e){let r=e.length;const n=[];for(;r--;)n[r]=Xt.trex(e[r]);return Xt.box.apply(null,[Xt.types.mvex,...n])}static mvhd(e,r){r*=e;const n=Math.floor(r/(hy+1)),i=Math.floor(r%(hy+1)),o=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,n>>24,n>>16&255,n>>8&255,n&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Xt.box(Xt.types.mvhd,o)}static sdtp(e){const r=e.samples||[],n=new Uint8Array(4+r.length);let i,o;for(i=0;i>>8&255),r.push(c&255),r=r.concat(Array.prototype.slice.call(o));for(i=0;i>>8&255),n.push(c&255),n=n.concat(Array.prototype.slice.call(o));const a=Xt.box(Xt.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(n))),f=e.width,p=e.height,y=e.pixelRatio[0],v=e.pixelRatio[1];return Xt.box(Xt.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,f>>8&255,f&255,p>>8&255,p&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Xt.box(Xt.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Xt.box(Xt.types.pasp,new Uint8Array([y>>24,y>>16&255,y>>8&255,y&255,v>>24,v>>16&255,v>>8&255,v&255])))}static esds(e){const r=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...r,6,1,2])}static audioStsd(e){const r=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,r>>8&255,r&255,0,0])}static mp4a(e){return Xt.box(Xt.types.mp4a,Xt.audioStsd(e),Xt.box(Xt.types.esds,Xt.esds(e)))}static mp3(e){return Xt.box(Xt.types[".mp3"],Xt.audioStsd(e))}static ac3(e){return Xt.box(Xt.types["ac-3"],Xt.audioStsd(e),Xt.box(Xt.types.dac3,e.config))}static stsd(e){const{segmentCodec:r}=e;if(e.type==="audio"){if(r==="aac")return Xt.box(Xt.types.stsd,Xt.STSD,Xt.mp4a(e));if(r==="ac3"&&e.config)return Xt.box(Xt.types.stsd,Xt.STSD,Xt.ac3(e));if(r==="mp3"&&e.codec==="mp3")return Xt.box(Xt.types.stsd,Xt.STSD,Xt.mp3(e))}else if(e.pps&&e.sps){if(r==="avc")return Xt.box(Xt.types.stsd,Xt.STSD,Xt.avc1(e));if(r==="hevc"&&e.vps)return Xt.box(Xt.types.stsd,Xt.STSD,Xt.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${r}/${e.codec})`)}static tkhd(e){const r=e.id,n=(e.duration||0)*(e.timescale||0),i=e.width||0,o=e.height||0,c=Math.floor(n/(hy+1)),a=Math.floor(n%(hy+1));return Xt.box(Xt.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,r&255,0,0,0,0,c>>24,c>>16&255,c>>8&255,c&255,a>>24,a>>16&255,a>>8&255,a&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,o>>8&255,o&255,0,0]))}static traf(e,r){const n=Xt.sdtp(e),i=e.id,o=Math.floor(r/(hy+1)),c=Math.floor(r%(hy+1));return Xt.box(Xt.types.traf,Xt.box(Xt.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),Xt.box(Xt.types.tfdt,new Uint8Array([1,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,c>>24,c>>16&255,c>>8&255,c&255])),Xt.trun(e,n.length+16+20+8+16+8+8),n)}static trak(e){return e.duration=e.duration||4294967295,Xt.box(Xt.types.trak,Xt.tkhd(e),Xt.mdia(e))}static trex(e){const r=e.id;return Xt.box(Xt.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,r){const n=e.samples||[],i=n.length,o=12+16*i,c=new Uint8Array(o);let a,f,p,y,v,T;for(r+=8+o,c.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255],0),a=0;a>>24&255,p>>>16&255,p>>>8&255,p&255,y>>>24&255,y>>>16&255,y>>>8&255,y&255,v.isLeading<<2|v.dependsOn,v.isDependedOn<<6|v.hasRedundancy<<4|v.paddingValue<<1|v.isNonSync,v.degradPrio&61440,v.degradPrio&15,T>>>24&255,T>>>16&255,T>>>8&255,T&255],12+16*a);return Xt.box(Xt.types.trun,c)}static initSegment(e){Xt.types||Xt.init();const r=Xt.moov(e);return ph(Xt.FTYP,r)}static hvc1(e){const r=e.params,n=[e.vps,e.sps,e.pps],i=4,o=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),i-1|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),n.length]);let c=o.length;for(let k=0;k>8,n[k][P].length&255]),c),c+=2,a.set(n[k][P],c),c+=n[k][P].length}const p=Xt.box(Xt.types.hvcC,a),y=e.width,v=e.height,T=e.pixelRatio[0],E=e.pixelRatio[1];return Xt.box(Xt.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,y>>8&255,y&255,v>>8&255,v&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),p,Xt.box(Xt.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Xt.box(Xt.types.pasp,new Uint8Array([T>>24,T>>16&255,T>>8&255,T&255,E>>24,E>>16&255,E>>8&255,E&255])))}}Xt.types=void 0;Xt.HDLR_TYPES=void 0;Xt.STTS=void 0;Xt.STSC=void 0;Xt.STCO=void 0;Xt.STSZ=void 0;Xt.VMHD=void 0;Xt.SMHD=void 0;Xt.STSD=void 0;Xt.FTYP=void 0;Xt.DINF=void 0;const hAe=9e4;function HK(t,e,r=1,n=!1){const i=t*e*r;return n?Math.round(i):i}function L3t(t,e,r=1,n=!1){return HK(t,e,1/r,n)}function k2(t,e=!1){return HK(t,1e3,1/hAe,e)}function D3t(t,e=1){return HK(t,hAe,1/e)}function eue(t){const{baseTime:e,timescale:r,trackId:n}=t;return`${e/r} (${e}/${r}) trackId: ${n}`}const M3t=10*1e3,O3t=1024,F3t=1152,B3t=1536;let Cw=null,_6=null;function tue(t,e,r,n){return{duration:e,size:r,cts:n,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class XL extends _h{constructor(e,r,n,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=r,this.typeSupported=n,this.ISGenerated=!1,Cw===null){const c=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Cw=c?parseInt(c[1]):0}if(_6===null){const o=navigator.userAgent.match(/Safari\/(\d+)/i);_6=o?parseInt(o[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const r=this._initPTS;(!r||!e||e.trackId!==r.trackId||e.baseTime!==r.baseTime||e.timescale!==r.timescale)&&this.log(`Reset initPTS: ${r&&eue(r)} > ${e&&eue(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let r=!1;const n=e[0].pts,i=e.reduce((o,c)=>{let a=c.pts,f=a-o;return f<-4294967296&&(r=!0,a=rd(a,n),f=a-o),f>0?o:a},n);return r&&this.debug("PTS rollover detected"),i}remux(e,r,n,i,o,c,a,f){let p,y,v,T,E,k,P=o,R=o;const D=e.pid>-1,M=r.pid>-1,B=r.samples.length,V=e.samples.length>0,G=a&&B>0||B>1;if((!D||V)&&(!M||G)||this.ISGenerated||a){if(this.ISGenerated){var Y,J,Q,ee;const je=this.videoTrackConfig;(je&&(r.width!==je.width||r.height!==je.height||((Y=r.pixelRatio)==null?void 0:Y[0])!==((J=je.pixelRatio)==null?void 0:J[0])||((Q=r.pixelRatio)==null?void 0:Q[1])!==((ee=je.pixelRatio)==null?void 0:ee[1]))||!je&&G||this.nextAudioTs===null&&V)&&this.resetInitSegment()}this.ISGenerated||(v=this.generateIS(e,r,o,c));const le=this.isVideoContiguous;let pe=-1,Se;if(G&&(pe=$3t(r.samples),!le&&this.config.forceKeyFrameOnDiscontinuity))if(k=!0,pe>0){this.warn(`Dropped ${pe} out of ${B} video samples due to a missing keyframe`);const je=this.getVideoStartPts(r.samples);r.samples=r.samples.slice(pe),r.dropped+=pe,R+=(r.samples[0].pts-je)/r.inputTimeScale,Se=R}else pe===-1&&(this.warn(`No keyframe found out of ${B} video samples`),k=!1);if(this.ISGenerated){if(V&&G){const je=this.getVideoStartPts(r.samples),Ae=(rd(e.samples[0].pts,je)-je)/r.inputTimeScale;P+=Math.max(0,Ae),R+=Math.max(0,-Ae)}if(V){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),v=this.generateIS(e,r,o,c)),y=this.remuxAudio(e,P,this.isAudioContiguous,c,M||G||f===Tn.AUDIO?R:void 0),G){const je=y?y.endPTS-y.startPTS:0;r.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),v=this.generateIS(e,r,o,c)),p=this.remuxVideo(r,R,le,je)}}else G&&(p=this.remuxVideo(r,R,le,0));p&&(p.firstKeyFrame=pe,p.independent=pe!==-1,p.firstKeyFramePTS=Se)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(E=fAe(n,o,this._initPTS,this._initDTS)),i.samples.length&&(T=mAe(i,o,this._initPTS))),{audio:y,video:p,initSegment:v,independent:k,text:T,id3:E}}computeInitPts(e,r,n,i){const o=Math.round(n*r);let c=rd(e,o);if(c0?Ee-1:Ee].dts&&(M=!0)}M&&c.sort(function(Ee,we){const He=Ee.dts-we.dts,tt=Ee.pts-we.pts;return He||tt}),k=c[0].dts,P=c[c.length-1].dts;const V=P-k,G=V?Math.round(V/(f-1)):E||e.inputTimeScale/30;if(n){const Ee=k-B,we=Ee>G,He=Ee<-1;if((we||He)&&(we?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${k2(Ee,!0)} ms (${Ee}dts) hole between fragments detected at ${r.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${k2(-Ee,!0)} ms (${Ee}dts) overlapping between fragments detected at ${r.toFixed(3)}`),!He||B>=c[0].pts||Cw)){k=B;const tt=c[0].pts-Ee;if(we)c[0].dts=k,c[0].pts=tt;else{let at=!0;for(let Et=0;Ettt&&at);Et++){const vt=c[Et].pts;if(c[Et].dts-=Ee,c[Et].pts-=Ee,Et0?we.dts-c[Ee-1].dts:G;if(at=Ee>0?we.pts-c[Ee-1].pts:G,vt.stretchShortVideoTrack&&this.nextAudioTs!==null){const pt=Math.floor(vt.maxBufferHole*o),Pt=(i?R+i*o:this.nextAudioTs+y)-we.pts;Pt>pt?(E=Pt-Gt,E<0?E=Gt:pe=!0,this.log(`It is approximately ${Pt/90} ms to the next segment; using duration ${E/90} ms for the last video frame.`)):E=Gt}else E=Gt}const Et=Math.round(we.pts-we.dts);Se=Math.min(Se,E),Le=Math.max(Le,E),je=Math.min(je,at),Ae=Math.max(Ae,at),a.push(tue(we.key,E,tt,Et))}if(a.length){if(Cw){if(Cw<70){const Ee=a[0].flags;Ee.dependsOn=2,Ee.isNonSync=0}}else if(_6&&Ae-je0&&(i&&Math.abs(B-(D+M))<9e3||Math.abs(rd(P[0].pts,B)-(D+M))<20*y),P.forEach(function(Ae){Ae.pts=rd(Ae.pts,B)}),!n||D<0){const Ae=P.length;if(P=P.filter(be=>be.pts>=0),Ae!==P.length&&this.warn(`Removed ${P.length-Ae} of ${Ae} samples (initPTS ${M} / ${c})`),!P.length)return;o===0?D=0:i&&!k?D=Math.max(0,B-M):D=P[0].pts-M}if(e.segmentCodec==="aac"){const Ae=this.config.maxAudioFramesDrift;for(let be=0,me=D+M;be=Ae*y&&we0){Y+=R;try{W=new Uint8Array(Y)}catch(we){this.observer.emit(Ce.ERROR,Ce.ERROR,{type:Dn.MUX_ERROR,details:Jt.REMUX_ALLOC_ERROR,fatal:!1,error:we,bytes:Y,reason:`fail allocating audio mdat ${Y}`});return}T||(new DataView(W.buffer).setUint32(0,Y),W.set(Xt.types.mdat,4))}else return;W.set(Te,R);const Ee=Te.byteLength;R+=Ee,E.push(tue(!0,p,Ee,0)),G=Ne}const Q=E.length;if(!Q)return;const ee=E[E.length-1];D=G-M,this.nextAudioTs=D+f*ee.duration;const le=T?new Uint8Array(0):Xt.moof(e.sequenceNumber++,V/f,Js({},e,{samples:E}));e.samples=[];const pe=(V-M)/c,Se=this.nextAudioTs/c,Le={data1:le,data2:W,startPTS:pe,endPTS:Se,startDTS:pe,endDTS:Se,type:"audio",hasAudio:!0,hasVideo:!1,nb:Q};return this.isAudioContiguous=!0,Le}}function rd(t,e){let r;if(e===null)return t;for(e4294967296;)t+=r;return t}function $3t(t){for(let e=0;ec.pts-a.pts);const o=t.samples;return t.samples=[],{samples:o}}class z3t extends _h{constructor(e,r,n,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const r=this.initPTS;r&&e&&r.baseTime===e.baseTime&&r.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,r,n,i){this.audioCodec=r,this.videoCodec=n,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,r){let{audioCodec:n,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:o,video:c}=this.initData=_2e(e);if(r)kMt(e,r);else{const f=o||c;f!=null&&f.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${f.codec}")!`)}o&&(n=rue(o,na.AUDIO,this)),c&&(i=rue(c,na.VIDEO,this));const a={};o&&c?a.audiovideo={container:"video/mp4",codec:n+","+i,supplemental:c.supplemental,encrypted:c.encrypted,initSegment:e,id:"main"}:o?a.audio={container:"audio/mp4",codec:n,encrypted:o.encrypted,initSegment:e,id:"audio"}:c?a.video={container:"video/mp4",codec:i,supplemental:c.supplemental,encrypted:c.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,r,n,i,o,c){var a,f;let{initPTS:p,lastEndTime:y}=this;const v={audio:void 0,video:void 0,text:i,id3:n,initSegment:void 0};pn(y)||(y=this.lastEndTime=o||0);const T=r.samples;if(!T.length)return v;const E={initPTS:void 0,timescale:void 0,trackId:void 0};let k=this.initData;if((a=k)!=null&&a.length||(this.generateInitSegment(T),k=this.initData),!((f=k)!=null&&f.length))return this.warn("Failed to generate initSegment."),v;this.emitInitSegment&&(E.tracks=this.initTracks,this.emitInitSegment=!1);const P=NMt(T,k,this),R=k.audio?P[k.audio.id]:null,D=k.video?P[k.video.id]:null,M=QR(D,1/0),B=QR(R,1/0),V=QR(D,0,!0),G=QR(R,0,!0);let W=o,Y=0;const J=R&&(!D||!p&&B0?this.lastEndTime=le:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const pe=!!k.audio,Se=!!k.video;let je="";pe&&(je+="audio"),Se&&(je+="video");const Le=(k.audio?k.audio.encrypted:!1)||(k.video?k.video.encrypted:!1),Ae={data1:T,startPTS:ee,startDTS:ee,endPTS:le,endDTS:le,type:je,hasAudio:pe,hasVideo:Se,nb:1,dropped:0,encrypted:Le};v.audio=pe&&!Se?Ae:void 0,v.video=Se?Ae:void 0;const be=D==null?void 0:D.sampleCount;if(be){const me=D.keyFrameIndex,Te=me!==-1;Ae.nb=be,Ae.dropped=me===0||this.isVideoContiguous?0:Te?me:be,Ae.independent=Te,Ae.firstKeyFrame=me,Te&&D.keyFrameStart&&(Ae.firstKeyFramePTS=(D.keyFrameStart-p.baseTime)/p.timescale),this.isVideoContiguous||(v.independent=Te),this.isVideoContiguous||(this.isVideoContiguous=Te),Ae.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${me}/${be} dropped: ${Ae.dropped} start: ${Ae.firstKeyFramePTS||"NA"}`)}return v.initSegment=E,v.id3=fAe(n,o,p,p),i.samples.length&&(v.text=mAe(i,o,p)),v}}function QR(t,e,r=!1){return(t==null?void 0:t.start)!==void 0?(t.start+(r?t.duration:0))/t.timescale:e}function U3t(t,e,r,n){if(t===null)return!0;const i=Math.max(n,1),o=e-t.baseTime/t.timescale;return Math.abs(o-r)>i}function rue(t,e,r){const n=t.codec;return n&&n.length>4?n:e===na.AUDIO?n==="ec-3"||n==="ac-3"||n==="alac"?n:n==="fLaC"||n==="Opus"?_O(n,!1):(r.warn(`Unhandled audio codec "${n}" in mp4 MAP`),n||"mp4a"):(r.warn(`Unhandled video codec "${n}" in mp4 MAP`),n||"avc1")}let kp;try{kp=self.performance.now.bind(self.performance)}catch{kp=Date.now}const QL=[{demux:A3t,remux:z3t},{demux:jy,remux:XL},{demux:S3t,remux:XL},{demux:E3t,remux:XL}];QL.splice(2,0,{demux:T3t,remux:XL});class nue{constructor(e,r,n,i,o,c){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=r,this.config=n,this.id=o,this.logger=c}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,r,n,i){const o=n.transmuxing;o.executeStart=kp();let c=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:f}=this;i&&(this.currentTransmuxState=i);const{contiguous:p,discontinuity:y,trackSwitch:v,accurateTimeOffset:T,timeOffset:E,initSegmentChange:k}=i||a,{audioCodec:P,videoCodec:R,defaultInitPts:D,duration:M,initSegmentData:B}=f,V=V3t(c,r);if(V&&N1(V.method)){const J=this.getDecrypter(),Q=OK(V.method);if(J.isSync()){let ee=J.softwareDecrypt(c,V.key.buffer,V.iv.buffer,Q);if(n.part>-1){const pe=J.flush();ee=pe&&pe.buffer}if(!ee)return o.executeEnd=kp(),b6(n);c=new Uint8Array(ee)}else return this.asyncResult=!0,this.decryptionPromise=J.webCryptoDecrypt(c,V.key.buffer,V.iv.buffer,Q).then(ee=>{const le=this.push(ee,null,n);return this.decryptionPromise=null,le}),this.decryptionPromise}const G=this.needsProbing(y,v);if(G){const J=this.configureTransmuxer(c);if(J)return this.logger.warn(`[transmuxer] ${J.message}`),this.observer.emit(Ce.ERROR,Ce.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.FRAG_PARSING_ERROR,fatal:!1,error:J,reason:J.message}),o.executeEnd=kp(),b6(n)}(y||v||k||G)&&this.resetInitSegment(B,P,R,M,r),(y||k||G)&&this.resetInitialTimestamp(D),p||this.resetContiguity();const W=this.transmux(c,V,E,T,n);this.asyncResult=lC(W);const Y=this.currentTransmuxState;return Y.contiguous=!0,Y.discontinuity=!1,Y.trackSwitch=!1,o.executeEnd=kp(),W}flush(e){const r=e.transmuxing;r.executeStart=kp();const{decrypter:n,currentTransmuxState:i,decryptionPromise:o}=this;if(o)return this.asyncResult=!0,o.then(()=>this.flush(e));const c=[],{timeOffset:a}=i;if(n){const v=n.flush();v&&c.push(this.push(v.buffer,null,e))}const{demuxer:f,remuxer:p}=this;if(!f||!p){r.executeEnd=kp();const v=[b6(e)];return this.asyncResult?Promise.resolve(v):v}const y=f.flush(a);return lC(y)?(this.asyncResult=!0,y.then(v=>(this.flushRemux(c,v,e),c))):(this.flushRemux(c,y,e),this.asyncResult?Promise.resolve(c):c)}flushRemux(e,r,n){const{audioTrack:i,videoTrack:o,id3Track:c,textTrack:a}=r,{accurateTimeOffset:f,timeOffset:p}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?" part: "+n.part:""} of ${this.id===Tn.MAIN?"level":"track"} ${n.level}`);const y=this.remuxer.remux(i,o,c,a,p,f,!0,this.id);e.push({remuxResult:y,chunkMeta:n}),n.transmuxing.executeEnd=kp()}resetInitialTimestamp(e){const{demuxer:r,remuxer:n}=this;!r||!n||(r.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:r}=this;!e||!r||(e.resetContiguity(),r.resetNextTimestamp())}resetInitSegment(e,r,n,i,o){const{demuxer:c,remuxer:a}=this;!c||!a||(c.resetInitSegment(e,r,n,i),a.resetInitSegment(e,r,n,o))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,r,n,i,o){let c;return r&&r.method==="SAMPLE-AES"?c=this.transmuxSampleAes(e,r,n,i,o):c=this.transmuxUnencrypted(e,n,i,o),c}transmuxUnencrypted(e,r,n,i){const{audioTrack:o,videoTrack:c,id3Track:a,textTrack:f}=this.demuxer.demux(e,r,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(o,c,a,f,r,n,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,r,n,i,o){return this.demuxer.demuxSampleAes(e,r,n).then(c=>({remuxResult:this.remuxer.remux(c.audioTrack,c.videoTrack,c.id3Track,c.textTrack,n,i,!1,this.id),chunkMeta:o}))}configureTransmuxer(e){const{config:r,observer:n,typeSupported:i}=this;let o;for(let v=0,T=QL.length;v0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(r=e),r}const b6=t=>({remuxResult:{},chunkMeta:t});function lC(t){return"then"in t&&t.then instanceof Function}class q3t{constructor(e,r,n,i,o){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=r,this.initSegmentData=n,this.duration=i,this.defaultInitPts=o||null}}class G3t{constructor(e,r,n,i,o,c){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=r,this.accurateTimeOffset=n,this.trackSwitch=i,this.timeOffset=o,this.initSegmentChange=c}}let iue=0;class pAe{constructor(e,r,n,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=iue++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=f=>{const p=f.data,y=this.hls;if(!(!y||!(p!=null&&p.event)||p.instanceNo!==this.instanceNo))switch(p.event){case"init":{var v;const T=(v=this.workerContext)==null?void 0:v.objectURL;T&&self.URL.revokeObjectURL(T);break}case"transmuxComplete":{this.handleTransmuxComplete(p.data);break}case"flush":{this.onFlush(p.data);break}case"workerLog":{y.logger[p.data.logType]&&y.logger[p.data.logType](p.data.message);break}default:{p.data=p.data||{},p.data.frag=this.frag,p.data.part=this.part,p.data.id=this.id,y.trigger(p.event,p.data);break}}},this.onWorkerError=f=>{if(!this.hls)return;const p=new Error(`${f.message} (${f.filename}:${f.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(Ce.ERROR,{type:Dn.OTHER_ERROR,details:Jt.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:p})};const o=e.config;this.hls=e,this.id=r,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=n,this.onFlush=i;const c=(f,p)=>{p=p||{},p.frag=this.frag||void 0,f===Ce.ERROR&&(p=p,p.parent=this.id,p.part=this.part,this.error=p.error),this.hls.trigger(f,p)};this.observer=new $K,this.observer.on(Ce.FRAG_DECRYPTED,c),this.observer.on(Ce.ERROR,c);const a=vce(o.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const f=this.hls.logger;if(o.workerPath||YOt()){try{o.workerPath?(f.log(`loading Web Worker ${o.workerPath} for "${r}"`),this.workerContext=XOt(o.workerPath)):(f.log(`injecting Web Worker for "${r}"`),this.workerContext=ZOt());const{worker:y}=this.workerContext;y.addEventListener("message",this.onWorkerMessage),y.addEventListener("error",this.onWorkerError),y.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:r,config:aa(o)})}catch(y){f.warn(`Error setting up "${r}" Web Worker, fallback to inline`,y),this.terminateWorker(),this.error=null,this.transmuxer=new nue(this.observer,a,o,"",r,e.logger)}return}}this.transmuxer=new nue(this.observer,a,o,"",r,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=iue++;const r=this.hls.config,n=vce(r.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:n,id:this.id,config:aa(r)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),QOt(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const r=this.transmuxer;r&&(r.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,r,n,i,o,c,a,f,p,y){var v,T;p.transmuxing.start=self.performance.now();const{instanceNo:E,transmuxer:k}=this,P=c?c.start:o.start,R=o.decryptdata,D=this.frag,M=!(D&&o.cc===D.cc),B=!(D&&p.level===D.level),V=D?p.sn-D.sn:-1,G=this.part?p.part-this.part.index:-1,W=V===0&&p.id>1&&p.id===(D==null?void 0:D.stats.chunkCount),Y=!B&&(V===1||V===0&&(G===1||W&&G<=0)),J=self.performance.now();(B||V||o.stats.parsing.start===0)&&(o.stats.parsing.start=J),c&&(G||!Y)&&(c.stats.parsing.start=J);const Q=!(D&&((v=o.initSegment)==null?void 0:v.url)===((T=D.initSegment)==null?void 0:T.url)),ee=new G3t(M,Y,f,B,P,Q);if(!Y||M||Q){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${o.type} sn: ${p.sn}${p.part>-1?" part: "+p.part:""} ${this.id===Tn.MAIN?"level":"track"}: ${p.level} id: ${p.id} discontinuity: ${M} trackSwitch: ${B} contiguous: ${Y} accurateTimeOffset: ${f} timeOffset: ${P} initSegmentChange: ${Q}`);const le=new q3t(n,i,r,a,y);this.configureTransmuxer(le)}if(this.frag=o,this.part=c,this.workerContext)this.workerContext.worker.postMessage({instanceNo:E,cmd:"demux",data:e,decryptdata:R,chunkMeta:p,state:ee},e instanceof ArrayBuffer?[e]:[]);else if(k){const le=k.push(e,R,p,ee);lC(le)?le.then(pe=>{this.handleTransmuxComplete(pe)}).catch(pe=>{this.transmuxerError(pe,p,"transmuxer-interface push error")}):this.handleTransmuxComplete(le)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:r,transmuxer:n}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:e});else if(n){const i=n.flush(e);lC(i)?i.then(o=>{this.handleFlushResult(o,e)}).catch(o=>{this.transmuxerError(o,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,r,n){this.hls&&(this.error=e,this.hls.trigger(Ce.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.FRAG_PARSING_ERROR,chunkMeta:r,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,r){e.forEach(n=>{this.handleTransmuxComplete(n)}),this.onFlush(r)}configureTransmuxer(e){const{instanceNo:r,transmuxer:n}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:r,cmd:"configure",config:e}):n&&n.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const sue=100;class H3t extends BK{constructor(e,r,n){super(e,r,n,"audio-stream-controller",Tn.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Ce.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Ce.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Ce.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Ce.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Ce.BUFFER_RESET,this.onBufferReset,this),e.on(Ce.BUFFER_CREATED,this.onBufferCreated,this),e.on(Ce.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Ce.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Ce.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Ce.FRAG_LOADING,this.onFragLoading,this),e.on(Ce.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(Ce.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Ce.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Ce.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Ce.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Ce.BUFFER_RESET,this.onBufferReset,this),e.off(Ce.BUFFER_CREATED,this.onBufferCreated,this),e.off(Ce.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Ce.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Ce.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Ce.FRAG_LOADING,this.onFragLoading,this),e.off(Ce.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:r,id:n,initPTS:i,timescale:o,trackId:c}){if(n===Tn.MAIN){const a=r.cc,f=this.fragCurrent;if(this.initPTS[a]={baseTime:i,timescale:o,trackId:c},this.log(`InitPTS for cc: ${a} found from main: ${i/o} (${i}/${o}) trackId: ${c}`),this.mainAnchor=r,this.state===wr.WAITING_INIT_PTS){const p=this.waitingData;(!p&&!this.loadingParts||p&&p.frag.cc!==a)&&this.syncWithAnchor(r,p==null?void 0:p.frag)}else!this.hls.hasEnoughToStart&&f&&f.cc!==a?(f.abortRequests(),this.syncWithAnchor(r,f)):this.state===wr.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,r){var n;const i=((n=this.mainFragLoading)==null?void 0:n.frag)||null;if(r&&(i==null?void 0:i.cc)===r.cc)return;const o=(i||e).cc,c=this.getLevelDetails(),a=this.getLoadPosition(),f=I2e(c,o,a);f&&(this.log(`Syncing with main frag at ${f.start} cc ${f.cc}`),this.startFragRequested=!1,this.nextLoadPosition=f.start,this.resetLoadingState(),this.state===wr.IDLE&&this.doTickIdle())}startLoad(e,r){if(!this.levels){this.startPosition=e,this.state=wr.STOPPED;return}const n=this.lastCurrentTime;this.stopLoad(),this.setInterval(sue),n>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n,this.state=wr.IDLE):this.state=wr.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=r?-1:e,this.tick()}doTick(){switch(this.state){case wr.IDLE:this.doTickIdle();break;case wr.WAITING_TRACK:{const{levels:e,trackId:r}=this,n=e==null?void 0:e[r],i=n==null?void 0:n.details;if(i&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(i))break;this.state=wr.WAITING_INIT_PTS}break}case wr.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case wr.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:r,part:n,cache:i,complete:o}=e,c=this.mainAnchor;if(this.initPTS[r.cc]!==void 0){this.waitingData=null,this.state=wr.FRAG_LOADING;const a=i.flush().buffer,f={frag:r,part:n,payload:a,networkDetails:null};this._handleFragmentLoadProgress(f),o&&super._handleFragmentLoadComplete(f)}else c&&c.cc!==e.frag.cc&&this.syncWithAnchor(c,e.frag)}else this.state=wr.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:r,levels:n,media:i,trackId:o}=this,c=r.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!c.startFragPrefetch)||!(n!=null&&n[o]))return;const a=n[o],f=a.details;if(!f||this.waitForLive(a)||this.waitForCdnTuneIn(f)){this.state=wr.WAITING_TRACK,this.startFragRequested=!1;return}const p=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&p&&(this.bufferFlushed=!1,this.afterBufferFlushed(p,na.AUDIO,Tn.AUDIO));const y=this.getFwdBufferInfo(p,Tn.AUDIO);if(y===null)return;if(!this.switchingTrack&&this._streamEnded(y,f)){r.trigger(Ce.BUFFER_EOS,{type:"audio"}),this.state=wr.ENDED;return}const v=y.len,T=r.maxBufferLength,E=f.fragments,k=E[0].start,P=this.getLoadPosition(),R=this.flushing?P:y.end;if(this.switchingTrack&&i){const B=P;f.PTSKnown&&Bk||y.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=k+.05)}if(v>=T&&!this.switchingTrack&&RM.end){const V=this.fragmentTracker.getFragAtPos(R,Tn.MAIN);V&&V.end>M.end&&(M=V,this.mainFragLoading={frag:V,targetBufferTime:null})}if(D.start>M.end)return}this.loadFragment(D,a,R)}onMediaDetaching(e,r){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,r)}onAudioTracksUpdated(e,{audioTracks:r}){this.resetTransmuxer(),this.levels=r.map(n=>new sC(n))}onAudioTrackSwitching(e,r){const n=!!r.url;this.trackId=r.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),n?(this.switchingTrack=r,this.flushAudioIfNeeded(r),this.state!==wr.STOPPED&&(this.setInterval(sue),this.state=wr.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=r,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,r){this.mainDetails=r.details;const n=this.cachedTrackLoadedData;n&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(Ce.AUDIO_TRACK_LOADED,n))}onAudioTrackLoaded(e,r){var n;const{levels:i}=this,{details:o,id:c,groupId:a,track:f}=r;if(!i){this.warn(`Audio tracks reset while loading track ${c} "${f.name}" of "${a}"`);return}const p=this.mainDetails;if(!p||o.endCC>p.endCC||p.expired){this.cachedTrackLoadedData=r,this.state!==wr.STOPPED&&(this.state=wr.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${c} "${f.name}" of "${a}" loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""},duration:${o.totalduration}`);const y=i[c];let v=0;if(o.live||(n=y.details)!=null&&n.live){if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;if(y.details){var T;v=this.alignPlaylists(o,y.details,(T=this.levelLastLoaded)==null?void 0:T.details)}o.alignedSliding||(Y2e(o,p),o.alignedSliding||AO(o,p),v=o.fragmentStart)}y.details=o,this.levelLastLoaded=y,this.startFragRequested||this.setStartPosition(p,v),this.hls.trigger(Ce.AUDIO_TRACK_UPDATED,{details:o,id:c,groupId:r.groupId}),this.state===wr.WAITING_TRACK&&!this.waitForCdnTuneIn(o)&&(this.state=wr.IDLE),this.tick()}_handleFragmentLoadProgress(e){var r;const n=e.frag,{part:i,payload:o}=e,{config:c,trackId:a,levels:f}=this;if(!f){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const p=f[a];if(!p){this.warn("Audio track is undefined on fragment load progress");return}const y=p.details;if(!y){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(n.start);return}const v=c.defaultAudioCodec||p.audioCodec||"mp4a.40.2";let T=this.transmuxer;T||(T=this.transmuxer=new pAe(this.hls,Tn.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const E=this.initPTS[n.cc],k=(r=n.initSegment)==null?void 0:r.data;if(E!==void 0){const R=i?i.index:-1,D=R!==-1,M=new MK(n.level,n.sn,n.stats.chunkCount,o.byteLength,R,D);T.push(o,k,v,"",n,i,y.totalduration,!1,M,E)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${y.startSN} ,${y.endSN}],track ${a}`);const{cache:P}=this.waitingData=this.waitingData||{frag:n,part:i,cache:new Z2e,complete:!1};P.push(new Uint8Array(o)),this.state!==wr.STOPPED&&(this.state=wr.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,r){this.bufferFlushed=this.flushing=!1;const n=r.tracks.audio;n&&(this.mediaBuffer=n.buffer||null)}onFragLoading(e,r){!this.audioOnly&&r.frag.type===Tn.MAIN&&Io(r.frag)&&(this.mainFragLoading=r,this.state===wr.IDLE&&this.tick())}onFragBuffered(e,r){const{frag:n,part:i}=r;if(n.type!==Tn.AUDIO){!this.audioOnly&&n.type===Tn.MAIN&&!n.elementaryStreams.video&&!n.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${i?" p: "+i.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Io(n)){this.fragPrevious=n;const o=this.switchingTrack;o&&(this.bufferedTrack=o,this.switchingTrack=null,this.hls.trigger(Ce.AUDIO_TRACK_SWITCHED,Us({},o)))}this.fragBufferedComplete(n,i),this.media&&this.tick()}onError(e,r){var n;if(r.fatal){this.state=wr.ERROR;return}switch(r.details){case Jt.FRAG_GAP:case Jt.FRAG_PARSING_ERROR:case Jt.FRAG_DECRYPT_ERROR:case Jt.FRAG_LOAD_ERROR:case Jt.FRAG_LOAD_TIMEOUT:case Jt.KEY_LOAD_ERROR:case Jt.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Tn.AUDIO,r);break;case Jt.AUDIO_TRACK_LOAD_ERROR:case Jt.AUDIO_TRACK_LOAD_TIMEOUT:case Jt.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===wr.WAITING_TRACK&&((n=r.context)==null?void 0:n.type)===Wi.AUDIO_TRACK&&(this.state=wr.IDLE);break;case Jt.BUFFER_ADD_CODEC_ERROR:case Jt.BUFFER_APPEND_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case Jt.BUFFER_FULL_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Jt.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onBufferFlushing(e,{type:r}){r!==na.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:r}){if(r!==na.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===wr.ENDED&&(this.state=wr.IDLE);const n=this.mediaBuffer||this.media;n&&(this.afterBufferFlushed(n,r,Tn.AUDIO),this.tick())}}_handleTransmuxComplete(e){var r;const n="audio",{hls:i}=this,{remuxResult:o,chunkMeta:c}=e,a=this.getCurrentContext(c);if(!a){this.resetWhenMissingContext(c);return}const{frag:f,part:p,level:y}=a,{details:v}=y,{audio:T,text:E,id3:k,initSegment:P}=o;if(this.fragContextChanged(f)||!v){this.fragmentTracker.removeFragment(f);return}if(this.state=wr.PARSING,this.switchingTrack&&T&&this.completeAudioSwitch(this.switchingTrack),P!=null&&P.tracks){const R=f.initSegment||f;if(this.unhandledEncryptionError(P,f))return;this._bufferInitSegment(y,P.tracks,R,c),i.trigger(Ce.FRAG_PARSING_INIT_SEGMENT,{frag:R,id:n,tracks:P.tracks})}if(T){const{startPTS:R,endPTS:D,startDTS:M,endDTS:B}=T;p&&(p.elementaryStreams[na.AUDIO]={startPTS:R,endPTS:D,startDTS:M,endDTS:B}),f.setElementaryStreamInfo(na.AUDIO,R,D,M,B),this.bufferFragmentData(T,f,p,c)}if(k!=null&&(r=k.samples)!=null&&r.length){const R=Js({id:n,frag:f,details:v},k);i.trigger(Ce.FRAG_PARSING_METADATA,R)}if(E){const R=Js({id:n,frag:f,details:v},E);i.trigger(Ce.FRAG_PARSING_USERDATA,R)}}_bufferInitSegment(e,r,n,i){if(this.state!==wr.PARSING||(r.video&&delete r.video,r.audiovideo&&delete r.audiovideo,!r.audio))return;const o=r.audio;o.id=Tn.AUDIO;const c=e.audioCodec;this.log(`Init audio buffer, container:${o.container}, codecs[level/parsed]=[${c}/${o.codec}]`),c&&c.split(",").length===1&&(o.levelCodec=c),this.hls.trigger(Ce.BUFFER_CODECS,r);const a=o.initSegment;if(a!=null&&a.byteLength){const f={type:"audio",frag:n,part:null,chunkMeta:i,parent:n.type,data:a};this.hls.trigger(Ce.BUFFER_APPENDING,f)}this.tickImmediate()}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===dl.NOT_LOADED||i===dl.PARTIAL){var o;if(!Io(e))this._loadInitSegment(e,r);else if((o=r.details)!=null&&o.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=wr.WAITING_INIT_PTS;const c=this.mainDetails;c&&c.fragmentStart!==r.details.fragmentStart&&AO(r.details,c)}else super.loadFragment(e,r,n)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:r,lang:n,assocLang:i,characteristics:o,audioCodec:c,channels:a}=this.bufferedTrack;Yv({name:r,lang:n,assocLang:i,characteristics:o,audioCodec:c,channels:a},e,vv)||(wO(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:r}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,r.trigger(Ce.AUDIO_TRACK_SWITCHED,Us({},e))}}class WK extends _h{constructor(e,r){super(r,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,r,n){const i=r==null?void 0:r.renditionReports;if(i){let o=-1;for(let c=0;c=0&&y>r.partTarget&&(f+=1)}const p=n&&_ce(n);return new bce(a,f>=0?f:void 0,p)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,r){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,r){if(r)try{return r.addDirectives(e)}catch(n){this.warn(`Could not construct new URL with HLS Delivery Directives: ${n}`)}return e}playlistLoaded(e,r,n){const{details:i,stats:o}=r,c=self.performance.now(),a=o.loading.first?Math.max(0,c-o.loading.first):0;i.advancedDateTime=Date.now()-a;const f=this.hls.config.timelineOffset;if(f!==i.appliedTimelineOffset){const y=Math.max(f||0,0);i.appliedTimelineOffset=y,i.fragments.forEach(v=>{v.setStart(v.playlistOffset+y)})}if(i.live||n!=null&&n.live){const y="levelInfo"in r?r.levelInfo:r.track;if(i.reloaded(n),n&&i.fragments.length>0){FOt(n,i,this);const M=i.playlistParsingError;if(M){this.warn(M);const B=this.hls;if(!B.config.ignorePlaylistParsingErrors){var p;const{networkDetails:V}=r;B.trigger(Ce.ERROR,{type:Dn.NETWORK_ERROR,details:Jt.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:M,reason:M.message,level:r.level||void 0,parent:(p=i.fragments[0])==null?void 0:p.type,networkDetails:V,stats:o});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=o.loading.start);const v=this.hls.mainForwardBufferInfo,T=v?v.end-v.len:0,E=(i.edge-T)*1e3,k=q2e(i,E);if(i.requestScheduled+k0){if(Q>i.targetduration*3)this.log(`Playlist last advanced ${J.toFixed(2)}s ago. Omitting segment and part directives.`),R=void 0,D=void 0;else if(n!=null&&n.tuneInGoal&&Q-i.partTarget>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${ee} with playlist age: ${i.age}`),ee=0;else{const le=Math.floor(ee/i.targetduration);if(R+=le,D!==void 0){const pe=Math.round(ee%i.targetduration/i.partTarget);D+=pe}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${J.toFixed(2)}s goal: ${ee} skip sn ${le} to part ${D}`)}i.tuneInGoal=ee}if(P=this.getDeliveryDirectives(i,r.deliveryDirectives,R,D),M||!Y){i.requestScheduled=c,this.loadingPlaylist(y,P);return}}else(i.canBlockReload||i.canSkipUntil)&&(P=this.getDeliveryDirectives(i,r.deliveryDirectives,R,D));P&&R!==void 0&&i.canBlockReload&&(i.requestScheduled=o.loading.first+Math.max(k-a*2,k/2)),this.scheduleLoading(y,P,i)}else this.clearTimer()}scheduleLoading(e,r,n){const i=n||e.details;if(!i){this.loadingPlaylist(e,r);return}const o=self.performance.now(),c=i.requestScheduled;if(o>=c){this.loadingPlaylist(e,r);return}const a=c-o;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,r),a)}getDeliveryDirectives(e,r,n,i){let o=_ce(e);return r!=null&&r.skip&&e.deltaUpdateFailed&&(n=r.msn,i=r.part,o=YL.No),new bce(n,i,o)}checkRetry(e){const r=e.details,n=SO(e),i=e.errorAction,{action:o,retryCount:c=0,retryConfig:a}=i||{},f=!!i&&!!a&&(o===Kl.RetryRequest||!i.resolved&&o===Kl.SendAlternateToPenaltyBox);if(f){var p;if(c>=a.maxNumRetry)return!1;if(n&&(p=e.context)!=null&&p.deliveryDirectives)this.warn(`Retrying playlist loading ${c+1}/${a.maxNumRetry} after "${r}" without delivery-directives`),this.loadPlaylist();else{const y=LK(a,c);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),y),this.warn(`Retrying playlist loading ${c+1}/${a.maxNumRetry} after "${r}" in ${y}ms`)}e.levelRetry=!0,i.resolved=!0}return f}}function gAe(t,e){if(t.length!==e.length)return!1;for(let r=0;rt[i]!==e[i])}function mG(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class W3t extends WK{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ce.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Ce.LEVEL_LOADING,this.onLevelLoading,this),e.on(Ce.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Ce.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Ce.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ce.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Ce.LEVEL_LOADING,this.onLevelLoading,this),e.off(Ce.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Ce.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Ce.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,r){this.tracks=r.audioTracks||[]}onAudioTrackLoaded(e,r){const{id:n,groupId:i,details:o}=r,c=this.tracksInGroup[n];if(!c||c.groupId!==i){this.warn(`Audio track with id:${n} and group:${i} not found in active group ${c==null?void 0:c.groupId}`);return}const a=c.details;c.details=r.details,this.log(`Audio track ${n} "${c.name}" lang:${c.lang} group:${i} loaded [${o.startSN}-${o.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,a)}onLevelLoading(e,r){this.switchLevel(r.level)}onLevelSwitching(e,r){this.switchLevel(r.level)}switchLevel(e){const r=this.hls.levels[e];if(!r)return;const n=r.audioGroups||null,i=this.groupIds;let o=this.currentTrack;if(!n||(i==null?void 0:i.length)!==(n==null?void 0:n.length)||n!=null&&n.some(a=>(i==null?void 0:i.indexOf(a))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(T=>!n||n.indexOf(T.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(T=>T.default)&&(this.selectDefaultTrack=!1),a.forEach((T,E)=>{T.id=E});else if(!o&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const f=this.hls.config.audioPreference;if(!o&&f){const T=dm(f,a,vv);if(T>-1)o=a[T];else{const E=dm(f,this.tracks);o=this.tracks[E]}}let p=this.findTrackId(o);p===-1&&o&&(p=this.findTrackId(null));const y={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${n==null?void 0:n.join(",")}`),this.hls.trigger(Ce.AUDIO_TRACKS_UPDATED,y);const v=this.trackId;if(p!==-1&&v===-1)this.setAudioTrack(p);else if(a.length&&v===-1){var c;const T=new Error(`No audio track selected for current audio group-ID(s): ${(c=this.groupIds)==null?void 0:c.join(",")} track count: ${a.length}`);this.warn(T.message),this.hls.trigger(Ce.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:T})}}}onError(e,r){r.fatal||!r.context||r.context.type===Wi.AUDIO_TRACK&&r.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(r.context.groupId)!==-1)&&this.checkRetry(r)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const r=this.hls;if(r.config.audioPreference=e,e){const n=this.allAudioTracks;if(this.selectDefaultTrack=!1,n.length){const i=this.currentTrack;if(i&&Yv(e,i,vv))return i;const o=dm(e,this.tracksInGroup,vv);if(o>-1){const c=this.tracksInGroup[o];return this.setAudioTrack(o),c}else if(i){let c=r.loadLevel;c===-1&&(c=r.firstAutoLevel);const a=sOt(e,r.levels,n,c,vv);if(a===-1)return null;r.nextLoadLevel=a}if(e.channels||e.audioCodec){const c=dm(e,n);if(c>-1)return n[c]}}}return null}setAudioTrack(e){const r=this.tracksInGroup;if(e<0||e>=r.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const n=this.currentTrack,i=r[e],o=i.details&&!i.details.live;if(e===this.trackId&&i===n&&o||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(Ce.AUDIO_TRACK_SWITCHING,Us({},i)),o))return;const c=this.switchParams(i.url,n==null?void 0:n.details,i.details);this.loadPlaylist(c)}findTrackId(e){const r=this.tracksInGroup;for(let n=0;n{const n={label:"async-blocker",execute:r,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(n,e)})}prependBlocker(e){return new Promise(r=>{if(this.queues){const n={label:"async-blocker-prepend",execute:r,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(n)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var r;const n=(r=e[0])==null?void 0:r.label;(n==="async-blocker"||n==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const r=this.queues[e];if(r.length){const i=r[0];try{i.execute()}catch(o){var n;if(i.onError(o),this.queues===null||this.tracks===null)return;const c=(n=this.tracks[e])==null?void 0:n.buffer;c!=null&&c.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var r;return((r=this.queues)==null?void 0:r[e][0])||null}toString(){const{queues:e,tracks:r}=this;return e===null||r===null?"":` ${this.list("video")} ${this.list("audio")} ${this.list("audiovideo")}}`}list(e){var r,n;return(r=this.queues)!=null&&r[e]||(n=this.tracks)!=null&&n[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var r;const n=(r=this.tracks)==null?void 0:r[e],i=n==null?void 0:n.buffer;return i?`SourceBuffer${i.updating?" updating":""}${n.ended?" ended":""}${n.ending?" ending":""}`:"none"}listOps(e){var r;return((r=this.queues)==null?void 0:r[e].map(n=>n.label).join(", "))||""}}const aue=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,yAe="HlsJsTrackRemovedError";class Y3t extends Error{constructor(e){super(e),this.name=yAe}}class Z3t extends _h{constructor(e,r){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=n=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=n=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=n=>{const{media:i,mediaSource:o}=this;n&&this.log("Media source opened"),!(!i||!o)&&(o.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(Ce.MEDIA_ATTACHED,{media:i,mediaSource:o}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:n,_objectUrl:i}=this;n!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${n})`)},this.hls=e,this.fragmentTracker=r,this.appendSource=xMt(Ex(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(Ce.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ce.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Ce.BUFFER_RESET,this.onBufferReset,this),e.on(Ce.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Ce.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Ce.BUFFER_EOS,this.onBufferEos,this),e.on(Ce.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Ce.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Ce.FRAG_PARSED,this.onFragParsed,this),e.on(Ce.FRAG_CHANGED,this.onFragChanged,this),e.on(Ce.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Ce.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ce.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Ce.BUFFER_RESET,this.onBufferReset,this),e.off(Ce.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Ce.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Ce.BUFFER_EOS,this.onBufferEos,this),e.off(Ce.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Ce.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Ce.FRAG_PARSED,this.onFragParsed,this),e.off(Ce.FRAG_CHANGED,this.onFragChanged,this),e.off(Ce.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:r}=this;if(!e)return null;const n={};if(this.operationQueue){const o=this.isUpdating();o||this.operationQueue.removeBlockers();const c=this.isQueued();(o||c)&&this.warn(`Transfering MediaSource with${c?" operations in queue":""}${o?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===r?Js(n,i.tracks):this.sourceBuffers.forEach(o=>{const[c]=o;c&&(n[c]=Js({},this.tracks[c]),this.removeBuffer(c)),o[0]=o[1]=null}),{media:e,mediaSource:r,tracks:n}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,r){var n;let i=2;(r.audio&&!r.video||!r.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(n=this.transferData)!=null&&n.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,r){const n=this.media=r.media;this.transferData=this.overrides=void 0;const i=Ex(this.appendSource);if(i){const o=!!r.mediaSource;(o||r.overrides)&&(this.transferData=r,this.overrides=r.overrides);const c=this.mediaSource=r.mediaSource||new i;if(this.assignMediaSource(c),o)this._objectUrl=n.src,this.attachTransferred();else{const a=this._objectUrl=self.URL.createObjectURL(c);if(this.appendSource)try{n.removeAttribute("src");const f=self.ManagedMediaSource;n.disableRemotePlayback=n.disableRemotePlayback||f&&c instanceof f,oue(n),X3t(n,a),n.load()}catch{n.src=a}else n.src=a}n.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var r,n;this.log(`${((r=this.transferData)==null?void 0:r.mediaSource)===e?"transferred":"created"} media source: ${(n=e.constructor)==null?void 0:n.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,r=this.transferData;if(!r||!e)return;const n=this.tracks,i=r.tracks,o=i?Object.keys(i):null,c=o?o.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&o&&c){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) required tracks: ${aa(n,(f,p)=>f==="initSegment"?void 0:p)}; transfer tracks: ${aa(i,(f,p)=>f==="initSegment"?void 0:p)}}`),!f2e(i,n)){r.mediaSource=null,r.tracks=void 0;const f=e.currentTime,p=this.details,y=Math.max(f,(p==null?void 0:p.fragments[0].start)||0);if(y-f>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${f} -> ${y}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(n)}") start time: ${y} currentTime: ${f}`),this.onMediaDetaching(Ce.MEDIA_DETACHING,{}),this.onMediaAttaching(Ce.MEDIA_ATTACHING,r),e.currentTime=y;return}this.transferData=void 0,o.forEach(f=>{const p=f,y=i[p];if(y){const v=y.buffer;if(v){const T=this.fragmentTracker,E=y.id;if(T.hasFragments(E)||T.hasParts(E)){const R=Ti.getBuffered(v);T.detectEvictedFragments(p,R,E,null,!0)}const k=w6(p),P=[p,v];this.sourceBuffers[k]=P,v.updating&&this.operationQueue&&this.operationQueue.prependBlocker(p),this.trackSourceBuffer(p,y)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const r=(e=this.mediaSource)==null?void 0:e.readyState;return r==="open"||r==="ended"}onMediaDetaching(e,r){const n=!!r.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:o,_objectUrl:c}=this;if(o){if(this.log(`media source ${n?"transferring":"detaching"}`),n)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const a=o.readyState==="open";try{const f=o.sourceBuffers;for(let p=f.length;p--;)a&&f[p].abort(),o.removeSourceBuffer(f[p]);a&&o.endOfStream()}catch(f){this.warn(`onMediaDetaching: ${f.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}o.removeEventListener("sourceopen",this._onMediaSourceOpen),o.removeEventListener("sourceended",this._onMediaSourceEnded),o.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(o.removeEventListener("startstreaming",this._onStartStreaming),o.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),n||(c&&self.URL.revokeObjectURL(c),this.mediaSrc===c?(i.removeAttribute("src"),this.appendSource&&oue(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(Ce.MEDIA_DETACHED,r)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var r;const n=(r=this.tracks[e])==null?void 0:r.buffer;if(this.removeBuffer(e),n)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(n)}catch(o){this.warn(`onBufferReset ${e}`,o)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[w6(e)]=[null,null];const r=this.tracks[e];r&&(r.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new K3t(this.tracks)}onBufferCodecs(e,r){var n;const i=this.tracks,o=Object.keys(r);this.log(`BUFFER_CODECS: "${o}" (current SB count ${this.sourceBufferCount})`);const c="audiovideo"in r&&(i.audio||i.video)||i.audiovideo&&("audio"in r||"video"in r),a=!c&&this.sourceBufferCount&&this.media&&o.some(f=>!i[f]);if(c||a){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${o}" SourceBuffers`);return}o.forEach(f=>{var p,y;const v=r[f],{id:T,codec:E,levelCodec:k,container:P,metadata:R,supplemental:D}=v;let M=i[f];const B=(p=this.transferData)==null||(p=p.tracks)==null?void 0:p[f],V=B!=null&&B.buffer?B:M,G=(V==null?void 0:V.pendingCodec)||(V==null?void 0:V.codec),W=V==null?void 0:V.levelCodec;M||(M=i[f]={buffer:void 0,listeners:[],codec:E,supplemental:D,container:P,levelCodec:k,metadata:R,id:T});const Y=KL(G,W),J=Y==null?void 0:Y.replace(aue,"$1");let Q=KL(E,k);const ee=(y=Q)==null?void 0:y.replace(aue,"$1");Q&&Y&&J!==ee&&(f.slice(0,5)==="audio"&&(Q=_O(Q,this.appendSource)),this.log(`switching codec ${G} to ${Q}`),Q!==(M.pendingCodec||M.codec)&&(M.pendingCodec=Q),M.container=P,this.appendChangeType(f,P,Q))}),(this.tracksReady||this.sourceBufferCount)&&(r.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!r.video&&((n=r.audio)==null?void 0:n.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,r)=>{const n=this.tracks[r];return e[r]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},e},{})}appendChangeType(e,r,n){const i=`${r};codecs=${n}`,o={label:`change-type=${i}`,execute:()=>{const c=this.tracks[e];if(c){const a=c.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),a.changeType(i),c.codec=n,c.container=r)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:c=>{this.warn(`Failed to change ${e} SourceBuffer type`,c)}};this.append(o,e,this.isPending(this.tracks[e]))}blockAudio(e){var r;const n=e.start,i=n+e.duration*.05;if(((r=this.fragmentTracker.getAppendedFrag(n,Tn.MAIN))==null?void 0:r.gap)===!0)return;const c={label:"block-audio",execute:()=>{var a;const f=this.tracks.video;(this.lastVideoAppendEnd>i||f!=null&&f.buffer&&Ti.isBuffered(f.buffer,i)||((a=this.fragmentTracker.getAppendedFrag(i,Tn.MAIN))==null?void 0:a.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn("Error executing block-audio operation",a)}};this.blockedAudioAppend={op:c,frag:e},this.append(c,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:r}=this;e&&r&&(this.blockedAudioAppend=null,r.unblockAudio(e.op))}onBufferAppending(e,r){const{tracks:n}=this,{data:i,type:o,parent:c,frag:a,part:f,chunkMeta:p,offset:y}=r,v=p.buffering[o],{sn:T,cc:E}=a,k=self.performance.now();v.start=k;const P=a.stats.buffering,R=f?f.stats.buffering:null;P.start===0&&(P.start=k),R&&R.start===0&&(R.start=k);const D=n.audio;let M=!1;o==="audio"&&(D==null?void 0:D.container)==="audio/mpeg"&&(M=!this.lastMpegAudioChunk||p.id===1||this.lastMpegAudioChunk.sn!==p.sn,this.lastMpegAudioChunk=p);const B=n.video,V=B==null?void 0:B.buffer;if(V&&T!=="initSegment"){const Y=f||a,J=this.blockedAudioAppend;if(o==="audio"&&c!=="main"&&!this.blockedAudioAppend&&!(B.ending||B.ended)){const ee=Y.start+Y.duration*.05,le=V.buffered,pe=this.currentOp("video");!le.length&&!pe?this.blockAudio(Y):!pe&&!Ti.isBuffered(V,ee)&&this.lastVideoAppendEndee||Q{var Y;v.executeStart=self.performance.now();const J=(Y=this.tracks[o])==null?void 0:Y.buffer;J&&(M?this.updateTimestampOffset(J,G,.1,o,T,E):y!==void 0&&pn(y)&&this.updateTimestampOffset(J,y,1e-6,o,T,E)),this.appendExecutor(i,o)},onStart:()=>{},onComplete:()=>{const Y=self.performance.now();v.executeEnd=v.end=Y,P.first===0&&(P.first=Y),R&&R.first===0&&(R.first=Y);const J={};this.sourceBuffers.forEach(([Q,ee])=>{Q&&(J[Q]=Ti.getBuffered(ee))}),this.appendErrors[o]=0,o==="audio"||o==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(Ce.BUFFER_APPENDED,{type:o,frag:a,part:f,chunkMeta:p,parent:a.type,timeRanges:J})},onError:Y=>{var J;const Q={type:Dn.MEDIA_ERROR,parent:a.type,details:Jt.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:a,part:f,chunkMeta:p,error:Y,err:Y,fatal:!1},ee=(J=this.media)==null?void 0:J.error;if(Y.code===DOMException.QUOTA_EXCEEDED_ERR||Y.name=="QuotaExceededError"||"quota"in Y)Q.details=Jt.BUFFER_FULL_ERROR;else if(Y.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!ee)Q.errorAction=C1(!0);else if(Y.name===yAe&&this.sourceBufferCount===0)Q.errorAction=C1(!0);else{const le=++this.appendErrors[o];this.warn(`Failed ${le}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${o}" sourceBuffer (${ee||"no media error"})`),(le>=this.hls.config.appendErrorMaxRetry||ee)&&(Q.fatal=!0)}this.hls.trigger(Ce.ERROR,Q)}};this.log(`queuing "${o}" append sn: ${T}${f?" p: "+f.index:""} of ${a.type===Tn.MAIN?"level":"track"} ${a.level} cc: ${E}`),this.append(W,o,this.isPending(this.tracks[o]))}getFlushOp(e,r,n){return this.log(`queuing "${e}" remove ${r}-${n}`),{label:"remove",execute:()=>{this.removeExecutor(e,r,n)},onStart:()=>{},onComplete:()=>{this.hls.trigger(Ce.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${r}-${n} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,r){const{type:n,startOffset:i,endOffset:o}=r;n?this.append(this.getFlushOp(n,i,o),n):this.sourceBuffers.forEach(([c])=>{c&&this.append(this.getFlushOp(c,i,o),c)})}onFragParsed(e,r){const{frag:n,part:i}=r,o=[],c=i?i.elementaryStreams:n.elementaryStreams;c[na.AUDIOVIDEO]?o.push("audiovideo"):(c[na.AUDIO]&&o.push("audio"),c[na.VIDEO]&&o.push("video"));const a=()=>{const f=self.performance.now();n.stats.buffering.end=f,i&&(i.stats.buffering.end=f);const p=i?i.stats:n.stats;this.hls.trigger(Ce.FRAG_BUFFERED,{frag:n,part:i,stats:p,id:n.type})};o.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(a,o).catch(f=>{this.warn(`Fragment buffered callback ${f}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,r){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const r=this.tracks[e];if(r)return!r.ended||r.ending}return!1})}onBufferEos(e,r){var n;this.sourceBuffers.forEach(([c])=>{if(c){const a=this.tracks[c];(!r.type||r.type===c)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${c} buffer reached EOS`)))}});const i=((n=this.overrides)==null?void 0:n.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([c])=>{var a;return c&&!((a=this.tracks[c])!=null&&a.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:c}=this;if(!c||c.readyState!=="open"){c&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${c.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),c.endOfStream(),this.hls.trigger(Ce.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(Ce.BUFFERED_TO_END,void 0)):r.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const r=this.tracks[e];r&&(r.ending=!1)}})}onLevelUpdated(e,{details:r}){r.fragments.length&&(this.details=r,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,r){if(r.details===Jt.BUFFER_APPEND_ERROR&&r.frag){var n;const i=(n=r.errorAction)==null?void 0:n.nextAutoLevel;pn(i)&&i!==r.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:r,media:n}=this;if(!n||r===null||!this.sourceBufferCount)return;const i=e.config,o=n.currentTime,c=r.levelTargetDuration,a=r.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(pn(a)&&a>=0){const p=Math.max(a,c),y=Math.floor(o/c)*c-p;this.flushBackBuffer(o,c,y)}const f=i.frontBufferFlushThreshold;if(pn(f)&&f>0){const p=Math.max(i.maxBufferLength,f),y=Math.max(p,c),v=Math.floor(o/c)*c+y;this.flushFrontBuffer(o,c,v)}}flushBackBuffer(e,r,n){this.sourceBuffers.forEach(([i,o])=>{if(o){const a=Ti.getBuffered(o);if(a.length>0&&n>a.start(0)){var c;this.hls.trigger(Ce.BACK_BUFFER_REACHED,{bufferEnd:n});const f=this.tracks[i];if((c=this.details)!=null&&c.live)this.hls.trigger(Ce.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(f!=null&&f.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(Ce.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:i})}}})}flushFrontBuffer(e,r,n){this.sourceBuffers.forEach(([i,o])=>{if(o){const c=Ti.getBuffered(o),a=c.length;if(a<2)return;const f=c.start(a-1),p=c.end(a-1);if(n>f||e>=f&&e<=p)return;this.hls.trigger(Ce.BUFFER_FLUSHING,{startOffset:f,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:r,mediaSource:n}=this;if(!r||!this.media||(n==null?void 0:n.readyState)!=="open")return null;const i=r.edge;if(r.live&&this.hls.config.liveDurationInfinity){if(r.fragments.length&&n.setLiveSeekableRange){const p=Math.max(0,r.fragmentStart),y=Math.max(p,i);return{duration:1/0,start:p,end:y}}return{duration:1/0}}const o=(e=this.overrides)==null?void 0:e.duration;if(o)return pn(o)?{duration:o}:null;const c=this.media.duration,a=pn(n.duration)?n.duration:0;return i>a&&i>c||!pn(c)?{duration:i}:null}updateMediaSource({duration:e,start:r,end:n}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(pn(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),r!==void 0&&n!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${r}-${n}.`),i.setLiveSeekableRange(r,n)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:r,tracks:n}=this;if(this.log(`checkPendingTracks (pending: ${r} codec events expected: ${e}) ${aa(n)}`),this.tracksReady){var i;const o=(i=this.transferData)==null?void 0:i.tracks;o&&Object.keys(o).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([r,n])=>{if(r){const i=this.tracks[r];e[r]={buffer:n,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(Ce.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([r])=>{this.executeNext(r)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Ce.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:r,mediaSource:n}=this;if(!n)throw new Error("createSourceBuffers called when mediaSource was null");for(const o in e){const c=o,a=e[c];if(this.isPending(a)){const f=this.getTrackCodec(a,c),p=`${a.container};codecs=${f}`;a.codec=f,this.log(`creating sourceBuffer(${p})${this.currentOp(c)?" Queued":""} ${aa(a)}`);try{const y=n.addSourceBuffer(p),v=w6(c),T=[c,y];r[v]=T,a.buffer=y}catch(y){var i;this.error(`error while trying to add sourceBuffer: ${y.message}`),this.shiftAndExecuteNext(c),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[c],this.hls.trigger(Ce.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:y,sourceBufferName:c,mimeType:p,parent:a.id});return}this.trackSourceBuffer(c,a)}}this.bufferCreated()}getTrackCodec(e,r){const n=e.supplemental;let i=e.codec;n&&(r==="video"||r==="audiovideo")&&nC(n,"video")&&(i=$Mt(i,n));const o=KL(i,e.levelCodec);return o?r.slice(0,5)==="audio"?_O(o,this.appendSource):o:""}trackSourceBuffer(e,r){const n=r.buffer;if(!n)return;const i=this.getTrackCodec(r,e);this.tracks[e]={buffer:n,codec:i,container:r.container,levelCodec:r.levelCodec,supplemental:r.supplemental,metadata:r.metadata,id:r.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(o,c)=>{const a=c.removedRanges;a!=null&&a.length&&this.hls.trigger(Ce.BUFFER_FLUSHED,{type:o})})}get mediaSrc(){var e,r;const n=((e=this.media)==null||(r=e.querySelector)==null?void 0:r.call(e,"source"))||this.media;return n==null?void 0:n.src}onSBUpdateStart(e){const r=this.currentOp(e);r&&r.onStart()}onSBUpdateEnd(e){var r;if(((r=this.mediaSource)==null?void 0:r.readyState)==="closed"){this.resetBuffer(e);return}const n=this.currentOp(e);n&&(n.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,r){var n;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(n=this.mediaSource)==null?void 0:n.readyState}`);this.error(`${i}`,r),this.hls.trigger(Ce.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const o=this.currentOp(e);o&&o.onError(i)}updateTimestampOffset(e,r,n,i,o,c){const a=r-e.timestampOffset;Math.abs(a)>=n&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${r} (sn: ${o} cc: ${c})`),e.timestampOffset=r)}removeExecutor(e,r,n){const{media:i,mediaSource:o}=this,c=this.tracks[e],a=c==null?void 0:c.buffer;if(!i||!o||!a){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const f=pn(i.duration)?i.duration:1/0,p=pn(o.duration)?o.duration:1/0,y=Math.max(0,r),v=Math.min(n,f,p);v>y&&(!c.ending||c.ended)?(c.ended=!1,this.log(`Removing [${y},${v}] from the ${e} SourceBuffer`),a.remove(y,v)):this.shiftAndExecuteNext(e)}appendExecutor(e,r){const n=this.tracks[r],i=n==null?void 0:n.buffer;if(!i)throw new Y3t(`Attempting to append to the ${r} SourceBuffer, but it does not exist`);n.ending=!1,n.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(r=>{this.warn(`SourceBuffer blocked callback ${r}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(r){this.warn(`Callback run without blocking ${this.operationQueue} ${r}`)}}isUpdating(){return this.sourceBuffers.some(([e,r])=>e&&r.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,r=this.sourceBufferTypes){if(!r.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:n}=this,i=r.map(c=>this.appendBlocker(c));return r.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(c=>{n===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(r=>{var n;const i=(n=this.tracks[r])==null?void 0:n.buffer;!i||i.updating||this.shiftAndExecuteNext(r)})}append(e,r,n){this.operationQueue&&this.operationQueue.append(e,r,n)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,r)=>e+(this.isPending(this.tracks[r])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[r])=>e+(r?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,r,n){const i=this.tracks[e];if(!i)return;const o=i.buffer;if(!o)return;const c=n.bind(this,e);i.listeners.push({event:r,listener:c}),o.addEventListener(r,c)}removeBufferListeners(e){const r=this.tracks[e];if(!r)return;const n=r.buffer;n&&(r.listeners.forEach(i=>{n.removeEventListener(i.event,i.listener)}),r.listeners.length=0)}}function oue(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(r=>{t.removeChild(r)})}function X3t(t,e){const r=self.document.createElement("source");r.type="video/mp4",r.src=e,t.appendChild(r)}function w6(t){return t==="audio"?1:0}class KK{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(Ce.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Ce.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Ce.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Ce.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Ce.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Ce.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(Ce.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Ce.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Ce.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Ce.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Ce.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Ce.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,r){const n=this.hls.levels[r.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(e,r){this.media=r.media instanceof HTMLVideoElement?r.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,r){const n=this.hls;this.restrictedLevels=[],this.firstLevel=r.firstLevel,n.config.capLevelToPlayerSize&&r.video&&this.startCapping()}onLevelsUpdated(e,r){this.timer&&pn(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,r){this.hls.config.capLevelToPlayerSize&&r.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const r=this.hls,n=this.getMaxLevel(e.length-1);n!==this.autoLevelCapping&&r.logger.log(`Setting autoLevelCapping to ${n}: ${e[n].height}p@${e[n].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),r.autoLevelCapping=n,r.autoLevelEnabled&&r.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=r.autoLevelCapping}}}getMaxLevel(e){const r=this.hls.levels;if(!r.length)return-1;const n=r.filter((i,o)=>this.isLevelAllowed(i)&&o<=e);return this.clientRect=null,KK.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,r={width:0,height:0};if(e){const n=e.getBoundingClientRect();r.width=n.width,r.height=n.height,!r.width&&!r.height&&(r.width=n.right-n.left||e.width||0,r.height=n.bottom-n.top||e.height||0)}return this.clientRect=r,r}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(n=>e.bitrate===n.bitrate&&e.width===n.width&&e.height===n.height)}static getMaxLevelByMediaSize(e,r,n){if(!(e!=null&&e.length))return-1;const i=(a,f)=>f?a.width!==f.width||a.height!==f.height:!0;let o=e.length-1;const c=Math.max(r,n);for(let a=0;a=c||f.height>=c)&&i(f,e[a+1])){o=a;break}}return o}}const Q3t={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Su=Q3t,J3t={HLS:"h"},eFt=J3t;class Am{constructor(e,r){Array.isArray(e)&&(e=e.map(n=>n instanceof Am?n:new Am(n))),this.value=e,this.params=r}}const tFt="Dict";function rFt(t){return Array.isArray(t)?JSON.stringify(t):t instanceof Map?"Map{}":t instanceof Set?"Set{}":typeof t=="object"?JSON.stringify(t):String(t)}function nFt(t,e,r,n){return new Error(`failed to ${t} "${rFt(e)}" as ${r}`,{cause:n})}function km(t,e,r){return nFt("serialize",t,e,r)}class xAe{constructor(e){this.description=e}}const lue="Bare Item",iFt="Boolean";function sFt(t){if(typeof t!="boolean")throw km(t,iFt);return t?"?1":"?0"}function aFt(t){return btoa(String.fromCharCode(...t))}const oFt="Byte Sequence";function lFt(t){if(ArrayBuffer.isView(t)===!1)throw km(t,oFt);return`:${aFt(t)}:`}const cFt="Integer";function uFt(t){return t<-999999999999999||99999999999999912)throw km(t,hFt);const r=e.toString();return r.includes(".")?r:`${r}.0`}const mFt="String",pFt=/[\x00-\x1f\x7f]+/;function gFt(t){if(pFt.test(t))throw km(t,mFt);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function yFt(t){return t.description||t.toString().slice(7,-1)}const xFt="Token";function cue(t){const e=yFt(t);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw km(e,xFt);return e}function pG(t){switch(typeof t){case"number":if(!pn(t))throw km(t,lue);return Number.isInteger(t)?vAe(t):fFt(t);case"string":return gFt(t);case"symbol":return cue(t);case"boolean":return sFt(t);case"object":if(t instanceof Date)return dFt(t);if(t instanceof Uint8Array)return lFt(t);if(t instanceof xAe)return cue(t);default:throw km(t,lue)}}const vFt="Key";function gG(t){if(/^[a-z*][a-z0-9\-_.*]*$/.test(t)===!1)throw km(t,vFt);return t}function YK(t){return t==null?"":Object.entries(t).map(([e,r])=>r===!0?`;${gG(e)}`:`;${gG(e)}=${pG(r)}`).join("")}function bAe(t){return t instanceof Am?`${pG(t.value)}${YK(t.params)}`:pG(t)}function _Ft(t){return`(${t.value.map(bAe).join(" ")})${YK(t.params)}`}function bFt(t,e={whitespace:!0}){if(typeof t!="object"||t==null)throw km(t,tFt);const r=t instanceof Map?t.entries():Object.entries(t),n=e!=null&&e.whitespace?" ":"";return Array.from(r).map(([i,o])=>{o instanceof Am||(o=new Am(o));let c=gG(i);return o.value===!0?c+=YK(o.params):(c+="=",Array.isArray(o.value)?c+=_Ft(o):c+=bAe(o)),c}).join(`,${n}`)}function wAe(t,e){return bFt(t,e)}const Gf="CMCD-Object",po="CMCD-Request",lv="CMCD-Session",fy="CMCD-Status",wFt={br:Gf,ab:Gf,d:Gf,ot:Gf,tb:Gf,tpb:Gf,lb:Gf,tab:Gf,lab:Gf,url:Gf,pb:po,bl:po,tbl:po,dl:po,ltc:po,mtp:po,nor:po,nrr:po,rc:po,sn:po,sta:po,su:po,ttfb:po,ttfbb:po,ttlb:po,cmsdd:po,cmsds:po,smrt:po,df:po,cs:po,ts:po,cid:lv,pr:lv,sf:lv,sid:lv,st:lv,v:lv,msd:lv,bs:fy,bsd:fy,cdn:fy,rtp:fy,bg:fy,pt:fy,ec:fy,e:fy},SFt={REQUEST:po};function TFt(t){return Object.keys(t).reduce((e,r)=>{var n;return(n=t[r])===null||n===void 0||n.forEach(i=>e[i]=r),e},{})}function EFt(t,e){const r={};if(!t)return r;const n=Object.keys(t),i=e?TFt(e):{};return n.reduce((o,c)=>{var a;const f=wFt[c]||i[c]||SFt.REQUEST,p=(a=o[f])!==null&&a!==void 0?a:o[f]={};return p[c]=t[c],o},r)}function jFt(t){return["ot","sf","st","e","sta"].includes(t)}function AFt(t){return typeof t=="number"?pn(t):t!=null&&t!==""&&t!==!1}const SAe="event";function kFt(t,e){const r=new URL(t),n=new URL(e);if(r.origin!==n.origin)return t;const i=r.pathname.split("/").slice(1),o=n.pathname.split("/").slice(1,-1);for(;i[0]===o[0];)i.shift(),o.shift();for(;o.length;)o.shift(),i.unshift("..");return i.join("/")+r.search+r.hash}const JL=t=>Math.round(t),yG=(t,e)=>Array.isArray(t)?t.map(r=>yG(r,e)):t instanceof Am&&typeof t.value=="string"?new Am(yG(t.value,e),t.params):(e.baseUrl&&(t=kFt(t,e.baseUrl)),e.version===1?encodeURIComponent(t):t),JR=t=>JL(t/100)*100,CFt=(t,e)=>{let r=t;return e.version>=2&&(t instanceof Am&&typeof t.value=="string"?r=new Am([t]):typeof t=="string"&&(r=[t])),yG(r,e)},NFt={br:JL,d:JL,bl:JR,dl:JR,mtp:JR,nor:CFt,rtp:JR,tb:JL},TAe="request",EAe="response",ZK=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],IFt=["e"],PFt=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function b5(t){return PFt.test(t)}function RFt(t){return ZK.includes(t)||IFt.includes(t)||b5(t)}const jAe=["d","dl","nor","ot","rtp","su"];function LFt(t){return ZK.includes(t)||jAe.includes(t)||b5(t)}const DFt=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function MFt(t){return ZK.includes(t)||jAe.includes(t)||DFt.includes(t)||b5(t)}const OFt=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function FFt(t){return OFt.includes(t)||b5(t)}const BFt={[EAe]:MFt,[SAe]:RFt,[TAe]:LFt};function AAe(t,e={}){const r={};if(t==null||typeof t!="object")return r;const n=e.version||t.v||1,i=e.reportingMode||TAe,o=n===1?FFt:BFt[i];let c=Object.keys(t).filter(o);const a=e.filter;typeof a=="function"&&(c=c.filter(a));const f=i===EAe||i===SAe;f&&!c.includes("ts")&&c.push("ts"),n>1&&!c.includes("v")&&c.push("v");const p=Js({},NFt,e.formatters),y={version:n,reportingMode:i,baseUrl:e.baseUrl};return c.sort().forEach(v=>{let T=t[v];const E=p[v];if(typeof E=="function"&&(T=E(T,y)),v==="v"){if(n===1)return;T=n}v=="pr"&&T===1||(f&&v==="ts"&&!pn(T)&&(T=Date.now()),AFt(T)&&(jFt(v)&&typeof T=="string"&&(T=new xAe(T)),r[v]=T))}),r}function $Ft(t,e={}){const r={};if(!t)return r;const n=AAe(t,e),i=EFt(n,e==null?void 0:e.customHeaderMap);return Object.entries(i).reduce((o,[c,a])=>{const f=wAe(a,{whitespace:!1});return f&&(o[c]=f),o},r)}function zFt(t,e,r){return Js(t,$Ft(e,r))}const UFt="CMCD";function VFt(t,e={}){return t?wAe(AAe(t,e),{whitespace:!1}):""}function qFt(t,e={}){if(!t)return"";const r=VFt(t,e);return encodeURIComponent(r)}function GFt(t,e={}){if(!t)return"";const r=qFt(t,e);return`${UFt}=${r}`}const uue=/CMCD=[^&#]+/;function HFt(t,e,r){const n=GFt(e,r);if(!n)return t;if(uue.test(t))return t.replace(uue,n);const i=t.includes("?")?"&":"?";return`${t}${i}${n}`}class WFt{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:Su.MANIFEST,su:!this.initialized})}catch(o){this.hls.logger.warn("Could not generate manifest CMCD data.",o)}},this.applyFragmentData=i=>{try{const{frag:o,part:c}=i,a=this.hls.levels[o.level],f=this.getObjectType(o),p={d:(c||o).duration*1e3,ot:f};(f===Su.VIDEO||f===Su.AUDIO||f==Su.MUXED)&&(p.br=a.bitrate/1e3,p.tb=this.getTopBandwidth(f)/1e3,p.bl=this.getBufferLength(f));const y=c?this.getNextPart(c):this.getNextFrag(o);y!=null&&y.url&&y.url!==o.url&&(p.nor=y.url),this.apply(i,p)}catch(o){this.hls.logger.warn("Could not generate segment CMCD data.",o)}},this.hls=e;const r=this.config=e.config,{cmcd:n}=r;n!=null&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||e.sessionId,this.cid=n.contentId,this.useHeaders=n.useHeaders===!0,this.includeKeys=n.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Ce.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Ce.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Ce.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Ce.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,r){this.media=r.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,r){var n,i;this.audioBuffer=(n=r.tracks.audio)==null?void 0:n.buffer,this.videoBuffer=(i=r.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:eFt.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,r={}){Js(r,this.createData());const n=r.ot===Su.INIT||r.ot===Su.VIDEO||r.ot===Su.MUXED;this.starved&&n&&(r.bs=!0,r.su=!0,this.starved=!1),r.su==null&&(r.su=this.buffering);const{includeKeys:i}=this;i&&(r=Object.keys(r).reduce((c,a)=>(i.includes(a)&&(c[a]=r[a]),c),{}));const o={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),zFt(e.headers,r,o)):e.url=HFt(e.url,r,o)}getNextFrag(e){var r;const n=(r=this.hls.levels[e.level])==null?void 0:r.details;if(n){const i=e.sn-n.startSN;return n.fragments[i+1]}}getNextPart(e){var r;const{index:n,fragment:i}=e,o=(r=this.hls.levels[i.level])==null||(r=r.details)==null?void 0:r.partList;if(o){const{sn:c}=i;for(let a=o.length-1;a>=0;a--){const f=o[a];if(f.index===n&&f.fragment.sn===c)return o[a+1]}}}getObjectType(e){const{type:r}=e;if(r==="subtitle")return Su.TIMED_TEXT;if(e.sn==="initSegment")return Su.INIT;if(r==="audio")return Su.AUDIO;if(r==="main")return this.hls.audioTracks.length?Su.VIDEO:Su.MUXED}getTopBandwidth(e){let r=0,n;const i=this.hls;if(e===Su.AUDIO)n=i.audioTracks;else{const o=i.maxAutoLevel,c=o>-1?o+1:i.levels.length;n=i.levels.slice(0,c)}return n.forEach(o=>{o.bitrate>r&&(r=o.bitrate)}),r>0?r:NaN}getBufferLength(e){const r=this.media,n=e===Su.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!r?NaN:Ti.bufferInfo(n,r.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,r=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(o){this.loader=void 0,this.loader=new n(o)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(o,c,a){r(o),this.loader.load(o,c,a)}}}createFragmentLoader(){const{fLoader:e}=this.config,r=this.applyFragmentData,n=e||this.config.loader;return class{constructor(o){this.loader=void 0,this.loader=new n(o)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(o,c,a){r(o),this.loader.load(o,c,a)}}}}const KFt=3e5;class YFt extends _h{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ce.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Ce.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Ce.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ce.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Ce.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Ce.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,r)=>(e.indexOf(r.pathwayId)===-1&&e.push(r.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const r=this.levels;r&&(this.levels=r.filter(n=>n!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,r){const{contentSteering:n}=r;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,r){this.audioTracks=r.audioTracks,this.subtitleTracks=r.subtitleTracks}onError(e,r){const{errorAction:n}=r;if((n==null?void 0:n.action)===Kl.SendAlternateToPenaltyBox&&n.flags===td.MoveAllAlternatesMatchingHost){const i=this.levels;let o=this._pathwayPriority,c=this.pathwayId;if(r.context){const{groupId:a,pathwayId:f,type:p}=r.context;a&&i?c=this.getPathwayForGroupId(a,p,c):f&&(c=f)}c in this.penalizedPathways||(this.penalizedPathways[c]=performance.now()),!o&&i&&(o=this.pathways()),o&&o.length>1&&(this.updatePathwayPriority(o),n.resolved=this.pathwayId!==c),r.details===Jt.BUFFER_APPEND_ERROR&&!r.fatal?n.resolved=!0:n.resolved||this.warn(`Could not resolve ${r.details} ("${r.error.message}") with content-steering for Pathway: ${c} levels: ${i&&i.length} priorities: ${aa(o)} penalized: ${aa(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let r=this.getLevelsForPathway(this.pathwayId);if(r.length===0){const n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),r=this.getLevelsForPathway(n),this.pathwayId=n}return r.length!==e.length&&this.log(`Found ${r.length}/${e.length} levels in Pathway "${this.pathwayId}"`),r}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(r=>e===r.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let r;const n=this.penalizedPathways,i=performance.now();Object.keys(n).forEach(o=>{i-n[o]>KFt&&delete n[o]});for(let o=0;o0){this.log(`Setting Pathway to "${c}"`),this.pathwayId=c,W2e(r),this.hls.trigger(Ce.LEVELS_UPDATED,{levels:r});const p=this.hls.levels[a];f&&p&&this.levels&&(p.attrs["STABLE-VARIANT-ID"]!==f.attrs["STABLE-VARIANT-ID"]&&p.bitrate!==f.bitrate&&this.log(`Unstable Pathways change from bitrate ${f.bitrate} to ${p.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,r,n){const i=this.getLevelsForPathway(n).concat(this.levels||[]);for(let o=0;o{const{ID:c,"BASE-ID":a,"URI-REPLACEMENT":f}=o;if(r.some(y=>y.pathwayId===c))return;const p=this.getLevelsForPathway(a).map(y=>{const v=new Qa(y.attrs);v["PATHWAY-ID"]=c;const T=v.AUDIO&&`${v.AUDIO}_clone_${c}`,E=v.SUBTITLES&&`${v.SUBTITLES}_clone_${c}`;T&&(n[v.AUDIO]=T,v.AUDIO=T),E&&(i[v.SUBTITLES]=E,v.SUBTITLES=E);const k=kAe(y.uri,v["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",f),P=new sC({attrs:v,audioCodec:y.audioCodec,bitrate:y.bitrate,height:y.height,name:y.name,url:k,videoCodec:y.videoCodec,width:y.width});if(y.audioGroups)for(let R=1;R{this.log(`Loaded steering manifest: "${i}"`);const k=y.data;if((k==null?void 0:k.VERSION)!==1){this.log(`Steering VERSION ${k.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=k.TTL;const{"RELOAD-URI":P,"PATHWAY-CLONES":R,"PATHWAY-PRIORITY":D}=k;if(P)try{this.uri=new self.URL(P,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${P}`);return}this.scheduleRefresh(this.uri||T.url),R&&this.clonePathways(R);const M={steeringManifest:k,url:i.toString()};this.hls.trigger(Ce.STEERING_MANIFEST_LOADED,M),D&&this.updatePathwayPriority(D)},onError:(y,v,T,E)=>{if(this.log(`Error loading steering manifest: ${y.code} ${y.text} (${v.url})`),this.stopLoad(),y.code===410){this.enabled=!1,this.log(`Steering manifest ${v.url} no longer available`);return}let k=this.timeToLoad*1e3;if(y.code===429){const P=this.loader;if(typeof(P==null?void 0:P.getResponseHeader)=="function"){const R=P.getResponseHeader("Retry-After");R&&(k=parseFloat(R)*1e3)}this.log(`Steering manifest ${v.url} rate limited`);return}this.scheduleRefresh(this.uri||v.url,k)},onTimeout:(y,v,T)=>{this.log(`Timeout loading steering manifest (${v.url})`),this.scheduleRefresh(this.uri||v.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(o,f,p)}scheduleRefresh(e,r=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var n;const i=(n=this.hls)==null?void 0:n.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},r)}}function due(t,e,r,n){t&&Object.keys(e).forEach(i=>{const o=t.filter(c=>c.groupId===i).map(c=>{const a=Js({},c);return a.details=void 0,a.attrs=new Qa(a.attrs),a.url=a.attrs.URI=kAe(c.url,c.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),a.groupId=a.attrs["GROUP-ID"]=e[i],a.attrs["PATHWAY-ID"]=n,a});t.push(...o)})}function kAe(t,e,r,n){const{HOST:i,PARAMS:o,[r]:c}=n;let a;e&&(a=c==null?void 0:c[e],a&&(t=a));const f=new self.URL(t);return i&&!a&&(f.host=i),o&&Object.keys(o).sort().forEach(p=>{p&&f.searchParams.set(p,o[p])}),f.href}class I1 extends _h{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=I1.CDMCleanupPromise?[I1.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=r=>{const{initDataType:n,initData:i}=r,o=`"${r.type}" event: init data type: "${n}"`;if(this.debug(o),i!==null){if(!this.keyFormatPromise){let c=Object.keys(this.keySystemAccessPromises);c.length||(c=W2(this.config));const a=c.map(m6).filter(f=>!!f);this.keyFormatPromise=this.getKeyFormatPromise(a)}this.keyFormatPromise.then(c=>{const a=ZL(c);if(n!=="sinf"||a!==to.FAIRPLAY){this.log(`Ignoring "${r.type}" event with init data type: "${n}" for selected key-system ${a}`);return}let f;try{const E=cl(new Uint8Array(i)),k=FK(JSON.parse(E).sinf),P=w2e(k);if(!P)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");f=new Uint8Array(P.subarray(8,24))}catch(E){this.warn(`${o} Failed to parse sinf: ${E}`);return}const p=Xl(f),{keyIdToKeySessionPromise:y,mediaKeySessions:v}=this;let T=y[p];for(let E=0;Ethis.generateRequestWithPreferredKeySession(k,n,i,"encrypted-event-key-match")),T.catch(D=>this.handleError(D));break}}T||this.handleError(new Error(`Key ID ${p} not encountered in playlist. Key-system sessions ${v.length}.`))}).catch(c=>this.handleError(c))}},this.onWaitingForKey=r=>{this.log(`"${r.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Ce.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Ce.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Ce.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(Ce.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Ce.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Ce.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Ce.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(Ce.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:r,widevineLicenseUrl:n}=this.config,i=r==null?void 0:r[e];if(i)return i.licenseUrl;if(e===to.WIDEVINE&&n)return n}getLicenseServerUrlOrThrow(e){const r=this.getLicenseServerUrl(e);if(r===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return r}getServerCertificateUrl(e){const{drmSystems:r}=this.config,n=r==null?void 0:r[e];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const r=this.hls.levels,n=(c,a,f)=>!!c&&f.indexOf(c)===a,i=r.map(c=>c.audioCodec).filter(n),o=r.map(c=>c.videoCodec).filter(n);return i.length+o.length===0&&o.push("avc1.42e01e"),new Promise((c,a)=>{const f=p=>{const y=p.shift();this.getMediaKeysPromise(y,i,o).then(v=>c({keySystem:y,mediaKeys:v})).catch(v=>{p.length?f(p):v instanceof Qu?a(v):a(new Qu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_NO_ACCESS,error:v,fatal:!0},v.message))})};f(e)})}requestMediaKeySystemAccess(e,r){const{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${n}`;return B2e===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return n(e,r)}getMediaKeysPromise(e,r,n){var i;const o=COt(e,r,n,this.config.drmSystemOptions||{});let c=this.keySystemAccessPromises[e],a=(i=c)==null?void 0:i.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${aa(o)}`),a=this.requestMediaKeySystemAccess(e,o);const f=c=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(p=>{this.log(`Failed to obtain access to key-system "${e}": ${p}`)}),a.then(p=>{this.log(`Access for key-system "${p.keySystem}" obtained`);const y=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const v=f.mediaKeys=p.createMediaKeys().then(T=>(this.log(`Media-keys created for "${e}"`),f.hasMediaKeys=!0,y.then(E=>E?this.setMediaKeysServerCertificate(T,e,E):T)));return v.catch(T=>{this.error(`Failed to create media-keys for "${e}"}: ${T}`)}),v})}return a.then(()=>c.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:r,mediaKeys:n}){this.log(`Creating key-system session "${r}" keyId: ${Xl(e.keyId||[])} keyUri: ${e.uri}`);const i=n.createSession(),o={decryptdata:e,keySystem:r,mediaKeys:n,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(o),o}renewKeySession(e){const r=e.decryptdata;if(r.pssh){const n=this.createMediaKeySessionContext(e),i=eL(r),o="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(n,o,r.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,r){const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyId ${Xl(e.decryptdata.keyId||[])} } (data length: ${r.byteLength})`),n.update(r)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>m6(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:r,mediaKeys:n})=>this.attemptSetMediaKeys(r,n))}selectKeySystem(e){return new Promise((r,n)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{const o=m6(i);o?r(o):n(new Error(`Unable to find format for key-system "${i}"`))}).catch(n)})}selectKeySystemFormat(e){const r=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)),this.keyFormatPromise}getKeyFormatPromise(e){const r=W2(this.config),n=e.map(ZL).filter(i=>!!i&&r.indexOf(i)!==-1);return this.selectKeySystem(n)}getKeyStatus(e){const{mediaKeySessions:r}=this;for(let n=0;n(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${o}`),this.attemptSetMediaKeys(f,p).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:f,mediaKeys:p,decryptdata:r}))))).then(f=>{const p="cenc",y=r.pssh?r.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(f,p,y,"playlist-key")});return a.catch(f=>this.handleError(f,e.frag)),this.keyIdToKeySessionPromise[n]=a,a}return c.catch(a=>{if(a instanceof Qu){const f=Us({},a.data);this.getKeyStatus(r)==="internal-error"&&(f.decryptdata=r);const p=new Qu(f,a.message);this.handleError(p,e.frag)}}),c}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,r){if(this.hls)if(e instanceof Qu){r&&(e.data.frag=r);const n=e.data.decryptdata;this.error(`${e.message}${n?` (${Xl(n.keyId||[])})`:""}`),this.hls.trigger(Ce.ERROR,e.data)}else this.error(e.message),this.hls.trigger(Ce.ERROR,{type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const r=eL(e),n=this.keyIdToKeySessionPromise[r];if(!n){const i=ZL(e.keyFormat),o=i?[i]:W2(this.config);return this.attemptKeySystemAccess(o)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=W2(this.config)),e.length===0)throw new Qu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${aa({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,r){if(this.mediaResolved=void 0,this.mediaKeys===r)return Promise.resolve();const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(n).then(()=>this.media?this.media.setMediaKeys(r):new Promise((o,c)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return c(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=r,this.media.setMediaKeys(r).then(o).catch(c)}}));return this.mediaKeys=r,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),n.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(o=>n.indexOf(o)===-1)})}generateRequestWithPreferredKeySession(e,r,n,i){var o;const c=(o=this.config.drmSystems)==null||(o=o[e.keySystem])==null?void 0:o.generateRequest;if(c)try{const k=c.call(this.hls,r,n,e);if(!k)throw new Error("Invalid response from configured generateRequest filter");r=k.initDataType,n=k.initData?k.initData:null,e.decryptdata.pssh=n?new Uint8Array(n):null}catch(k){if(this.warn(k.message),this.hls&&this.hls.config.debug)throw k}if(n===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const a=eL(e.decryptdata),f=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${a} URI: ${f} (init data type: ${r} length: ${n.byteLength})`);const p=new $K,y=e._onmessage=k=>{const P=e.mediaKeysSession;if(!P){p.emit("error",new Error("invalid state"));return}const{messageType:R,message:D}=k;this.log(`"${R}" message event for session "${P.sessionId}" message size: ${D.byteLength}`),R==="license-request"||R==="license-renewal"?this.renewLicense(e,D).catch(M=>{p.eventNames().length?p.emit("error",M):this.handleError(M)}):R==="license-release"?e.keySystem===to.FAIRPLAY&&this.updateKeySession(e,cG("acknowledged")).then(()=>this.removeSession(e)).catch(M=>this.handleError(M)):this.warn(`unhandled media key message type "${R}"`)},v=(k,P)=>{P.keyStatus=k;let R;k.startsWith("usable")?p.emit("resolved"):k==="internal-error"||k==="output-restricted"||k==="output-downscaled"?R=hue(k,P.decryptdata):k==="expired"?R=new Error(`key expired (keyId: ${a})`):k==="released"?R=new Error("key released"):k==="status-pending"||this.warn(`unhandled key status change "${k}" (keyId: ${a})`),R&&(p.eventNames().length?p.emit("error",R):this.handleError(R))},T=e._onkeystatuseschange=k=>{if(!e.mediaKeysSession){p.emit("error",new Error("invalid state"));return}const R=this.getKeyStatuses(e);if(!Object.keys(R).some(V=>R[V]!=="status-pending"))return;if(R[a]==="expired"){this.log(`Expired key ${aa(R)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let M=R[a];if(M)v(M,e);else{var B;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(B=e.keyStatusTimeouts)[a]||(B[a]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const G=this.getKeyStatus(e.decryptdata);if(G&&G!=="status-pending")return this.log(`No status for keyId ${a} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${G} from other session.`),v(G,e);this.log(`key status for ${a} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),M="internal-error",v(M,e)},1e3)),this.log(`No status for keyId ${a} (${aa(R)}).`)}};ru(e.mediaKeysSession,"message",y),ru(e.mediaKeysSession,"keystatuseschange",T);const E=new Promise((k,P)=>{p.on("error",P),p.on("resolved",k)});return e.mediaKeysSession.generateRequest(r,n).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${a} URI: ${f}`)}).catch(k=>{throw new Qu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_NO_SESSION,error:k,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${k}`)}).then(()=>E).catch(k=>(p.removeAllListeners(),this.removeSession(e).then(()=>{throw k}))).then(()=>(p.removeAllListeners(),e))}getKeyStatuses(e){const r={};return e.mediaKeysSession.keyStatuses.forEach((n,i)=>{if(typeof i=="string"&&typeof n=="object"){const a=i;i=n,n=a}const o="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===to.PLAYREADY&&o.length===16){const a=Xl(o);r[a]=n,O2e(o)}const c=Xl(o);n==="internal-error"&&(this.bannedKeyIds[c]=n),this.log(`key status change "${n}" for keyStatuses keyId: ${c} key-session "${e.mediaKeysSession.sessionId}"`),r[c]=n}),r}fetchServerCertificate(e){const r=this.config,n=r.loader,i=new n(r),o=this.getServerCertificateUrl(e);return o?(this.log(`Fetching server certificate for "${e}"`),new Promise((c,a)=>{const f={responseType:"arraybuffer",url:o},p=r.certLoadPolicy.default,y={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},v={onSuccess:(T,E,k,P)=>{c(T.data)},onError:(T,E,k,P)=>{a(new Qu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:k,response:Us({url:f.url,data:void 0},T)},`"${e}" certificate request failed (${o}). Status: ${T.code} (${T.text})`))},onTimeout:(T,E,k)=>{a(new Qu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:k,response:{url:f.url,data:void 0}},`"${e}" certificate request timed out (${o})`))},onAbort:(T,E,k)=>{a(new Error("aborted"))}};i.load(f,y,v)})):Promise.resolve()}setMediaKeysServerCertificate(e,r,n){return new Promise((i,o)=>{e.setServerCertificate(n).then(c=>{this.log(`setServerCertificate ${c?"success":"not supported by CDM"} (${n.byteLength}) on "${r}"`),i(e)}).catch(c=>{o(new Qu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:c,fatal:!0},c.message))})})}renewLicense(e,r){return this.requestLicense(e,new Uint8Array(r)).then(n=>this.updateKeySession(e,new Uint8Array(n)).catch(i=>{throw new Qu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,r){const n=String.fromCharCode.apply(null,new Uint16Array(r.buffer));if(!n.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),r;const i=new DOMParser().parseFromString(n,"application/xml"),o=i.querySelectorAll("HttpHeader");if(o.length>0){let y;for(let v=0,T=o.length;v in key message");return cG(atob(p))}setupLicenseXHR(e,r,n,i){const o=this.config.licenseXhrSetup;return o?Promise.resolve().then(()=>{if(!n.decryptdata)throw new Error("Key removed");return o.call(this.hls,e,r,n,i)}).catch(c=>{if(!n.decryptdata)throw c;return e.open("POST",r,!0),o.call(this.hls,e,r,n,i)}).then(c=>(e.readyState||e.open("POST",r,!0),{xhr:e,licenseChallenge:c||i})):(e.open("POST",r,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,r){const n=this.config.keyLoadPolicy.default;return new Promise((i,o)=>{const c=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${c}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return o(new Error("invalid state"));if(a.readyState===4)if(a.status===200){this._requestLicenseFailureCount=0;let f=a.response;this.log(`License received ${f instanceof ArrayBuffer?f.byteLength:f}`);const p=this.config.licenseResponseCallback;if(p)try{f=p.call(this.hls,a,c,e)}catch(y){this.error(y)}i(f)}else{const f=n.errorRetry,p=f?f.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>p||a.status>=400&&a.status<500)o(new Qu({type:Dn.KEY_SYSTEM_ERROR,details:Jt.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:a,response:{url:c,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${c}). Status: ${a.status} (${a.statusText})`));else{const y=p-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${y} attempts left`),this.requestLicense(e,r).then(i,o)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,c,e,r).then(({xhr:f,licenseChallenge:p})=>{e.keySystem==to.PLAYREADY&&(p=this.unpackPlayReadyKeyMessage(f,p)),f.send(p)}).catch(o)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,r){if(!this.config.emeEnabled)return;const n=r.media;this.media=n,ru(n,"encrypted",this.onMediaEncrypted),ru(n,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=n.mediaKeys}onMediaDetached(){const e=this.media;e&&(Ru(e,"encrypted",this.onMediaEncrypted),Ru(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const r=this.mediaResolved;if(r&&r(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const n=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,ox.clearKeyUriToKeyIdMap();const o=i.length;I1.CDMCleanupPromise=Promise.all(i.map(c=>this.removeSession(c)).concat((n==null||(e=n.setMediaKeys(null))==null?void 0:e.catch(c=>{this.log(`Could not clear media keys: ${c}`),this.hls&&this.hls.trigger(Ce.ERROR,{type:Dn.OTHER_ERROR,details:Jt.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${c}`)})}))||Promise.resolve())).catch(c=>{this.log(`Could not close sessions and clear media keys: ${c}`),this.hls&&this.hls.trigger(Ce.ERROR,{type:Dn.OTHER_ERROR,details:Jt.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${c}`)})}).then(()=>{o&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:r}){if(!(!r||!this.config.emeEnabled)&&!this.keyFormatPromise){const n=r.reduce((i,o)=>(i.indexOf(o.keyFormat)===-1&&i.push(o.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)}}removeSession(e){const{mediaKeysSession:r,licenseXhr:n,decryptdata:i}=e;if(r){this.log(`Remove licenses and keys and close session "${r.sessionId}" keyId: ${Xl((i==null?void 0:i.keyId)||[])}`),e._onmessage&&(r.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const o=this.mediaKeySessions.indexOf(e);o>-1&&this.mediaKeySessions.splice(o,1);const{keyStatusTimeouts:c}=e;c&&Object.keys(c).forEach(p=>self.clearTimeout(c[p]));const{drmSystemOptions:a}=this.config;return(IOt(a)?new Promise((p,y)=>{self.setTimeout(()=>y(new Error("MediaKeySession.remove() timeout")),8e3),r.remove().then(p).catch(y)}):Promise.resolve()).catch(p=>{this.log(`Could not remove session: ${p}`),this.hls&&this.hls.trigger(Ce.ERROR,{type:Dn.OTHER_ERROR,details:Jt.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${p}`)})}).then(()=>r.close()).catch(p=>{this.log(`Could not close session: ${p}`),this.hls&&this.hls.trigger(Ce.ERROR,{type:Dn.OTHER_ERROR,details:Jt.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${p}`)})})}return Promise.resolve()}}I1.CDMCleanupPromise=void 0;function eL(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(t.keyId===null)throw new Error("keyId is null");return Xl(t.keyId)}function ZFt(t,e){if(t.keyId&&e.mediaKeysSession.keyStatuses.has(t.keyId))return e.mediaKeysSession.keyStatuses.get(t.keyId);if(t.matches(e.decryptdata))return e.keyStatus}class Qu extends Error{constructor(e,r){super(r),this.data=void 0,e.error||(e.error=new Error(r)),this.data=e,e.err=e.error}}function hue(t,e){const r=t==="output-restricted",n=r?Jt.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Jt.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Qu({type:Dn.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:e},r?"HDCP level output restricted":`key status changed to "${t}"`)}class XFt{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(Ce.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Ce.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Ce.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Ce.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,r){const n=this.hls.config;if(n.capLevelOnFPSDrop){const i=r.media instanceof self.HTMLVideoElement?r.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,r,n){const i=performance.now();if(r){if(this.lastTime){const o=i-this.lastTime,c=n-this.lastDroppedFrames,a=r-this.lastDecodedFrames,f=1e3*c/o,p=this.hls;if(p.trigger(Ce.FPS_DROP,{currentDropped:c,currentDecoded:a,totalDroppedFrames:n}),f>0&&c>p.config.fpsDroppedMonitoringThreshold*a){let y=p.currentLevel;p.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+y),y>0&&(p.autoLevelCapping===-1||p.autoLevelCapping>=y)&&(y=y-1,p.trigger(Ce.FPS_DROP_LEVEL_CAPPING,{level:y,droppedLevel:p.currentLevel}),p.autoLevelCapping=y,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=n,this.lastDecodedFrames=r}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const r=e.getVideoPlaybackQuality();this.checkFPS(e,r.totalVideoFrames,r.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function CAe(t,e){let r;try{r=new Event("addtrack")}catch{r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function NAe(t,e){const r=t.mode;if(r==="disabled"&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(n){qs.debug(`[texttrack-utils]: ${n}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(i){qs.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}r==="disabled"&&(t.mode=r)}function a1(t,e){const r=t.mode;if(r==="disabled"&&(t.mode="hidden"),t.cues)for(let n=t.cues.length;n--;)e&&t.cues[n].removeEventListener("enter",e),t.removeCue(t.cues[n]);r==="disabled"&&(t.mode=r)}function xG(t,e,r,n){const i=t.mode;if(i==="disabled"&&(t.mode="hidden"),t.cues&&t.cues.length>0){const o=JFt(t.cues,e,r);for(let c=0;ct[r].endTime)return-1;let n=0,i=r,o;for(;n<=i;)if(o=Math.floor((i+n)/2),et[o].startTime&&n-1)for(let o=i,c=t.length;o=e&&a.endTime<=r)n.push(a);else if(a.startTime>r)return n}return n}function eD(t){const e=[];for(let r=0;rthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let r=null;const n=eD(this.media.textTracks);for(let o=0;o-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ce.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Ce.LEVEL_LOADING,this.onLevelLoading,this),e.on(Ce.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Ce.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Ce.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ce.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Ce.LEVEL_LOADING,this.onLevelLoading,this),e.off(Ce.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Ce.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Ce.ERROR,this.onError,this)}onMediaAttached(e,r){this.media=r.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,r){const n=this.media;if(!n)return;const i=!!r.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||n.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;eD(n.textTracks).forEach(c=>{a1(c)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,r){this.tracks=r.subtitleTracks}onSubtitleTrackLoaded(e,r){const{id:n,groupId:i,details:o}=r,c=this.tracksInGroup[n];if(!c||c.groupId!==i){this.warn(`Subtitle track with id:${n} and group:${i} not found in active group ${c==null?void 0:c.groupId}`);return}const a=c.details;c.details=r.details,this.log(`Subtitle track ${n} "${c.name}" lang:${c.lang} group:${i} loaded [${o.startSN}-${o.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,a)}onLevelLoading(e,r){this.switchLevel(r.level)}onLevelSwitching(e,r){this.switchLevel(r.level)}switchLevel(e){const r=this.hls.levels[e];if(!r)return;const n=r.subtitleGroups||null,i=this.groupIds;let o=this.currentTrack;if(!n||(i==null?void 0:i.length)!==(n==null?void 0:n.length)||n!=null&&n.some(c=>(i==null?void 0:i.indexOf(c))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const c=this.tracks.filter(y=>!n||n.indexOf(y.groupId)!==-1);if(c.length)this.selectDefaultTrack&&!c.some(y=>y.default)&&(this.selectDefaultTrack=!1),c.forEach((y,v)=>{y.id=v});else if(!o&&!this.tracksInGroup.length)return;this.tracksInGroup=c;const a=this.hls.config.subtitlePreference;if(!o&&a){this.selectDefaultTrack=!1;const y=dm(a,c);if(y>-1)o=c[y];else{const v=dm(a,this.tracks);o=this.tracks[v]}}let f=this.findTrackId(o);f===-1&&o&&(f=this.findTrackId(null));const p={subtitleTracks:c};this.log(`Updating subtitle tracks, ${c.length} track(s) found in "${n==null?void 0:n.join(",")}" group-id`),this.hls.trigger(Ce.SUBTITLE_TRACKS_UPDATED,p),f!==-1&&this.trackId===-1&&this.setSubtitleTrack(f)}}findTrackId(e){const r=this.tracksInGroup,n=this.selectDefaultTrack;for(let i=0;i-1){const o=this.tracksInGroup[i];return this.setSubtitleTrack(i),o}else{if(n)return null;{const o=dm(e,r);if(o>-1)return r[o]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,r){super.loadingPlaylist(e,r);const n=e.id,i=e.groupId,o=this.getUrlWithDirectives(e.url,r),c=e.details,a=c==null?void 0:c.age;this.log(`Loading subtitle ${n} "${e.name}" lang:${e.lang} group:${i}${(r==null?void 0:r.msn)!==void 0?" at sn "+r.msn+" part "+r.part:""}${a&&c.live?" age "+a.toFixed(1)+(c.type&&" "+c.type||""):""} ${o}`),this.hls.trigger(Ce.SUBTITLE_TRACK_LOADING,{url:o,id:n,groupId:i,deliveryDirectives:r||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const r=eD(e.textTracks),n=this.currentTrack;let i;if(n&&(i=r.filter(o=>mG(n,o))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${n.name}" and language "${n.lang}"`)),[].slice.call(r).forEach(o=>{o.mode!=="disabled"&&o!==i&&(o.mode="disabled")}),i){const o=this.subtitleDisplay?"showing":"hidden";i.mode!==o&&(i.mode=o)}}setSubtitleTrack(e){const r=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=r.length||!pn(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const n=this.currentTrack,i=r[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(Ce.SUBTITLE_TRACK_SWITCH,{id:e});return}const o=!!i.details&&!i.details.live;if(e===this.trackId&&i===n&&o)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:c,groupId:a="",name:f,type:p,url:y}=i;this.hls.trigger(Ce.SUBTITLE_TRACK_SWITCH,{id:c,groupId:a,name:f,type:p,url:y});const v=this.switchParams(i.url,n==null?void 0:n.details,i.details);this.loadPlaylist(v)}}function t5t(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),r=e.toString();return URL.revokeObjectURL(e),r.slice(r.lastIndexOf("/")+1)}catch{let r=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const o=(r+Math.random()*16)%16|0;return r=Math.floor(r/16),(i=="x"?o:o&3|8).toString(16)})}}}function AA(t){let e=5381,r=t.length;for(;r;)e=e*33^t.charCodeAt(--r);return(e>>>0).toString()}const P1=.025;let CO=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function r5t(t,e,r){return`${t.identifier}-${r+1}-${AA(e)}`}class n5t{constructor(e,r){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=r,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var r;if(e>0&&e>=this.assetList.length)return!0;const n=this.playoutLimit;return e<=0||isNaN(n)?!1:n===0?!0:(((r=this.assetList[e])==null?void 0:r.startOffset)||0)>n}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const r=this.dateRange.tagAnchor;if(r)return S6(e,r)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const r=this.dateRange.startTime,n=S6(r,e);return r-n<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,r=pn(e)?e:this.duration;return this.cumulativeDuration+r}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const r=this.resumeAnchor;if(r)return S6(e,r)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||this.assetListResponse!==null}toString(){return i5t(this)}}function S6(t,e){return t-e.start":t.cue.post?"":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`}function Mw(t){const e=t.timelineStart,r=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+r).toFixed(2)}]`}class s5t{constructor(e,r,n,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(Ce.PLAYOUT_LIMIT_REACHED,{})};const o=this.hls=new e(r);this.interstitial=n,this.assetItem=i;const c=()=>{this.hasDetails=!0};o.once(Ce.LEVEL_LOADED,c),o.once(Ce.AUDIO_TRACK_LOADED,c),o.once(Ce.SUBTITLE_TRACK_LOADED,c),o.on(Ce.MEDIA_ATTACHING,(a,{media:f})=>{this.removeMediaListeners(),this.mediaAttached=f,this.interstitial.playoutLimit&&(f.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&o.on(Ce.BUFFER_APPENDED,()=>{const y=this.bufferedEnd;this.reachedPlayout(y)&&(this._bufferedEosTime=y,o.trigger(Ce.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let r=this.assetItem.uri;try{r=IAe(r,e.config.primarySessionId||"").href}catch{}e.loadSource(r)}}bufferedInPlaceToEnd(e){var r;if(!this.appendInPlace)return!1;if((r=this.hls)!=null&&r.bufferedToEnd)return!0;if(!e)return!1;const n=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,o=Ti.bufferInfo(e,i,0);return this.getAssetTime(o.end)>=n-.02}reachedPlayout(e){const n=this.interstitial.playoutLimit;return this.startOffset+e>=n}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const r=Ti.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(r.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const r=this.interstitial.playoutLimit;if(r){const n=r-this.startOffset;if(n>0&&n1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const r=this.timelineOffset,n=this.duration;return Math.min(Math.max(0,e-r),n)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var r;this.loadSource(),(r=this.hls)==null||r.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const r=n=>delete n.details;e.levels.forEach(r),e.allAudioTracks.forEach(r),e.allSubtitleTracks.forEach(r),this.hasDetails=!1}}on(e,r,n){var i;(i=this.hls)==null||i.on(e,r)}once(e,r,n){var i;(i=this.hls)==null||i.once(e,r)}off(e,r,n){var i;(i=this.hls)==null||i.off(e,r)}toString(){var e;return`HlsAssetPlayer: ${Mw(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const fue=.033;class a5t extends _h{constructor(e,r){super("interstitials-sched",r),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,r){return this.events?this.events.reduce((n,i)=>e<=i.startOffset&&r>i.startOffset?(delete i.error,n+1):n,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,r){if(e.event)return this.findEventIndex(e.event.identifier);let n=-1;e.nextEvent?n=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(n=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[n]||(r===void 0&&(r=e.start),n=this.findItemIndexAtTime(r));n>=0&&(o=i[n])!=null&&o.event;){var o;n--}return n}findItemIndexAtTime(e,r){const n=this.items;if(n)for(let i=0;io.start&&e1)for(let o=0;oa&&(r!a.includes(p.identifier)):[];c.length&&c.sort((p,y)=>{const v=p.cue.pre,T=p.cue.post,E=y.cue.pre,k=y.cue.post;if(v&&!E)return-1;if(E&&!v||T&&!k)return 1;if(k&&!T)return-1;if(!v&&!E&&!T&&!k){const P=p.startTime,R=y.startTime;if(P!==R)return P-R}return p.dateRange.tagOrder-y.dateRange.tagOrder}),this.events=c,f.forEach(p=>{this.removeEvent(p)}),this.updateSchedule(e,f)}updateSchedule(e,r=[],n=!1){const i=this.events||[];if(i.length||r.length||this.length<2){const o=this.items,c=this.parseSchedule(i,e);(n||r.length||(o==null?void 0:o.length)!==c.length||c.some((f,p)=>Math.abs(f.playout.start-o[p].playout.start)>.005||Math.abs(f.playout.end-o[p].playout.end)>.005))&&(this.items=c,this.onScheduleUpdate(r,o))}}parseDateRanges(e,r,n){const i=[],o=Object.keys(e);for(let c=0;c!f.error&&!(f.cue.once&&f.hasPlayed)),e.length){this.resolveOffsets(e,r);let f=0,p=0;if(e.forEach((y,v)=>{const T=y.cue.pre,E=y.cue.post,k=e[v-1]||null,P=y.appendInPlace,R=E?o:y.startOffset,D=y.duration,M=y.timelineOccupancy===CO.Range?D:0,B=y.resumptionOffset,V=(k==null?void 0:k.startTime)===R,G=R+y.cumulativeDuration;let W=P?G+D:R+B;if(T||!E&&R<=0){const J=p;p+=M,y.timelineStart=G;const Q=c;c+=D,n.push({event:y,start:G,end:W,playout:{start:Q,end:c},integrated:{start:J,end:p}})}else if(R<=o){if(!V){const ee=R-f;if(ee>fue){const le=f,pe=p;p+=ee;const Se=c;c+=ee;const je={previousEvent:e[v-1]||null,nextEvent:y,start:le,end:le+ee,playout:{start:Se,end:c},integrated:{start:pe,end:p}};n.push(je)}else ee>0&&k&&(k.cumulativeDuration+=ee,n[n.length-1].end=R)}E&&(W=G),y.timelineStart=G;const J=p;p+=M;const Q=c;c+=D,n.push({event:y,start:G,end:W,playout:{start:Q,end:c},integrated:{start:J,end:p}})}else return;const Y=y.resumeTime;E||Y>o?f=o:f=Y}),f{const p=a.cue.pre,y=a.cue.post,v=p?0:y?i:a.startTime;this.updateAssetDurations(a),c===v?a.cumulativeDuration=o:(o=0,c=v),!y&&a.snapOptions.in&&(a.resumeAnchor=g_(null,n.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,r)||(a.appendInPlace=!1)),!a.appendInPlace&&f+1P1?(this.log(`"${e.identifier}" resumption ${n} not aligned with estimated timeline end ${i}`),!1):!Object.keys(r).some(c=>{const a=r[c].details,f=a.edge;if(n>=f)return this.log(`"${e.identifier}" resumption ${n} past ${c} playlist end ${f}`),!1;const p=g_(null,a.fragments,n);if(!p)return this.log(`"${e.identifier}" resumption ${n} does not align with any fragments in ${c} playlist (${a.fragStart}-${a.fragmentEnd})`),!0;const y=c==="audio"?.175:0;return Math.abs(p.start-n){const R=T.data,D=R==null?void 0:R.ASSETS;if(!Array.isArray(D)){const M=this.assignAssetListError(e,Jt.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),k.url,E,P);this.hls.trigger(Ce.ERROR,M);return}e.assetListResponse=R,this.hls.trigger(Ce.ASSET_LIST_LOADED,{event:e,assetListResponse:R,networkDetails:P})},onError:(T,E,k,P)=>{const R=this.assignAssetListError(e,Jt.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${T.code} ${T.text} (${E.url})`),E.url,P,k);this.hls.trigger(Ce.ERROR,R)},onTimeout:(T,E,k)=>{const P=this.assignAssetListError(e,Jt.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${E.url})`),E.url,T,k);this.hls.trigger(Ce.ERROR,P)}};return a.load(f,y,v),this.hls.trigger(Ce.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,r,n,i,o,c){return e.error=n,{type:Dn.NETWORK_ERROR,details:r,fatal:!1,interstitial:e,url:i,error:n,networkDetails:c,stats:o}}}function mue(t){var e;t==null||(e=t.play())==null||e.catch(()=>{})}function Nw(t,e){return`[${t}] Advancing timeline position to ${e}`}class l5t extends _h{constructor(e,r){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const n=this.currentTime;if(n===void 0||this.playbackDisabled||!this.schedule)return;const i=n-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const c=i<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=n,this.bufferedPos=n;const a=this.playingItem;if(!a){this.checkBuffer();return}if(c&&this.schedule.resetErrorsInRange(n,n-i)&&this.updateSchedule(!0),this.checkBuffer(),c&&n=a.end){var f;const E=this.findItemIndex(a);let k=this.schedule.findItemIndexAtTime(n);if(k===-1&&(k=E+(c?-1:1),this.log(`seeked ${c?"back ":""}to position not covered by schedule ${n} (resolving from ${E} to ${k})`)),!this.isInterstitial(a)&&(f=this.media)!=null&&f.paused&&(this.shouldPlay=!1),!c&&k>E){const P=this.schedule.findJumpRestrictedIndex(E+1,k);if(P>E){this.setSchedulePosition(P);return}}this.setSchedulePosition(k);return}const p=this.playingAsset;if(!p){if(this.playingLastItem&&this.isInterstitial(a)){const E=a.event.assetList[0];E&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(n,E))}return}const y=p.timelineStart,v=p.duration||0;if(c&&n=y+v){var T;(T=a.event)!=null&&T.appendInPlace&&(this.clearAssetPlayers(a.event,a),this.flushFrontBuffer(n)),this.setScheduleToAssetAtTime(n,p)}},this.onTimeupdate=()=>{const n=this.currentTime;if(n===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),n>this.timelinePos)this.timelinePos=n,n>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(n>=i.end){this.timelinePos=i.end;const a=this.findItemIndex(i);this.setSchedulePosition(a+1)}const o=this.playingAsset;if(!o)return;const c=o.timelineStart+(o.duration||0);n>=c&&this.setScheduleToAssetAtTime(n,o)},this.onScheduleUpdate=(n,i)=>{const o=this.schedule;if(!o)return;const c=this.playingItem,a=o.events||[],f=o.items||[],p=o.durations,y=n.map(P=>P.identifier),v=!!(a.length||y.length);(v||i)&&this.log(`INTERSTITIALS_UPDATED (${a.length}): ${a} Schedule: ${f.map(P=>Vh(P))} pos: ${this.timelinePos}`),y.length&&this.log(`Removed events ${y}`);let T=null,E=null;c&&(T=this.updateItem(c,this.timelinePos),this.itemsMatch(c,T)?this.playingItem=T:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const k=this.bufferingItem;if(k&&(E=this.updateItem(k,this.bufferedPos),this.itemsMatch(k,E)?this.bufferingItem=E:k.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(k.event,null))),n.forEach(P=>{P.assetList.forEach(R=>{this.clearAssetPlayer(R.identifier,null)})}),this.playerQueue.forEach(P=>{if(P.interstitial.appendInPlace){const R=P.assetItem.timelineStart,D=P.timelineOffset-R;if(D)try{P.timelineOffset=R}catch(M){Math.abs(D)>P1&&this.warn(`${M} ("${P.assetId}" ${P.timelineOffset}->${R})`)}}}),v||i){if(this.hls.trigger(Ce.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:f.slice(0),durations:p,removedIds:y}),this.isInterstitial(c)&&y.includes(c.event.identifier)){this.warn(`Interstitial "${c.event.identifier}" removed while playing`),this.primaryFallback(c.event);return}c&&this.trimInPlace(T,c),k&&E!==T&&this.trimInPlace(E,k),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=r,this.assetListLoader=new o5t(e),this.schedule=new a5t(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(Ce.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ce.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Ce.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Ce.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(Ce.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Ce.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(Ce.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(Ce.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(Ce.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Ce.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Ce.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(Ce.MEDIA_ENDED,this.onMediaEnded,this),e.on(Ce.ERROR,this.onError,this),e.on(Ce.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(Ce.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ce.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Ce.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Ce.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(Ce.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Ce.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(Ce.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(Ce.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(Ce.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Ce.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Ce.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Ce.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(Ce.MEDIA_ENDED,this.onMediaEnded,this),e.off(Ce.ERROR,this.onError,this),e.off(Ce.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Ru(e,"play",this.onPlay),Ru(e,"pause",this.onPause),Ru(e,"seeking",this.onSeeking),Ru(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,r){const n=this.media=r.media;ru(n,"seeking",this.onSeeking),ru(n,"timeupdate",this.onTimeupdate),ru(n,"play",this.onPlay),ru(n,"pause",this.onPause)}onMediaAttached(e,r){const n=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,n===null)this.checkStart();else if(!i){this.clearScheduleState();const o=this.findItemIndex(n);this.setSchedulePosition(o)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,r){const n=!!r.transferMedia,i=this.media;if(this.media=null,!n&&(i&&this.removeMediaListeners(i),this.detachedData)){const o=this.getBufferingPlayer();o&&(this.log(`Removing schedule state for detachedData and ${o}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,o.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,r=()=>e.bufferingItem||e.waitingItem,n=v=>v&&e.getAssetPlayer(v.identifier),i=(v,T,E,k,P)=>{if(v){let R=v[T].start;const D=v.event;if(D){if(T==="playout"||D.timelineOccupancy!==CO.Point){const M=n(E);(M==null?void 0:M.interstitial)===D&&(R+=M.assetItem.startOffset+M[P])}}else{const M=k==="bufferedPos"?c():e[k];R+=M-v.start}return R}return 0},o=(v,T)=>{var E;if(v!==0&&T!=="primary"&&(E=e.schedule)!=null&&E.length){var k;const P=e.schedule.findItemIndexAtTime(v),R=(k=e.schedule.items)==null?void 0:k[P];if(R){const D=R[T].start-R.start;return v+D}}return v},c=()=>{const v=e.bufferedPos;return v===Number.MAX_VALUE?a("primary"):Math.max(v,0)},a=v=>{var T,E;return(T=e.primaryDetails)!=null&&T.live?e.primaryDetails.edge:((E=e.schedule)==null?void 0:E.durations[v])||0},f=(v,T)=>{var E,k;const P=e.effectivePlayingItem;if(P!=null&&(E=P.event)!=null&&E.restrictions.skip||!e.schedule)return;e.log(`seek to ${v} "${T}"`);const R=e.effectivePlayingItem,D=e.schedule.findItemIndexAtTime(v,T),M=(k=e.schedule.items)==null?void 0:k[D],B=e.getBufferingPlayer(),V=B==null?void 0:B.interstitial,G=V==null?void 0:V.appendInPlace,W=R&&e.itemsMatch(R,M);if(R&&(G||W)){const Y=n(e.playingAsset),J=(Y==null?void 0:Y.media)||e.primaryMedia;if(J){const Q=T==="primary"?J.currentTime:i(R,T,e.playingAsset,"timelinePos","currentTime"),ee=v-Q,le=(G?Q:J.currentTime)+ee;if(le>=0&&(!Y||G||le<=Y.duration)){J.currentTime=le;return}}}if(M){let Y=v;if(T!=="primary"){const Q=M[T].start,ee=v-Q;Y=M.start+ee}const J=!e.isInterstitial(M);if((!e.isInterstitial(R)||R.event.appendInPlace)&&(J||M.event.appendInPlace)){const Q=e.media||(G?B==null?void 0:B.media:null);Q&&(Q.currentTime=Y)}else if(R){const Q=e.findItemIndex(R);if(D>Q){const le=e.schedule.findJumpRestrictedIndex(Q+1,D);if(le>Q){e.setSchedulePosition(le);return}}let ee=0;if(J)e.timelinePos=Y,e.checkBuffer();else{const le=M.event.assetList,pe=v-(M[T]||M).start;for(let Se=le.length;Se--;){const je=le[Se];if(je.duration&&pe>=je.startOffset&&pe{const v=e.effectivePlayingItem;if(e.isInterstitial(v))return v;const T=r();return e.isInterstitial(T)?T:null},y={get bufferedEnd(){const v=r(),T=e.bufferingItem;if(T&&T===v){var E;return i(T,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-T.playout.start||((E=e.bufferingAsset)==null?void 0:E.startOffset)||0}return 0},get currentTime(){const v=p(),T=e.effectivePlayingItem;return T&&T===v?i(T,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-T.playout.start:0},set currentTime(v){const T=p(),E=e.effectivePlayingItem;E&&E===T&&f(v+E.playout.start,"playout")},get duration(){const v=p();return v?v.playout.end-v.playout.start:0},get assetPlayers(){var v;const T=(v=p())==null?void 0:v.event.assetList;return T?T.map(E=>e.getAssetPlayer(E.identifier)):[]},get playingIndex(){var v;const T=(v=p())==null?void 0:v.event;return T&&e.effectivePlayingAsset?T.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return p()}};return this.manager={get events(){var v;return((v=e.schedule)==null||(v=v.events)==null?void 0:v.slice(0))||[]},get schedule(){var v;return((v=e.schedule)==null||(v=v.items)==null?void 0:v.slice(0))||[]},get interstitialPlayer(){return p()?y:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return r()},get bufferingIndex(){const v=r();return e.findItemIndex(v)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const v=e.effectivePlayingItem;return e.findItemIndex(v)},primary:{get bufferedEnd(){return c()},get currentTime(){const v=e.timelinePos;return v>0?v:0},set currentTime(v){f(v,"primary")},get duration(){return a("primary")},get seekableStart(){var v;return((v=e.primaryDetails)==null?void 0:v.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(r(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(v){f(v,"integrated")},get duration(){return a("integrated")},get seekableStart(){var v;return o(((v=e.primaryDetails)==null?void 0:v.fragmentStart)||0,"integrated")}},skip:()=>{const v=e.effectivePlayingItem,T=v==null?void 0:v.event;if(T&&!T.restrictions.skip){const E=e.findItemIndex(v);if(T.appendInPlace){const k=v.playout.start+v.event.duration;f(k+.001,"playout")}else e.advanceAfterAssetEnded(T,E,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const r=this.playingItem,n=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!r||!n?!1:this.findItemIndex(r)===n.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,r;if(this.mediaSelection===null)return;const n=this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&!n.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const o=(r=i)==null?void 0:r.currentTime;if(!(o===void 0||!pn(o)))return o}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,r){const n=this.getAssetPlayer(e);n&&this.transferMediaFromPlayer(n,r)}transferMediaFromPlayer(e,r){const n=e.interstitial.appendInPlace,i=e.media;if(n&&i===this.primaryMedia){if(this.bufferingAsset=null,(!r||this.isInterstitial(r)&&!r.event.appendInPlace)&&r&&i){this.detachedData={media:i};return}const o=e.transferMedia();this.log(`transfer MediaSource from ${e} ${aa(o)}`),this.detachedData=o}else r&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,r){var n,i;if(e.media===r)return;let o=null;const c=this.hls,a=e!==c,f=a&&e.interstitial.appendInPlace,p=(n=this.detachedData)==null?void 0:n.mediaSource;let y;if(c.media)f&&(o=c.transferMedia(),this.detachedData=o),y="Primary";else if(p){const k=this.getBufferingPlayer();k?(o=k.transferMedia(),y=`${k}`):y="detached MediaSource"}else y="detached media";if(!o){if(p)o=this.detachedData,this.log(`using detachedData: MediaSource ${aa(o)}`);else if(!this.detachedData||c.media===r){const k=this.playerQueue;k.length>1&&k.forEach(P=>{if(a&&P.interstitial.appendInPlace!==f){const R=P.interstitial;this.clearInterstitial(P.interstitial,null),R.appendInPlace=!1,R.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${R}`)}}),this.hls.detachMedia(),this.detachedData={media:r}}}const v=o&&"mediaSource"in o&&((i=o.mediaSource)==null?void 0:i.readyState)!=="closed",T=v&&o?o:r;this.log(`${v?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${y} (media.currentTime: ${r.currentTime})`);const E=this.schedule;if(T===o&&E){const k=a&&e.assetId===E.assetIdAtEnd;T.overrides={duration:E.duration,endOfStream:!a||k,cueRemoval:!a}}e.attachMedia(T)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,r=e==null?void 0:e.events;if(!r||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const n=this.timelinePos,i=this.effectivePlayingItem;if(n===-1){const o=this.hls.startPosition;if(this.timelinePos=o,r.length===0)this.setSchedulePosition(0);else if(r[0].cue.pre){this.log(Nw("checkStart (preroll)",o));const c=e.findEventIndex(r[0].identifier);this.setSchedulePosition(c)}else if(o>=0||!this.primaryLive){this.log(Nw("checkStart",o));const c=this.timelinePos=o>0?o:0,a=e.findItemIndexAtTime(c);this.setSchedulePosition(a)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(i&&!this.playingItem){this.log(Nw("checkStart (playing item)",i.start));const o=e.findItemIndex(i);this.setSchedulePosition(o)}}advanceAssetBuffering(e,r){const n=e.event,i=n.findAssetIndex(r),o=T6(n,i);if(!n.isAssetPastPlayoutLimit(o))this.bufferedToEvent(e,o);else if(this.schedule){var c;const a=(c=this.schedule.items)==null?void 0:c[this.findItemIndex(e)+1];a&&this.bufferedToItem(a)}}advanceAfterAssetEnded(e,r,n){const i=T6(e,n);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const o=this.schedule.items;if(o){const c=r+1,a=o.length;if(c>=a){this.setSchedulePosition(-1);return}const f=e.resumeTime;this.timelinePos=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${r} (${o&&Vh(o)}) pos: ${this.timelinePos}`);const c=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(c)){const y=c.event,v=this.playingAsset,T=v==null?void 0:v.identifier,E=T?this.getAssetPlayer(T):null;if(E&&T&&(!this.eventItemsMatch(c,o)||r!==void 0&&T!==y.assetList[r].identifier)){var f;const k=y.findAssetIndex(v);if(this.log(`INTERSTITIAL_ASSET_ENDED ${k+1}/${y.assetList.length} ${Mw(v)}`),this.endedAsset=v,this.playingAsset=null,this.hls.trigger(Ce.INTERSTITIAL_ASSET_ENDED,{asset:v,assetListIndex:k,event:y,schedule:i.slice(0),scheduleIndex:e,player:E}),c!==this.playingItem){this.itemsMatch(c,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(y,this.findItemIndex(this.playingItem),k);return}this.retreiveMediaSource(T,o),E.media&&!((f=this.detachedData)!=null&&f.mediaSource)&&E.detachMedia()}if(!this.eventItemsMatch(c,o)&&(this.endedItem=c,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${y} ${Vh(c)}`),y.hasPlayed=!0,this.hls.trigger(Ce.INTERSTITIAL_ENDED,{event:y,schedule:i.slice(0),scheduleIndex:e}),y.cue.once)){var p;this.updateSchedule();const k=(p=this.schedule)==null?void 0:p.items;if(o&&k){const P=this.findItemIndex(o);this.advanceSchedule(P,k,r,c,a)}return}}this.advanceSchedule(e,i,r,c,a)}advanceSchedule(e,r,n,i,o){const c=this.schedule;if(!c)return;const a=r[e]||null,f=this.primaryMedia,p=this.playerQueue;if(p.length&&p.forEach(y=>{const v=y.interstitial,T=c.findEventIndex(v.identifier);(Te+1)&&this.clearInterstitial(v,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const y=a.event;if(n===void 0){n=c.findAssetIndex(y,this.timelinePos);const k=T6(y,n-1);if(y.isAssetPastPlayoutLimit(k)||y.appendInPlace&&this.timelinePos===a.end){this.advanceAfterAssetEnded(y,e,n);return}n=k}const v=this.waitingItem;this.assetsBuffered(a,f)||this.setBufferingItem(a);let T=this.preloadAssets(y,n);if(this.eventItemsMatch(a,v||i)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${Vh(a)} ${y.appendInPlace?"append in place":""}`),this.hls.trigger(Ce.INTERSTITIAL_STARTED,{event:y,schedule:r.slice(0),scheduleIndex:e})),!y.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${y}`);return}if(y.assetListLoader&&(y.assetListLoader.destroy(),y.assetListLoader=void 0),!f){this.log(`Waiting for attachMedia to start Interstitial ${y}`);return}this.waitingItem=this.endedItem=null,this.playingItem=a;const E=y.assetList[n];if(!E){this.advanceAfterAssetEnded(y,e,n||0);return}if(T||(T=this.getAssetPlayer(E.identifier)),T===null||T.destroyed){const k=y.assetList.length;this.warn(`asset ${n+1}/${k} player destroyed ${y}`),T=this.createAssetPlayer(y,E,n),T.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&y.appendInPlace&&this.isAssetBuffered(E))return;this.startAssetPlayer(T,n,r,e,f),this.shouldPlay&&mue(T.media)}else a?(this.resumePrimary(a,e,i),this.shouldPlay&&mue(this.hls.media)):o&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(c.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,r,n){var i,o;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Vh(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let a=this.timelinePos;(a=e.end)&&(a=this.getPrimaryResumption(e,r),this.log(Nw("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)}if(!n)return;const c=(o=this.schedule)==null?void 0:o.items;c&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Vh(e)}`),this.hls.trigger(Ce.INTERSTITIALS_PRIMARY_RESUMED,{schedule:c.slice(0),scheduleIndex:r}),this.checkBuffer())}getPrimaryResumption(e,r){const n=e.start;if(this.primaryLive){const i=this.primaryDetails;if(r===0)return this.hls.startPosition;if(i&&(ni.edge))return this.hls.liveSyncPosition||-1}return n}isAssetBuffered(e){const r=this.getAssetPlayer(e.identifier);return r!=null&&r.hls?r.hls.bufferedToEnd:Ti.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,r,n){r?this.setBufferingItem(r):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const o=this.hls;o.media?this.checkBuffer():(this.transferMediaTo(o,i),n&&this.startLoadingPrimaryAt(e,n)),n||(this.log(Nw("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,n))}startLoadingPrimaryAt(e,r){var n;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((n=i.mainForwardBufferInfo)==null?void 0:n.start)||i.media.currentTime)-e)>.5?i.startLoad(e,r):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(Ce.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Ce.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,r){if(r.level===-1||!this.schedule)return;const n=this.hls.levels[r.level];if(!n.details)return;const i=Us(Us({},this.mediaSelection||this.altSelection),{},{main:n});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,r){const n=this.hls.audioTracks[r.id],i=this.mediaSelection;if(!i){this.altSelection=Us(Us({},this.altSelection),{},{audio:n});return}const o=Us(Us({},i),{},{audio:n});this.mediaSelection=o}onSubtitleTrackUpdated(e,r){const n=this.hls.subtitleTracks[r.id],i=this.mediaSelection;if(!i){this.altSelection=Us(Us({},this.altSelection),{},{subtitles:n});return}const o=Us(Us({},i),{},{subtitles:n});this.mediaSelection=o}onAudioTrackSwitching(e,r){const n=Sce(r);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(r)||i.setAudioOption(n)))}onSubtitleTrackSwitch(e,r){const n=Sce(r);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(r)||r.id!==-1&&i.setSubtitleOption(n)))}onBufferCodecs(e,r){const n=r.tracks;n&&(this.requiredTracks=n)}onBufferAppended(e,r){this.checkBuffer()}onBufferFlushed(e,r){const n=this.playingItem;if(n&&!this.itemsMatch(n,this.bufferingItem)&&!this.isInterstitial(n)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const r=this.schedule.events;if(this.bufferedPos.25){e.event.assetList.forEach((o,c)=>{e.event.isAssetPastPlayoutLimit(c)&&this.clearAssetPlayer(o.identifier,null)});const n=e.end+.25,i=Ti.bufferInfo(this.primaryMedia,n,0);(i.end>n||(i.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${Vh(e)} (was ${Vh(r)})`),this.attachPrimary(n,null,!0),this.flushFrontBuffer(n))}}itemsMatch(e,r){return!!r&&(e===r||e.event&&r.event&&this.eventItemsMatch(e,r)||!e.event&&!r.event&&this.findItemIndex(e)===this.findItemIndex(r))}eventItemsMatch(e,r){var n;return!!r&&(e===r||e.event.identifier===((n=r.event)==null?void 0:n.identifier))}findItemIndex(e,r){return e&&this.schedule?this.schedule.findItemIndex(e,r):-1}updateSchedule(e=!1){var r;const n=this.mediaSelection;n&&((r=this.schedule)==null||r.updateSchedule(n,[],e))}checkBuffer(e){var r;const n=(r=this.schedule)==null?void 0:r.items;if(!n)return;const i=Ti.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,n,e)}updateBufferedPos(e,r,n){const i=this.schedule,o=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(r.length===1&&this.itemsMatch(r[0],o)){this.bufferedPos=e;return}const c=this.playingItem,a=this.findItemIndex(c);let f=i.findItemIndexAtTime(e);if(this.bufferedPos=o.end||(p=T.event)!=null&&p.appendInPlace&&e+.01>=T.start)&&(f=v),this.isInterstitial(o)){const E=o.event;if(v-a>1&&E.appendInPlace===!1||E.assetList.length===0&&E.assetListLoader)return}if(this.bufferedPos=e,f>y&&f>a)this.bufferedToItem(T);else{const E=this.primaryDetails;this.primaryLive&&E&&e>E.edge-E.targetduration&&T.start{const o=this.getAssetPlayer(i.identifier);return!(o!=null&&o.bufferedInPlaceToEnd(r))})}setBufferingItem(e){const r=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(e,r)&&n){const{items:i,events:o}=n;if(!i||!o)return r;const c=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const f=a?a.remaining:r?r.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Vh(e)}`+(r?` (${f.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(c){const p=n.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((y,v)=>{const T=this.getAssetPlayer(y.identifier);T&&(v===p&&T.loadSource(),T.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(p=>p.pauseBuffering());this.hls.trigger(Ce.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:o.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return r}bufferedToItem(e,r=0){const n=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,r);else if(n!==null){this.bufferingAsset=null;const i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const r=this.findItemIndex(e),n=this.getPrimaryResumption(e,r);this.startLoadingPrimaryAt(n)}bufferedToEvent(e,r){const n=e.event,i=n.assetList.length===0&&!n.assetListLoader,o=n.cue.once;if(i||!o){const c=this.preloadAssets(n,r);if(c!=null&&c.interstitial.appendInPlace){const a=this.primaryMedia;a&&this.bufferAssetPlayer(c,a)}}}preloadAssets(e,r){const n=e.assetUrl,i=e.assetList.length,o=i===0&&!e.assetListLoader,c=e.cue.once;if(o){const f=e.timelineStart;if(e.appendInPlace){var a;const T=this.playingItem;!this.isInterstitial(T)&&(T==null||(a=T.nextEvent)==null?void 0:a.identifier)===e.identifier&&this.flushFrontBuffer(f+.25)}let p,y=0;if(!this.playingItem&&this.primaryLive&&(y=this.hls.startPosition,y===-1&&(y=this.hls.liveSyncPosition||0)),y&&!(e.cue.pre||e.cue.post)){const T=y-f;T>0&&(p=Math.round(T*1e3)/1e3)}if(this.log(`Load interstitial asset ${r+1}/${n?1:i} ${e}${p?` live-start: ${y} start-offset: ${p}`:""}`),n)return this.createAsset(e,0,0,f,e.duration,n);const v=this.assetListLoader.loadAssetList(e,p);v&&(e.assetListLoader=v)}else if(!c&&i){for(let p=r;p{this.hls.trigger(Ce.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){const r=this.playerQueue;for(let n=0;n1){const G=r.duration;G&&V{if(V.live){var G;const J=new Error(`Interstitials MUST be VOD assets ${e}`),Q={fatal:!0,type:Dn.OTHER_ERROR,details:Jt.INTERSTITIAL_ASSET_ITEM_ERROR,error:J},ee=((G=this.schedule)==null?void 0:G.findEventIndex(e.identifier))||-1;this.handleAssetItemError(Q,e,ee,n,J.message);return}const W=V.edge-V.fragmentStart,Y=r.duration;(P||Y===null||W>Y)&&(P=!1,this.log(`Interstitial asset "${v}" duration change ${Y} > ${W}`),r.duration=W,this.updateSchedule())};k.on(Ce.LEVEL_UPDATED,(V,{details:G})=>R(G)),k.on(Ce.LEVEL_PTS_UPDATED,(V,{details:G})=>R(G)),k.on(Ce.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const D=(V,G)=>{const W=this.getAssetPlayer(v);if(W&&G.tracks){W.off(Ce.BUFFER_CODECS,D),W.tracks=G.tracks;const Y=this.primaryMedia;this.bufferingAsset===W.assetItem&&Y&&!W.media&&this.bufferAssetPlayer(W,Y)}};k.on(Ce.BUFFER_CODECS,D);const M=()=>{var V;const G=this.getAssetPlayer(v);if(this.log(`buffered to end of asset ${G}`),!G||!this.schedule)return;const W=this.schedule.findEventIndex(e.identifier),Y=(V=this.schedule.items)==null?void 0:V[W];this.isInterstitial(Y)&&this.advanceAssetBuffering(Y,r)};k.on(Ce.BUFFERED_TO_END,M);const B=V=>()=>{if(!this.getAssetPlayer(v)||!this.schedule)return;this.shouldPlay=!0;const W=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,W,V)};return k.once(Ce.MEDIA_ENDED,B(n)),k.once(Ce.PLAYOUT_LIMIT_REACHED,B(1/0)),k.on(Ce.ERROR,(V,G)=>{if(!this.schedule)return;const W=this.getAssetPlayer(v);if(G.details===Jt.BUFFER_STALLED_ERROR){if(W!=null&&W.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(G,e,this.schedule.findEventIndex(e.identifier),n,`Asset player error ${G.error} ${e}`)}),k.on(Ce.DESTROYING,()=>{if(!this.getAssetPlayer(v)||!this.schedule)return;const G=new Error(`Asset player destroyed unexpectedly ${v}`),W={fatal:!0,type:Dn.OTHER_ERROR,details:Jt.INTERSTITIAL_ASSET_ITEM_ERROR,error:G};this.handleAssetItemError(W,e,this.schedule.findEventIndex(e.identifier),n,G.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Mw(r)}`),this.hls.trigger(Ce.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:r,assetListIndex:n,event:e,player:k}),k}clearInterstitial(e,r){this.clearAssetPlayers(e,r),e.reset()}clearAssetPlayers(e,r){e.assetList.forEach(n=>{this.clearAssetPlayer(n.identifier,r)})}resetAssetPlayer(e){const r=this.getAssetPlayerQueueIndex(e);if(r!==-1){this.log(`reset asset player "${e}" after error`);const n=this.playerQueue[r];this.transferMediaFromPlayer(n,null),n.resetDetails()}}clearAssetPlayer(e,r){const n=this.getAssetPlayerQueueIndex(e);if(n!==-1){const i=this.playerQueue[n];this.log(`clear ${i} toSegment: ${r&&Vh(r)}`),this.transferMediaFromPlayer(i,r),this.playerQueue.splice(n,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,r,n,i,o){const{interstitial:c,assetItem:a,assetId:f}=e,p=c.assetList.length,y=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(!y||y.identifier!==f)&&(y&&(this.clearAssetPlayer(y.identifier,n[i]),delete y.error),this.log(`INTERSTITIAL_ASSET_STARTED ${r+1}/${p} ${Mw(a)}`),this.hls.trigger(Ce.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:r,event:c,schedule:n.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,o)}bufferAssetPlayer(e,r){var n,i;if(!this.schedule)return;const{interstitial:o,assetItem:c}=e,a=this.schedule.findEventIndex(o.identifier),f=(n=this.schedule.items)==null?void 0:n[a];if(!f)return;e.loadSource(),this.setBufferingItem(f),this.bufferingAsset=c;const p=this.getBufferingPlayer();if(p===e)return;const y=o.appendInPlace;if(y&&(p==null?void 0:p.interstitial.appendInPlace)===!1)return;const v=(p==null?void 0:p.tracks)||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(y&&c!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(v&&!f2e(v,e.tracks)){const T=new Error(`Asset ${Mw(c)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(v)}')`),E={fatal:!0,type:Dn.OTHER_ERROR,details:Jt.INTERSTITIAL_ASSET_ITEM_ERROR,error:T},k=o.findAssetIndex(c);this.handleAssetItemError(E,o,a,k,T.message);return}}this.transferMediaTo(e,r)}handleInPlaceStall(e){const r=this.schedule,n=this.primaryMedia;if(!r||!n)return;const i=n.currentTime,o=r.findAssetIndex(e,i),c=e.assetList[o];if(c){const a=this.getAssetPlayer(c.identifier);if(a){const f=a.currentTime||i-c.timelineStart,p=a.duration-f;if(this.warn(`Stalled at ${f} of ${f+p} in ${a} ${e} (media.currentTime: ${i})`),f&&(p/n.playbackRate<.5||a.bufferedInPlaceToEnd(n))&&a.hls){const y=r.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,y,o)}}}}advanceInPlace(e){const r=this.primaryMedia;r&&r.currentTime!P.error))r.error=k;else for(let P=i;P{const D=parseFloat(P.DURATION);this.createAsset(o,R,y,f+y,D,P.URI),y+=D}),o.duration=y,this.log(`Loaded asset-list with duration: ${y} (was: ${p}) ${o}`);const v=this.waitingItem,T=(v==null?void 0:v.event.identifier)===c;this.updateSchedule();const E=(i=this.bufferingItem)==null?void 0:i.event;if(T){var k;const P=this.schedule.findEventIndex(c),R=(k=this.schedule.items)==null?void 0:k[P];if(R){if(!this.playingItem&&this.timelinePos>R.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==P){o.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${o}`),this.log(o.error.message),this.updateSchedule(!0),this.primaryFallback(o);return}this.setBufferingItem(R)}this.setSchedulePosition(P)}else if((E==null?void 0:E.identifier)===c){const P=o.assetList[0];if(P){const R=this.getAssetPlayer(P.identifier);if(E.appendInPlace){const D=this.primaryMedia;R&&D&&this.bufferAssetPlayer(R,D)}else R&&R.loadSource()}}}onError(e,r){if(this.schedule)switch(r.details){case Jt.ASSET_LIST_PARSING_ERROR:case Jt.ASSET_LIST_LOAD_ERROR:case Jt.ASSET_LIST_LOAD_TIMEOUT:{const n=r.interstitial;n&&(this.updateSchedule(!0),this.primaryFallback(n));break}case Jt.BUFFER_STALLED_ERROR:{const n=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&n.event.appendInPlace){this.handleInPlaceStall(n.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const pue=500;class c5t extends BK{constructor(e,r,n){super(e,r,n,"subtitle-stream-controller",Tn.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Ce.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Ce.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Ce.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Ce.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Ce.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Ce.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Ce.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Ce.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Ce.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Ce.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Ce.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Ce.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,r){this.stopLoad(),this.state=wr.IDLE,this.setInterval(pue),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=r?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,r){this.tracksBuffered=[],super.onMediaDetaching(e,r)}onLevelLoaded(e,r){this.mainDetails=r.details}onSubtitleFragProcessed(e,r){const{frag:n,success:i}=r;if(this.fragContextChanged(n)||(Io(n)&&(this.fragPrevious=n),this.state=wr.IDLE),!i)return;const o=this.tracksBuffered[this.currentTrackId];if(!o)return;let c;const a=n.start;for(let p=0;p=o[p].start&&a<=o[p].end){c=o[p];break}const f=n.start+n.duration;c?c.end=f:(c={start:a,end:f},o.push(c)),this.fragmentTracker.fragBuffered(n),this.fragBufferedComplete(n,null),this.media&&this.tick()}onBufferFlushing(e,r){const{startOffset:n,endOffset:i}=r;if(n===0&&i!==Number.POSITIVE_INFINITY){const o=i-1;if(o<=0)return;r.endOffsetSubtitles=Math.max(0,o),this.tracksBuffered.forEach(c=>{for(let a=0;anew sC(n));return}this.tracksBuffered=[],this.levels=r.map(n=>{const i=new sC(n);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Tn.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,r){var n;if(this.currentTrackId=r.id,!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==wr.STOPPED&&this.setInterval(pue)}onSubtitleTrackLoaded(e,r){var n;const{currentTrackId:i,levels:o}=this,{details:c,id:a}=r;if(!o){this.warn(`Subtitle tracks were reset while loading level ${a}`);return}const f=o[a];if(a>=o.length||!f)return;this.log(`Subtitle track ${a} loaded [${c.startSN},${c.endSN}]${c.lastPartSn?`[part-${c.lastPartSn}-${c.lastPartIndex}]`:""},duration:${c.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let p=0;if(c.live||(n=f.details)!=null&&n.live){if(c.deltaUpdateFailed)return;const v=this.mainDetails;if(!v){this.startFragRequested=!1;return}const T=v.fragments[0];if(!f.details)c.hasProgramDateTime&&v.hasProgramDateTime?(AO(c,v),p=c.fragmentStart):T&&(p=T.start,dG(c,p));else{var y;p=this.alignPlaylists(c,f.details,(y=this.levelLastLoaded)==null?void 0:y.details),p===0&&T&&(p=T.start,dG(c,p))}v&&!this.startFragRequested&&this.setStartPosition(v,p)}f.details=c,this.levelLastLoaded=f,a===i&&(this.hls.trigger(Ce.SUBTITLE_TRACK_UPDATED,{details:c,id:a,groupId:r.groupId}),this.tick(),c.live&&!this.fragCurrent&&this.media&&this.state===wr.IDLE&&(g_(null,c.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),f.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:r,payload:n}=e,i=r.decryptdata,o=this.hls;if(!this.fragContextChanged(r)&&n&&n.byteLength>0&&i!=null&&i.key&&i.iv&&N1(i.method)){const c=performance.now();this.decrypter.decrypt(new Uint8Array(n),i.key.buffer,i.iv.buffer,OK(i.method)).catch(a=>{throw o.trigger(Ce.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:r}),a}).then(a=>{const f=performance.now();o.trigger(Ce.FRAG_DECRYPTED,{frag:r,payload:a,stats:{tstart:c,tdecrypt:f}})}).catch(a=>{this.warn(`${a.name}: ${a.message}`),this.state=wr.IDLE})}}doTick(){if(!this.media){this.state=wr.IDLE;return}if(this.state===wr.IDLE){const{currentTrackId:e,levels:r}=this,n=r==null?void 0:r[e];if(!n||!r.length||!n.details||this.waitForLive(n))return;const{config:i}=this,o=this.getLoadPosition(),c=Ti.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],o,i.maxBufferHole),{end:a,len:f}=c,p=n.details,y=this.hls.maxBufferLength+p.levelTargetDuration;if(f>y)return;const v=p.fragments,T=v.length,E=p.edge;let k=null;const P=this.fragPrevious;if(aE-M?0:M;k=g_(P,v,Math.max(v[0].start,a),B),!k&&P&&P.start{if(i=i>>>0,i>o-1)throw new DOMException(`Failed to execute '${n}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${o})`);return e[i][n]};this.buffered={get length(){return e.length},end(n){return r("end",n,e.length)},start(n){return r("start",n,e.length)}}}}const d5t={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},PAe=t=>String.fromCharCode(d5t[t]||t),Hh=15,_p=100,h5t={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},f5t={17:2,18:4,21:6,22:8,23:10,19:13,20:15},m5t={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},p5t={25:2,26:4,29:6,30:8,31:10,27:13,28:15},g5t=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class y5t{constructor(){this.time=null,this.verboseLevel=0}log(e,r){if(this.verboseLevel>=e){const n=typeof r=="function"?r():r;qs.log(`${this.time} [${e}] ${n}`)}}}const cv=function(e){const r=[];for(let n=0;n_p&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=_p)}moveCursor(e){const r=this.pos+e;if(e>1)for(let n=this.pos+1;n=144&&this.backSpace();const r=PAe(e);if(this.pos>=_p){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+r+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1)}clearFromPos(e){let r;for(r=e;r<_p;r++)this.chars[r].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let r=!0;for(let n=0;n<_p;n++){const i=this.chars[n].uchar;i!==" "&&(r=!1),e.push(i)}return r?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class E6{constructor(e){this.rows=[],this.currRow=Hh-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let r=0;r"pacData = "+aa(e));let r=e.row-1;if(this.nrRollUpRows&&r"bkgData = "+aa(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,r=this.rows.splice(e,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const r=[];let n="",i=-1;for(let o=0;o0&&(e?n="["+r.join(" | ")+"]":n=r.join(` `)),n}getTextAndFormat(){return this.rows}}class gue{constructor(e,r,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new E6(n),this.nonDisplayedMemory=new E6(n),this.lastOutputScreen=new E6(n),this.currRollUpRow=this.displayedMemory.rows[Hh-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Hh-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let n=0;nr+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const r={flash:!1};if(r.underline=e%2===1,r.italics=e>=46,r.italics)r.foreground="white";else{const n=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];r.foreground=i[n]}this.logger.log(2,"MIDROW: "+aa(r)),this.writeScreen.setPen(r)}outputDataUpdate(e=!1){const r=this.logger.time;r!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=r:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,r,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:r),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class yue{constructor(e,r,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=b5t(),this.logger=void 0;const i=this.logger=new y5t;this.channels=[null,new gue(e,r,i),new gue(e+1,n,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,r){this.channels[e].setHandler(r)}addData(e,r){this.logger.time=e;for(let n=0;n"["+cv([r[n],r[n+1]])+"] -> ("+cv([i,o])+")");const f=this.cmdHistory;if(i>=16&&i<=31){if(_5t(i,o,f)){tL(null,null,f),this.logger.log(3,()=>"Repeated command ("+cv([i,o])+") is dropped");continue}tL(i,o,this.cmdHistory),c=this.parseCmd(i,o),c||(c=this.parseMidrow(i,o)),c||(c=this.parsePAC(i,o)),c||(c=this.parseBackgroundAttributes(i,o))}else tL(null,null,f);if(!c&&(a=this.parseChars(i,o),a)){const y=this.currentChannel;y&&y>0?this.channels[y].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!c&&!a&&this.logger.log(2,()=>"Couldn't parse cleaned data "+cv([i,o])+" orig: "+cv([r[n],r[n+1]]))}}parseCmd(e,r){const n=(e===20||e===28||e===21||e===29)&&r>=32&&r<=47,i=(e===23||e===31)&&r>=33&&r<=35;if(!(n||i))return!1;const o=e===20||e===21||e===23?1:2,c=this.channels[o];return e===20||e===21||e===28||e===29?r===32?c.ccRCL():r===33?c.ccBS():r===34?c.ccAOF():r===35?c.ccAON():r===36?c.ccDER():r===37?c.ccRU(2):r===38?c.ccRU(3):r===39?c.ccRU(4):r===40?c.ccFON():r===41?c.ccRDC():r===42?c.ccTR():r===43?c.ccRTD():r===44?c.ccEDM():r===45?c.ccCR():r===46?c.ccENM():r===47&&c.ccEOC():c.ccTO(r-32),this.currentChannel=o,!0}parseMidrow(e,r){let n=0;if((e===17||e===25)&&r>=32&&r<=47){if(e===17?n=1:n=2,n!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[n];return i?(i.ccMIDROW(r),this.logger.log(3,()=>"MIDROW ("+cv([e,r])+")"),!0):!1}return!1}parsePAC(e,r){let n;const i=(e>=17&&e<=23||e>=25&&e<=31)&&r>=64&&r<=127,o=(e===16||e===24)&&r>=64&&r<=95;if(!(i||o))return!1;const c=e<=23?1:2;r>=64&&r<=95?n=c===1?h5t[e]:m5t[e]:n=c===1?f5t[e]:p5t[e];const a=this.channels[c];return a?(a.setPAC(this.interpretPAC(n,r)),this.currentChannel=c,!0):!1}interpretPAC(e,r){let n;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return r>95?n=r-96:n=r-64,i.underline=(n&1)===1,n<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(n/2)]:n<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((n-16)/2)*4,i}parseChars(e,r){let n,i=null,o=null;if(e>=25?(n=2,o=e-8):(n=1,o=e),o>=17&&o<=19){let c;o===17?c=r+80:o===18?c=r+112:c=r+144,this.logger.log(2,()=>"Special char '"+PAe(c)+"' in channel "+n),i=[c]}else e>=32&&e<=127&&(i=r===0?[e]:[e,r]);return i&&this.logger.log(3,()=>"Char codes = "+cv(i).join(",")),i}parseBackgroundAttributes(e,r){const n=(e===16||e===24)&&r>=32&&r<=47,i=(e===23||e===31)&&r>=45&&r<=47;if(!(n||i))return!1;let o;const c={};e===16||e===24?(o=Math.floor((r-32)/2),c.background=g5t[o],r%2===1&&(c.background=c.background+"_semi")):r===45?c.background="transparent":(c.foreground="black",r===47&&(c.underline=!0));const a=e<=23?1:2;return this.channels[a].setBkgData(c),!0}reset(){for(let e=0;e100)throw new Error("Position must be between 0 and 100.");W=ee,this.hasBeenReset=!0}})),Object.defineProperty(y,"positionAlign",o({},v,{get:function(){return Y},set:function(ee){const le=i(ee);if(!le)throw new SyntaxError("An invalid or illegal string was specified.");Y=le,this.hasBeenReset=!0}})),Object.defineProperty(y,"size",o({},v,{get:function(){return J},set:function(ee){if(ee<0||ee>100)throw new Error("Size must be between 0 and 100.");J=ee,this.hasBeenReset=!0}})),Object.defineProperty(y,"align",o({},v,{get:function(){return Q},set:function(ee){const le=i(ee);if(!le)throw new SyntaxError("An invalid or illegal string was specified.");Q=le,this.hasBeenReset=!0}})),y.displayState=void 0}return c.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},c}();class w5t{decode(e,r){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function LAe(t){function e(n,i,o,c){return(n|0)*3600+(i|0)*60+(o|0)+parseFloat(c||0)}const r=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?e(r[2],r[3],0,r[4]):e(r[1],r[2],r[3],r[4]):null}class S5t{constructor(){this.values=Object.create(null)}set(e,r){!this.get(e)&&r!==""&&(this.values[e]=r)}get(e,r,n){return n?this.has(e)?this.values[e]:r[n]:this.has(e)?this.values[e]:r}has(e){return e in this.values}alt(e,r,n){for(let i=0;i=0&&n<=100)return this.set(e,n),!0}return!1}}function DAe(t,e,r,n){const i=n?t.split(n):[t];for(const o in i){if(typeof i[o]!="string")continue;const c=i[o].split(r);if(c.length!==2)continue;const a=c[0],f=c[1];e(a,f)}}const vG=new XK(0,0,""),rL=vG.align==="middle"?"middle":"center";function T5t(t,e,r){const n=t;function i(){const a=LAe(t);if(a===null)throw new Error("Malformed timestamp: "+n);return t=t.replace(/^[^\sa-zA-Z-]+/,""),a}function o(a,f){const p=new S5t;DAe(a,function(T,E){let k;switch(T){case"region":for(let P=r.length-1;P>=0;P--)if(r[P].id===E){p.set(T,r[P].region);break}break;case"vertical":p.alt(T,E,["rl","lr"]);break;case"line":k=E.split(","),p.integer(T,k[0]),p.percent(T,k[0])&&p.set("snapToLines",!1),p.alt(T,k[0],["auto"]),k.length===2&&p.alt("lineAlign",k[1],["start",rL,"end"]);break;case"position":k=E.split(","),p.percent(T,k[0]),k.length===2&&p.alt("positionAlign",k[1],["start",rL,"end","line-left","line-right","auto"]);break;case"size":p.percent(T,E);break;case"align":p.alt(T,E,["start",rL,"end","left","right"]);break}},/:/,/\s/),f.region=p.get("region",null),f.vertical=p.get("vertical","");let y=p.get("line","auto");y==="auto"&&vG.line===-1&&(y=-1),f.line=y,f.lineAlign=p.get("lineAlign","start"),f.snapToLines=p.get("snapToLines",!0),f.size=p.get("size",100),f.align=p.get("align",rL);let v=p.get("position","auto");v==="auto"&&vG.position===50&&(v=f.align==="start"||f.align==="left"?0:f.align==="end"||f.align==="right"?100:50),f.position=v}function c(){t=t.replace(/^\s+/,"")}if(c(),e.startTime=i(),c(),t.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+n);t=t.slice(3),c(),e.endTime=i(),c(),o(t,e)}function MAe(t){return t.replace(//gi,` `)}class E5t{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new w5t,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const r=this;e&&(r.buffer+=r.decoder.decode(e,{stream:!0}));function n(){let o=r.buffer,c=0;for(o=MAe(o);c")===-1){r.cue.id=o;continue}case"CUE":if(!r.cue){r.state="BADCUE";continue}try{T5t(o,r.cue,r.regionList)}catch{r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":{const a=o.indexOf("-->")!==-1;if(!o||a&&(c=!0)){r.oncue&&r.cue&&r.oncue(r.cue),r.cue=null,r.state="ID";continue}if(r.cue===null)continue;r.cue.text&&(r.cue.text+=` `),r.cue.text+=o}continue;case"BADCUE":o||(r.state="ID")}}}catch{r.state==="CUETEXT"&&r.cue&&r.oncue&&r.oncue(r.cue),r.cue=null,r.state=r.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=` `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(r){e.onparsingerror&&e.onparsingerror(r)}return e.onflush&&e.onflush(),this}}const j5t=/\r\n|\n\r|\n|\r/g,j6=function(e,r,n=0){return e.slice(n,n+r.length)===r},A5t=function(e){let r=parseInt(e.slice(-3));const n=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),o=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!pn(r)||!pn(n)||!pn(i)||!pn(o))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return r+=1e3*n,r+=60*1e3*i,r+=60*60*1e3*o,r};function QK(t,e,r){return AA(t.toString())+AA(e.toString())+AA(r)}const k5t=function(e,r,n){let i=e[r],o=e[i.prevCC];if(!o||!o.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(c=o)!=null&&c.new;){var c;e.ccOffset+=i.start-o.start,i.new=!1,i=o,o=e[i.prevCC]}e.presentationOffset=n};function C5t(t,e,r,n,i,o,c){const a=new E5t,f=pd(new Uint8Array(t)).trim().replace(j5t,` `).split(` `),p=[],y=e?D3t(e.baseTime,e.timescale):0;let v="00:00.000",T=0,E=0,k,P=!0;a.oncue=function(R){const D=r[n];let M=r.ccOffset;const B=(T-y)/9e4;if(D!=null&&D.new&&(E!==void 0?M=r.ccOffset=D.start:k5t(r,n,B)),B){if(!e){k=new Error("Missing initPTS for VTT MPEGTS");return}M=B-r.presentationOffset}const V=R.endTime-R.startTime,G=rd((R.startTime+M-E)*9e4,i*9e4)/9e4;R.startTime=Math.max(G,0),R.endTime=Math.max(G+V,0);const W=R.text.trim();R.text=decodeURIComponent(encodeURIComponent(W)),R.id||(R.id=QK(R.startTime,R.endTime,W)),R.endTime>0&&p.push(R)},a.onparsingerror=function(R){k=R},a.onflush=function(){if(k){c(k);return}o(p)},f.forEach(R=>{if(P)if(j6(R,"X-TIMESTAMP-MAP=")){P=!1,R.slice(16).split(",").forEach(D=>{j6(D,"LOCAL:")?v=D.slice(6):j6(D,"MPEGTS:")&&(T=parseInt(D.slice(7)))});try{E=A5t(v)/1e3}catch(D){k=D}return}else R===""&&(P=!1);a.parse(R+` `)}),a.flush()}const A6="stpp.ttml.im1t",OAe=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,FAe=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,N5t={left:"start",center:"center",right:"end",start:"start",end:"end"};function xue(t,e,r,n){const i=Hi(new Uint8Array(t),["mdat"]);if(i.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const o=i.map(a=>pd(a)),c=L3t(e.baseTime,1,e.timescale);try{o.forEach(a=>r(I5t(a,c)))}catch(a){n(a)}}function I5t(t,e){const i=new DOMParser().parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const o={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},c=Object.keys(o).reduce((v,T)=>(v[T]=i.getAttribute(`ttp:${T}`)||o[T],v),{}),a=i.getAttribute("xml:space")!=="preserve",f=vue(k6(i,"styling","style")),p=vue(k6(i,"layout","region")),y=k6(i,"body","[begin]");return[].map.call(y,v=>{const T=BAe(v,a);if(!T||!v.hasAttribute("begin"))return null;const E=N6(v.getAttribute("begin"),c),k=N6(v.getAttribute("dur"),c);let P=N6(v.getAttribute("end"),c);if(E===null)throw _ue(v);if(P===null){if(k===null)throw _ue(v);P=E+k}const R=new XK(E-e,P-e,T);R.id=QK(R.startTime,R.endTime,R.text);const D=p[v.getAttribute("region")],M=f[v.getAttribute("style")],B=P5t(D,M,f),{textAlign:V}=B;if(V){const G=N5t[V];G&&(R.lineAlign=G),R.align=V}return Js(R,B),R}).filter(v=>v!==null)}function k6(t,e,r){const n=t.getElementsByTagName(e)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function vue(t){return t.reduce((e,r)=>{const n=r.getAttribute("xml:id");return n&&(e[n]=r),e},{})}function BAe(t,e){return[].slice.call(t.childNodes).reduce((r,n,i)=>{var o;return n.nodeName==="br"&&i?r+` `:(o=n.childNodes)!=null&&o.length?BAe(n,e):e?r+n.textContent.trim().replace(/\s+/g," "):r+n.textContent},"")}function P5t(t,e,r){const n="http://www.w3.org/ns/ttml#styling";let i=null;const o=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],c=t!=null&&t.hasAttribute("style")?t.getAttribute("style"):null;return c&&r.hasOwnProperty(c)&&(i=r[c]),o.reduce((a,f)=>{const p=C6(e,n,f)||C6(t,n,f)||C6(i,n,f);return p&&(a[f]=p),a},{})}function C6(t,e,r){return t&&t.hasAttributeNS(e,r)?t.getAttributeNS(e,r):null}function _ue(t){return new Error(`Could not parse ttml timestamp ${t}`)}function N6(t,e){if(!t)return null;let r=LAe(t);return r===null&&(OAe.test(t)?r=R5t(t,e):FAe.test(t)&&(r=L5t(t,e))),r}function R5t(t,e){const r=OAe.exec(t),n=(r[4]|0)+(r[5]|0)/e.subFrameRate;return(r[1]|0)*3600+(r[2]|0)*60+(r[3]|0)+n/e.frameRate}function L5t(t,e){const r=FAe.exec(t),n=Number(r[1]);switch(r[2]){case"h":return n*3600;case"m":return n*60;case"ms":return n*1e3;case"f":return n/e.frameRate;case"t":return n/e.tickRate}return n}class nL{constructor(e,r){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=r}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,r,n){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=r,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class D5t{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=wue(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(Ce.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ce.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Ce.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Ce.FRAG_LOADING,this.onFragLoading,this),e.on(Ce.FRAG_LOADED,this.onFragLoaded,this),e.on(Ce.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Ce.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Ce.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Ce.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Ce.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Ce.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ce.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Ce.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Ce.FRAG_LOADING,this.onFragLoading,this),e.off(Ce.FRAG_LOADED,this.onFragLoaded,this),e.off(Ce.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Ce.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Ce.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Ce.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Ce.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new nL(this,"textTrack1"),r=new nL(this,"textTrack2"),n=new nL(this,"textTrack3"),i=new nL(this,"textTrack4");this.cea608Parser1=new yue(1,e,r),this.cea608Parser2=new yue(3,n,i)}addCues(e,r,n,i,o){let c=!1;for(let a=o.length;a--;){const f=o[a],p=M5t(f[0],f[1],r,n);if(p>=0&&(f[0]=Math.min(f[0],r),f[1]=Math.max(f[1],n),c=!0,p/(n-r)>.5))return}if(c||o.push([r,n]),this.config.renderTextTracksNatively){const a=this.captionsTracks[e];this.Cues.newCue(a,r,n,i)}else{const a=this.Cues.newCue(null,r,n,i);this.hls.trigger(Ce.CUES_PARSED,{type:"captions",cues:a,track:e})}}onInitPtsFound(e,{frag:r,id:n,initPTS:i,timescale:o,trackId:c}){const{unparsedVttFrags:a}=this;n===Tn.MAIN&&(this.initPTS[r.cc]={baseTime:i,timescale:o,trackId:c}),a.length&&(this.unparsedVttFrags=[],a.forEach(f=>{this.initPTS[f.frag.cc]?this.onFragLoaded(Ce.FRAG_LOADED,f):this.hls.trigger(Ce.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:f.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,r){const{media:n}=this;if(n)for(let i=0;i{a1(i[o]),delete i[o]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=wue(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const r=e.textTracks;if(r)for(let n=0;no.textCodec===A6);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(gAe(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){const c=this.media,a=c?eD(c.textTracks):null;if(this.tracks.forEach((f,p)=>{let y;if(a){let v=null;for(let T=0;Tp!==null).map(p=>p.label);f.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${f.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const c=this.tracks.map(a=>({label:a.name,kind:a.type.toLowerCase(),default:a.default,subtitleTrack:a}));this.hls.trigger(Ce.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:c})}}}onManifestLoaded(e,r){this.config.enableCEA708Captions&&r.captions&&r.captions.forEach(n=>{const i=/(?:CC|SERVICE)([1-4])/.exec(n.instreamId);if(!i)return;const o=`textTrack${i[1]}`,c=this.captionsProperties[o];c&&(c.label=n.name,n.lang&&(c.languageCode=n.lang),c.media=n)})}closedCaptionsForLevel(e){const r=this.hls.levels[e.level];return r==null?void 0:r.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,r){if(this.enabled&&r.frag.type===Tn.MAIN){var n,i;const{cea608Parser1:o,cea608Parser2:c,lastSn:a}=this,{cc:f,sn:p}=r.frag,y=(n=(i=r.part)==null?void 0:i.index)!=null?n:-1;o&&c&&(p!==a+1||p===a&&y!==this.lastPartIndex+1||f!==this.lastCc)&&(o.reset(),c.reset()),this.lastCc=f,this.lastSn=p,this.lastPartIndex=y}}onFragLoaded(e,r){const{frag:n,payload:i}=r;if(n.type===Tn.SUBTITLE)if(i.byteLength){const o=n.decryptdata,c="stats"in r;if(o==null||!o.encrypted||c){const a=this.tracks[n.level],f=this.vttCCs;f[n.cc]||(f[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),a&&a.textCodec===A6?this._parseIMSC1(n,i):this._parseVTTs(r)}}else this.hls.trigger(Ce.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,r){const n=this.hls;xue(r,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),n.trigger(Ce.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{n.logger.log(`Failed to parse IMSC1: ${i}`),n.trigger(Ce.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var r;const{frag:n,payload:i}=e,{initPTS:o,unparsedVttFrags:c}=this,a=o.length-1;if(!o[n.cc]&&a===-1){c.push(e);return}const f=this.hls,p=(r=n.initSegment)!=null&&r.data?ph(n.initSegment.data,new Uint8Array(i)).buffer:i;C5t(p,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,y=>{this._appendCues(y,n.level),f.trigger(Ce.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},y=>{const v=y.message==="Missing initPTS for VTT MPEGTS";v?c.push(e):this._fallbackToIMSC1(n,i),f.logger.log(`Failed to parse VTT cue: ${y}`),!(v&&a>n.cc)&&f.trigger(Ce.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:y})})}_fallbackToIMSC1(e,r){const n=this.tracks[e.level];n.textCodec||xue(r,this.initPTS[e.cc],()=>{n.textCodec=A6,this._parseIMSC1(e,r)},()=>{n.textCodec="wvtt"})}_appendCues(e,r){const n=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[r];if(!i||i.mode==="disabled")return;e.forEach(o=>NAe(i,o))}else{const i=this.tracks[r];if(!i)return;const o=i.default?"default":"subtitles"+r;n.trigger(Ce.CUES_PARSED,{type:"subtitles",cues:e,track:o})}}onFragDecrypted(e,r){const{frag:n}=r;n.type===Tn.SUBTITLE&&this.onFragLoaded(Ce.FRAG_LOADED,r)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,r){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:n,samples:i}=r;if(!(n.type===Tn.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let o=0;oxG(a[f],r,n))}if(this.config.renderTextTracksNatively&&r===0&&i!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(f=>xG(a[f],r,i))}}}extractCea608Data(e){const r=[[],[]],n=e[0]&31;let i=2;for(let o=0;o=16?f--:f++;const E=MAe(p.trim()),k=QK(e,r,E);t!=null&&(v=t.cues)!=null&&v.getCueById(k)||(c=new y(e,r,E),c.id=k,c.line=T+1,c.align="left",c.position=10+Math.min(80,Math.floor(f*8/32)*10),i.push(c))}return t&&i.length&&(i.sort((T,E)=>T.line==="auto"||E.line==="auto"?0:T.line>8&&E.line>8?E.line-T.line:T.line-E.line),i.forEach(T=>NAe(t,T))),i}};function B5t(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const $5t=/(\d+)-(\d+)\/(\d+)/;class Sue{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||q5t,this.controller=new self.AbortController,this.stats=new NK}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,r,n){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const o=z5t(e,this.controller.signal),c=e.responseType==="arraybuffer",a=c?"byteLength":"length",{maxTimeToFirstByteMs:f,maxLoadTimeMs:p}=r.loadPolicy;this.context=e,this.config=r,this.callbacks=n,this.request=this.fetchSetup(e,o),self.clearTimeout(this.requestTimeout),r.timeout=f&&pn(f)?f:p,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},r.timeout),(lC(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(v=>{var T;this.response=this.loader=v;const E=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),r.timeout=p,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},p-(E-i.loading.start)),!v.ok){const{status:P,statusText:R}=v;throw new G5t(R||"fetch, bad network response",P,v)}i.loading.first=E,i.total=V5t(v.headers)||i.total;const k=(T=this.callbacks)==null?void 0:T.onProgress;return k&&pn(r.highWaterMark)?this.loadProgressively(v,i,e,r.highWaterMark,k):c?v.arrayBuffer():e.responseType==="json"?v.json():v.text()}).then(v=>{var T,E;const k=this.response;if(!k)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const P=v[a];P&&(i.loaded=i.total=P);const R={url:k.url,data:v,code:k.status},D=(T=this.callbacks)==null?void 0:T.onProgress;D&&!pn(r.highWaterMark)&&D(i,e,v,k),(E=this.callbacks)==null||E.onSuccess(R,i,e,k)}).catch(v=>{var T;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const E=v&&v.code||0,k=v?v.message:null;(T=this.callbacks)==null||T.onError({code:E,text:k},e,v?v.details:null,i)})}getCacheAge(){let e=null;if(this.response){const r=this.response.headers.get("age");e=r?parseFloat(r):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,r,n,i=0,o){const c=new Z2e,a=e.body.getReader(),f=()=>a.read().then(p=>{if(p.done)return c.dataLength&&o(r,n,c.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const y=p.value,v=y.length;return r.loaded+=v,v=i&&o(r,n,c.flush().buffer,e)):o(r,n,y.buffer,e),f()}).catch(()=>Promise.reject());return f()}}function z5t(t,e){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Js({},t.headers))};return t.rangeEnd&&r.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),r}function U5t(t){const e=$5t.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}function V5t(t){const e=t.get("Content-Range");if(e){const n=U5t(e);if(pn(n))return n}const r=t.get("Content-Length");if(r)return parseInt(r)}function q5t(t,e){return new self.Request(t.url,e)}class G5t extends Error{constructor(e,r,n){super(e),this.code=void 0,this.details=void 0,this.code=r,this.details=n}}const H5t=/^age:\s*[\d.]+\s*$/im;class zAe{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new NK,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,r,n){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=r,this.callbacks=n,this.loadInternal()}loadInternal(){const{config:e,context:r}=this;if(!e||!r)return;const n=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const o=this.xhrSetup;o?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return o(n,r.url)}).catch(c=>{if(!(this.loader!==n||this.stats.aborted))return n.open("GET",r.url,!0),o(n,r.url)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,r,e)}).catch(c=>{var a;(a=this.callbacks)==null||a.onError({code:n.status,text:c.message},r,n,i)}):this.openAndSendXhr(n,r,e)}openAndSendXhr(e,r,n){e.readyState||e.open("GET",r.url,!0);const i=r.headers,{maxTimeToFirstByteMs:o,maxLoadTimeMs:c}=n.loadPolicy;if(i)for(const a in i)e.setRequestHeader(a,i[a]);r.rangeEnd&&e.setRequestHeader("Range","bytes="+r.rangeStart+"-"+(r.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=r.responseType,self.clearTimeout(this.requestTimeout),n.timeout=o&&pn(o)?o:c,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){const{context:e,loader:r,stats:n}=this;if(!e||!r)return;const i=r.readyState,o=this.config;if(!n.aborted&&i>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),o.timeout!==o.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),o.timeout=o.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),o.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),r.onreadystatechange=null,r.onprogress=null;const p=r.status,y=r.responseType==="text"?r.responseText:null;if(p>=200&&p<300){const k=y??r.response;if(k!=null){var c,a;n.loading.end=Math.max(self.performance.now(),n.loading.first);const P=r.responseType==="arraybuffer"?k.byteLength:k.length;n.loaded=n.total=P,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);const R=(c=this.callbacks)==null?void 0:c.onProgress;R&&R(n,e,k,r);const D={url:r.responseURL,data:k,code:p};(a=this.callbacks)==null||a.onSuccess(D,n,e,r);return}}const v=o.loadPolicy.errorRetry,T=n.retry,E={url:e.url,data:void 0,code:p};if(TO(v,T,!1,E))this.retry(v);else{var f;qs.error(`${p} while loading ${e.url}`),(f=this.callbacks)==null||f.onError({code:p,text:r.statusText},e,r,n)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,r=this.stats.retry;if(TO(e,r,!0))this.retry(e);else{var n;qs.warn(`timeout while loading ${(n=this.context)==null?void 0:n.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:r,stats:n}=this;this.retryDelay=LK(e,n.retry),n.retry++,qs.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${r==null?void 0:r.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const r=this.stats;r.loaded=e.loaded,e.lengthComputable&&(r.total=e.total)}getCacheAge(){let e=null;if(this.loader&&H5t.test(this.loader.getAllResponseHeaders())){const r=this.loader.getResponseHeader("age");e=r?parseFloat(r):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const W5t={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},K5t=Us(Us({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:zAe,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:aOt,bufferController:Z3t,capLevelController:KK,errorController:dOt,fpsController:XFt,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:B2e,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:W5t},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Y5t()),{},{subtitleStreamController:c5t,subtitleTrackController:e5t,timelineController:D5t,audioStreamController:H3t,audioTrackController:W3t,emeController:I1,cmcdController:WFt,contentSteeringController:YFt,interstitialsController:l5t});function Y5t(){return{cueHandler:F5t,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Z5t(t,e,r){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const n=_G(t),i=["manifest","level","frag"],o=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(c=>{const a=`${c==="level"?"playlist":c}LoadPolicy`,f=e[a]===void 0,p=[];o.forEach(y=>{const v=`${c}Loading${y}`,T=e[v];if(T!==void 0&&f){p.push(v);const E=n[a].default;switch(e[a]={default:E},y){case"TimeOut":E.maxLoadTimeMs=T,E.maxTimeToFirstByteMs=T;break;case"MaxRetry":E.errorRetry.maxNumRetry=T,E.timeoutRetry.maxNumRetry=T;break;case"RetryDelay":E.errorRetry.retryDelayMs=T,E.timeoutRetry.retryDelayMs=T;break;case"MaxRetryTimeout":E.errorRetry.maxRetryDelayMs=T,E.timeoutRetry.maxRetryDelayMs=T;break}}}),p.length&&r.warn(`hls.js config: "${p.join('", "')}" setting(s) are deprecated, use "${a}": ${aa(e[a])}`)}),Us(Us({},n),e)}function _G(t){return t&&typeof t=="object"?Array.isArray(t)?t.map(_G):Object.keys(t).reduce((e,r)=>(e[r]=_G(t[r]),e),{}):t}function X5t(t,e){const r=t.loader;r!==Sue&&r!==zAe?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):B5t()&&(t.loader=Sue,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const tD=2,Q5t=.1,J5t=.05,e4t=100;class t4t extends L2e{constructor(e,r){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var n;(n=this.media)!=null&&n.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var n;this.ended=((n=this.media)==null?void 0:n.currentTime)||1,this.hls.trigger(Ce.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=r,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ce.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ce.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,r){this.setInterval(e4t),this.mediaSource=r.mediaSource;const n=this.media=r.media;ru(n,"playing",this.onMediaPlaying),ru(n,"waiting",this.onMediaWaiting),ru(n,"ended",this.onMediaEnded)}onMediaDetaching(e,r){this.clearInterval();const{media:n}=this;n&&(Ru(n,"playing",this.onMediaPlaying),Ru(n,"waiting",this.onMediaWaiting),Ru(n,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,r){this.buffered=r.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const r=this.media.currentTime;this.poll(r,this.lastCurrentTime),this.lastCurrentTime=r}poll(e,r){var n,i;const o=(n=this.hls)==null?void 0:n.config;if(!o)return;const c=this.media;if(!c)return;const{seeking:a}=c,f=this.seeking&&!a,p=!this.seeking&&a,y=c.paused&&!a||c.ended||c.playbackRate===0;if(this.seeking=a,e!==r){r&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,o.nudgeOnVideoHole&&!y&&e>r&&this.nudgeOnVideoHole(e,r)),this.waiting===0&&this.stallResolved(e);return}if(p||f){f&&this.stallResolved(e);return}if(y){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&c.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(Ce.MEDIA_ENDED,{stalled:!1}));return}if(!Ti.getBuffered(c).length){this.nudgeRetry=0;return}const v=Ti.bufferInfo(c,e,0),T=v.nextStart||0,E=this.fragmentTracker;if(a&&E&&this.hls){const W=Tue(this.hls.inFlightFragments,e),Y=v.len>tD,J=!T||W||T-e>tD&&!E.getPartialFragment(e);if(Y||J)return;this.moved=!1}const k=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&E){if(!(v.len>0)&&!T)return;const Y=Math.max(T,v.start||0)-e,Q=!!(k!=null&&k.live)?k.targetduration*2:tD,ee=iL(e,E);if(Y>0&&(Y<=Q||ee)){c.paused||this._trySkipBufferHole(ee);return}}const P=o.detectStallWithCurrentTimeMs,R=self.performance.now(),D=this.waiting;let M=this.stalled;if(M===null)if(D>0&&R-D=P||D)&&this.hls){var V;if(((V=this.mediaSource)==null?void 0:V.readyState)==="ended"&&!(k!=null&&k.live)&&Math.abs(e-((k==null?void 0:k.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(Ce.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(v),!this.media||!this.hls)return}const G=Ti.bufferInfo(c,e,o.maxBufferHole);this._tryFixBufferStall(G,B,e)}stallResolved(e){const r=this.stalled;if(r&&this.hls&&(this.stalled=null,this.stallReported)){const n=self.performance.now()-r;this.log(`playback not stuck anymore @${e}, after ${Math.round(n)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(Ce.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,r){var n;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(n=this.buffered.audio)!=null&&n.length&&i&&i.length>1&&e>i.end(0)){const o=Ti.bufferedInfo(Ti.timeRangesToArray(this.buffered.audio),e,0);if(o.len>1&&r>=o.start){const c=Ti.timeRangesToArray(i),a=Ti.bufferedInfo(c,r,0).bufferedIndex;if(a>-1&&aa)&&y-p<1&&e-p<2){const v=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${p} -> ${y} buffered index: ${f}`);this.warn(v.message),this.media.currentTime+=1e-6;let T=iL(e,this.fragmentTracker);T&&"fragment"in T?T=T.fragment:T||(T=void 0);const E=Ti.bufferInfo(this.media,e,0);this.hls.trigger(Ce.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:v,reason:v.message,frag:T,buffer:E.len,bufferInfo:E})}}}}}_tryFixBufferStall(e,r,n){var i,o;const{fragmentTracker:c,media:a}=this,f=(i=this.hls)==null?void 0:i.config;if(!a||!c||!f)return;const p=(o=this.hls)==null?void 0:o.latestLevelDetails,y=iL(n,c);if((y||p!=null&&p.live&&n1&&e.len>f.maxBufferHole||e.nextStart&&(e.nextStart-nf.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,r){const n=this.fragmentTracker,i=e.nextStart;if(n&&i){const o=n.getFragAtPos(r,Tn.MAIN),c=n.getFragAtPos(i,Tn.MAIN);if(o&&c)return c.sn-o.sn<2}return!1}_reportStall(e){const{hls:r,media:n,stallReported:i,stalled:o}=this;if(!i&&o!==null&&n&&r){this.stallReported=!0;const c=new Error(`Playback stalling at @${n.currentTime} due to low buffer (${aa(e)})`);this.warn(c.message),r.trigger(Ce.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.BUFFER_STALLED_ERROR,fatal:!1,error:c,buffer:e.len,bufferInfo:e,stalled:{start:o}})}}_trySkipBufferHole(e){var r;const{fragmentTracker:n,media:i}=this,o=(r=this.hls)==null?void 0:r.config;if(!i||!n||!o)return 0;const c=i.currentTime,a=Ti.bufferInfo(i,c,0),f=c0&&a.len<1&&i.readyState<3,T=f-c;if(T>0&&(y||v)){if(T>o.maxBufferHole){let k=!1;if(c===0){const P=n.getAppendedFrag(0,Tn.MAIN);P&&f"u"))return self.VTTCue||self.TextTrackCue}function I6(t,e,r,n,i){let o=new t(e,r,"");try{o.value=n,i&&(o.type=i)}catch{o=new t(e,r,aa(i?Us({type:i},n):n))}return o}const sL=(()=>{const t=bG();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class n4t{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(Ce.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(Ce.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ce.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Ce.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Ce.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Ce.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Ce.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ce.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Ce.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Ce.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Ce.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,r){var n;this.media=r.media,((n=r.overrides)==null?void 0:n.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const r=(e=this.hls)==null?void 0:e.latestLevelDetails;r&&this.updateDateRangeCues(r)}onMediaDetaching(e,r){this.media=null,!r.transferMedia&&(this.id3Track&&(this.removeCues&&a1(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const r=this.getID3Track(e.textTracks);return r.mode="hidden",r}getID3Track(e){if(this.media){for(let r=0;rsL&&(v=sL),v-y<=0&&(v=y+r4t);for(let E=0;Ey.type===od.audioId3&&f:i==="video"?p=y=>y.type===od.emsg&&a:p=y=>y.type===od.audioId3&&f||y.type===od.emsg&&a,xG(o,r,n,p)}}onLevelUpdated(e,{details:r}){this.updateDateRangeCues(r,!0)}onLevelPtsUpdated(e,r){Math.abs(r.drift)>.01&&this.updateDateRangeCues(r.details)}updateDateRangeCues(e,r){if(!this.hls||!this.media)return;const{assetPlayerId:n,timelineOffset:i,enableDateRangeMetadataCues:o,interstitialsController:c}=this.hls.config;if(!o)return;const a=bG();if(n&&i&&!c){const{fragmentStart:P,fragmentEnd:R}=e;let D=this.assetCue;D?(D.startTime=P,D.endTime=R):a&&(D=this.assetCue=I6(a,P,R,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),D&&(D.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(D),D.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:f}=this,{dateRanges:p}=e,y=Object.keys(p);let v=this.dateRangeCuesAppended;if(f&&r){var T;if((T=f.cues)!=null&&T.length){const P=Object.keys(v).filter(R=>!y.includes(R));for(let R=P.length;R--;){var E;const D=P[R],M=(E=v[D])==null?void 0:E.cues;delete v[D],M&&Object.keys(M).forEach(B=>{const V=M[B];if(V){V.removeEventListener("enter",this.onEventCueEnter);try{f.removeCue(V)}catch{}}})}}else v=this.dateRangeCuesAppended={}}const k=e.fragments[e.fragments.length-1];if(!(y.length===0||!pn(k==null?void 0:k.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let P=0;P{if(pe!==D.id){const Se=p[pe];if(Se.class===D.class&&Se.startDate>D.startDate&&(!le||D.startDate.01&&(pe.startTime=M,pe.endTime=W);else if(a){let Se=D.attr[le];EOt(le)&&(Se=m2e(Se));const Le=I6(a,M,W,{key:le,data:Se},od.dateRange);Le&&(Le.id=R,this.id3Track.addCue(Le),V[le]=Le,c&&(le==="X-ASSET-LIST"||le==="X-ASSET-URL")&&Le.addEventListener("enter",this.onEventCueEnter))}}v[R]={cues:V,dateRange:D,durationKnown:G}}}}}class i4t{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:r}=this,n=this.levelDetails;if(!r||!n)return;this.currentTime=r.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:o,maxLiveSyncPlaybackRate:c}=this.config;if(!o||c===1||!n.live)return;const a=this.targetLatency;if(a===null)return;const f=i-a,p=Math.min(this.maxLatency,a+n.targetduration);if(f.05&&this.forwardBufferLength>1){const v=Math.min(2,Math.max(1,c)),T=Math.round(2/(1+Math.exp(-.75*f-this.edgeStalled))*20)/20,E=Math.min(v,Math.max(1,T));this.changeMediaPlaybackRate(r,E)}else r.playbackRate!==1&&r.playbackRate!==0&&this.changeMediaPlaybackRate(r,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const r=this.levelDetails;return r?e.liveMaxLatencyDurationCount*r.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:r,partHoldBack:n,targetduration:i}=e,{liveSyncDuration:o,liveSyncDurationCount:c,lowLatencyMode:a}=this.config,f=this.hls.userConfig;let p=a&&n||r;(this._targetLatencyUpdated||f.liveSyncDuration||f.liveSyncDurationCount||p===0)&&(p=o!==void 0?o:c*i);const y=i;return p+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,y)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),r=this.targetLatency;if(e===null||r===null)return null;const n=this.levelDetails;if(n===null)return null;const i=n.edge,o=e-r-this.edgeStalled,c=i-n.totalduration,a=i-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(c,o),a)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const r=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-r,0)}get forwardBufferLength(){const{media:e}=this,r=this.levelDetails;if(!e||!r)return 0;const n=e.buffered.length;return(n?e.buffered.end(n-1):r.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ce.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Ce.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Ce.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Ce.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ce.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Ce.ERROR,this.onError,this))}onMediaAttached(e,r){this.media=r.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:r}){r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,r){var n;r.details===Jt.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(n=this.levelDetails)!=null&&n.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,r){var n,i;e.playbackRate!==r&&((n=this.hls)==null||n.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${r}`),e.playbackRate=r)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class s4t extends WK{constructor(e,r){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=r,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ce.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Ce.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Ce.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Ce.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Ce.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ce.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Ce.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Ce.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Ce.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Ce.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(r=>{r.loadError=0,r.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,r){this.resetLevels()}onManifestLoaded(e,r){const n=this.hls.config.preferManagedMediaSource,i=[],o={},c={};let a=!1,f=!1,p=!1;r.levels.forEach(y=>{const v=y.attrs;let{audioCodec:T,videoCodec:E}=y;T&&(y.audioCodec=T=_O(T,n)||void 0),E&&(E=y.videoCodec=zMt(E));const{width:k,height:P,unknownCodecs:R}=y,D=(R==null?void 0:R.length)||0;if(a||(a=!!(k&&P)),f||(f=!!E),p||(p=!!T),D||T&&!this.isAudioSupported(T)||E&&!this.isVideoSupported(E)){this.log(`Some or all CODECS not supported "${v.CODECS}"`);return}const{CODECS:M,"FRAME-RATE":B,"HDCP-LEVEL":V,"PATHWAY-ID":G,RESOLUTION:W,"VIDEO-RANGE":Y}=v,Q=`${`${G||"."}-`}${y.bitrate}-${W}-${B}-${M}-${Y}-${V}`;if(o[Q])if(o[Q].uri!==y.url&&!y.attrs["PATHWAY-ID"]){const ee=c[Q]+=1;y.attrs["PATHWAY-ID"]=new Array(ee+1).join(".");const le=this.createLevel(y);o[Q]=le,i.push(le)}else o[Q].addGroupId("audio",v.AUDIO),o[Q].addGroupId("text",v.SUBTITLES);else{const ee=this.createLevel(y);o[Q]=ee,c[Q]=1,i.push(ee)}}),this.filterAndSortMediaOptions(i,r,a,f,p)}createLevel(e){const r=new sC(e),n=e.supplemental;if(n!=null&&n.videoCodec&&!this.isVideoSupported(n.videoCodec)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(i.message),r.supportedResult=j2e(i,[])}return r}isAudioSupported(e){return nC(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return nC(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,r,n,i,o){var c;let a=[],f=[],p=e;const y=((c=r.stats)==null?void 0:c.parsing)||{};if((n||i)&&o&&(p=p.filter(({videoCodec:M,videoRange:B,width:V,height:G})=>(!!M||!!(V&&G))&&XMt(B))),p.length===0){Promise.resolve().then(()=>{if(this.hls){let M="no level with compatible codecs found in manifest",B=M;r.levels.length&&(B=`one or more CODECS in variant not supported: ${aa(r.levels.map(G=>G.attrs.CODECS).filter((G,W,Y)=>Y.indexOf(G)===W))}`,this.warn(B),M+=` (${B})`);const V=new Error(M);this.hls.trigger(Ce.ERROR,{type:Dn.MEDIA_ERROR,details:Jt.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:r.url,error:V,reason:B})}}),y.end=performance.now();return}r.audioTracks&&(a=r.audioTracks.filter(M=>!M.audioCodec||this.isAudioSupported(M.audioCodec)),jue(a)),r.subtitles&&(f=r.subtitles,jue(f));const v=p.slice(0);p.sort((M,B)=>{if(M.attrs["HDCP-LEVEL"]!==B.attrs["HDCP-LEVEL"])return(M.attrs["HDCP-LEVEL"]||"")>(B.attrs["HDCP-LEVEL"]||"")?1:-1;if(n&&M.height!==B.height)return M.height-B.height;if(M.frameRate!==B.frameRate)return M.frameRate-B.frameRate;if(M.videoRange!==B.videoRange)return bO.indexOf(M.videoRange)-bO.indexOf(B.videoRange);if(M.videoCodec!==B.videoCodec){const V=yce(M.videoCodec),G=yce(B.videoCodec);if(V!==G)return G-V}if(M.uri===B.uri&&M.codecSet!==B.codecSet){const V=vO(M.codecSet),G=vO(B.codecSet);if(V!==G)return G-V}return M.averageBitrate!==B.averageBitrate?M.averageBitrate-B.averageBitrate:0});let T=v[0];if(this.steering&&(p=this.steering.filterParsedLevels(p),p.length!==v.length)){for(let M=0;MV&&V===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=G)}break}const k=o&&!i,P=this.hls.config,R=!!(P.audioStreamController&&P.audioTrackController),D={levels:p,audioTracks:a,subtitleTracks:f,sessionData:r.sessionData,sessionKeys:r.sessionKeys,firstLevel:this._firstLevel,stats:r.stats,audio:o,video:i,altAudio:R&&!k&&a.some(M=>!!M.url)};y.end=performance.now(),this.hls.trigger(Ce.MANIFEST_PARSED,D)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const r=this._levels;if(r.length===0)return;if(e<0||e>=r.length){const y=new Error("invalid level idx"),v=e<0;if(this.hls.trigger(Ce.ERROR,{type:Dn.OTHER_ERROR,details:Jt.LEVEL_SWITCH_ERROR,level:e,fatal:v,error:y,reason:y.message}),v)return;e=Math.min(e,r.length-1)}const n=this.currentLevelIndex,i=this.currentLevel,o=i?i.attrs["PATHWAY-ID"]:void 0,c=r[e],a=c.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=c,n===e&&i&&o===a)return;this.log(`Switching to level ${e} (${c.height?c.height+"p ":""}${c.videoRange?c.videoRange+" ":""}${c.codecSet?c.codecSet+" ":""}@${c.bitrate})${a?" with Pathway "+a:""} from level ${n}${o?" with Pathway "+o:""}`);const f={level:e,attrs:c.attrs,details:c.details,bitrate:c.bitrate,averageBitrate:c.averageBitrate,maxBitrate:c.maxBitrate,realBitrate:c.realBitrate,width:c.width,height:c.height,codecSet:c.codecSet,audioCodec:c.audioCodec,videoCodec:c.videoCodec,audioGroups:c.audioGroups,subtitleGroups:c.subtitleGroups,loaded:c.loaded,loadError:c.loadError,fragmentError:c.fragmentError,name:c.name,id:c.id,uri:c.uri,url:c.url,urlId:0,audioGroupIds:c.audioGroupIds,textGroupIds:c.textGroupIds};this.hls.trigger(Ce.LEVEL_SWITCHING,f);const p=c.details;if(!p||p.live){const y=this.switchParams(c.uri,i==null?void 0:i.details,p);this.loadPlaylist(y)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const r=this.steering.pathways(),n=e.filter(i=>r.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${r}`);return}this.steering.pathwayPriority=n}}onError(e,r){r.fatal||!r.context||r.context.type===Wi.LEVEL&&r.context.level===this.level&&this.checkRetry(r)}onFragBuffered(e,{frag:r}){if(r!==void 0&&r.type===Tn.MAIN){const n=r.elementaryStreams;if(!Object.keys(n).some(o=>!!n[o]))return;const i=this._levels[r.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,r){var n;const{level:i,details:o}=r,c=r.levelInfo;if(!c){var a;this.warn(`Invalid level index ${i}`),(a=r.deliveryDirectives)!=null&&a.skip&&(o.deltaUpdateFailed=!0);return}if(c===this.currentLevel||r.withoutMultiVariant){c.fragmentError===0&&(c.loadError=0);let f=c.details;f===r.details&&f.advanced&&(f=void 0),this.playlistLoaded(i,r,f)}else(n=r.deliveryDirectives)!=null&&n.skip&&(o.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,r){super.loadingPlaylist(e,r);const n=this.getUrlWithDirectives(e.uri,r),i=this.currentLevelIndex,o=e.attrs["PATHWAY-ID"],c=e.details,a=c==null?void 0:c.age;this.log(`Loading level index ${i}${(r==null?void 0:r.msn)!==void 0?" at sn "+r.msn+" part "+r.part:""}${o?" Pathway "+o:""}${a&&c.live?" age "+a.toFixed(1)+(c.type&&" "+c.type||""):""} ${n}`),this.hls.trigger(Ce.LEVEL_LOADING,{url:n,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var r;if(this._levels.length===1)return;const n=this._levels.filter((o,c)=>c!==e?!0:(this.steering&&this.steering.removeLevel(o),o===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,o.details&&o.details.fragments.forEach(a=>a.level=-1)),!1));W2e(n),this._levels=n,this.currentLevelIndex>-1&&(r=this.currentLevel)!=null&&r.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=n.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(Ce.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:r}){this._levels=r}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:r,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(Ce.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}}function jue(t){const e={};t.forEach(r=>{const n=r.groupId||"";r.id=e[n]=e[n]||0,e[n]++})}function UAe(){return self.SourceBuffer||self.WebKitSourceBuffer}function VAe(){if(!Ex())return!1;const e=UAe();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function a4t(){if(!VAe())return!1;const t=Ex();return typeof(t==null?void 0:t.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(iC(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(iC(e,"audio"))))}function o4t(){var t;const e=UAe();return typeof(e==null||(t=e.prototype)==null?void 0:t.changeType)=="function"}const l4t=100;class c4t extends BK{constructor(e,r,n){super(e,r,n,"stream-controller",Tn.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const i=this.media,o=i?i.currentTime:null;if(o===null||!pn(o)||(this.log(`Media seeked to ${o.toFixed(3)}`),!this.getBufferedFrag(o)))return;const c=this.getFwdBufferInfoAtPos(i,o,Tn.MAIN,0);if(c===null||c.len===0){this.warn(`Main forward buffer length at ${o} on "seeked" event ${c?c.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Ce.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Ce.LEVEL_LOADING,this.onLevelLoading,this),e.on(Ce.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Ce.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Ce.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Ce.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Ce.BUFFER_CREATED,this.onBufferCreated,this),e.on(Ce.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Ce.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Ce.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Ce.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Ce.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Ce.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Ce.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Ce.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Ce.BUFFER_CREATED,this.onBufferCreated,this),e.off(Ce.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Ce.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Ce.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,r){if(this.levels){const{lastCurrentTime:n,hls:i}=this;if(this.stopLoad(),this.setInterval(l4t),this.level=-1,!this.startFragRequested){let o=i.startLevel;o===-1&&(i.config.testBandwidth&&this.levels.length>1?(o=0,this.bitrateTest=!0):o=i.firstAutoLevel),i.nextLoadLevel=o,this.level=i.loadLevel,this._hasEnoughToStart=!!r}n>0&&e===-1&&!r&&(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n),this.state=wr.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=r?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=wr.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case wr.WAITING_LEVEL:{const{levels:e,level:r}=this,n=e==null?void 0:e[r],i=n==null?void 0:n.details;if(i&&(!i.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(i))break;this.state=wr.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=wr.IDLE;break}break}case wr.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===wr.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:r,levels:n,media:i}=this;if(r===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const o=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(n!=null&&n[o]))return;const c=n[o],a=this.getMainFwdBufferInfo();if(a===null)return;const f=this.getLevelDetails();if(f&&this._streamEnded(a,f)){const P={};this.altAudio===2&&(P.type="video"),this.hls.trigger(Ce.BUFFER_EOS,P),this.state=wr.ENDED;return}if(!this.buffering)return;e.loadLevel!==o&&e.manualLevel===-1&&this.log(`Adapting to level ${o} from level ${this.level}`),this.level=e.nextLoadLevel=o;const p=c.details;if(!p||this.state===wr.WAITING_LEVEL||this.waitForLive(c)){this.level=o,this.state=wr.WAITING_LEVEL,this.startFragRequested=!1;return}const y=a.len,v=this.getMaxBufferLength(c.maxBitrate);if(y>=v)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const T=this.backtrackFragment?this.backtrackFragment.start:a.end;let E=this.getNextFragment(T,p);if(this.couldBacktrack&&!this.fragPrevious&&E&&Io(E)&&this.fragmentTracker.getState(E)!==dl.OK){var k;const R=((k=this.backtrackFragment)!=null?k:E).sn-p.startSN,D=p.fragments[R-1];D&&E.cc===D.cc&&(E=D,this.fragmentTracker.removeFragment(D))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(E&&this.isLoopLoading(E,T)){if(!E.gap){const R=this.audioOnly&&!this.altAudio?na.AUDIO:na.VIDEO,D=(R===na.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;D&&this.afterBufferFlushed(D,R,Tn.MAIN)}E=this.getNextFragmentLoopLoading(E,p,a,Tn.MAIN,v)}E&&(this.exceedsMaxBuffer(a,v,E)||(E.initSegment&&!E.initSegment.data&&!this.bitrateTest&&(E=E.initSegment),this.loadFragment(E,c,T)))}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);i===dl.NOT_LOADED||i===dl.PARTIAL?Io(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,r)):super.loadFragment(e,r,n):this._loadInitSegment(e,r):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Tn.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:e,media:r}=this;if(r!=null&&r.readyState){let n;const i=this.getAppendedFrag(r.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const o=this.getLevelDetails();if(o!=null&&o.live){const a=this.getMainFwdBufferInfo();if(!a||a.len=c-r.maxFragLookUpTolerance&&o<=a;if(i!==null&&n.duration>i&&(o{this.hls&&this.hls.trigger(Ce.AUDIO_TRACK_SWITCHED,r)}),n.trigger(Ce.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}n.trigger(Ce.AUDIO_TRACK_SWITCHED,r)}}onAudioTrackSwitched(e,r){const n=wO(r.url,this.hls);if(n){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=n?2:0,this.tick()}onBufferCreated(e,r){const n=r.tracks;let i,o,c=!1;for(const a in n){const f=n[a];if(f.id==="main"){if(o=a,i=f,a==="video"){const p=n[a];p&&(this.videoBuffer=p.buffer)}}else c=!0}c&&i?(this.log(`Alternate track found, use ${o}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,r){const{frag:n,part:i}=r,o=n.type===Tn.MAIN;if(o){if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${i?" p: "+i.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===wr.PARSED&&(this.state=wr.IDLE);return}const a=i?i.stats:n.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),Io(n)&&(this.fragPrevious=n),this.fragBufferedComplete(n,i)}const c=this.media;c&&(!this._hasEnoughToStart&&Ti.getBuffered(c).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),o&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,r){var n;if(r.fatal){this.state=wr.ERROR;return}switch(r.details){case Jt.FRAG_GAP:case Jt.FRAG_PARSING_ERROR:case Jt.FRAG_DECRYPT_ERROR:case Jt.FRAG_LOAD_ERROR:case Jt.FRAG_LOAD_TIMEOUT:case Jt.KEY_LOAD_ERROR:case Jt.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Tn.MAIN,r);break;case Jt.LEVEL_LOAD_ERROR:case Jt.LEVEL_LOAD_TIMEOUT:case Jt.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===wr.WAITING_LEVEL&&((n=r.context)==null?void 0:n.type)===Wi.LEVEL&&(this.state=wr.IDLE);break;case Jt.BUFFER_ADD_CODEC_ERROR:case Jt.BUFFER_APPEND_ERROR:if(r.parent!=="main")return;this.reduceLengthAndFlushBuffer(r)&&this.resetLoadingState();break;case Jt.BUFFER_FULL_ERROR:if(r.parent!=="main")return;this.reduceLengthAndFlushBuffer(r)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case Jt.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onFragLoadEmergencyAborted(){this.state=wr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:r}){if(r!==na.AUDIO||!this.altAudio){const n=(r===na.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;n&&(this.afterBufferFlushed(n,r,Tn.MAIN),this.tick())}}onLevelsUpdated(e,r){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=r.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const r=e.currentTime;let n=this.startPosition;if(n>=0&&r0&&(f{const{hls:i}=this,o=n==null?void 0:n.frag;if(!o||this.fragContextChanged(o))return;r.fragmentError=0,this.state=wr.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const c=o.stats;c.parsing.start=c.parsing.end=c.buffering.start=c.buffering.end=self.performance.now(),i.trigger(Ce.FRAG_LOADED,n),o.bitrateTest=!1}).catch(n=>{this.state===wr.STOPPED||this.state===wr.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const r=this.playlistType,{hls:n}=this,{remuxResult:i,chunkMeta:o}=e,c=this.getCurrentContext(o);if(!c){this.resetWhenMissingContext(o);return}const{frag:a,part:f,level:p}=c,{video:y,text:v,id3:T,initSegment:E}=i,{details:k}=p,P=this.altAudio?void 0:i.audio;if(this.fragContextChanged(a)){this.fragmentTracker.removeFragment(a);return}if(this.state=wr.PARSING,E){const R=E.tracks;if(R){const V=a.initSegment||a;if(this.unhandledEncryptionError(E,a))return;this._bufferInitSegment(p,R,V,o),n.trigger(Ce.FRAG_PARSING_INIT_SEGMENT,{frag:V,id:r,tracks:R})}const D=E.initPTS,M=E.timescale,B=this.initPTS[a.cc];if(pn(D)&&(!B||B.baseTime!==D||B.timescale!==M)){const V=E.trackId;this.initPTS[a.cc]={baseTime:D,timescale:M,trackId:V},n.trigger(Ce.INIT_PTS_FOUND,{frag:a,id:r,initPTS:D,timescale:M,trackId:V})}}if(y&&k){P&&y.type==="audiovideo"&&this.logMuxedErr(a);const R=k.fragments[a.sn-1-k.startSN],D=a.sn===k.startSN,M=!R||a.cc>R.cc;if(i.independent!==!1){const{startPTS:B,endPTS:V,startDTS:G,endDTS:W}=y;if(f)f.elementaryStreams[y.type]={startPTS:B,endPTS:V,startDTS:G,endDTS:W};else if(y.firstKeyFrame&&y.independent&&o.id===1&&!M&&(this.couldBacktrack=!0),y.dropped&&y.independent){const Y=this.getMainFwdBufferInfo(),J=(Y?Y.end:this.getLoadPosition())+this.config.maxBufferHole,Q=y.firstKeyFramePTS?y.firstKeyFramePTS:B;if(!D&&JtD&&(a.gap=!0);a.setElementaryStreamInfo(y.type,B,V,G,W),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(y,a,f,o,D||M)}else if(D||M)a.gap=!0;else{this.backtrack(a);return}}if(P){const{startPTS:R,endPTS:D,startDTS:M,endDTS:B}=P;f&&(f.elementaryStreams[na.AUDIO]={startPTS:R,endPTS:D,startDTS:M,endDTS:B}),a.setElementaryStreamInfo(na.AUDIO,R,D,M,B),this.bufferFragmentData(P,a,f,o)}if(k&&T!=null&&T.samples.length){const R={id:r,frag:a,details:k,samples:T.samples};n.trigger(Ce.FRAG_PARSING_METADATA,R)}if(k&&v){const R={id:r,frag:a,details:k,samples:v.samples};n.trigger(Ce.FRAG_PARSING_USERDATA,R)}}logMuxedErr(e){this.warn(`${Io(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,r,n,i){if(this.state!==wr.PARSING)return;this.audioOnly=!!r.audio&&!r.video,this.altAudio&&!this.audioOnly&&(delete r.audio,r.audiovideo&&this.logMuxedErr(n));const{audio:o,video:c,audiovideo:a}=r;if(o){const p=e.audioCodec;let y=KL(o.codec,p);y==="mp4a"&&(y="mp4a.40.5");const v=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){y&&(y.indexOf("mp4a.40.5")!==-1?y="mp4a.40.2":y="mp4a.40.5");const T=o.metadata;T&&"channelCount"in T&&(T.channelCount||1)!==1&&v.indexOf("firefox")===-1&&(y="mp4a.40.5")}y&&y.indexOf("mp4a.40.5")!==-1&&v.indexOf("android")!==-1&&o.container!=="audio/mpeg"&&(y="mp4a.40.2",this.log(`Android: force audio codec to ${y}`)),p&&p!==y&&this.log(`Swapping manifest audio codec "${p}" for "${y}"`),o.levelCodec=y,o.id=Tn.MAIN,this.log(`Init audio buffer, container:${o.container}, codecs[selected/level/parsed]=[${y||""}/${p||""}/${o.codec}]`),delete r.audiovideo}if(c){c.levelCodec=e.videoCodec,c.id=Tn.MAIN;const p=c.codec;if((p==null?void 0:p.length)===4)switch(p){case"hvc1":case"hev1":c.codec="hvc1.1.6.L120.90";break;case"av01":c.codec="av01.0.04M.08";break;case"avc1":c.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${c.container}, codecs[level/parsed]=[${e.videoCodec||""}/${p}]${c.codec!==p?" parsed-corrected="+c.codec:""}${c.supplemental?" supplemental="+c.supplemental:""}`),delete r.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete r.video,delete r.audio);const f=Object.keys(r);if(f.length){if(this.hls.trigger(Ce.BUFFER_CODECS,r),!this.hls)return;f.forEach(p=>{const v=r[p].initSegment;v!=null&&v.byteLength&&this.hls.trigger(Ce.BUFFER_APPENDING,{type:p,data:v,frag:n,part:null,chunkMeta:i,parent:n.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,Tn.MAIN)}get maxBufferLength(){const{levels:e,level:r}=this,n=e==null?void 0:e[r];return n?this.getMaxBufferLength(n.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=wr.IDLE}checkFragmentChanged(){const e=this.media;let r=null;if(e&&e.readyState>1&&e.seeking===!1){const n=e.currentTime;if(Ti.isBuffered(e,n)?r=this.getAppendedFrag(n):Ti.isBuffered(e,n+.1)&&(r=this.getAppendedFrag(n+.1)),r){this.backtrackFragment=null;const i=this.fragPlaying,o=r.level;(!i||r.sn!==i.sn||i.level!==o)&&(this.fragPlaying=r,this.hls.trigger(Ce.FRAG_CHANGED,{frag:r}),(!i||i.level!==o)&&this.hls.trigger(Ce.LEVEL_SWITCHED,{level:o}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const r=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return pn(r)?this.getAppendedFrag(r):null}get currentProgramDateTime(){var e;const r=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(pn(r)){const n=this.getLevelDetails(),i=this.currentFrag||(n?g_(null,n.fragments,r):null);if(i){const o=i.programDateTime;if(o!==null){const c=o+(r-i.start)*1e3;return new Date(c)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class u4t extends _h{constructor(e,r){super("key-loader",r),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const n in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[n].loader;if(i){var r;if(e&&e!==((r=i.context)==null?void 0:r.frag.type))return;i.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[e];(r.mediaKeySessionContext||r.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[e].loader;r&&r.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,r=Jt.KEY_LOAD_ERROR,n,i,o){return new Ap({type:Dn.NETWORK_ERROR,details:r,fatal:!1,frag:e,response:o,error:n,networkDetails:i})}loadClear(e,r,n){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(r.length)for(let i=0,o=r.length;i{if(!this.emeController)return;c.setKeyFormat(a);const f=ZL(a);if(f)return this.emeController.getKeySystemAccess([f])})}if(this.config.requireKeySystemAccessOnStart){const i=W2(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(r=>this.loadInternal(e,r)):this.loadInternal(e)}loadInternal(e,r){var n,i;r&&e.setKeyFormat(r);const o=e.decryptdata;if(!o){const p=new Error(r?`Expected frag.decryptdata to be defined after setting format ${r}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,Jt.KEY_LOAD_ERROR,p))}const c=o.uri;if(!c)return Promise.reject(this.createKeyLoadError(e,Jt.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${c}"`)));const a=P6(o);let f=this.keyIdToKeyInfo[a];if((n=f)!=null&&n.decryptdata.key)return o.key=f.decryptdata.key,Promise.resolve({frag:e,keyInfo:f});if(this.emeController&&(i=f)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(f.decryptdata)){case"usable":case"usable-in-future":return f.keyLoadPromise.then(y=>{const{keyInfo:v}=y;return o.key=v.decryptdata.key,{frag:e,keyInfo:v}})}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${o.keyId?" keyId: "+Xl(o.keyId):""} URI: ${o.uri} from ${e.type} ${e.level}`),f=this.keyIdToKeyInfo[a]={decryptdata:o,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},o.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return o.keyFormat==="identity"?this.loadKeyHTTP(f,e):this.loadKeyEME(f,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(f,e);default:return Promise.reject(this.createKeyLoadError(e,Jt.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${o.method}"`)))}}loadKeyEME(e,r){const n={frag:r,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=r.initSegment)!=null&&i.data){const c=CMt(r.initSegment.data);if(c.length){let a=c[0];a.some(f=>f!==0)?(this.log(`Using keyId found in init segment ${Xl(a)}`),ox.setKeyIdForUri(e.decryptdata.uri,a)):(a=ox.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Xl(a)}`)),e.decryptdata.keyId=a}}if(!e.decryptdata.keyId&&!Io(r))return Promise.resolve(n);const o=this.emeController.loadKey(n);return(e.keyLoadPromise=o.then(c=>(e.mediaKeySessionContext=c,n))).catch(c=>{throw e.keyLoadPromise=null,"data"in c&&(c.data.frag=r),c})}return Promise.resolve(n)}loadKeyHTTP(e,r){const n=this.config,i=n.loader,o=new i(n);return r.keyLoader=e.loader=o,e.keyLoadPromise=new Promise((c,a)=>{const f={keyInfo:e,frag:r,responseType:"arraybuffer",url:e.decryptdata.uri},p=n.keyLoadPolicy.default,y={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},v={onSuccess:(T,E,k,P)=>{const{frag:R,keyInfo:D}=k,M=P6(D.decryptdata);if(!R.decryptdata||D!==this.keyIdToKeyInfo[M])return a(this.createKeyLoadError(R,Jt.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),P));D.decryptdata.key=R.decryptdata.key=new Uint8Array(T.data),R.keyLoader=null,D.loader=null,c({frag:R,keyInfo:D})},onError:(T,E,k,P)=>{this.resetLoader(E),a(this.createKeyLoadError(r,Jt.KEY_LOAD_ERROR,new Error(`HTTP Error ${T.code} loading key ${T.text}`),k,Us({url:f.url,data:void 0},T)))},onTimeout:(T,E,k)=>{this.resetLoader(E),a(this.createKeyLoadError(r,Jt.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),k))},onAbort:(T,E,k)=>{this.resetLoader(E),a(this.createKeyLoadError(r,Jt.INTERNAL_ABORTED,new Error("key loading aborted"),k))}};o.load(f,y,v)})}resetLoader(e){const{frag:r,keyInfo:n,url:i}=e,o=n.loader;r.keyLoader===o&&(r.keyLoader=null,n.loader=null);const c=P6(n.decryptdata)||i;delete this.keyIdToKeyInfo[c],o&&o.destroy()}}function P6(t){if(t.keyFormat!==Ql.FAIRPLAY){const e=t.keyId;if(e)return Xl(e)}return t.uri}function Aue(t){const{type:e}=t;switch(e){case Wi.AUDIO_TRACK:return Tn.AUDIO;case Wi.SUBTITLE_TRACK:return Tn.SUBTITLE;default:return Tn.MAIN}}function R6(t,e){let r=t.url;return(r===void 0||r.indexOf("data:")===0)&&(r=e.url),r}class d4t{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ce.LEVEL_LOADING,this.onLevelLoading,this),e.on(Ce.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Ce.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(Ce.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(Ce.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ce.LEVEL_LOADING,this.onLevelLoading,this),e.off(Ce.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Ce.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(Ce.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const r=this.hls.config,n=r.pLoader,i=r.loader,o=n||i,c=new o(r);return this.loaders[e.type]=c,c}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const r=this.loaders[e];r&&r.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,r){const{url:n}=r;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Wi.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,r){const{id:n,level:i,pathwayId:o,url:c,deliveryDirectives:a,levelInfo:f}=r;this.load({id:n,level:i,pathwayId:o,responseType:"text",type:Wi.LEVEL,url:c,deliveryDirectives:a,levelOrTrack:f})}onAudioTrackLoading(e,r){const{id:n,groupId:i,url:o,deliveryDirectives:c,track:a}=r;this.load({id:n,groupId:i,level:null,responseType:"text",type:Wi.AUDIO_TRACK,url:o,deliveryDirectives:c,levelOrTrack:a})}onSubtitleTrackLoading(e,r){const{id:n,groupId:i,url:o,deliveryDirectives:c,track:a}=r;this.load({id:n,groupId:i,level:null,responseType:"text",type:Wi.SUBTITLE_TRACK,url:o,deliveryDirectives:c,levelOrTrack:a})}onLevelsUpdated(e,r){const n=this.loaders[Wi.LEVEL];if(n){const i=n.context;i&&!r.levels.some(o=>o===i.levelOrTrack)&&(n.abort(),delete this.loaders[Wi.LEVEL])}}load(e){var r;const n=this.hls.config;let i=this.getInternalLoader(e);if(i){const p=this.hls.logger,y=i.context;if(y&&y.levelOrTrack===e.levelOrTrack&&(y.url===e.url||y.deliveryDirectives&&!e.deliveryDirectives)){y.url===e.url?p.log(`[playlist-loader]: ignore ${e.url} ongoing request`):p.log(`[playlist-loader]: ignore ${e.url} in favor of ${y.url}`);return}p.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let o;if(e.type===Wi.MANIFEST?o=n.manifestLoadPolicy.default:o=Js({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),pn((r=e.deliveryDirectives)==null?void 0:r.part)){let p;if(e.type===Wi.LEVEL&&e.level!==null?p=this.hls.levels[e.level].details:e.type===Wi.AUDIO_TRACK&&e.id!==null?p=this.hls.audioTracks[e.id].details:e.type===Wi.SUBTITLE_TRACK&&e.id!==null&&(p=this.hls.subtitleTracks[e.id].details),p){const y=p.partTarget,v=p.targetduration;if(y&&v){const T=Math.max(y*3,v*.8)*1e3;o=Js({},o,{maxTimeToFirstByteMs:Math.min(T,o.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(T,o.maxTimeToFirstByteMs)})}}}const c=o.errorRetry||o.timeoutRetry||{},a={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:c.maxNumRetry||0,retryDelay:c.retryDelayMs||0,maxRetryDelay:c.maxRetryDelayMs||0},f={onSuccess:(p,y,v,T)=>{const E=this.getInternalLoader(v);this.resetInternalLoader(v.type);const k=p.data;y.parsing.start=performance.now(),hm.isMediaPlaylist(k)||v.type!==Wi.MANIFEST?this.handleTrackOrLevelPlaylist(p,y,v,T||null,E):this.handleMasterPlaylist(p,y,v,T)},onError:(p,y,v,T)=>{this.handleNetworkError(y,v,!1,p,T)},onTimeout:(p,y,v)=>{this.handleNetworkError(y,v,!0,void 0,p)}};i.load(e,a,f)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:r},forceStartLoad:n}=this.hls;(e||n)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${r}`),this.hls.startLoad(r))}handleMasterPlaylist(e,r,n,i){const o=this.hls,c=e.data,a=R6(e,n),f=hm.parseMasterPlaylist(c,a);if(f.playlistParsingError){r.parsing.end=performance.now(),this.handleManifestParsingError(e,n,f.playlistParsingError,i,r);return}const{contentSteering:p,levels:y,sessionData:v,sessionKeys:T,startTimeOffset:E,variableList:k}=f;this.variableList=k,y.forEach(M=>{const{unknownCodecs:B}=M;if(B){const{preferManagedMediaSource:V}=this.hls.config;let{audioCodec:G,videoCodec:W}=M;for(let Y=B.length;Y--;){const J=B[Y];nC(J,"audio",V)?(M.audioCodec=G=G?`${G},${J}`:J,qS.audio[G.substring(0,4)]=2,B.splice(Y,1)):nC(J,"video",V)&&(M.videoCodec=W=W?`${W},${J}`:J,qS.video[W.substring(0,4)]=2,B.splice(Y,1))}}});const{AUDIO:P=[],SUBTITLES:R,"CLOSED-CAPTIONS":D}=hm.parseMasterPlaylistMedia(c,a,f);P.length&&!P.some(B=>!B.url)&&y[0].audioCodec&&!y[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),P.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Qa({}),bitrate:0,url:""})),o.trigger(Ce.MANIFEST_LOADED,{levels:y,audioTracks:P,subtitles:R,captions:D,contentSteering:p,url:a,stats:r,networkDetails:i,sessionData:v,sessionKeys:T,startTimeOffset:E,variableList:k})}handleTrackOrLevelPlaylist(e,r,n,i,o){const c=this.hls,{id:a,level:f,type:p}=n,y=R6(e,n),v=pn(f)?f:pn(a)?a:0,T=Aue(n),E=hm.parseLevelPlaylist(e.data,y,v,T,0,this.variableList);if(p===Wi.MANIFEST){const k={attrs:new Qa({}),bitrate:0,details:E,name:"",url:y};E.requestScheduled=r.loading.start+q2e(E,0),c.trigger(Ce.MANIFEST_LOADED,{levels:[k],audioTracks:[],url:y,stats:r,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}r.parsing.end=performance.now(),n.levelDetails=E,this.handlePlaylistLoaded(E,e,r,n,i,o)}handleManifestParsingError(e,r,n,i,o){this.hls.trigger(Ce.ERROR,{type:Dn.NETWORK_ERROR,details:Jt.MANIFEST_PARSING_ERROR,fatal:r.type===Wi.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:r,networkDetails:i,stats:o})}handleNetworkError(e,r,n=!1,i,o){let c=`A network ${n?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===Wi.LEVEL?c+=`: ${e.level} id: ${e.id}`:(e.type===Wi.AUDIO_TRACK||e.type===Wi.SUBTITLE_TRACK)&&(c+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(c);this.hls.logger.warn(`[playlist-loader]: ${c}`);let f=Jt.UNKNOWN,p=!1;const y=this.getInternalLoader(e);switch(e.type){case Wi.MANIFEST:f=n?Jt.MANIFEST_LOAD_TIMEOUT:Jt.MANIFEST_LOAD_ERROR,p=!0;break;case Wi.LEVEL:f=n?Jt.LEVEL_LOAD_TIMEOUT:Jt.LEVEL_LOAD_ERROR,p=!1;break;case Wi.AUDIO_TRACK:f=n?Jt.AUDIO_TRACK_LOAD_TIMEOUT:Jt.AUDIO_TRACK_LOAD_ERROR,p=!1;break;case Wi.SUBTITLE_TRACK:f=n?Jt.SUBTITLE_TRACK_LOAD_TIMEOUT:Jt.SUBTITLE_LOAD_ERROR,p=!1;break}y&&this.resetInternalLoader(e.type);const v={type:Dn.NETWORK_ERROR,details:f,fatal:p,url:e.url,loader:y,context:e,error:a,networkDetails:r,stats:o};if(i){const T=(r==null?void 0:r.url)||e.url;v.response=Us({url:T,data:void 0},i)}this.hls.trigger(Ce.ERROR,v)}handlePlaylistLoaded(e,r,n,i,o,c){const a=this.hls,{type:f,level:p,levelOrTrack:y,id:v,groupId:T,deliveryDirectives:E}=i,k=R6(r,i),P=Aue(i);let R=typeof i.level=="number"&&P===Tn.MAIN?p:void 0;const D=e.playlistParsingError;if(D){if(this.hls.logger.warn(`${D} ${e.url}`),!a.config.ignorePlaylistParsingErrors){a.trigger(Ce.ERROR,{type:Dn.NETWORK_ERROR,details:Jt.LEVEL_PARSING_ERROR,fatal:!1,url:k,error:D,reason:D.message,response:r,context:i,level:R,parent:P,networkDetails:o,stats:n});return}e.playlistParsingError=null}if(!e.fragments.length){const M=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(Ce.ERROR,{type:Dn.NETWORK_ERROR,details:Jt.LEVEL_EMPTY_ERROR,fatal:!1,url:k,error:M,reason:M.message,response:r,context:i,level:R,parent:P,networkDetails:o,stats:n});return}switch(e.live&&c&&(c.getCacheAge&&(e.ageHeader=c.getCacheAge()||0),(!c.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),f){case Wi.MANIFEST:case Wi.LEVEL:if(R){if(!y)R=0;else if(y!==a.levels[R]){const M=a.levels.indexOf(y);M>-1&&(R=M)}}a.trigger(Ce.LEVEL_LOADED,{details:e,levelInfo:y||a.levels[0],level:R||0,id:v||0,stats:n,networkDetails:o,deliveryDirectives:E,withoutMultiVariant:f===Wi.MANIFEST});break;case Wi.AUDIO_TRACK:a.trigger(Ce.AUDIO_TRACK_LOADED,{details:e,track:y,id:v||0,groupId:T||"",stats:n,networkDetails:o,deliveryDirectives:E});break;case Wi.SUBTITLE_TRACK:a.trigger(Ce.SUBTITLE_TRACK_LOADED,{details:e,track:y,id:v||0,groupId:T||"",stats:n,networkDetails:o,deliveryDirectives:E});break}}}class lm{static get version(){return aC}static isMSESupported(){return VAe()}static isSupported(){return a4t()}static getMediaSource(){return Ex()}static get Events(){return Ce}static get MetadataSchema(){return od}static get ErrorTypes(){return Dn}static get ErrorDetails(){return Jt}static get DefaultConfig(){return lm.defaultConfig?lm.defaultConfig:K5t}static set DefaultConfig(e){lm.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new $K,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const r=this.logger=yMt(e.debug||!1,"Hls instance",e.assetPlayerId),n=this.config=Z5t(lm.DefaultConfig,e,r);this.userConfig=e,n.progressive&&X5t(n,r);const{abrController:i,bufferController:o,capLevelController:c,errorController:a,fpsController:f}=n,p=new a(this),y=this.abrController=new i(this),v=new hOt(this),T=n.interstitialsController,E=T?this.interstitialsController=new T(this,lm):null,k=this.bufferController=new o(this,v),P=this.capLevelController=new c(this),R=new f(this),D=new d4t(this),M=n.contentSteeringController,B=M?new M(this):null,V=this.levelController=new s4t(this,B),G=new n4t(this),W=new u4t(this.config,this.logger),Y=this.streamController=new c4t(this,v,W),J=this.gapController=new t4t(this,v);P.setStreamController(Y),R.setStreamController(Y);const Q=[D,V,Y];E&&Q.splice(1,0,E),B&&Q.splice(1,0,B),this.networkControllers=Q;const ee=[y,k,J,P,R,G,v];this.audioTrackController=this.createController(n.audioTrackController,Q);const le=n.audioStreamController;le&&Q.push(this.audioStreamController=new le(this,v,W)),this.subtitleTrackController=this.createController(n.subtitleTrackController,Q);const pe=n.subtitleStreamController;pe&&Q.push(this.subtititleStreamController=new pe(this,v,W)),this.createController(n.timelineController,ee),W.emeController=this.emeController=this.createController(n.emeController,ee),this.cmcdController=this.createController(n.cmcdController,ee),this.latencyController=this.createController(i4t,ee),this.coreComponents=ee,Q.push(p);const Se=p.onErrorOut;typeof Se=="function"&&this.on(Ce.ERROR,Se,p),this.on(Ce.MANIFEST_LOADED,D.onManifestLoaded,D)}createController(e,r){if(e){const n=new e(this);return r&&r.push(n),n}return null}on(e,r,n=this){this._emitter.on(e,r,n)}once(e,r,n=this){this._emitter.once(e,r,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,r,n=this,i){this._emitter.off(e,r,n,i)}listeners(e){return this._emitter.listeners(e)}emit(e,r,n){return this._emitter.emit(e,r,n)}trigger(e,r){if(this.config.debug)return this.emit(e,e,r);try{return this.emit(e,e,r)}catch(n){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+n.message+'". Here is a stacktrace:',n),!this.triggeringException){this.triggeringException=!0;const i=e===Ce.ERROR;this.trigger(Ce.ERROR,{type:Dn.OTHER_ERROR,details:Jt.INTERNAL_EXCEPTION,fatal:i,event:e,error:n}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(Ce.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(r=>r.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(r=>r.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const o=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(Ce.ERROR,{type:Dn.OTHER_ERROR,details:Jt.ATTACH_MEDIA_ERROR,fatal:!0,error:o});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const r="media"in e,n=r?e.media:e,i=r?e:{media:n};this._media=n,this.trigger(Ce.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(Ce.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(Ce.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const r=this.media,n=this._url,i=this._url=CK.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),r&&n&&(n!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(Ce.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,r){this.logger.log(`startLoad(${e+(r?", ":"")})`),this.started=!0,this.resumeBuffering();for(let n=0;n{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[Tn.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Tn.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[Tn.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,r=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),r&&this.startLoad(r))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=t5t()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const r=!!e;r!==this.config.capLevelToPlayerSize&&(r?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){ZMt(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:r}}=this;if(!e)return 0;const n=e.length;for(let i=0;i=r)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:r,maxHdcpLevel:n}=this;let i;if(r===-1&&e!=null&&e.length?i=e.length-1:i=r,n)for(let o=i;o--;){const c=e[o].attrs["HDCP-LEVEL"];if(c&&c<=n)return o}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var r;return((r=this.audioTrackController)==null?void 0:r.setAudioOption(e))||null}setSubtitleOption(e){var r;return((r=this.subtitleTrackController)==null?void 0:r.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const r=this.audioTrackController;r&&(r.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const r=this.subtitleTrackController;r&&(r.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const r=this.subtitleTrackController;r&&(r.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,r=this.allAudioTracks){const n=C2e(r);return A2e(e,n,navigator.mediaCapabilities)}}lm.defaultConfig=void 0;const h4t=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function K2(t){return!!t&&h4t.test(t)&&!/\.mp4($|\?)/i.test(t)}function f4t(t){const e=t.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return e?{libraryId:e[1],videoId:e[2]}:null}function m4t(t,e){if(!t)return null;const r=f4t(t);if(r){const n=new URLSearchParams({autoplay:e!=null&&e.autoplay?"true":"false",muted:e!=null&&e.muted?"true":"false",loop:e!=null&&e.loop?"true":"false",preload:"true",responsive:"true",playsinline:"true"});return`https://player.mediadelivery.net/embed/${r.libraryId}/${r.videoId}?${n.toString()}`}return/player\.mediadelivery\.net\/embed\//i.test(t)?t:/iframe\.mediadelivery\.net\/(?:play|embed)\//i.test(t)?t.replace("iframe.mediadelivery.net/play/","player.mediadelivery.net/embed/").replace("iframe.mediadelivery.net/embed/","player.mediadelivery.net/embed/"):t}function p4t(t){const e=t.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return e?e[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const kue=C.forwardRef(function({sourceUrl:e,thumbnailUrl:r,autoPlay:n,muted:i,loop:o,playsInline:c=!0,...a},f){const p=C.useRef(null),[y,v]=C.useState(null),T=C.useMemo(()=>m4t(e,{autoplay:!!n,muted:!!i,loop:!!o}),[e,n,i,o]);C.useEffect(()=>{let k=!1;if(!e){v(null);return}if(!K2(e)){v(e);return}if(!T){v(null);return}return v(null),fetch(T).then(async P=>{if(!P.ok)throw new Error(`Failed to load Bunny embed (${P.status})`);const R=await P.text();return p4t(R)}).then(P=>{k||v(P)}).catch(()=>{k||v(null)}),()=>{k=!0}},[T,e]),C.useEffect(()=>{const k=p.current;if(!k||!y)return;let P=null;const R=()=>{if(!n)return;const M=k.play();M&&M.catch(()=>{})};if(k.loop=!!o,y.endsWith(".m3u8")){if(k.canPlayType("application/vnd.apple.mpegurl")){k.src=y;const M=()=>R();return k.addEventListener("loadedmetadata",M),()=>{k.removeEventListener("loadedmetadata",M),k.removeAttribute("src"),k.load()}}return lm.isSupported()?(P=new lm({enableWorker:!0,lowLatencyMode:!1,maxBufferLength:30,backBufferLength:30}),P.loadSource(y),P.attachMedia(k),P.on(lm.Events.MANIFEST_PARSED,R),()=>{P==null||P.destroy(),k.removeAttribute("src"),k.load()}):void 0}k.src=y;const D=()=>R();return k.addEventListener("loadedmetadata",D),()=>{k.removeEventListener("loadedmetadata",D),k.removeAttribute("src"),k.load()}},[n,o,y]),C.useEffect(()=>{const k=p.current;if(k){if(k.muted=!!i,k.loop=!!o,n&&y){const P=k.play();P&&P.catch(()=>{});return}k.pause()}},[n,o,i,y]);const E=k=>{if(p.current=k,typeof f=="function"){f(k);return}f&&(f.current=k)};return s.jsx("video",{ref:E,poster:r||void 0,autoPlay:n,muted:i,loop:o,playsInline:c,preload:"metadata",...a})}),g4t={portrait:{sm:{w:130,h:231},md:{w:170,h:302},lg:{w:210,h:373}},landscape:{sm:{w:178,h:100},md:{w:220,h:124},lg:{w:270,h:152}}};function y4t(){try{let t=localStorage.getItem("vg_visitor_token");return t||(t=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",t)),t}catch{return null}}function Cue(t,e){return!t||t.length===0?!1:t.some(r=>r?r===e?!0:r.endsWith("*")?e.startsWith(r.slice(0,-1)):e.startsWith(r):!1)}function x4t({config:t,appSlug:e="video_greeter",preview:r=!1,embedded:n=!1}){const[i,o]=C.useState(!1),[c,a]=C.useState(!1),[f,p]=C.useState(!0),[y,v]=C.useState(!1),[T,E]=C.useState("portrait"),[k,P]=C.useState(!1),[R,D]=C.useState(!1),[M,B]=C.useState({name:"",email:"",phone:""}),[V,G]=C.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),W=C.useRef(null),Y=C.useRef(null),J=C.useRef(!1),Q=async(ur,xr)=>{if(!r)try{await Re.from("widget_events").insert({user_id:t.user_id,app_slug:e,event_type:ur,visitor_token:y4t(),page_url:typeof window<"u"?window.location.href:null,metadata:xr||{}})}catch{}};C.useEffect(()=>{if(y)return;const ur=typeof window<"u"?window.location.pathname:"/",xr=t.targeting||{mode:"all"};if(xr.mode==="include"&&!Cue(xr.include,ur)||xr.mode==="exclude"&&Cue(xr.exclude,ur))return;const rr=t.trigger||{type:"immediate"};if(rr.type==="immediate"||r){o(!0);return}if(rr.type==="delay"){const vn=(rr.value||3)*1e3,ct=setTimeout(()=>o(!0),vn);return()=>clearTimeout(ct)}if(rr.type==="scroll"){const vn=(rr.value||25)/100,ct=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=vn&&(o(!0),window.removeEventListener("scroll",ct))};return window.addEventListener("scroll",ct,{passive:!0}),()=>window.removeEventListener("scroll",ct)}if(rr.type==="exit_intent"){const vn=ct=>{ct.clientY<=0&&o(!0)};return document.addEventListener("mouseleave",vn),()=>document.removeEventListener("mouseleave",vn)}},[y,t.targeting,t.trigger,r]),C.useEffect(()=>{i&&!J.current&&(J.current=!0,Q("impression"))},[i]),C.useEffect(()=>{if(c&&Y.current&&!K2(t.video_url)){Y.current.currentTime=0,Y.current.muted=!1,p(!1);const ur=Y.current.play();ur&&ur.catch(()=>{})}else c&&K2(t.video_url)&&p(!1)},[c,t.video_url]),C.useEffect(()=>{if(!t.thumbnail_url)return;let ur=!1;const xr=new Image;return xr.onload=()=>{ur||E(xr.naturalWidth>xr.naturalHeight?"landscape":"portrait")},xr.src=t.thumbnail_url,()=>{ur=!0}},[t.thumbnail_url]),C.useEffect(()=>{const ur=()=>{G({width:window.innerWidth,height:window.innerHeight})};return ur(),window.addEventListener("resize",ur),()=>window.removeEventListener("resize",ur)},[]);const ee=()=>{a(!0),Q("expand")},le=ur=>{ur.stopPropagation(),v(!0),a(!1)},pe=ur=>{Q("cta_click",{cta_id:ur.id,label:ur.label,url:ur.url})},Se=async ur=>{if(ur.preventDefault(),r){P(!0);return}if(!(!M.email||!M.name)){D(!0);try{const{error:xr}=await Re.functions.invoke("submit-widget-lead",{body:{user_id:t.user_id,app_slug:e,name:M.name,email:M.email,phone:M.phone||void 0,page_url:window.location.href}});if(xr)throw xr;Q("lead_capture",{email:M.email}),P(!0)}catch(xr){console.error("lead submit failed",xr)}finally{D(!1)}}};if(!i||y||!t.video_url&&!t.video_embed_url)return null;const je=g4t[T][t.size||"md"],Le=n?"absolute left-2 bottom-2":r?t.position==="bottom-right"?"absolute right-4 bottom-4":"absolute left-4 bottom-4":t.position==="bottom-right"?"fixed right-4 bottom-4 md:right-6 md:bottom-6":"fixed left-4 bottom-4 md:left-6 md:bottom-6",Ae=t.shape==="circle"?"rounded-full":"rounded-2xl",be=r?T==="landscape"?"w-[280px]":"w-[220px]":T==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",me=T==="landscape"?"aspect-video":"aspect-[9/16]",Te=t.agent||{},Ne=t.lead_form_fields||["name","email","phone"],Ee=!!(t.show_socials&&(Te.instagram_url||Te.facebook_url||Te.linkedin_url)),we=108+(t.ctas||[]).length*48+(t.lead_form_enabled&&!k?72+Ne.length*42:0)+(k?40:0)+(Ee?34:0),He=Math.max(300,V.height-32),tt=Math.max(220,V.width-32),at=Math.max(150,He-we),Et=Math.floor(T==="landscape"?at*(16/9):at*(9/16)),vt=T==="landscape"?Math.max(220,Math.min(420,tt,Et)):Math.max(180,Math.min(340,tt,Et)),Gt=n?"bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col":`${be} max-h-[calc(100dvh-2rem)] bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col`,pt=n?{width:`${vt}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,Pt=n?"p-3 space-y-2.5":"p-4 space-y-3",tr=n?"w-9 h-9 rounded-full object-cover":"w-10 h-10 rounded-full object-cover",_t=n?"font-bold text-[15px] text-gray-900 leading-tight":"font-bold text-gray-900 leading-tight",cr=n?"text-[11px] text-gray-500 mt-0.5":"text-xs text-gray-500 mt-0.5",Tr=n?"w-full px-3 py-1.5 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400":"w-full px-3 py-2 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400",sn=n?"w-full flex items-center justify-center gap-2 px-3 py-2 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60":"w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60";return s.jsx("div",{"data-vg-widget":!0,"data-expanded":c?"true":"false",className:`${Le} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:c?s.jsxs("div",{className:Gt,style:pt,children:[s.jsxs("div",{className:`relative bg-black ${me}`,children:[K2(t.video_url)?s.jsx(kue,{ref:Y,sourceUrl:t.video_url,thumbnailUrl:t.thumbnail_url,autoPlay:!0,muted:f,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:ur=>{const{videoWidth:xr,videoHeight:rr}=ur.currentTarget;xr&&rr&&E(xr>rr?"landscape":"portrait")},onEnded:()=>Q("watch_complete")},`expanded-${t.video_url}-${t.thumbnail_url||"no-thumb"}-${c?"on":"off"}`):s.jsx("video",{ref:Y,src:t.video_url||void 0,poster:t.thumbnail_url||void 0,autoPlay:!0,playsInline:!0,controls:!1,className:"w-full h-full object-cover",onEnded:()=>Q("watch_complete"),onLoadedMetadata:ur=>{const{videoWidth:xr,videoHeight:rr}=ur.currentTarget;xr&&rr&&E(xr>rr?"landscape":"portrait")}}),s.jsx("button",{onClick:()=>{Y.current&&(Y.current.muted=!Y.current.muted,p(Y.current.muted))},className:"absolute bottom-3 right-3 w-9 h-9 rounded-full bg-black/60 hover:bg-black text-white flex items-center justify-center backdrop-blur",children:f?s.jsx(mMe,{className:"w-4 h-4"}):s.jsx(fMe,{className:"w-4 h-4"})}),s.jsx("button",{onClick:()=>a(!1),className:"absolute top-3 right-3 w-8 h-8 rounded-full bg-black/60 hover:bg-black text-white flex items-center justify-center backdrop-blur","aria-label":"Minimize",children:s.jsx(Os,{className:"w-4 h-4"})})]}),s.jsxs("div",{className:Pt,children:[s.jsxs("div",{className:"flex items-center gap-3",children:[Te.avatar_url&&s.jsx("img",{src:Te.avatar_url,alt:Te.name||"",className:tr}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:_t,children:t.greeting_title||"Glad you're here!"}),t.greeting_subtitle&&s.jsx("p",{className:cr,children:t.greeting_subtitle})]})]}),(t.ctas||[]).length>0&&s.jsx("div",{className:"space-y-2",children:(t.ctas||[]).map(ur=>{var xr;return s.jsxs("a",{href:ur.url,target:(xr=ur.url)!=null&&xr.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>pe(ur),className:`flex items-center justify-between gap-2 ${n?"px-3 py-2":"px-3.5 py-2.5"} rounded-xl text-sm font-semibold transition-colors ${ur.style==="secondary"?"bg-gray-100 text-gray-900 hover:bg-gray-200":"bg-gray-900 text-white hover:bg-gray-800"}`,children:[s.jsx("span",{children:ur.label}),s.jsx(b_,{className:"w-3.5 h-3.5 opacity-60"})]},ur.id)})}),t.lead_form_enabled&&!k&&s.jsxs("form",{onSubmit:Se,className:"space-y-2 pt-1",children:[Ne.includes("name")&&s.jsx("input",{type:"text",placeholder:"Name",required:!0,value:M.name,onChange:ur=>B({...M,name:ur.target.value}),className:Tr}),Ne.includes("email")&&s.jsx("input",{type:"email",placeholder:"Email",required:!0,value:M.email,onChange:ur=>B({...M,email:ur.target.value}),className:Tr}),Ne.includes("phone")&&s.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:M.phone,onChange:ur=>B({...M,phone:ur.target.value}),className:Tr}),s.jsxs("button",{type:"submit",disabled:R,className:sn,children:[s.jsx(kD,{className:"w-3.5 h-3.5"}),R?"Sending...":"Send"]})]}),k&&s.jsx("p",{className:"text-sm text-emerald-600 font-medium text-center py-2",children:"Thanks! I'll be in touch shortly."}),t.show_socials&&(Te.instagram_url||Te.facebook_url||Te.linkedin_url)&&s.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[Te.instagram_url&&s.jsx("a",{href:Te.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>Q("cta_click",{social:"instagram"}),children:s.jsx(mme,{className:"w-4 h-4"})}),Te.facebook_url&&s.jsx("a",{href:Te.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>Q("cta_click",{social:"facebook"}),children:s.jsx(hme,{className:"w-4 h-4"})}),Te.linkedin_url&&s.jsx("a",{href:Te.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>Q("cta_click",{social:"linkedin"}),children:s.jsx(yme,{className:"w-4 h-4"})})]})]})]}):s.jsxs("div",{className:"relative animate-in fade-in slide-in-from-bottom-4 duration-500",children:[s.jsxs("button",{onClick:ee,className:`relative ${Ae} overflow-hidden shadow-2xl ring-2 ring-white/40 hover:ring-white/80 hover:scale-105 transition-all bg-black`,style:{width:je.w,height:je.h},"aria-label":"Play video greeting",children:[K2(t.video_url)?s.jsx(kue,{ref:W,sourceUrl:t.video_url,thumbnailUrl:t.thumbnail_url,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-cover pointer-events-none",onLoadedMetadata:ur=>{const{videoWidth:xr,videoHeight:rr}=ur.currentTarget;xr&&rr&&E(xr>rr?"landscape":"portrait")}},`collapsed-${t.video_url}-${t.thumbnail_url||"no-thumb"}`):s.jsx("video",{ref:W,src:t.video_url||void 0,poster:t.thumbnail_url||void 0,autoPlay:!0,muted:!0,loop:!0,playsInline:!0,preload:"metadata",className:"w-full h-full object-cover",onLoadedMetadata:ur=>{const{videoWidth:xr,videoHeight:rr}=ur.currentTarget;xr&&rr&&E(xr>rr?"landscape":"portrait")}}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent pointer-events-none"}),s.jsx("div",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 w-12 h-12 rounded-full bg-white/95 flex items-center justify-center shadow-lg pointer-events-none",children:s.jsx("svg",{viewBox:"0 0 24 24",className:"w-6 h-6 text-black ml-0.5",fill:"currentColor",children:s.jsx("path",{d:"M8 5v14l11-7z"})})}),s.jsx("span",{className:"absolute top-2 right-2 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider bg-red-500 text-white rounded-full animate-pulse",children:"Live"})]}),s.jsx("button",{onClick:le,className:"absolute -top-2 -right-2 w-7 h-7 rounded-full bg-black/80 text-white shadow-lg hover:bg-black flex items-center justify-center","aria-label":"Close",children:s.jsx(Os,{className:"w-3.5 h-3.5"})})]})})}function JK({slug:t}){const[e,r]=C.useState(null);return C.useEffect(()=>{if(!t)return;let n=!1;return(async()=>{const{data:i,error:o}=await Re.rpc("get_public_video_greeter_config",{_slug:t});!n&&!o&&i&&r(i)})(),()=>{n=!0}},[t]),e?s.jsx(x4t,{config:e}):null}const qAe="eip_last_shown",Nue="eip_visitor_token";function v4t(){try{let t=localStorage.getItem(Nue);return t||(t=crypto.randomUUID(),localStorage.setItem(Nue,t)),t}catch{return}}function _4t(t){try{const e=Number(localStorage.getItem(qAe)||0);return e?Date.now()-e>t*24*60*60*1e3:!0}catch{return!0}}function b4t(t){if(!t||t.mode==="all")return!0;const e=window.location.pathname,n=(t.mode==="include"?t.include||[]:t.exclude||[]).some(i=>e.startsWith(i));return t.mode==="include"?n:!n}function w4t({config:t,preview:e=!1,forceOpen:r=!1}){const[n,i]=C.useState(r),[o,c]=C.useState(!1),[a,f]=C.useState(!1),[p,y]=C.useState({name:"",email:"",phone:""}),v=C.useRef(!1),T=C.useRef(!1),E=async(W,Y={})=>{if(!e)try{await Re.from("widget_events").insert({user_id:t.user_id,app_slug:"exit_intent",event_type:W,visitor_token:v4t(),page_url:window.location.href,metadata:Y})}catch{}};C.useEffect(()=>{if(e||!b4t(t.targeting)||!_4t(t.frequency_days))return;const W=/Mobi|Android/i.test(navigator.userAgent),Y={low:5,medium:15,high:30}[t.trigger_sensitivity]||15,J=pe=>{if(!v.current){v.current=!0,i(!0);try{localStorage.setItem(qAe,String(Date.now()))}catch{}E("impression",{reason:pe})}},Q=pe=>{pe.clientY<=Y&&J("mouse_leave")},ee=()=>{t.enable_mobile_back&&W&&J("back_button")};if(t.enable_mobile_back&&W){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",ee)}else document.addEventListener("mouseleave",Q);let le;return t.enable_time_fallback&&(le=window.setTimeout(()=>J("time_fallback"),Math.max(5,t.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",Q),window.removeEventListener("popstate",ee),le&&window.clearTimeout(le)}},[t,e]),C.useEffect(()=>{n&&!T.current&&!e&&!v.current&&(T.current=!0)},[n,e]);const k=()=>{i(!1),e||E("close")},P=async W=>{if(W.preventDefault(),e){c(!0);return}if(!(!p.email||!p.name)){f(!0);try{const{error:Y}=await Re.functions.invoke("submit-widget-lead",{body:{user_id:t.user_id,app_slug:"exit_intent",name:p.name,email:p.email,phone:p.phone||void 0,page_url:window.location.href}});if(Y)throw Y;E("lead_capture",{email:p.email}),c(!0),t.cta_url&&setTimeout(()=>{window.location.href=t.cta_url},1200)}catch(Y){console.error("exit intent submit failed",Y)}finally{f(!1)}}};if(!n)return null;const R=t.form_fields||["name","email"],D=t.agent||{},M=[D.first_name,D.last_name].filter(Boolean).join(" "),B=t.use_agent_photo&&D.avatar_url||t.image_url,V=t.theme_color||"#f97316",G=e?"absolute inset-0 flex items-center justify-center p-4 z-10":"fixed inset-0 z-[80] flex items-center justify-center p-4";return s.jsx("div",{className:G,style:{background:e?"transparent":"rgba(0,0,0,0.6)"},children:s.jsxs("div",{className:"relative w-full max-w-md bg-background rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-300",onClick:W=>W.stopPropagation(),children:[s.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${V}, ${L6(V,-25)})`}}),s.jsx("button",{onClick:k,className:"absolute top-3 right-3 z-10 w-8 h-8 rounded-full bg-background/80 backdrop-blur hover:bg-background flex items-center justify-center text-muted-foreground hover:text-foreground transition","aria-label":"Close",children:s.jsx(Os,{className:"w-4 h-4"})}),s.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[B&&s.jsx("img",{src:B,alt:M||"Agent",className:"w-14 h-14 rounded-full object-cover ring-2 shadow-md",style:{boxShadow:`0 0 0 2px ${V}33`,"--tw-ring-color":V}}),s.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold",style:{background:`${V}1A`,color:V},children:[s.jsx(xs,{className:"w-3 h-3"}),t.offer_label]})]}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:t.headline}),s.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:t.subheadline})]}),o?s.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${V}10`,color:V},children:[s.jsx("div",{className:"text-3xl",children:"🎉"}),s.jsx("p",{className:"text-sm font-medium",style:{color:V},children:t.success_message})]}):t.form_enabled?s.jsxs("form",{onSubmit:P,className:"space-y-2.5",children:[R.includes("name")&&s.jsx("input",{type:"text",placeholder:"Your name",value:p.name,onChange:W=>y({...p,name:W.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":V},required:!0}),R.includes("email")&&s.jsx("input",{type:"email",placeholder:"you@email.com",value:p.email,onChange:W=>y({...p,email:W.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":V},required:!0}),R.includes("phone")&&s.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:p.phone,onChange:W=>y({...p,phone:W.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":V}}),s.jsx("button",{type:"submit",disabled:a,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60",style:{background:`linear-gradient(135deg, ${V}, ${L6(V,-20)})`},children:a?"Sending...":t.cta_label}),s.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We respect your inbox. Unsubscribe anytime."})]}):s.jsx("a",{href:t.cta_url||"#",onClick:()=>E("cta_click",{url:t.cta_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 transition",style:{background:`linear-gradient(135deg, ${V}, ${L6(V,-20)})`},children:t.cta_label}),M&&s.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",M]})]})]})})}function L6(t,e){try{const r=parseInt(t.slice(1),16),n=e<0?0:255,i=Math.abs(e)/100,o=r>>16,c=r>>8&255,a=r&255,f=Math.round((n-o)*i)+o,p=Math.round((n-c)*i)+c,y=Math.round((n-a)*i)+a;return"#"+(16777216+(f<<16)+(p<<8)+y).toString(16).slice(1)}catch{return t}}function eY({slug:t}){const[e,r]=C.useState(null);return C.useEffect(()=>{if(!t)return;let n=!1;return(async()=>{const{data:i,error:o}=await Re.rpc("get_public_exit_intent_config",{_slug:t});!n&&!o&&i&&r(i)})(),()=>{n=!0}},[t]),e?s.jsx(w4t,{config:e}):null}const Iue="lm_dismissed",Pue="lm_visitor_token";function S4t(){try{let t=localStorage.getItem(Pue);return t||(t=crypto.randomUUID(),localStorage.setItem(Pue,t)),t}catch{return}}function T4t(t){if(!t||t.mode==="all")return!0;const e=window.location.pathname,n=(t.mode==="include"?t.include||[]:t.exclude||[]).some(i=>e.startsWith(i));return t.mode==="include"?n:!n}function E4t({config:t,preview:e=!1}){const[r,n]=C.useState(!1),[i,o]=C.useState(!1),[c,a]=C.useState(!1),[f,p]=C.useState(!1),[y,v]=C.useState({name:"",email:"",phone:""}),T=C.useRef(!1),E=async(B,V={})=>{if(!e)try{await Re.from("widget_events").insert({user_id:t.user_id,app_slug:"lead_magnet",event_type:B,visitor_token:S4t(),page_url:window.location.href,metadata:V})}catch{}};C.useEffect(()=>{if(e){n(!0);return}if(!T4t(t.targeting))return;try{if(sessionStorage.getItem(Iue))return}catch{}const B=()=>{T.current||(T.current=!0,n(!0),E("impression"))};if(t.trigger_type==="immediate")B();else if(t.trigger_type==="delay"){const V=window.setTimeout(B,Math.max(0,t.trigger_value)*1e3);return()=>window.clearTimeout(V)}else if(t.trigger_type==="scroll"){const V=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100>=(t.trigger_value||30)&&B()};return window.addEventListener("scroll",V,{passive:!0}),()=>window.removeEventListener("scroll",V)}},[t,e]);const k=()=>{n(!1);try{sessionStorage.setItem(Iue,"1")}catch{}e||E("close")},P=async B=>{if(B.preventDefault(),e){a(!0);return}if(!(!y.email||!y.name)){p(!0);try{const{error:V}=await Re.functions.invoke("submit-widget-lead",{body:{user_id:t.user_id,app_slug:"lead_magnet",name:y.name,email:y.email,phone:y.phone||void 0,page_url:window.location.href}});if(V)throw V;E("lead_capture",{email:y.email}),a(!0),(t.delivery_method==="instant"||t.delivery_method==="both")&&t.download_url&&setTimeout(()=>{const G=document.createElement("a");G.href=t.download_url,G.target="_blank",G.rel="noopener",G.download="",document.body.appendChild(G),G.click(),G.remove()},600)}catch(V){console.error("lead magnet submit failed",V)}finally{p(!1)}}};if(!r)return null;const R=t.theme_color||"#2563eb",D=e?t.position==="bottom-left"?"absolute left-4 bottom-4":"absolute right-4 bottom-4":t.position==="bottom-left"?"fixed left-4 bottom-4 md:left-6 md:bottom-6":"fixed right-4 bottom-4 md:right-6 md:bottom-6";if(t.display_style==="bar")return s.jsxs("div",{className:e?"absolute left-0 right-0 bottom-0 z-10":"fixed left-0 right-0 bottom-0 z-[75]",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[s.jsx("div",{className:"text-white shadow-2xl",style:{background:`linear-gradient(90deg, ${R}, ${C2(R,-20)})`},children:s.jsxs("div",{className:"max-w-6xl mx-auto px-4 py-3 flex items-center gap-3 flex-wrap",children:[s.jsx(hf,{className:"w-5 h-5 shrink-0"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm font-semibold truncate",children:t.title}),s.jsx("p",{className:"text-xs text-white/80 truncate",children:t.description})]}),s.jsx("button",{onClick:()=>{o(!0),E("expand")},className:"px-4 py-2 rounded-lg text-sm font-semibold bg-white shrink-0 hover:bg-white/95 transition",style:{color:R},children:t.download_label}),s.jsx("button",{onClick:k,className:"text-white/80 hover:text-white","aria-label":"Close",children:s.jsx(Os,{className:"w-4 h-4"})})]})}),i&&M()]});if(!i)return s.jsxs(s.Fragment,{children:[s.jsxs("button",{onClick:()=>{o(!0),E("expand")},className:`${D} z-[75] group flex items-center gap-3 pl-3 pr-4 py-3 rounded-2xl shadow-2xl hover:shadow-3xl transition-all hover:scale-[1.03] animate-in fade-in slide-in-from-bottom-4 duration-500`,style:{background:`linear-gradient(135deg, ${R}, ${C2(R,-20)})`,paddingBottom:"env(safe-area-inset-bottom)"},children:[s.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 backdrop-blur flex items-center justify-center text-white",children:s.jsx(Q1,{className:"w-5 h-5"})}),s.jsxs("div",{className:"text-left text-white",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider opacity-90 font-semibold",children:t.badge_label}),s.jsx("div",{className:"text-sm font-bold leading-tight max-w-[180px] truncate",children:t.title})]}),s.jsx("button",{onClick:B=>{B.stopPropagation(),k()},className:"ml-1 w-6 h-6 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center text-white","aria-label":"Close",children:s.jsx(Os,{className:"w-3 h-3"})})]}),i&&M()]});return M();function M(){const B=t.form_fields||["name","email"],V=t.agent||{},G=[V.first_name,V.last_name].filter(Boolean).join(" ");return s.jsx("div",{className:e?"absolute inset-0 flex items-center justify-center p-4 z-20":"fixed inset-0 z-[85] flex items-center justify-center p-4",style:{background:e?"transparent":"rgba(0,0,0,0.6)"},onClick:()=>o(!1),children:s.jsxs("div",{className:"relative w-full max-w-lg bg-background rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-300",onClick:W=>W.stopPropagation(),children:[s.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${R}, ${C2(R,-25)})`},children:[t.cover_image_url?s.jsx("img",{src:t.cover_image_url,alt:t.title,className:"w-full h-full object-cover opacity-90"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(_m,{className:"w-20 h-20 text-white/40"})}),s.jsxs("div",{className:"absolute top-3 left-3 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-white shadow",style:{color:R},children:[s.jsx(hf,{className:"w-3 h-3"}),t.badge_label]}),s.jsx("button",{onClick:()=>o(!1),className:"absolute top-3 right-3 w-8 h-8 rounded-full bg-white/95 hover:bg-white flex items-center justify-center text-foreground/70 hover:text-foreground transition","aria-label":"Close",children:s.jsx(Os,{className:"w-4 h-4"})})]}),s.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:t.title}),s.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:t.description})]}),c?s.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${R}10`},children:[s.jsx(sc,{className:"w-8 h-8 mx-auto",style:{color:R}}),s.jsx("p",{className:"text-sm font-medium",style:{color:R},children:t.success_message}),t.download_url&&s.jsx("a",{href:t.download_url,target:"_blank",rel:"noopener",className:"inline-block mt-2 text-xs underline",style:{color:R},children:"Click here if download didn't start"})]}):t.form_enabled?s.jsxs("form",{onSubmit:P,className:"space-y-2.5",children:[B.includes("name")&&s.jsx("input",{type:"text",placeholder:"Your name",value:y.name,onChange:W=>v({...y,name:W.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":R},required:!0}),B.includes("email")&&s.jsx("input",{type:"email",placeholder:"you@email.com",value:y.email,onChange:W=>v({...y,email:W.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":R},required:!0}),B.includes("phone")&&s.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:y.phone,onChange:W=>v({...y,phone:W.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":R}}),s.jsxs("button",{type:"submit",disabled:f,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60 inline-flex items-center justify-center gap-2",style:{background:`linear-gradient(135deg, ${R}, ${C2(R,-20)})`},children:[s.jsx(sc,{className:"w-4 h-4"}),f?"Sending...":t.download_label]}),s.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We'll email you a copy too. No spam — promise."})]}):s.jsx("a",{href:t.download_url||"#",target:"_blank",rel:"noopener",onClick:()=>E("cta_click",{url:t.download_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg",style:{background:`linear-gradient(135deg, ${R}, ${C2(R,-20)})`},children:t.download_label}),G&&s.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",G]})]})]})})}}function C2(t,e){try{const r=parseInt(t.slice(1),16),n=e<0?0:255,i=Math.abs(e)/100,o=r>>16,c=r>>8&255,a=r&255,f=Math.round((n-o)*i)+o,p=Math.round((n-c)*i)+c,y=Math.round((n-a)*i)+a;return"#"+(16777216+(f<<16)+(p<<8)+y).toString(16).slice(1)}catch{return t}}function tY({slug:t}){const[e,r]=C.useState(null);return C.useEffect(()=>{if(!t)return;let n=!1;return(async()=>{const{data:i,error:o}=await Re.rpc("get_public_lead_magnet_config",{_slug:t});!n&&!o&&i&&r(i)})(),()=>{n=!0}},[t]),e?s.jsx(E4t,{config:e}):null}function rY({siteConfig:t,className:e="",iconClassName:r=""}){var o;const n=((o=t==null?void 0:t.themeConfig)==null?void 0:o.socialLinks)||null;if(!n)return null;const i=[{key:"facebook",url:n.facebook,Icon:hme,label:"Facebook"},{key:"instagram",url:n.instagram,Icon:mme,label:"Instagram"},{key:"linkedin",url:n.linkedin,Icon:yme,label:"LinkedIn"},{key:"youtube",url:n.youtube,Icon:gMe,label:"YouTube"}].filter(c=>!!c.url);return i.length?s.jsx("div",{className:`flex items-center gap-3 ${e}`,children:i.map(({key:c,url:a,Icon:f,label:p})=>s.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer","aria-label":p,className:`inline-flex items-center justify-center h-9 w-9 rounded-full border border-current/20 opacity-70 hover:opacity-100 transition-opacity ${r}`,children:s.jsx(f,{className:"h-4 w-4"})},c))}):null}function j4t(t){const e=String(t||"").trim().toLowerCase();return/^\/search\/*(?:[?#]|$)/.test(e)}const A4t="7605cc2e-ce21-4f4f-8bb1-4c0f217b1109";function k4t({children:t,siteConfig:e}){var gr,En,ni,ii,Ui,Ta,vi,ca;const r=ki(),n=Hs(),[i,o]=C.useState(!1),[c,a]=C.useState(!1);C.useEffect(()=>{typeof window<"u"&&new URLSearchParams(window.location.search).get("join")==="1"&&a(!0)},[]);const[f,p]=C.useState(!1),[y,v]=C.useState([]),[T,E]=C.useState([]),[k,P]=C.useState([]),[R,D]=C.useState(null),M=C.useRef(null),B=C.useRef(null),{user:V,profile:G,signOut:W}=Hx();d5(e,V==null?void 0:V.id),h5(e,V==null?void 0:V.id);const Y=((gr=e.agent)==null?void 0:gr.full_name)||"Agent",J=e.siteTitle||`${Y} Real Estate`,Q=r.pathname==="/search",ee=r.pathname==="/",le=e.leadRegistrationMode!=="disabled",pe=e.id===A4t;C.useEffect(()=>{(async()=>{const{data:Vn}=await Re.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",e.id).eq("is_published",!0).order("sort_order",{ascending:!0});v(Vn||[])})()},[e.id]),C.useEffect(()=>{(async()=>{const{data:Vn}=await Re.from("lead_site_menu_items").select("*").eq("site_id",e.id).order("sort_order",{ascending:!0});P(Vn||[]),E((Vn||[]).filter(Ks=>Ks.is_visible!==!1))})()},[e.id]),C.useEffect(()=>{const Nr=Vn=>{M.current&&!M.current.contains(Vn.target)&&p(!1),B.current&&!B.current.contains(Vn.target)&&D(null)};return document.addEventListener("mousedown",Nr),()=>document.removeEventListener("mousedown",Nr)},[]);const Se=wx(e),je=e==null?void 0:e.bookingUrl,{data:Le}=u5(Se?e.agentId:null),Ae=((Le==null?void 0:Le.length)??0)>0,{data:be}=_K(e.agentId),me=((be==null?void 0:be.length)??0)>0,Te=T.filter(Nr=>{const Vn=String(Nr.target_url||"").toLowerCase().replace(/\/+$/,"");return!(Se&&j4t(Nr.target_url)||Vn==="/listings"&&Se&&!Ae||Vn==="/sold"&&!me)}),Ne=Se&&Ae&&Te.length>0&&!Te.some(Nr=>String(Nr.target_url||"").toLowerCase().startsWith("/listings"))?[...Te,{id:"__my-listings",label:"My Listings",target_url:"/listings",parent_id:null,is_visible:!0}]:Te,Ee=Ne.length>0,we=[{to:"/",label:"Home"},...Se?[]:[{to:"/search",label:"Search"}],...Se&&Ae?[{to:"/listings",label:"My Listings"}]:[],...me?[{to:"/sold",label:"Sold"}]:[],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],He=Ne.filter(Nr=>!Nr.parent_id),tt=Nr=>Ne.filter(Vn=>Vn.parent_id===Nr),at=k.filter(Nr=>!Nr.parent_id),Et=new Set([...at,...He].filter(Nr=>String(Nr.target_url||"").trim()!=="").map(Nr=>String(Nr.target_url).toLowerCase().replace(/\/+$/,"")||"/")),vt=new Set([...at,...He].map(Nr=>String(Nr.label||"").trim().toLowerCase())),pt=["/","/search","/about","/contact","/sell","/blog"].some(Nr=>Et.has(Nr)),Pt=pt?[]:we.filter(Nr=>!Et.has(Nr.to.toLowerCase())&&!vt.has(Nr.label.toLowerCase())),tr=pt?He.filter(Nr=>Nr.is_visible!==!1&&String(Nr.target_url||"").trim()!=="").map(Nr=>({to:String(Nr.target_url),label:String(Nr.label||"").trim()||"Link"})):Pt,_t=at.find(Nr=>Nr.item_type==="cities"),cr=String((_t==null?void 0:_t.label)||"Cities").trim()||"Cities",Tr=y.length>0&&!pe,sn=Tr&&!_t,ur=Nr=>`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${Nr?ee?"bg-white/15 text-white":"bg-gray-100 text-gray-900":ee?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,xr=r.pathname.startsWith("/homes-for-sale-in-"),rr=Nr=>s.jsxs("div",{ref:M,className:"relative",children:[s.jsxs("button",{onClick:()=>p(!f),className:`flex items-center gap-1 ${ur(xr)}`,children:[Nr," ",s.jsx(yl,{className:`h-3.5 w-3.5 transition-transform ${f?"rotate-180":""}`})]}),f&&s.jsx("div",{className:"absolute top-full right-0 mt-2 w-52 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:y.map(Vn=>s.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${Vn.city_slug}`),p(!1)},className:"w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 hover:text-gray-900 transition-colors",children:Vn.city_name},Vn.city_slug))})]},"__cities"),vn=Nr=>s.jsxs("div",{children:[s.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${ee?"text-white/40":"text-gray-400"}`,children:Nr}),y.map(Vn=>s.jsx(Wr,{to:`/homes-for-sale-in-${Vn.city_slug}`,onClick:()=>o(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===`/homes-for-sale-in-${Vn.city_slug}`?ee?"bg-white/15 text-white":"bg-gray-100 text-gray-900":ee?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Vn.city_name},Vn.city_slug))]},"__cities-mobile"),ct=ee?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",jt=e.seoMetaTitle||e.siteTitle||`${Y} - Real Estate`,er=e.seoMetaDescription||e.siteTagline||`Browse homes and listings with ${Y}`,Pr=e.ogImageUrl||((En=e.agent)==null?void 0:En.avatar_url)||"",dr=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug||""}.thelocalmove.com`,ar=jK(e.siteTitle,Y),Nt=(e.googleSearchConsoleVerification||"").trim().replace(/^google-site-verification[=:]\s*/i,"").replace(/^content=/i,"").replace(/^["']|["']$/g,"");return s.jsxs("div",{className:`flex flex-col ${Q?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[s.jsx(AK,{siteConfig:e,pagePath:r.pathname}),(!pe||r.pathname==="/p/frequently-asked-questions")&&s.jsx(kK,{siteConfig:e}),s.jsxs(Zo,{children:[s.jsx("title",{children:jt}),s.jsx("meta",{name:"description",content:er}),Nt&&s.jsx("meta",{name:"google-site-verification",content:Nt}),s.jsx("meta",{property:"og:site_name",content:ar}),s.jsx("meta",{property:"og:title",content:jt}),s.jsx("meta",{property:"og:description",content:er}),s.jsx("meta",{property:"og:type",content:"website"}),s.jsx("meta",{property:"og:url",content:dr+r.pathname}),Pr&&s.jsx("meta",{property:"og:image",content:Pr}),s.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),s.jsx("meta",{name:"twitter:title",content:jt}),s.jsx("meta",{name:"twitter:description",content:er}),Pr&&s.jsx("meta",{name:"twitter:image",content:Pr}),e.faviconUrl&&s.jsx("link",{rel:"icon",href:e.faviconUrl,type:"image/png"}),s.jsx("link",{rel:"canonical",href:`${dr}${r.pathname}`}),e.subdomainSlug==="matthogg"&&s.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),s.jsxs("header",{className:`${ee?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${ct}`,children:[s.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:s.jsxs("div",{className:"flex items-center justify-between h-20",children:[s.jsxs(Wr,{to:"/",className:"flex items-center gap-3",children:[e.showTeamLogo&&e.teamLogoUrl?s.jsx("img",{src:e.teamLogoUrl,alt:`${J} logo`,className:`${KRt(e.headerLogoSize)} w-auto object-contain`}):(ni=e.agent)!=null&&ni.avatar_url?s.jsx("img",{src:e.agent.avatar_url,alt:Y,className:"h-10 w-10 rounded-full object-cover ring-2 ring-white/20"}):null,s.jsx("div",{children:s.jsx("span",{className:"font-bold text-lg leading-none tracking-tight",children:J})})]}),s.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[e.bookingUrl&&!pe&&s.jsx(Gp,{bookingUrl:e.bookingUrl,label:"Schedule",size:"sm",className:"order-last ml-3",source:"nav"}),Pt.map(Nr=>s.jsx(Wr,{to:Nr.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${r.pathname===Nr.to?ee?"bg-white/15 text-white":"bg-gray-100 text-gray-900":ee?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:Nr.label},Nr.to)),Ee&&He.map(Nr=>{if(Nr.item_type==="cities")return Tr?rr(String(Nr.label||"Cities")):null;if(Nr.item_type==="dropdown"){const Vn=tt(Nr.id);return s.jsxs("div",{ref:B,className:"relative",children:[s.jsxs("button",{onClick:()=>D(R===Nr.id?null:Nr.id),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${ee?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[Nr.label," ",s.jsx(yl,{className:`h-3.5 w-3.5 transition-transform ${R===Nr.id?"rotate-180":""}`})]}),R===Nr.id&&Vn.length>0&&s.jsx("div",{className:"absolute top-full right-0 mt-2 w-52 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:Vn.map(Ks=>s.jsx(aL,{item:Ks,onClick:()=>D(null),className:"w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 hover:text-gray-900 transition-colors block"},Ks.id))})]},Nr.id)}return s.jsx(aL,{item:Nr,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${ee?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`},Nr.id)}),sn&&rr(cr),!pe&&(V?s.jsx("div",{className:"ml-2",children:s.jsx(m5,{savedClassName:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${ee?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,triggerClassName:`flex items-center gap-1.5 rounded-full py-1 pl-1 pr-2.5 text-sm font-medium outline-none transition-colors ${ee?"bg-white/10 text-white hover:bg-white/20":"bg-gray-100 text-gray-800 hover:bg-gray-200"}`})}):le?s.jsx("button",{onClick:()=>a(!0),className:`ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${ee?"bg-white/15 text-white hover:bg-white/25":"bg-blue-600 text-white hover:bg-blue-700"}`,children:"Sign In"}):null)]}),s.jsx("button",{onClick:()=>o(!i),"aria-label":i?"Close menu":"Open menu","aria-expanded":i,className:`md:hidden p-2 rounded-lg ${ee?"text-white hover:bg-white/10":"text-gray-600 hover:bg-gray-100"}`,children:i?s.jsx(Os,{className:"h-5 w-5"}):s.jsx(QS,{className:"h-5 w-5"})})]})}),i&&s.jsx("div",{className:`md:hidden border-t ${ee?"border-white/10 bg-black/95 backdrop-blur":"border-gray-100 bg-white"} max-h-[calc(100vh-5rem)] overflow-y-auto overscroll-contain`,children:s.jsxs("div",{className:"px-4 py-3 space-y-1 pb-8",children:[e.bookingUrl&&!pe&&s.jsx(Gp,{bookingUrl:e.bookingUrl,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),Pt.map(Nr=>s.jsx(Wr,{to:Nr.to,onClick:()=>o(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===Nr.to?ee?"bg-white/15 text-white":"bg-gray-100 text-gray-900":ee?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Nr.label},Nr.to)),Ee&&He.map(Nr=>{if(Nr.item_type==="cities")return Tr?vn(String(Nr.label||"Cities")):null;if(Nr.item_type==="dropdown"){const Vn=tt(Nr.id);return s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${ee?"text-white/40":"text-gray-400"}`,children:Nr.label}),Vn.map(Ks=>s.jsx(aL,{item:Ks,onClick:()=>o(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${ee?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},Ks.id))]},Nr.id)}return s.jsx(aL,{item:Nr,onClick:()=>o(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${ee?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},Nr.id)}),sn&&vn(cr),!pe&&(V?s.jsx(p5,{dark:ee,onNavigate:()=>o(!1)}):le?s.jsx("button",{onClick:()=>{a(!0),o(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${ee?"text-white/70 hover:bg-white/10":"text-blue-600 hover:bg-blue-50"}`,children:"Sign In / Register"}):null)]})})]}),s.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:t}),!Q&&s.jsx("footer",{className:"bg-gray-950 text-gray-400",children:s.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-16",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-12",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[((ii=e.agent)==null?void 0:ii.avatar_url)&&s.jsx("img",{src:e.agent.avatar_url,alt:Y,className:"h-16 w-16 rounded-2xl object-cover ring-2 ring-white/10"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-bold text-white text-lg tracking-tight",children:Y}),s.jsx("p",{className:"text-sm text-gray-400",children:pe?"Personal Real Estate Advisor":((Ui=e.agent)==null?void 0:Ui.title)||"Real Estate Professional"})]})]}),((Ta=e.agent)==null?void 0:Ta.phone)&&s.jsx("p",{className:"text-sm mt-3",children:s.jsxs("a",{href:`tel:${e.agent.phone}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[s.jsx(ri,{className:"h-3.5 w-3.5"})," ",e.agent.phone]})}),((vi=e.agent)==null?void 0:vi.email)&&s.jsx("p",{className:"text-sm mt-1",children:s.jsxs("a",{href:`mailto:${e.agent.email}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[s.jsx(mi,{className:"h-3.5 w-3.5"})," ",e.agent.email]})}),s.jsx(rY,{siteConfig:e,className:"mt-4"}),pe&&s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-sm mt-4",children:"Helping you find the right real estate agent, wherever you need one."}),s.jsx("p",{className:"text-sm mt-2",children:"Columbia, Missouri"})]})]}),s.jsxs("div",{children:[s.jsx("h2",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),s.jsxs("ul",{className:"space-y-3 text-sm",children:[(pe?[{to:"/p/how-it-works",label:"How It Works"},{to:"/p/about-tom",label:"About Tom"},{to:"/p/who-i-help",label:"Who I Help"},{to:"/p/frequently-asked-questions",label:"Frequently Asked Questions"},{to:"/p/call-tom-first",label:"Call Tom First"}]:tr).map(Nr=>s.jsx("li",{children:/^https?:\/\//i.test(Nr.to)?s.jsx("a",{href:Nr.to,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:Nr.label}):s.jsx(Wr,{to:Nr.to,className:"hover:text-white transition-colors",children:Nr.label})},Nr.to)),je&&!pe&&s.jsx("li",{children:s.jsx("a",{href:je,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:"Schedule a Call"})})]}),y.length>0&&!pe&&s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"font-semibold text-white mt-8 mb-4 text-sm tracking-wider uppercase",children:"Local Areas"}),s.jsx("ul",{className:"space-y-3 text-sm",children:y.map(Nr=>s.jsx("li",{children:s.jsx(Wr,{to:`/homes-for-sale-in-${Nr.city_slug}`,className:"hover:text-white transition-colors",children:Nr.city_name})},Nr.city_slug))})]})]}),s.jsxs("div",{children:[s.jsx("h2",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Get In Touch"}),s.jsx("p",{className:"text-sm text-gray-400 leading-relaxed mb-4",children:pe?"Helping you find the right real estate agent, wherever you need one.":Se?"Have a real estate question or need a trusted connection? Get in touch today.":"Ready to find your dream home? Get in touch today for a personalized consultation."}),s.jsx(Wr,{to:pe?"/p/call-tom-first":"/contact",className:"inline-block px-5 py-2.5 bg-white text-gray-900 text-sm font-semibold rounded-lg hover:bg-gray-100 transition-colors",children:pe?"Call Tom First":"Contact Me"})]})]}),s.jsxs("div",{className:"mt-14 pt-6 border-t border-gray-800/50",children:[e.showTeamLogo&&e.teamLogoUrl&&s.jsx("div",{className:"flex items-center justify-center mb-6",children:s.jsx("img",{src:e.teamLogoUrl,alt:`${J} logo`,className:`${YRt(e.headerLogoSize)} w-auto object-contain`})}),e.brokerageLegalName&&s.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-xs text-gray-400 mb-3",children:[s.jsxs("span",{children:[Y," · ",e.brokerageLegalName]}),e.agentLicenseNumber&&s.jsx("span",{children:e.agentLicenseNumber}),e.brokerageLicenseNumber&&s.jsxs("span",{children:["Brokerage #",e.brokerageLicenseNumber]})]}),e.mlsDisclaimerText&&s.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[e.mlsLogoUrl&&s.jsx("img",{src:e.mlsLogoUrl,alt:"MLS",className:"h-8 w-auto flex-shrink-0 mt-0.5"}),s.jsx("p",{className:"text-[11px] text-gray-400 leading-relaxed max-w-3xl text-center",children:e.mlsDisclaimerText})]}),s.jsxs("div",{className:"flex items-center justify-center gap-4 text-xs text-gray-400",children:[e.equalHousingEnabled&&s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-5 w-5 text-gray-400",children:s.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),s.jsx("span",{children:"Equal Housing Opportunity"})]}),s.jsxs("span",{children:["© ",new Date().getFullYear()," ",Y,". Powered by LevelUp."]})]})]})]})}),!Q&&!pe&&((ca=e.agent)==null?void 0:ca.avatar_url)&&s.jsx(C4t,{agent:e.agent,bookingUrl:je}),c&&s.jsx(f5,{open:c,mode:"optional",siteConfig:e,onComplete:()=>a(!1),onSkip:()=>a(!1)}),s.jsx(JK,{slug:e.subdomainSlug}),s.jsx(eY,{slug:e.subdomainSlug}),!pe&&s.jsx(tY,{slug:e.subdomainSlug})]})}function C4t({agent:t,bookingUrl:e}){var o;const[r,n]=C.useState(!1),i=Hs();return t?s.jsx("div",{className:`fixed right-6 z-40 ${e?"bottom-24 md:bottom-6":"bottom-6"}`,children:r?s.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl border border-gray-200 w-72 overflow-hidden animate-in slide-in-from-bottom-4 fade-in duration-200",children:[s.jsxs("div",{className:"p-5",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[s.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-gray-100"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-bold text-gray-900 text-sm",children:t.full_name}),s.jsx("p",{className:"text-xs text-gray-600",children:t.title||"Real Estate Professional"})]})]}),s.jsx("p",{className:"text-xs text-gray-600 mb-4",children:"Have questions about a property or the area? I'm here to help!"}),s.jsxs("div",{className:"space-y-2",children:[t.phone&&s.jsxs("a",{href:`tel:${t.phone}`,className:"flex items-center gap-2 w-full px-3 py-2 bg-gray-50 hover:bg-gray-100 rounded-xl text-sm text-gray-700 transition-colors",children:[s.jsx(ri,{className:"h-4 w-4 text-gray-400"}),t.phone]}),t.email&&s.jsxs("a",{href:`mailto:${t.email}`,className:"flex items-center gap-2 w-full px-3 py-2 bg-gray-50 hover:bg-gray-100 rounded-xl text-sm text-gray-700 transition-colors",children:[s.jsx(mi,{className:"h-4 w-4 text-gray-400"}),"Email Me"]}),s.jsx("button",{onClick:()=>{n(!1),i("/contact")},className:"w-full px-3 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-xl transition-colors",children:"Ask a Question"}),e&&s.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"block text-center w-full px-3 py-2.5 bg-gray-900 hover:bg-gray-800 text-white text-sm font-semibold rounded-xl transition-colors",children:"Schedule a Call"})]})]}),s.jsx("button",{onClick:()=>n(!1),className:"absolute top-3 right-3 p-1 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100",children:s.jsx(Os,{className:"h-4 w-4"})})]}):s.jsxs("button",{onClick:()=>n(!0),className:"group flex items-center gap-3 bg-white pl-1.5 pr-5 py-1.5 rounded-full shadow-xl border border-gray-200 hover:shadow-2xl transition-all hover:scale-105",children:[s.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-10 w-10 rounded-full object-cover ring-2 ring-blue-100"}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:"text-xs font-bold text-gray-900 leading-none",children:(o=t.full_name)==null?void 0:o.split(" ")[0]}),s.jsx("p",{className:"text-[10px] text-blue-600 font-medium mt-0.5",children:"Chat with me →"})]})]})}):null}function aL({item:t,className:e,onClick:r}){const n=t.target_url||"#";return/^(https?:)?\/\//i.test(n)||/^(mailto:|tel:)/i.test(n)?s.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:e,onClick:r,children:t.label}):s.jsx(Wr,{to:n,className:e,onClick:r,children:t.label})}const N4t=new Set(["danicapatton"]);function GAe(t){if(!t)return!1;const e=t.themeConfig||{};return e.expReady===!1?!1:e.expReady===!0||N4t.has(t.subdomainSlug)}const I4t="/exp-ready",P4t="eXp Ready",Rue={california:"California DRE License",ca:"California DRE License"};function wG(t){const e=(t||"").trim();if(!e)return"Real Estate License";const r=e.toLowerCase();return Rue[r]?Rue[r]:`${e.replace(/\b\w/g,i=>i.toUpperCase())} Real Estate License`}function Lue(t){if(t)return t.replace(/^\s*DRE\s*#?\s*/i,"").replace(/^\s*#/,"").trim()||void 0}function R4t({children:t,siteConfig:e}){var tr,_t,cr,Tr,sn,ur,xr;const r=ki(),n=Hs(),[i,o]=C.useState(!1),[c,a]=C.useState(!1);C.useEffect(()=>{typeof window<"u"&&new URLSearchParams(window.location.search).get("join")==="1"&&a(!0)},[]);const[f,p]=C.useState(!1),[y,v]=C.useState(!1),[T,E]=C.useState([]),[k,P]=C.useState(!1),R=C.useRef(null),D=C.useRef(null),{user:M,profile:B,signOut:V}=Hx();d5(e,M==null?void 0:M.id),h5(e,M==null?void 0:M.id);const G=((tr=e.agent)==null?void 0:tr.full_name)||"Agent",W=Lue(e.agentLicenseNumber),Y=Lue(e.brokerageLicenseNumber),J=e.siteTitle||`${G} Real Estate`,Q=rr=>{if(!rr)return rr;const vn=G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ct=new RegExp(`^\\s*${vn}\\s*[|\\-–—:]\\s*`,"i");return rr.replace(ct,"").trim()},ee=J&&J!==`${G} Real Estate`?J:null,le=ee?Q(ee):null,pe=le&&le.toLowerCase()!==G.toLowerCase()?le:null,Se=r.pathname==="/search",je=r.pathname==="/",Le=e.leadRegistrationMode!=="disabled",Ae="#c9a96e",be=e.bookingUrl;C.useEffect(()=>{const rr=()=>P(window.scrollY>80);return window.addEventListener("scroll",rr,{passive:!0}),()=>window.removeEventListener("scroll",rr)},[]),C.useEffect(()=>{(async()=>{const{data:vn}=await Re.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",e.id).eq("is_published",!0).order("sort_order",{ascending:!0});E(vn||[])})()},[e.id]),C.useEffect(()=>{const rr=vn=>{R.current&&!R.current.contains(vn.target)&&p(!1),D.current&&!D.current.contains(vn.target)&&v(!1)};return document.addEventListener("mousedown",rr),()=>document.removeEventListener("mousedown",rr)},[]);const me=(((_t=e.themeConfig)==null?void 0:_t.focusPages)??[]).filter(rr=>rr==null?void 0:rr.slug).map(rr=>({to:`/${rr.slug}`,label:rr.navLabel||rr.title})).concat(GAe(e)?[{to:I4t,label:P4t}]:[]),Te=Jje(e)||wx(e),{data:Ne}=u5(Te?e.agentId:null),Ee=((Ne==null?void 0:Ne.length)??0)>0,{data:we}=_K(e.agentId),He=((we==null?void 0:we.length)??0)>0,tt=[{to:"/",label:"Home"},...Te?Ee?[{to:"/listings",label:"My Listings"}]:[]:[{to:"/search",label:"Search"}],...He?[{to:"/sold",label:"Sold"}]:[],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],at=[...tt,...me],Et=e.siteTitle||`${G} - Real Estate`,vt=e.siteTagline||`Browse homes and listings with ${G}`,Gt=e.ogImageUrl||((cr=e.agent)==null?void 0:cr.avatar_url)||"",pt=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug||""}.thelocalmove.com`,Pt=je?k?"bg-[#0d0b0a]/95 backdrop-blur-lg border-b border-white/5":"bg-transparent":"bg-[#0d0b0a] border-b border-white/5";return s.jsxs("div",{className:`flex flex-col ${Se?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[s.jsx(AK,{siteConfig:e,pagePath:r.pathname}),s.jsx(kK,{siteConfig:e}),s.jsxs(Zo,{children:[s.jsx("title",{children:Et}),s.jsx("meta",{name:"description",content:vt}),s.jsx("meta",{property:"og:title",content:Et}),s.jsx("meta",{property:"og:description",content:vt}),s.jsx("meta",{property:"og:type",content:"website"}),s.jsx("meta",{property:"og:url",content:pt+r.pathname}),Gt&&s.jsx("meta",{property:"og:image",content:Gt}),s.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),s.jsx("meta",{name:"twitter:title",content:Et}),s.jsx("meta",{name:"twitter:description",content:vt}),Gt&&s.jsx("meta",{name:"twitter:image",content:Gt}),e.faviconUrl&&s.jsx("link",{rel:"icon",href:e.faviconUrl,type:"image/png"}),s.jsx("link",{rel:"canonical",href:`${pt}${r.pathname}`}),s.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500&display=swap",rel:"stylesheet"})]}),s.jsxs("header",{className:`${je?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${Pt}`,children:[s.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:s.jsxs("div",{className:"flex items-center justify-between min-h-20 py-3 gap-6",children:[s.jsxs(Wr,{to:"/",className:"flex items-center gap-3 shrink-0",children:[e.showTeamLogo&&e.teamLogoUrl&&s.jsx("img",{src:e.teamLogoUrl,alt:`${G} brokerage logo`,className:"h-9 sm:h-11 w-auto max-w-[150px] object-contain"}),s.jsxs("span",{className:"flex flex-col leading-tight",children:[s.jsx("span",{className:"block whitespace-nowrap text-white text-base sm:text-lg xl:text-xl tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:G}),e.brokerageLegalName&&s.jsx("span",{className:"hidden sm:block whitespace-nowrap text-[10px] sm:text-[11px] tracking-[0.14em] uppercase text-white/60",children:e.brokerageLegalName}),pe&&s.jsx("span",{className:"hidden xl:block whitespace-nowrap text-[10px] tracking-[0.18em] uppercase text-white/40",children:pe})]})]}),s.jsxs("nav",{className:"hidden lg:flex items-center justify-end gap-0 flex-1 min-w-0",children:[tt.map(rr=>s.jsx(Wr,{to:rr.to,className:`whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${r.pathname===rr.to?"text-white":"text-white/40 hover:text-white"}`,children:rr.label},rr.to)),me.length>0&&s.jsxs("div",{ref:D,className:"relative",children:[s.jsxs("button",{onClick:()=>v(!y),className:`flex items-center gap-1 whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${me.some(rr=>r.pathname===rr.to)?"text-white":"text-white/40 hover:text-white"}`,children:["Specialty"," ",s.jsx(yl,{className:`h-3 w-3 transition-transform ${y?"rotate-180":""}`})]}),y&&s.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-[#1a1715] border border-white/10 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:me.map(rr=>s.jsx(Wr,{to:rr.to,onClick:()=>v(!1),className:`block px-5 py-2.5 text-xs tracking-wider text-white/50 hover:text-white hover:bg-white/5 uppercase transition-colors ${r.pathname===rr.to?"text-white":""}`,children:rr.label},rr.to))})]}),T.length>0&&s.jsxs("div",{ref:R,className:"relative",children:[s.jsxs("button",{onClick:()=>p(!f),className:`flex items-center gap-1 whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${r.pathname.startsWith("/homes-for-sale-in-")?"text-white":"text-white/40 hover:text-white"}`,children:["Cities ",s.jsx(yl,{className:`h-3 w-3 transition-transform ${f?"rotate-180":""}`})]}),f&&s.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-[#1a1715] border border-white/10 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:T.map(rr=>s.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${rr.city_slug}`),p(!1)},className:"w-full text-left px-5 py-2.5 text-xs tracking-wider text-white/50 hover:text-white hover:bg-white/5 uppercase transition-colors",children:rr.city_name},rr.city_slug))})]}),M?s.jsx("div",{className:"ml-3",children:s.jsx(m5,{savedClassName:"flex items-center gap-1.5 px-3 py-2 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",triggerClassName:"flex items-center gap-1.5 border border-white/20 py-1 pl-1 pr-3 text-xs uppercase tracking-wider text-white/70 outline-none transition-colors hover:text-white",avatarClassName:"flex h-6 w-6 items-center justify-center bg-white/15 text-[10px] font-semibold text-white"})}):Le?s.jsx("button",{onClick:()=>a(!0),className:"ml-3 px-5 py-2 text-xs tracking-[0.2em] uppercase border border-white/20 text-white/60 hover:bg-white hover:text-black transition-all duration-500",children:"Sign In"}):null,be&&s.jsx(Gp,{bookingUrl:be,label:"Schedule",size:"sm",className:"ml-3",source:"nav"})]}),s.jsxs("button",{onClick:()=>o(!i),className:"lg:hidden p-2 text-white/60 hover:text-white",children:[s.jsx("div",{className:"flex flex-col items-center gap-0.5",children:i?s.jsx(Os,{className:"h-5 w-5"}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"w-6 h-px bg-current"}),s.jsx("div",{className:"w-4 h-px bg-current mt-1.5"}),s.jsx("div",{className:"w-6 h-px bg-current mt-1.5"})]})}),s.jsx("span",{className:"text-[8px] tracking-[0.3em] uppercase mt-1 block",children:"MENU"})]})]})}),i&&s.jsx("div",{className:"lg:hidden border-t border-white/5 bg-[#0d0b0a]/98 backdrop-blur-lg",children:s.jsxs("div",{className:"px-6 py-4 space-y-1",children:[be&&s.jsx(Gp,{bookingUrl:be,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),tt.map(rr=>s.jsx(Wr,{to:rr.to,onClick:()=>o(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${r.pathname===rr.to?"text-white":"text-white/40 hover:text-white"}`,children:rr.label},rr.to)),me.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:Ae},children:"Specialty"}),me.map(rr=>s.jsx(Wr,{to:rr.to,onClick:()=>o(!1),className:`block px-3 py-2.5 text-xs tracking-wider uppercase transition-colors ${r.pathname===rr.to?"text-white":"text-white/40 hover:text-white"}`,children:rr.label},rr.to))]}),T.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:Ae},children:"Cities"}),T.map(rr=>s.jsx(Wr,{to:`/homes-for-sale-in-${rr.city_slug}`,onClick:()=>o(!1),className:"block px-3 py-2.5 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",children:rr.city_name},rr.city_slug))]}),M?s.jsx(p5,{dark:!0,onNavigate:()=>o(!1)}):Le?s.jsx("button",{onClick:()=>{a(!0),o(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign In / Register"}):null]})})]}),s.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:t}),!Se&&s.jsx("footer",{className:"bg-[#0a0908] text-white/70 border-t border-white/10",children:s.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-20",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-16",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-white text-xl tracking-tight mb-3",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:G}),s.jsx("p",{className:"text-white/70 text-xs tracking-[0.15em] uppercase mb-6",children:((Tr=e.agent)==null?void 0:Tr.title)||"Real Estate Professional"}),(W||Y)&&s.jsxs("div",{className:"mb-6 p-4 border border-white/10 bg-white/5",children:[W&&s.jsxs("p",{className:"text-sm text-white font-medium tracking-wide",children:[wG(e.licenseState)," #",W]}),Y&&s.jsxs("p",{className:"text-xs text-white/70 tracking-wider uppercase mt-1",children:["Brokerage License #",Y]})]}),((sn=e.agent)==null?void 0:sn.phone)&&s.jsxs("a",{href:`tel:${e.agent.phone}`,className:"flex items-center gap-3 text-sm text-white/70 hover:text-white transition-colors mb-3",children:[s.jsx(ri,{className:"h-3.5 w-3.5"})," ",e.agent.phone]}),((ur=e.agent)==null?void 0:ur.email)&&s.jsxs("a",{href:`mailto:${e.agent.email}`,className:"flex items-center gap-3 text-sm text-white/70 hover:text-white transition-colors",children:[s.jsx(mi,{className:"h-3.5 w-3.5"})," ",e.agent.email]}),s.jsx(rY,{siteConfig:e,className:"mt-6",iconClassName:"border-white/20"})]}),s.jsxs("div",{children:[s.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:Ae},children:"Quick Links"}),s.jsxs("ul",{className:"space-y-3",children:[at.map(rr=>s.jsx("li",{children:s.jsx(Wr,{to:rr.to,className:"text-xs tracking-wider uppercase text-white/70 hover:text-white transition-colors",children:rr.label})},rr.to)),be&&s.jsx("li",{children:s.jsx("a",{href:be,target:"_blank",rel:"noopener noreferrer",className:"text-xs tracking-wider uppercase transition-colors hover:opacity-80",style:{color:RT},children:"Schedule a Free Consultation"})})]})]}),s.jsxs("div",{children:[s.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:Ae},children:"Get In Touch"}),s.jsx("p",{className:"text-sm text-white/70 leading-relaxed mb-6",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:"Ready to experience luxury real estate? Let's connect."}),s.jsxs("div",{className:"flex flex-col items-start gap-3",children:[be&&s.jsx(Gp,{bookingUrl:be,label:"Schedule a Free Consultation",size:"sm",source:"footer"}),s.jsx(Wr,{to:"/contact",className:"inline-block px-8 py-3 text-xs tracking-[0.3em] uppercase border border-white/20 text-white/90 hover:bg-white hover:text-black transition-all duration-500",children:"Contact Me"})]})]})]}),s.jsxs("div",{className:"mt-16 pt-8 border-t border-white/10",children:[e.showTeamLogo&&e.teamLogoUrl&&s.jsx("div",{className:"flex items-center justify-center mb-6",children:s.jsx("img",{src:e.teamLogoUrl,alt:"Team",className:"h-10 w-auto object-contain opacity-70"})}),e.brokerageLegalName&&s.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-[11px] text-white/70 tracking-wider uppercase mb-3",children:[s.jsxs("span",{children:[G," · ",e.brokerageLegalName]}),W&&s.jsxs("span",{children:[wG(e.licenseState)," #",W]}),Y&&s.jsxs("span",{children:["Brokerage #",Y]})]}),e.mlsDisclaimerText&&s.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[e.mlsLogoUrl&&s.jsx("img",{src:e.mlsLogoUrl,alt:"MLS",className:"h-6 w-auto flex-shrink-0 mt-0.5 opacity-70"}),s.jsx("p",{className:"text-[11px] text-white/70 leading-relaxed max-w-3xl text-center",children:e.mlsDisclaimerText})]}),s.jsxs("div",{className:"flex items-center justify-center gap-4 text-[11px] text-white/70 tracking-wider uppercase",children:[e.equalHousingEnabled&&s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-4 w-4",children:s.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),s.jsx("span",{children:"Equal Housing Opportunity"})]}),s.jsxs("span",{children:["© ",new Date().getFullYear()," ",G,". Powered by LevelUp."]})]})]})]})}),!Se&&((xr=e.agent)==null?void 0:xr.avatar_url)&&s.jsx(L4t,{agent:e.agent,agentLicense:W,siteConfig:e,accentColor:Ae}),c&&s.jsx(f5,{open:c,mode:"optional",siteConfig:e,onComplete:()=>a(!1),onSkip:()=>a(!1),theme:"luxury",accentColor:Ae}),s.jsx(JK,{slug:e.subdomainSlug}),s.jsx(eY,{slug:e.subdomainSlug}),s.jsx(tY,{slug:e.subdomainSlug})]})}function L4t({agent:t,agentLicense:e,siteConfig:r,accentColor:n}){var a;const[i,o]=C.useState(!1),c=Hs();return t?s.jsx("div",{className:`fixed right-6 z-40 ${r.bookingUrl?"bottom-24 md:bottom-6":"bottom-6"}`,children:i?s.jsxs("div",{className:"bg-[#1a1715] border border-white/10 w-72 overflow-hidden animate-in slide-in-from-bottom-4 fade-in duration-200",children:[s.jsxs("div",{className:"p-5",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-12 w-12 rounded-full object-cover ring-1 ring-white/10"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-white text-sm font-medium",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:t.full_name}),s.jsx("p",{className:"text-white/50 text-[10px] tracking-[0.1em] uppercase",children:t.title||"Real Estate Professional"})]})]}),e&&s.jsxs("div",{className:"mb-3 px-3 py-2 bg-white/5 border border-white/10",children:[s.jsx("p",{className:"text-[10px] text-white/50 tracking-wider uppercase",children:wG(r.licenseState)}),s.jsxs("p",{className:"text-xs text-white font-medium",children:["#",e]})]}),s.jsxs("div",{className:"space-y-2",children:[t.phone&&s.jsxs("a",{href:`tel:${t.phone}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/70 hover:text-white transition-colors tracking-wider",children:[s.jsx(ri,{className:"h-3.5 w-3.5"})," ",t.phone]}),t.email&&s.jsxs("a",{href:`mailto:${t.email}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/70 hover:text-white transition-colors tracking-wider",children:[s.jsx(mi,{className:"h-3.5 w-3.5"})," Email Me"]}),s.jsx("button",{onClick:()=>{o(!1),c("/contact")},className:"w-full px-3 py-2.5 text-xs tracking-[0.2em] uppercase text-black hover:opacity-90 transition-colors",style:{backgroundColor:n},children:"Send a Message"})]})]}),s.jsx("button",{onClick:()=>o(!1),className:"absolute top-3 right-3 p-1 text-white/20 hover:text-white/50",children:s.jsx(Os,{className:"h-4 w-4"})})]}):s.jsxs("button",{onClick:()=>o(!0),className:"group flex items-center gap-3 bg-[#1a1715] border border-white/10 pl-1.5 pr-5 py-1.5 hover:border-white/20 transition-all",children:[s.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-10 w-10 rounded-full object-cover ring-1 ring-white/10"}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:"text-[11px] text-white leading-none",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:(a=t.full_name)==null?void 0:a.split(" ")[0]}),s.jsx("p",{className:"text-[9px] tracking-[0.15em] uppercase mt-1",style:{color:n},children:"Let's connect →"})]})]})}):null}const N2="#2c1810",bp="#b8860b";function D4t({children:t,siteConfig:e}){var je,Le,Ae;const r=ki();Hs();const[n,i]=C.useState(!1),[o,c]=C.useState(!1);C.useEffect(()=>{typeof window<"u"&&new URLSearchParams(window.location.search).get("join")==="1"&&c(!0)},[]);const[a,f]=C.useState(!1),[p,y]=C.useState([]),[v,T]=C.useState(!1),E=C.useRef(null),{user:k,profile:P,signOut:R}=Hx();d5(e,k==null?void 0:k.id),h5(e,k==null?void 0:k.id);const D=((je=e.agent)==null?void 0:je.full_name)||"Agent",M=e.siteTitle||`${D} Land & Ranch`,B=r.pathname==="/",V=e.leadRegistrationMode!=="disabled",G=wx(e);C.useEffect(()=>{const be=()=>T(window.scrollY>80);return window.addEventListener("scroll",be,{passive:!0}),()=>window.removeEventListener("scroll",be)},[]),C.useEffect(()=>{(async()=>{const{data:me}=await Re.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",e.id).eq("is_published",!0).order("sort_order");me&&y(me)})()},[e.id]),C.useEffect(()=>{const be=me=>{E.current&&!E.current.contains(me.target)&&f(!1)};return document.addEventListener("mousedown",be),()=>document.removeEventListener("mousedown",be)},[]);const{data:W}=_K(e.agentId),{data:Y}=u5(e.agentId),J=((W==null?void 0:W.length)??0)>0,Q=((Y==null?void 0:Y.length)??0)>0,ee=[{label:"Home",path:"/"},...G?[]:[{label:"Search Properties",path:"/search"}],...G&&Q?[{label:"My Listings",path:"/listings"}]:[],...J?[{label:"Sold",path:"/sold"}]:[],{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],le=v||!B?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",pe=v||!B?N2:"#ffffff",Se=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug||""}.thelocalmove.com`;return s.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[s.jsxs(Zo,{children:[s.jsx("title",{children:M}),s.jsx("meta",{property:"og:url",content:Se+r.pathname}),s.jsx("link",{rel:"canonical",href:`${Se}${r.pathname}`}),s.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700;800&family=Lora:wght@400;500;600&display=swap",rel:"stylesheet"})]}),s.jsx(AK,{siteConfig:e}),s.jsx(kK,{siteConfig:e}),s.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${le}`,children:[s.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6",children:s.jsxs("div",{className:"flex items-center justify-between h-16 md:h-20",children:[s.jsxs(Wr,{to:"/",className:"flex items-center gap-2.5",children:[s.jsx(Mee,{className:"w-7 h-7",style:{color:bp}}),s.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:pe,fontFamily:"'Playfair Display', Georgia, serif"},children:M})]}),s.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[ee.map(be=>s.jsx(Wr,{to:be.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:r.pathname===be.path?bp:pe},children:be.label},be.path)),p.length>0&&s.jsxs("div",{ref:E,className:"relative",children:[s.jsxs("button",{onClick:()=>f(!a),className:"px-4 py-2 text-sm font-medium tracking-wide uppercase flex items-center gap-1 transition-colors hover:opacity-80",style:{color:pe},children:["Area Guides ",s.jsx(yl,{className:`w-3.5 h-3.5 transition-transform ${a?"rotate-180":""}`})]}),a&&s.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-white rounded-xl shadow-xl border border-gray-100 py-2 animate-in fade-in-0 slide-in-from-top-2",children:p.map(be=>s.jsx(Wr,{to:`/homes-for-sale-in-${be.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:N2},onClick:()=>f(!1),children:be.city_name},be.city_slug))})]}),k?s.jsx("div",{className:"ml-3",children:s.jsx(m5,{showSaved:!1,triggerClassName:"flex items-center gap-1.5 rounded-full border-2 py-1 pl-1 pr-3 text-sm font-medium outline-none transition-all hover:scale-105",avatarClassName:"flex h-7 w-7 items-center justify-center rounded-full text-xs font-semibold text-white"})}):V?s.jsx("button",{onClick:()=>c(!0),className:"ml-3 px-5 py-2.5 text-sm font-semibold text-white rounded-full hover:shadow-lg transition-all hover:scale-105",style:{backgroundColor:bp},children:"Sign In"}):null]}),s.jsx("button",{onClick:()=>i(!n),className:"md:hidden p-2",style:{color:pe},children:n?s.jsx(Os,{className:"w-6 h-6"}):s.jsx(QS,{className:"w-6 h-6"})})]})}),n&&s.jsx("div",{className:"md:hidden bg-white border-t border-gray-100 shadow-xl animate-in slide-in-from-top-2",children:s.jsxs("div",{className:"px-4 py-4 space-y-1",children:[ee.map(be=>s.jsx(Wr,{to:be.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:r.pathname===be.path?bp:N2},onClick:()=>i(!1),children:be.label},be.path)),p.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-4 py-2 text-xs font-semibold tracking-wider uppercase text-gray-400",children:"Area Guides"}),p.map(be=>s.jsx(Wr,{to:`/homes-for-sale-in-${be.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:N2},onClick:()=>i(!1),children:be.city_name},be.city_slug))]}),k&&s.jsx(p5,{onNavigate:()=>i(!1)}),!k&&V&&s.jsx("button",{onClick:()=>{c(!0),i(!1)},className:"w-full mt-3 px-5 py-3 text-white font-semibold rounded-full",style:{backgroundColor:bp},children:"Sign In"})]})})]}),s.jsx("main",{children:t}),s.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:N2},children:s.jsxs("div",{className:"max-w-6xl mx-auto",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-10",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[s.jsx(Mee,{className:"w-6 h-6",style:{color:bp}}),s.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:M})]}),s.jsx("p",{className:"text-white/60 text-sm leading-relaxed",children:"Personal guidance for buying and selling land, homes, and rural property."}),s.jsx(rY,{siteConfig:e,className:"mt-5",iconClassName:"border-white/20 text-white"})]}),s.jsxs("div",{children:[s.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),s.jsx("div",{className:"space-y-2",children:ee.map(be=>s.jsx(Wr,{to:be.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:be.label},be.path))})]}),s.jsxs("div",{children:[s.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Contact"}),s.jsxs("div",{className:"space-y-3",children:[((Le=e.agent)==null?void 0:Le.phone)&&s.jsxs("a",{href:`tel:${e.agent.phone}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[s.jsx(ri,{className:"w-4 h-4",style:{color:bp}}),e.agent.phone]}),((Ae=e.agent)==null?void 0:Ae.email)&&s.jsxs("a",{href:`mailto:${e.agent.email}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[s.jsx(mi,{className:"w-4 h-4",style:{color:bp}}),e.agent.email]})]})]})]}),s.jsxs("div",{className:"mt-12 pt-8 border-t border-white/10 flex items-center justify-between",children:[s.jsxs("p",{className:"text-white/40 text-xs",children:["© ",new Date().getFullYear()," ",M,". All rights reserved."]}),s.jsx("div",{className:"h-px w-16",style:{backgroundColor:bp}})]})]})}),o&&s.jsx(f5,{open:o,mode:e.leadRegistrationMode==="required"?"required":"optional",siteConfig:e,onSkip:()=>c(!1),onComplete:()=>c(!1)}),s.jsx(JK,{slug:e.subdomainSlug}),s.jsx(eY,{slug:e.subdomainSlug}),s.jsx(tY,{slug:e.subdomainSlug})]})}function I2(){const{pathname:t}=ki();return C.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[t]),null}const M4t=C.lazy(()=>Fe(()=>import("./LeadSiteHome-_sM8RJp9.js"),__vite__mapDeps([9,10,11,12,13,14,15,16,17]))),O4t=C.lazy(()=>Fe(()=>import("./LeadSiteLuxuryHome-DnKoiQRJ.js"),__vite__mapDeps([18,19,13,14,20,17,21,22]))),F4t=C.lazy(()=>Fe(()=>import("./LeadSiteLandRanchHome-C-gl2im8.js"),__vite__mapDeps([23,10,11,12,13,14,15,24,25,26]))),P2=C.lazy(()=>Fe(()=>import("./LeadSiteSearch-Dc_z8dAt.js"),__vite__mapDeps([27,10,11,12,28,29,30,31]))),B4t=C.lazy(()=>Fe(()=>import("./LeadSiteLuxurySearch-srNM2dpt.js"),__vite__mapDeps([32,10,11,12,28,29,30,31]))),R2=C.lazy(()=>Fe(()=>import("./LeadSiteListingDetail-C7J2H_ry.js"),__vite__mapDeps([33,34,35,25,36,37,38,39,40]))),$4t=C.lazy(()=>Fe(()=>import("./LeadSiteLuxuryListingDetail-DpKa3KxF.js"),__vite__mapDeps([41,34,35,25,36,37,38,39,40]))),z4t=C.lazy(()=>Fe(()=>import("./LeadSiteAbout-S3o2vCyS.js"),__vite__mapDeps([42,16]))),U4t=C.lazy(()=>Fe(()=>import("./LeadSiteLuxuryAbout-c_5Z2AX2.js"),__vite__mapDeps([43,44]))),V4t=C.lazy(()=>Fe(()=>import("./LeadSiteContact-DZ_-zlHg.js"),[])),q4t=C.lazy(()=>Fe(()=>import("./LeadSiteLuxuryContact-u4q4o5B4.js"),[])),uv=C.lazy(()=>Fe(()=>import("./LeadSiteConsumerDashboard-BPU7-fLC.js"),[])),Hf=C.lazy(()=>Fe(()=>import("./LeadSiteBlog-Bc3LsBIb.js"),__vite__mapDeps([45,46]))),oL=C.lazy(()=>Fe(()=>import("./LeadSiteCommunity-Gi2eOLE7.js"),__vite__mapDeps([47,39,5,48,49,50,51]))),G4t=C.lazy(()=>Fe(()=>import("./LeadSiteSellers-IDGpfDNO.js"),__vite__mapDeps([52,44]))),H4t=C.lazy(()=>Fe(()=>import("./LeadSiteCityPage-COrxgaKu.js"),__vite__mapDeps([53,54,31,19,14]))),W4t=C.lazy(()=>Fe(()=>import("./LeadSiteSubdivisionPage-D3IEsuCG.js"),[])),lL=C.lazy(()=>Fe(()=>import("./LeadSiteCustomPage-Ak-V4g5f.js"),[])),K4t=C.lazy(()=>Fe(()=>import("./LeadSiteFocusPage-vIxaVDWJ.js"),__vite__mapDeps([55,50]))),Y4t=C.lazy(()=>Fe(()=>import("./LeadSiteExpReady-DzcVszMX.js"),__vite__mapDeps([56,57,49,21]))),Z4t=C.lazy(()=>Fe(()=>import("./LeadSiteConsultation-DbODMeu9.js"),[])),Iw=C.lazy(()=>Fe(()=>import("./LeadSiteReviews-DawYOLI9.js"),[])),X4t=C.lazy(()=>Fe(()=>import("./LeadSiteExchangeListings-GnHa8_Zr.js"),[]).then(t=>({default:t.LeadSiteExchangeListingsIndex}))),Q4t=C.lazy(()=>Fe(()=>import("./LeadSiteExchangeListings-GnHa8_Zr.js"),[]).then(t=>({default:t.LeadSiteSoldListingsIndex}))),J4t=C.lazy(()=>Fe(()=>import("./LeadSiteExchangeListings-GnHa8_Zr.js"),[]).then(t=>({default:t.LeadSiteExchangeListingDetail}))),eBt=C.lazy(()=>Fe(()=>import("./OrgSiteLayout-CjVommSx.js"),__vite__mapDeps([58,59]))),tBt=C.lazy(()=>Fe(()=>import("./OrgSiteHome-BEQqu82m.js"),__vite__mapDeps([60,59]))),rBt=C.lazy(()=>Fe(()=>import("./OrgSiteAgents-C0z63oMv.js"),__vite__mapDeps([61,59,60,62]))),nBt=C.lazy(()=>Fe(()=>import("./OrgSiteAgents-C0z63oMv.js"),__vite__mapDeps([61,59,60,62])).then(t=>({default:t.OrgSiteAgentProfile}))),Due=C.lazy(()=>Fe(()=>import("./OrgSiteListings-BCxz1F37.js"),__vite__mapDeps([63,59,60,62]))),iBt=C.lazy(()=>Fe(()=>import("./OrgSiteListings-BCxz1F37.js"),__vite__mapDeps([63,59,60,62])).then(t=>({default:t.OrgSiteListingDetail}))),sBt=C.lazy(()=>Fe(()=>import("./OrgSitePages-Dwj554ng.js"),__vite__mapDeps([62,59,60])).then(t=>({default:t.OrgSiteAbout}))),aBt=C.lazy(()=>Fe(()=>import("./OrgSitePages-Dwj554ng.js"),__vite__mapDeps([62,59,60])).then(t=>({default:t.OrgSiteContact}))),oBt=C.lazy(()=>Fe(()=>import("./OrgSitePages-Dwj554ng.js"),__vite__mapDeps([62,59,60])).then(t=>({default:t.OrgSiteJoin})));function Ow(){return s.jsx("div",{className:"min-h-[60vh] flex items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent"})})}function lBt({siteConfig:t}){const{data:e,isLoading:r}=u5(t.agentId);return r?s.jsx(Ow,{}):s.jsx(ci,{to:e!=null&&e.length?"/listings":"/contact?interest=Property%20search",replace:!0})}function cBt(){C.useEffect(()=>{document.body.classList.add("lead-site-page");const t=['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",".widget-visible"],e=()=>{t.forEach(n=>{document.querySelectorAll(n).forEach(i=>{i.style.display="none"})})};e();const r=[500,1500,3e3,5e3].map(n=>setTimeout(e,n));return()=>{document.body.classList.remove("lead-site-page"),r.forEach(clearTimeout)}},[])}function uBt(){var T,E,k,P,R;const{siteConfig:t,themeConfig:e,isLoading:r,error:n}=JRt();if(cBt(),r)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent mx-auto mb-4"}),s.jsx("p",{className:"text-gray-500",children:"Loading..."})]})});if(n||!t)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50 p-6",children:s.jsxs("div",{className:"text-center max-w-md",children:[s.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Site Not Found"}),s.jsx("p",{className:"text-gray-500",children:"This lead site is not available or has not been set up yet."})]})});if(((T=t.themeConfig)==null?void 0:T.orgPreset)==="remaxcreative"||((E=t.themeConfig)==null?void 0:E.orgPreset)==="remax"){const D=nMt;return s.jsxs(A2,{siteConfig:t,children:[s.jsx(I2,{}),s.jsx(C.Suspense,{fallback:s.jsx(Ow,{}),children:s.jsx(GDt,{siteConfig:t,children:s.jsxs(Cy,{children:[s.jsx(xe,{path:"/",element:s.jsx(KDt,{siteConfig:t})}),s.jsx(xe,{path:"/buy",element:s.jsx(QDt,{siteConfig:t})}),s.jsx(xe,{path:"/sell",element:s.jsx(JDt,{siteConfig:t})}),s.jsx(xe,{path:"/about",element:s.jsx(eMt,{siteConfig:t})}),s.jsx(xe,{path:"/agents",element:s.jsx(YDt,{siteConfig:t})}),s.jsx(xe,{path:"/team",element:s.jsx(ci,{to:"/agents",replace:!0})}),s.jsx(xe,{path:"/offices",element:s.jsx(ZDt,{siteConfig:t})}),s.jsx(xe,{path:"/join",element:s.jsx(tMt,{siteConfig:t})}),s.jsx(xe,{path:"/communities",element:s.jsx(XDt,{siteConfig:t})}),s.jsx(xe,{path:"/contact",element:s.jsx(rMt,{siteConfig:t})}),s.jsx(xe,{path:"/search",element:s.jsx(D,{children:s.jsx(P2,{siteConfig:t})})}),s.jsx(xe,{path:"/listing/:mlsNumber",element:s.jsx(D,{children:s.jsx(R2,{siteConfig:t})})}),s.jsx(xe,{path:"/dashboard",element:s.jsx(D,{children:s.jsx(uv,{siteConfig:t})})}),s.jsx(xe,{path:"/account",element:s.jsx(D,{children:s.jsx(uv,{siteConfig:t})})}),s.jsx(xe,{path:"/blog",element:s.jsx(D,{children:s.jsx(Hf,{siteConfig:t,isLuxury:!1})})}),s.jsx(xe,{path:"/blog/:slug",element:s.jsx(D,{children:s.jsx(Hf,{siteConfig:t,isLuxury:!1})})}),s.jsx(xe,{path:"/community",element:s.jsx(D,{children:s.jsx(oL,{siteConfig:t,isLuxury:!1})})}),s.jsx(xe,{path:"/p/:pageSlug",element:s.jsx(D,{children:s.jsx(lL,{siteConfig:t})})}),s.jsx(xe,{path:"/*",element:s.jsx(D,{children:s.jsx(L2,{siteConfig:t})})})]})})})]})}if(t.ownerType!=="brokerage"&&((k=t.themeConfig)==null?void 0:k.orgPreset)==="btb"){const D=rDt(t),M=Kd;return s.jsxs(A2,{siteConfig:t,children:[s.jsx(I2,{}),s.jsx(C.Suspense,{fallback:s.jsx(Ow,{}),children:s.jsx(rce,{siteId:t.id,agent:D,siteConfig:t,children:s.jsxs(Cy,{children:[s.jsx(xe,{path:"/",element:s.jsx(_Dt,{siteConfig:t})}),s.jsx(xe,{path:"/about",element:s.jsx(bDt,{siteConfig:t})}),s.jsx(xe,{path:"/contact",element:s.jsx(wDt,{siteConfig:t})}),s.jsx(xe,{path:"/buy",element:s.jsx(nce,{siteConfig:t})}),s.jsx(xe,{path:"/buying-process",element:s.jsx(lce,{siteConfig:t})}),s.jsx(xe,{path:"/financing",element:s.jsx(cce,{siteConfig:t})}),s.jsx(xe,{path:"/home-value",element:s.jsx(uce,{siteConfig:t})}),s.jsx(xe,{path:"/sell",element:s.jsx(ice,{siteConfig:t})}),s.jsx(xe,{path:"/communities",element:s.jsx(sce,{siteConfig:t})}),s.jsx(xe,{path:"/construction",element:s.jsx(ace,{siteConfig:t})}),s.jsx(xe,{path:"/cabinets",element:s.jsx(oce,{siteConfig:t})}),s.jsx(xe,{path:"/reviews",element:s.jsx(M,{children:s.jsx(Iw,{siteConfig:t,headingName:D.name})})}),s.jsx(xe,{path:"/reviews/:slug",element:s.jsx(M,{children:s.jsx(Iw,{siteConfig:t,headingName:D.name})})}),["/team","/agents","/careers","/join"].map(B=>s.jsx(xe,{path:B,element:s.jsx(ci,{to:"/about",replace:!0})},B)),s.jsx(xe,{path:"/search",element:s.jsx(M,{children:s.jsx(P2,{siteConfig:t})})}),s.jsx(xe,{path:"/listing/:mlsNumber",element:s.jsx(M,{children:s.jsx(R2,{siteConfig:t})})}),s.jsx(xe,{path:"/dashboard",element:s.jsx(M,{children:s.jsx(uv,{siteConfig:t})})}),s.jsx(xe,{path:"/account",element:s.jsx(M,{children:s.jsx(uv,{siteConfig:t})})}),s.jsx(xe,{path:"/blog",element:s.jsx(M,{children:s.jsx(Hf,{siteConfig:t,isLuxury:!1})})}),s.jsx(xe,{path:"/blog/:slug",element:s.jsx(M,{children:s.jsx(Hf,{siteConfig:t,isLuxury:!1})})}),s.jsx(xe,{path:"/community",element:s.jsx(M,{children:s.jsx(oL,{siteConfig:t,isLuxury:!1})})}),s.jsx(xe,{path:"/p/:pageSlug",element:s.jsx(M,{children:s.jsx(lL,{siteConfig:t})})}),s.jsx(xe,{path:"/*",element:s.jsx(M,{children:s.jsx(L2,{siteConfig:t})})})]})})})]})}if(t.ownerType==="brokerage"&&((P=t.themeConfig)==null?void 0:P.orgPreset)==="btb")return s.jsxs(A2,{siteConfig:t,children:[s.jsx(I2,{}),s.jsx(C.Suspense,{fallback:s.jsx(Ow,{}),children:s.jsx(rce,{siteId:t.id,siteConfig:t,children:s.jsxs(Cy,{children:[s.jsx(xe,{path:"/",element:s.jsx(fDt,{siteConfig:t})}),s.jsx(xe,{path:"/buy",element:s.jsx(nce,{siteConfig:t})}),s.jsx(xe,{path:"/buying-process",element:s.jsx(lce,{siteConfig:t})}),s.jsx(xe,{path:"/financing",element:s.jsx(cce,{siteConfig:t})}),s.jsx(xe,{path:"/home-value",element:s.jsx(uce,{siteConfig:t})}),s.jsx(xe,{path:"/construction",element:s.jsx(ace,{siteConfig:t})}),s.jsx(xe,{path:"/cabinets",element:s.jsx(oce,{siteConfig:t})}),s.jsx(xe,{path:"/careers",element:s.jsx(xDt,{siteConfig:t})}),s.jsx(xe,{path:"/reviews",element:s.jsx(Kd,{children:s.jsx(Iw,{siteConfig:t,headingName:"Building The Bluegrass Realty",googleReviewsUrl:"https://maps.app.goo.gl/Bc9GrsAy3sppB2XF7"})})}),s.jsx(xe,{path:"/reviews/:slug",element:s.jsx(Kd,{children:s.jsx(Iw,{siteConfig:t,headingName:"Building The Bluegrass Realty",googleReviewsUrl:"https://maps.app.goo.gl/Bc9GrsAy3sppB2XF7"})})}),s.jsx(xe,{path:"/sell",element:s.jsx(ice,{siteConfig:t})}),["/real-estate","/design","/work","/work/*"].map(D=>s.jsx(xe,{path:D,element:s.jsx(ci,{to:D==="/real-estate"?"/buy":D==="/design"?"/construction":"/",replace:!0})},D)),s.jsx(xe,{path:"/about",element:s.jsx(pDt,{siteConfig:t})}),s.jsx(xe,{path:"/team",element:s.jsx(gDt,{siteConfig:t})}),s.jsx(xe,{path:"/agents",element:s.jsx(ci,{to:"/team",replace:!0})}),s.jsx(xe,{path:"/join",element:s.jsx(ci,{to:"/careers",replace:!0})}),s.jsx(xe,{path:"/communities",element:s.jsx(sce,{siteConfig:t})}),s.jsx(xe,{path:"/contact",element:s.jsx(vDt,{siteConfig:t})}),s.jsx(xe,{path:"/search",element:s.jsx(Kd,{children:s.jsx(P2,{siteConfig:t})})}),s.jsx(xe,{path:"/listing/:mlsNumber",element:s.jsx(Kd,{children:s.jsx(R2,{siteConfig:t})})}),s.jsx(xe,{path:"/dashboard",element:s.jsx(Kd,{children:s.jsx(uv,{siteConfig:t})})}),s.jsx(xe,{path:"/account",element:s.jsx(Kd,{children:s.jsx(uv,{siteConfig:t})})}),s.jsx(xe,{path:"/blog",element:s.jsx(Kd,{children:s.jsx(Hf,{siteConfig:t,isLuxury:!1})})}),s.jsx(xe,{path:"/blog/:slug",element:s.jsx(Kd,{children:s.jsx(Hf,{siteConfig:t,isLuxury:!1})})}),s.jsx(xe,{path:"/community",element:s.jsx(Kd,{children:s.jsx(oL,{siteConfig:t,isLuxury:!1})})}),s.jsx(xe,{path:"/p/:pageSlug",element:s.jsx(Kd,{children:s.jsx(lL,{siteConfig:t})})}),s.jsx(xe,{path:"/*",element:s.jsx(Kd,{children:s.jsx(L2,{siteConfig:t})})})]})})})]});if(t.ownerType==="brokerage"||t.ownerType==="team"){const D=t.orgTier==="pro";return s.jsxs(A2,{siteConfig:t,children:[s.jsx(I2,{}),s.jsx(C.Suspense,{fallback:s.jsx(Ow,{}),children:s.jsx(eBt,{siteConfig:t,themeConfig:e??void 0,children:s.jsxs(Cy,{children:[s.jsx(xe,{path:"/",element:s.jsx(tBt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(xe,{path:"/listings",element:s.jsx(Due,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(xe,{path:"/sold",element:s.jsx(Due,{siteConfig:t,themeConfig:e??void 0,sold:!0})}),s.jsx(xe,{path:"/listings/:slug",element:s.jsx(iBt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(xe,{path:"/agents",element:s.jsx(rBt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(xe,{path:"/agents/:slug",element:s.jsx(nBt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(xe,{path:"/about",element:s.jsx(sBt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(xe,{path:"/contact",element:s.jsx(aBt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(xe,{path:"/join",element:s.jsx(oBt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(xe,{path:"/blog",element:s.jsx(Hf,{siteConfig:t,isLuxury:!1})}),s.jsx(xe,{path:"/blog/:slug",element:s.jsx(Hf,{siteConfig:t,isLuxury:!1})}),s.jsx(xe,{path:"/search",element:D?s.jsx(P2,{siteConfig:t}):s.jsx(ci,{to:"/listings",replace:!0})}),s.jsx(xe,{path:"/listing/:mlsNumber",element:D?s.jsx(R2,{siteConfig:t}):s.jsx(ci,{to:"/listings",replace:!0})}),s.jsx(xe,{path:"/*",element:s.jsx(L2,{siteConfig:t,referralMode:!D})})]})})})]})}const i=(e==null?void 0:e.themeTier)==="luxury",o=(e==null?void 0:e.themeTier)==="land-ranch",c=o?D4t:i?R4t:k4t,a=Jje(t),f=a||wx(t,e),p=t.id==="7605cc2e-ce21-4f4f-8bb1-4c0f217b1109",y=!a&&wx(t,e),v=o?s.jsx(F4t,{siteConfig:t,themeConfig:e??void 0}):i?s.jsx(O4t,{siteConfig:t,themeConfig:e??void 0}):s.jsx(M4t,{siteConfig:t,themeConfig:e??void 0});return s.jsxs(A2,{siteConfig:t,children:[s.jsx(I2,{}),s.jsxs(c,{siteConfig:t,children:[s.jsx(C.Suspense,{fallback:s.jsx(Ow,{}),children:s.jsxs(Cy,{children:[s.jsx(xe,{path:"/",element:v}),s.jsx(xe,{path:"/listings",element:s.jsx(X4t,{siteConfig:t})}),s.jsx(xe,{path:"/sold",element:s.jsx(Q4t,{siteConfig:t})}),s.jsx(xe,{path:"/listings/:slug",element:s.jsx(J4t,{siteConfig:t})}),s.jsx(xe,{path:"/search",element:f?s.jsx(lBt,{siteConfig:t}):i?s.jsx(B4t,{siteConfig:t}):s.jsx(P2,{siteConfig:t})}),s.jsx(xe,{path:"/listing/:mlsNumber",element:f?s.jsx(ci,{to:"/contact?interest=Property%20details",replace:!0}):i?s.jsx($4t,{siteConfig:t}):s.jsx(R2,{siteConfig:t})}),s.jsx(xe,{path:"/about",element:i?s.jsx(U4t,{siteConfig:t}):s.jsx(z4t,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(xe,{path:"/contact",element:i?s.jsx(q4t,{siteConfig:t}):s.jsx(V4t,{siteConfig:t})}),s.jsx(xe,{path:"/account",element:s.jsx(uv,{siteConfig:t})}),s.jsx(xe,{path:"/blog",element:s.jsx(Hf,{siteConfig:t,isLuxury:i})}),s.jsx(xe,{path:"/blog/:slug",element:s.jsx(Hf,{siteConfig:t,isLuxury:i})}),s.jsx(xe,{path:"/sell",element:s.jsx(G4t,{siteConfig:t,themeConfig:e??void 0,isLuxury:i})}),s.jsx(xe,{path:"/community",element:s.jsx(oL,{siteConfig:t,isLuxury:i})}),s.jsx(xe,{path:"/schedule",element:t.id===lLt?s.jsx(Z4t,{siteConfig:t}):s.jsx(oLt,{bookingUrl:t.bookingUrl,agentName:((R=t.agent)==null?void 0:R.full_name)||"your agent"})}),GAe(t)&&s.jsx(xe,{path:"/exp-ready",element:s.jsx(Y4t,{siteConfig:t})}),((e==null?void 0:e.focusPages)??[]).map(D=>s.jsx(xe,{path:`/${D.slug}`,element:s.jsx(K4t,{siteConfig:t,page:D,accentColor:(e==null?void 0:e.accentColor)||t.accentColor||"#c9a96e"})},D.slug)),s.jsx(xe,{path:"/reviews",element:s.jsx(Iw,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(xe,{path:"/reviews/:slug",element:s.jsx(Iw,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(xe,{path:"/p/:pageSlug",element:s.jsx(lL,{siteConfig:t})}),s.jsx(xe,{path:"/*",element:s.jsx(L2,{siteConfig:t,referralMode:y})})]})}),!p&&s.jsx(aLt,{bookingUrl:t.bookingUrl})]})]})}function L2({siteConfig:t,referralMode:e}){const r=ki(),n=r.pathname.match(/^\/homes-in-(.+)$/);if(n)return s.jsx(W4t,{siteConfig:t,subdivisionSlug:n[1]});const i=r.pathname.match(/^\/homes-for-sale-in-(.+)$/);if(i)return s.jsx(H4t,{siteConfig:t,citySlugOverride:i[1],referralMode:e});const o=r.pathname.match(/^\/communities\/([^/]+)\/?$/);if(o)return s.jsx(ci,{to:`/homes-for-sale-in-${o[1]}${r.search}`,replace:!0});const c=r.pathname.match(/^\/([a-z0-9][a-z0-9-]*)\/?$/i);return c?s.jsx(dBt,{siteId:t==null?void 0:t.id,slug:c[1],search:r.search}):null}function dBt({siteId:t,slug:e,search:r}){const[n,i]=C.useState(null);return C.useEffect(()=>{let o=!1;if(!t){i(!1);return}return Re.from("lead_site_pages").select("id").eq("site_id",t).eq("slug",e).eq("is_published",!0).maybeSingle().then(({data:c})=>{o||i(!!c)}),()=>{o=!0}},[t,e]),n?s.jsx(ci,{to:`/p/${e}${r}`,replace:!0}):null}function hBt(){const{user:t,loading:e}=Hn(),{data:r,isLoading:n}=mr({queryKey:["feature-entitlement","levelup_attract",t==null?void 0:t.id],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:i,error:o}=await Re.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",t.id).eq("feature_key","levelup_attract").maybeSingle();if(o)throw o;return i?{hasAccess:i.enabled&&(!i.expires_at||new Date(i.expires_at).getTime()>Date.now()),tier:i.tier??null}:{hasAccess:!1,tier:null}}});return{hasAccess:!!(r!=null&&r.hasAccess),tier:(r==null?void 0:r.tier)??null,isLoading:e||n}}function fBt({children:t}){const{user:e,loading:r}=Hn(),{hasAccess:n,isLoading:i}=hBt(),o=ki();return C.useEffect(()=>{!r&&!i&&e&&!n&&Vt.error("LevelUp Attract isn't available for your account yet.")},[r,i,e,n]),r||e&&i?s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e?n?s.jsx(s.Fragment,{children:t}):s.jsx(ci,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",o.pathname),s.jsx(ci,{to:"/auth",replace:!0}))}function Mue({children:t}){const{user:e,loading:r}=Hn(),{hasAccess:n,isLoading:i}=S7(),o=ki();return r||e&&i?s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e?n?s.jsx(s.Fragment,{children:t}):s.jsx(ci,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",o.pathname),s.jsx(ci,{to:"/auth",replace:!0}))}const mBt=C.lazy(()=>Fe(()=>import("./CommercialMarketplace-RoWQOXFE.js"),[])),Oue=C.lazy(()=>Fe(()=>import("./PrivacyPolicy-Bi7qCAs9.js"),[])),pBt=C.lazy(()=>Fe(()=>import("./CanvaSupport-Cgvr3T57.js"),__vite__mapDeps([64,65]))),Fue=C.lazy(()=>Fe(()=>import("./TermsOfService-BwNen3Yx.js"),[])),gBt=C.lazy(()=>Fe(()=>import("./DataDeletion-D0G2FkjR.js"),[])),Bue=C.lazy(()=>Fe(()=>import("./McpDataUse-B405F6C4.js"),[])),$ue=C.lazy(()=>Fe(()=>import("./SmsOptIn-D8hS2Lrs.js"),__vite__mapDeps([66,67]))),D6=C.lazy(()=>Fe(()=>import("./OAuthConsent-CaC7SCr7.js"),[])),yBt=C.lazy(()=>Fe(()=>import("./ConnectChatGPT-B5mQpA05.js"),__vite__mapDeps([68,69]))),zue=C.lazy(()=>Fe(()=>import("./LevelUpMCP-DGz77OC6.js"),__vite__mapDeps([70,71]))),xBt=C.lazy(()=>Fe(()=>import("./SubscriptionSuccess-C5CYZX6a.js"),__vite__mapDeps([72,69]))),vBt=C.lazy(()=>Fe(()=>import("./Subscription-DexjRXWm.js"),[])),_Bt=C.lazy(()=>Fe(()=>import("./SetupBrokerage-Bv6P0LmB.js"),__vite__mapDeps([73,69]))),Uue=C.lazy(()=>Fe(()=>import("./ClaimAccount-C0noD4vp.js"),[])),Vue=C.lazy(()=>Fe(()=>import("./ConfirmPasswordReset-Bx4RoTBI.js"),[])),bBt=C.lazy(()=>Fe(()=>import("./ActivateAccount-DPBs9kn6.js"),[])),wBt=C.lazy(()=>Fe(()=>import("./InviteSignup-ABw54DPK.js"),__vite__mapDeps([74,75]))),SBt=C.lazy(()=>Fe(()=>import("./CoachingHub-DmhdK55n.js"),__vite__mapDeps([76,77]))),TBt=C.lazy(()=>Fe(()=>import("./CoachAgentWorkspace-BX9ZprNL.js"),__vite__mapDeps([78,77,79,80,81]))),EBt=C.lazy(()=>Fe(()=>import("./MyCoach-CxcIObJb.js"),__vite__mapDeps([82,77,79,83,84,80]))),jBt=C.lazy(()=>Fe(()=>import("./AdminCoaching-CeNEAT5C.js"),__vite__mapDeps([85,86,87,88]))),ABt=C.lazy(()=>Fe(()=>import("./CoachBilling-D8-nRbBp.js"),__vite__mapDeps([89,77,90]))),kBt=C.lazy(()=>Fe(()=>import("./CoachSettings-CMJdnssC.js"),__vite__mapDeps([91,77,92,93,94,65,81,95]))),CBt=C.lazy(()=>Fe(()=>import("./GoogleCalendarReturn-CO_Fabfy.js"),[])),NBt=C.lazy(()=>Fe(()=>import("./Microsoft365Return-ZkE_j7yT.js"),__vite__mapDeps([96,97,98]))),IBt=C.lazy(()=>Fe(()=>import("./CoachWaitlist-xqAwrmDA.js"),__vite__mapDeps([99,77,100]))),PBt=C.lazy(()=>Fe(()=>import("./CoachesDirectory-DasM_05f.js"),[])),RBt=C.lazy(()=>Fe(()=>import("./CoachProfile-D-TMrJRh.js"),__vite__mapDeps([101,83]))),LBt=C.lazy(()=>Fe(()=>import("./CoachApply-B3Enn0f8.js"),[])),DBt=C.lazy(()=>Fe(()=>import("./Trial-CxV6-V7n.js"),__vite__mapDeps([102,103]))),MBt=C.lazy(()=>Fe(()=>import("./TrialSuccess-_GOlDSjK.js"),__vite__mapDeps([104,105]))),OBt=C.lazy(()=>Fe(()=>import("./LaborDaySale-BkgASybZ.js"),__vite__mapDeps([106,107,103,108,109]))),FBt=C.lazy(()=>Fe(()=>import("./BrokerageLaborDaySale-CGuTr8Go.js"),__vite__mapDeps([110,107,103,108,109]))),BBt=C.lazy(()=>Fe(()=>import("./BrokerageSolutions-MW5zHqHO.js"),__vite__mapDeps([111,108,112,113,114,109]))),$Bt=C.lazy(()=>Fe(()=>import("./Upgrade-C3ZqRgzS.js"),__vite__mapDeps([115,116]))),zBt=C.lazy(()=>Fe(()=>import("./InstagramGift-D7Se_yfk.js"),__vite__mapDeps([117,116,90]))),que=C.lazy(()=>Fe(()=>import("./VideoShare-CgtOcGQB.js"),__vite__mapDeps([118,119,120,25,38,105,5,121,122,123]))),UBt=C.lazy(()=>Fe(()=>import("./VideoShareLayout-Bj5ahaC5.js"),[])),VBt=C.lazy(()=>Fe(()=>import("./VideoOgRedirect-7vUK9OP-.js"),[])),qBt=C.lazy(()=>Fe(()=>Promise.resolve().then(()=>SXe),void 0)),GBt=C.lazy(()=>Fe(()=>Promise.resolve().then(()=>yXe),void 0)),HBt=C.lazy(()=>Fe(()=>import("./NewListingChooser-B5q3GjCL.js"),[])),Gue=C.lazy(()=>Fe(()=>import("./CommercialWizard-CwveRjPR.js"),__vite__mapDeps([124,125,126]))),WBt=C.lazy(()=>Fe(()=>import("./CommercialWorkspace-0yn0CM4e.js"),__vite__mapDeps([127,125,126,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,97,98,146,84,81,147,148]))),KBt=C.lazy(()=>Fe(()=>import("./CommercialPitchPreview-CHOEGUYh.js"),__vite__mapDeps([149,148]))),YBt=C.lazy(()=>Fe(()=>import("./PrivateListingView-Px1BeTXW.js"),[])),ZBt=C.lazy(()=>Fe(()=>import("./PublicAgentCard-9wX1xTYt.js"),[])),XBt=C.lazy(()=>Fe(()=>Promise.resolve().then(()=>NRt),void 0)),Hue=C.lazy(()=>Fe(()=>import("./PublicHomeValue-ex2MdmMp.js"),[])),QBt=C.lazy(()=>Fe(()=>import("./PublicLiveEvent-BYG5sOY9.js"),__vite__mapDeps([150,151,152,153,154]))),JBt=C.lazy(()=>Fe(()=>import("./LiveEvents-Bm2U_BYG.js"),__vite__mapDeps([155,156,157,158,146]))),e$t=C.lazy(()=>Fe(()=>import("./LiveEventConsole-ClNMboVK.js"),__vite__mapDeps([159,157,153,75,160,151,161]))),t$t=C.lazy(()=>Fe(()=>import("./Dashboard-Afc2AIaQ.js"),__vite__mapDeps([162,163,164,77,165,166,167,168,169,170,125,126,171,172,173,174,3,38,80,175]))),r$t=C.lazy(()=>Fe(()=>import("./Profile-BM8_PBs9.js"),__vite__mapDeps([176,95,80,90,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,81,192,193,194,195,29,112,8,196]))),n$t=C.lazy(()=>Fe(()=>import("./Events-CxrcD9-d.js"),__vite__mapDeps([197,165,166,167,198,172,199,200,201]))),i$t=C.lazy(()=>Fe(()=>import("./EventDetail-Cmb91V4S.js"),__vite__mapDeps([202,165,166,167,203,204,69]))),s$t=C.lazy(()=>Fe(()=>import("./Apps-XeDNmIn9.js"),__vite__mapDeps([205,121,90,206,207]))),a$t=C.lazy(()=>Fe(()=>import("./Templates-TsymEUVH.js"),__vite__mapDeps([208,95]))),o$t=C.lazy(()=>Fe(()=>import("./TemplateDetail-B1N287tk.js"),__vite__mapDeps([209,137,163,203,204,95]))),l$t=C.lazy(()=>Fe(()=>import("./Programs-Bsoh9ayq.js"),__vite__mapDeps([210,164]))),c$t=C.lazy(()=>Fe(()=>import("./ProgramDetail-iNFKI2C8.js"),__vite__mapDeps([211,212,213,164,29,90]))),u$t=C.lazy(()=>Fe(()=>import("./ProgramEnroll-cx7XoAoU.js"),__vite__mapDeps([214,164,215,90]))),d$t=C.lazy(()=>Fe(()=>import("./ProgramWorkspace-9BSCK1hi.js"),__vite__mapDeps([216,164,217,218]))),h$t=C.lazy(()=>Fe(()=>import("./Programs-BuQk0nOR.js"),__vite__mapDeps([219,164,81,158,215,220,90,206,133,221,213,84,29]))),f$t=C.lazy(()=>Fe(()=>import("./Academy-B8eSWWXy.js"),[])),m$t=C.lazy(()=>Fe(()=>import("./AcademyVideoDetail-DdkzEEtt.js"),__vite__mapDeps([222,137,163,203,204,223]))),p$t=C.lazy(()=>Fe(()=>import("./PublicAcademyWatch-BjFnhx6X.js"),[])),g$t=C.lazy(()=>Fe(()=>import("./Toolbox-CYagLxSS.js"),[])),y$t=C.lazy(()=>Fe(()=>import("./ToolboxDetail-D9f0sYa0.js"),__vite__mapDeps([224,137,163,203,204,223]))),x$t=C.lazy(()=>Fe(()=>import("./SocialSwag-CYIISl5_.js"),__vite__mapDeps([225,95]))),v$t=C.lazy(()=>Fe(()=>import("./SocialStudio-BbR7c5Y3.js"),__vite__mapDeps([226,137,227,228,30,229,230,231,232,126,233,191,234,218,235,236,237,238,65,158,239,240,241,242,81,243,166,84,69,244,129,130]))),_$t=C.lazy(()=>Fe(()=>import("./MarketingStudio-BnLvvIFk.js"),__vite__mapDeps([245,38,246]))),b$t=C.lazy(()=>Fe(()=>import("./BrandKit-BR7Jdldt.js"),__vite__mapDeps([247,248]))),w$t=C.lazy(()=>Fe(()=>import("./BrandingBarEditor-B1Y6nEgv.js"),__vite__mapDeps([249,244,248,250,251]))),S$t=C.lazy(()=>Fe(()=>import("./ListingTemplates-DOYrxbqV.js"),__vite__mapDeps([252,253,254,248,215]))),T$t=C.lazy(()=>Fe(()=>import("./PersonalBranding-Bd7HPa-i.js"),__vite__mapDeps([255,256,248,253]))),E$t=C.lazy(()=>Fe(()=>import("./SocialSwagDetail-D-ZNVPKE.js"),__vite__mapDeps([257,137,163,203,204,95]))),j$t=C.lazy(()=>Fe(()=>import("./Community-B2Dp2myL.js"),__vite__mapDeps([258,30,221,213,11,188,259,260,105,95,261,151]))),A$t=C.lazy(()=>Fe(()=>import("./Support-DzT_PogT.js"),__vite__mapDeps([262,137,263,264,175,146,69,84]))),k$t=C.lazy(()=>Fe(()=>import("./BrokerageResources-BjYiVSs2.js"),__vite__mapDeps([265,95]))),C$t=C.lazy(()=>Fe(()=>import("./BrokerageResourceDetail-CDDFSlsI.js"),[])),Wue=C.lazy(()=>Fe(()=>import("./AdminDashboard-CzHg3Xt4.js"),__vite__mapDeps([266,90,267,215,268,269,270]))),N$t=C.lazy(()=>Fe(()=>import("./Apps-CcQz9jXd.js"),[])),I$t=C.lazy(()=>Fe(()=>import("./MemberManagement-cxcpRKLI.js"),__vite__mapDeps([271,156,272,217,105,273,152,274,90,275,276,277,278,279,280,201,281,282,283,80,284,87,285,116]))),P$t=C.lazy(()=>Fe(()=>import("./UnassignedMembers-Csy7ImAg.js"),__vite__mapDeps([286,156]))),R$t=C.lazy(()=>Fe(()=>import("./InviteCodes-DhM9gKw2.js"),__vite__mapDeps([287,156]))),L$t=C.lazy(()=>Fe(()=>import("./Events-CfuML_Ps.js"),__vite__mapDeps([288,177,178,179,180,181,182,183,184,185,186,95,157,289,156,290]))),D$t=C.lazy(()=>Fe(()=>import("./MCPAuditLog-DG612QPL.js"),__vite__mapDeps([291,156,292]))),M$t=C.lazy(()=>Fe(()=>import("./Templates-Doy9z7LB.js"),__vite__mapDeps([293,156,177,178,179,180,181,182,183,184,185,186,95,289]))),O$t=C.lazy(()=>Fe(()=>import("./Academy-CrpR9RWC.js"),__vite__mapDeps([294,156,177,178,179,180,181,182,183,184,185,186,95,295,218,296,289]))),F$t=C.lazy(()=>Fe(()=>import("./Toolbox-Cq2uxxCZ.js"),__vite__mapDeps([297,177,178,179,180,181,182,183,184,185,186,95,295,218,289]))),B$t=C.lazy(()=>Fe(()=>import("./SocialSwag-BitQA1Ek.js"),__vite__mapDeps([298,156,177,178,179,180,181,182,183,184,185,186,95,289]))),$$t=C.lazy(()=>Fe(()=>import("./SocialSwag2-CNhiftvC.js"),__vite__mapDeps([299,289,132,95,133]))),z$t=C.lazy(()=>Fe(()=>import("./Community-n41Ks1AX.js"),__vite__mapDeps([300,156]))),U$t=C.lazy(()=>Fe(()=>import("./Analytics-CNYgl3t9.js"),__vite__mapDeps([301,273,152,274,69,302,303,304,305,306]))),V$t=C.lazy(()=>Fe(()=>import("./BrokerageResources-4SRxJW-7.js"),__vite__mapDeps([307,177,178,179,180,181,182,183,184,185,186,95,215]))),q$t=C.lazy(()=>Fe(()=>import("./DashboardManagement-G3LlFMOI.js"),__vite__mapDeps([308,133,160,75]))),G$t=C.lazy(()=>Fe(()=>import("./SupportTickets-BteGBgrk.js"),__vite__mapDeps([309,137,263,264,175,146,8,69,84]))),H$t=C.lazy(()=>Fe(()=>import("./EmailTemplates-CE4JgfGe.js"),__vite__mapDeps([310,178,179,311,183,184,185,186,95,312,313,81,314]))),W$t=C.lazy(()=>Fe(()=>import("./AgentEmailTemplates-DZkvrT6Q.js"),__vite__mapDeps([315,156,80]))),K$t=C.lazy(()=>Fe(()=>import("./BrokerageDashboard-sSP5mkhT.js"),__vite__mapDeps([316,272,217,105,152,274,69,95,84,275,283,284,302,273,198,172,199,317]))),Y$t=C.lazy(()=>Fe(()=>import("./MyBrokerage-BSViSleE.js"),__vite__mapDeps([318,151,116,199,191,81,319,320,84]))),Z$t=C.lazy(()=>Fe(()=>import("./BrokerageContent-ctKtRiVH.js"),__vite__mapDeps([321,170,80]))),X$t=C.lazy(()=>Fe(()=>import("./BrokerageContentDetail-rGo-wavY.js"),[])),Q$t=C.lazy(()=>Fe(()=>import("./BrokerageHelpBoard-BnZouWXV.js"),__vite__mapDeps([322,323,8]))),J$t=C.lazy(()=>Fe(()=>import("./BrokerageHelpBoardNew-OdSwdyfo.js"),__vite__mapDeps([324,323]))),ezt=C.lazy(()=>Fe(()=>import("./BrokerageHelpBoardDetail-CIgKRnwm.js"),__vite__mapDeps([325,323,11]))),tzt=C.lazy(()=>Fe(()=>import("./Newsletters-S8gfYlyB.js"),__vite__mapDeps([326,327,256,328,183,329,184,95,160,314,152,274,330,331,81,332,114,333,168,139,140,141,142,334,335,292,336,215,337,75]))),rzt=C.lazy(()=>Fe(()=>import("./NewsletterDetail-BjTJStXY.js"),__vite__mapDeps([338,163,203,204,332,327,256,328,183,329,184,95,160,314,152,274,330,114,333,168,139,140,141,142,334,335,292,336,215,337,75]))),nzt=C.lazy(()=>Fe(()=>import("./Newsletters-CqFSo02i.js"),__vite__mapDeps([339,289,156,177,178,179,180,181,182,183,184,185,186,95,328,133,340]))),izt=C.lazy(()=>Fe(()=>import("./MemberBroadcasts-C0c2buDf.js"),__vite__mapDeps([341,156,177,178,179,180,181,182,183,184,185,186,95,218,201,312,342,81]))),szt=C.lazy(()=>Fe(()=>import("./BoostAnnouncements-DwPphQyB.js"),__vite__mapDeps([343,156,6]))),azt=C.lazy(()=>Fe(()=>import("./NewsletterGraphics-D-yvnLJ_.js"),__vite__mapDeps([344,156,158]))),ozt=C.lazy(()=>Fe(()=>import("./Wishlist-slkkyAd4.js"),__vite__mapDeps([345,152]))),lzt=C.lazy(()=>Fe(()=>import("./WishlistDetail-D_1MvFvq.js"),__vite__mapDeps([346,259,152]))),czt=C.lazy(()=>Fe(()=>import("./Wishlist-ClcFDxSr.js"),[])),uzt=C.lazy(()=>Fe(()=>import("./LevelUpBrief-Bh3NE97g.js"),__vite__mapDeps([347,156,177,178,179,180,181,182,183,184,185,186,95]))),dzt=C.lazy(()=>Fe(()=>import("./AdditionalServices-BOtGsJ_b.js"),__vite__mapDeps([348,177,178,179,180,181,182,183,184,185,186,95]))),hzt=C.lazy(()=>Fe(()=>import("./Discounts-BGKiWw04.js"),__vite__mapDeps([349,156]))),fzt=C.lazy(()=>Fe(()=>import("./Subscriptions-BDQe2JLo.js"),__vite__mapDeps([350,156,351,90,284]))),mzt=C.lazy(()=>Fe(()=>import("./InstagramGiftEmails-DjnEnGBC.js"),__vite__mapDeps([352,351,314]))),pzt=C.lazy(()=>Fe(()=>import("./Referrals-BoyeJWO0.js"),__vite__mapDeps([353,156,69,84]))),gzt=C.lazy(()=>Fe(()=>import("./OnboardingChecklist-CzrQxeIe.js"),[])),yzt=C.lazy(()=>Fe(()=>import("./AgentOSControlCenter-DMnfqV2R.js"),__vite__mapDeps([354,156,121,133]))),xzt=C.lazy(()=>Fe(()=>import("./AdditionalServices-Dd6EbiC0.js"),[])),vzt=C.lazy(()=>Fe(()=>import("./AdditionalServiceDetail-DobNMTh8.js"),[])),_zt=C.lazy(()=>Fe(()=>import("./AIToolkit-2EbLm3Vm.js"),[])),bzt=C.lazy(()=>Fe(()=>import("./AskAI-D7jwcJH_.js"),__vite__mapDeps([355,2]))),wzt=C.lazy(()=>Fe(()=>import("./InnerCircleHome-B8KnEBPH.js"),__vite__mapDeps([356,173,174,357,7,152,274,284,358,168,138,137,139,140,141,142,143,144,145,97,98,146,359,360,361,362,363,160]))),Szt=C.lazy(()=>Fe(()=>import("./InnerCircleContacts-xo1YCZJY.js"),__vite__mapDeps([364,365,221,213,366,256,152,274,367,368,278,275,279,280,201,281,282,357,369,370,7,371,334,215,229,372,174,373,374,360,137,375,376,377,378,379,380,234,336,381,314,296,382,383,195,95,139,138,140,141,142,143,144,145,97,98,146,168,335,342,384,385,386,387,388,38,389,196,8,81,125,126,75,390,184]))),Tzt=C.lazy(()=>Fe(()=>import("./InnerCircleContactDetail-DpXZxLC4.js"),__vite__mapDeps([391,392,393,388,280,362,137,365,168,139,138,140,141,142,143,144,145,97,98,146,394,383,370,174,334,369,357,7,371,215,229,372,395,284,389,396,8,81,196,387,160,397,398,221,213,399,400,201,270,401,402,267,292,359,360,361]))),Ezt=C.lazy(()=>Fe(()=>import("./SentEmails-CDSN0JE-.js"),__vite__mapDeps([403,168,138,137,139,140,141,142,143,144,145,97,98,146,398,189,160,196,84,372]))),jzt=C.lazy(()=>Fe(()=>import("./InnerCirclePlans-9X32E1WP.js"),__vite__mapDeps([404,69,405,81,284,358]))),Azt=C.lazy(()=>Fe(()=>import("./CMAList-guvf3-Ci.js"),__vite__mapDeps([406,394,396,407,140,408]))),kzt=C.lazy(()=>Fe(()=>import("./CMABuilder-47EgfXRE.js"),__vite__mapDeps([409,394,407,140,296,410,161,411,412,413,414,314,7,81]))),Czt=C.lazy(()=>Fe(()=>import("./ListingPresentations-DIhV93QW.js"),__vite__mapDeps([415,416,417,129,418]))),Nzt=C.lazy(()=>Fe(()=>import("./ListingPresentationBuilder-CMjJOxKe.js"),__vite__mapDeps([419,137,212,213,420,421,129,416,417,422,158,218,152,274,418,81,342,423]))),Izt=C.lazy(()=>Fe(()=>Promise.resolve().then(()=>kit),void 0)),Pzt=C.lazy(()=>Fe(()=>import("./InnerCirclePopbys-D9Tmp363.js"),__vite__mapDeps([424,365,370,425,426,69]))),Rzt=C.lazy(()=>Fe(()=>import("./ListingExchange-CWrhA7-u.js"),__vite__mapDeps([427,125,126,428,121,134,51,429,334,385,386,384,141,142,215,199,430,400]))),Lzt=C.lazy(()=>Fe(()=>import("./ListingDetail-C_MPhFjZ.js"),__vite__mapDeps([431,128,125,126,129,130,430,134,428,121,135,136,137,138,139,140,141,142,143,144,145,97,98,146,229,8,51,148]))),Kue=C.lazy(()=>Fe(()=>import("./ListingForm-DafMk9SL.js"),__vite__mapDeps([432,132,125,126,131,133,383,340,128,129,130,75]))),Dzt=C.lazy(()=>Fe(()=>import("./CustomizeListingPage-C17JHlzB.js"),__vite__mapDeps([433,314,81,304,434,95,133])));function Mzt(){const{search:t}=ki();return s.jsx(ci,{to:`/video-studio${t}`,replace:!0})}const Ozt=C.lazy(()=>Fe(()=>import("./VideoStudio-DU7a071t.js"),__vite__mapDeps([435,436,333,230,231,383,437,119,120,25,38,105,5,121,122,123,221,213,145,97,98,137,375,168,95,191,238,65,158,438,439,269,440,87,116,441,151,282,414,442,443,444,445,412,161,281,446,447,448,449,51,7,411,75,314,340,450,81,235,451,234,148]))),Fzt=C.lazy(()=>Fe(()=>import("./DesktopStudio-DpN6_LEM.js"),[])),Yue=C.lazy(()=>Fe(()=>import("./MainStageGate-B4Uw7Qvo.js"),__vite__mapDeps([452,439,438,200,453,443,414,442,454,80,455,282,456,441,235,389,116]))),Bzt=C.lazy(()=>Fe(()=>import("./MainStageAdmin-DxV_q4Kw.js"),__vite__mapDeps([457,296,453,314,439,81,158]))),$zt=C.lazy(()=>Fe(()=>import("./StudioKitsAdmin-CuX1QWl4.js"),__vite__mapDeps([458,230,231,444,81]))),zzt=C.lazy(()=>Fe(()=>import("./StudioGuestJoin-DcaSVH4Z.js"),__vite__mapDeps([459,445,230,231,412,161,281,443,449,442,454,414,451]))),Uzt=C.lazy(()=>Fe(()=>import("./VideoLibrary-tmj7uNYX.js"),__vite__mapDeps([460,383,382,437,119,120,25,38,105,5,121,122,123,221,213,145,97,98,137,375,168,95,303,238,65,158,461,462,312]))),Vzt=C.lazy(()=>Fe(()=>import("./DealPipeline-QbuaHw0b.js"),__vite__mapDeps([463,464,113,186,185,465,401,436,466,467,274,86,279,152,468,469,161,470,8,29,48,183,342,434,381,471,122,400,285,93,472,36,473,474,475,57,306,69,476,84,449,477,478,479,120,336,312,123,267,368,283,480,90,284,270,121,281,241,455,35,75,481,482,483,175,484,147,217,485,264,269,411,80,486,487,488,489,133,490,282,462,11,181,182,491,492,201,493,233,158,447,88,108,372,494,218,340,95,337,184,495,362,425,496,116,100,363,497,498,196,390,12,199,499,500,246,501,502,442,414,456,206,413,314,26,503,160,303,504,423,231,51,426,505,448,304,146,105,7,358,405,114,454,261,151,50,506,507,148,112,508,367,290,260,189,220,81,450,509,235,292,510,511,268,512,67,207,38,154,387,280,5,451,513,215,461,71,514,37,515,25,49,21,441,516,234,329,333,229,65,204,87,517,518,195,389,519,313,39,109,188,371,125,126,395,520,221,213,521,522,523,524,296,525,410,412,383,168,138,137,139,140,141,142,143,144,145,97,98,526,212,244,392,527,528,529,530]))),qzt=C.lazy(()=>Fe(()=>import("./FormsLibrary-De3RIdz1.js"),__vite__mapDeps([531,523,532,81,421,503,381,234,514,522,481,152,274,455,401,484]))),Gzt=C.lazy(()=>Fe(()=>import("./TransactionCoordinator-D2XbHWTc.js"),__vite__mapDeps([533,526,212,213,290]))),Hzt=C.lazy(()=>Fe(()=>import("./PortalReferrals-C7NW-Y4H.js"),__vite__mapDeps([534,535]))),Wzt=C.lazy(()=>Fe(()=>import("./AgentVendors-BJ8jThMU.js"),__vite__mapDeps([536,537,75]))),Kzt=C.lazy(()=>Fe(()=>import("./BrokerageForms-RWv1JLC3.js"),__vite__mapDeps([538,523,532,81,421,503,381,234,514,486,487,401]))),Yzt=C.lazy(()=>Fe(()=>import("./BrokerageVendors-BIvhnnOD.js"),__vite__mapDeps([539,537,75]))),Zzt=C.lazy(()=>Fe(()=>import("./ClientPortalsHub-D_tyXs_H.js"),__vite__mapDeps([540,529,81,395,524,133,229,296,525,410,161,411,412,413,414,314,7,383,95,8,168,465,500,401,541,536,537,75,534,535,109]))),Xzt=C.lazy(()=>Fe(()=>import("./ClientPortalDetail-nkeZNlyD.js"),__vite__mapDeps([542,395,535,524,133,229,296,525,410,161,411,412,413,414,314,7,383,95,81,8,168,541,500,465,401]))),Qzt=C.lazy(()=>Fe(()=>import("./MyCardEditor-C6QBwB9t.js"),__vite__mapDeps([543,187,188,189,190,544,215,133,152,274,75,246,136,314,90,148,160]))),Jzt=C.lazy(()=>Fe(()=>import("./Integrations-BDikZQvU.js"),__vite__mapDeps([545,221,213,366,256,152,274,69,461,546,98,547,137,330,81,228,30,238,65,158,548,97,231,519,235]))),e6t=C.lazy(()=>Fe(()=>import("./BrowserExtension-C06WbHOM.js"),__vite__mapDeps([549,306]))),t6t=C.lazy(()=>Fe(()=>import("./IntegrationsGmailCallback-DxY88wj1.js"),__vite__mapDeps([550,69,84]))),r6t=C.lazy(()=>Fe(()=>import("./IntegrationsCanvaCallback-BcGlAmuu.js"),[])),n6t=C.lazy(()=>Fe(()=>import("./IntegrationsMetaCallback-9eVzPQOI.js"),__vite__mapDeps([551,69,84]))),i6t=C.lazy(()=>Fe(()=>import("./ScorecardAdmin-rxuY6JZ9.js"),[])),s6t=C.lazy(()=>Fe(()=>import("./AgentActivation-FLJrCW_T.js"),__vite__mapDeps([552,156,100,389]))),Zue=C.lazy(()=>Fe(()=>import("./ScorecardAgentView-DVE2Cpos.js"),[])),a6t=C.lazy(()=>Fe(()=>import("./ListingExchange-B_Ne-ZXc.js"),[])),o6t=C.lazy(()=>Fe(()=>import("./ListingLeads-Dkeo2XoM.js"),[])),l6t=C.lazy(()=>Fe(()=>import("./PublicSiteLeads-DwiflBhO.js"),[])),c6t=C.lazy(()=>Fe(()=>import("./MembershipReviews-COlf0JbB.js"),__vite__mapDeps([553,156]))),u6t=C.lazy(()=>Fe(()=>import("./LeadNotifications-doM3MgjP.js"),__vite__mapDeps([554,156]))),d6t=C.lazy(()=>Fe(()=>import("./WeeklyDigest-ZSfzlSKI.js"),__vite__mapDeps([555,84]))),h6t=C.lazy(()=>Fe(()=>import("./AgentPoints-Cf5WRuEW.js"),__vite__mapDeps([556,201]))),f6t=C.lazy(()=>Fe(()=>import("./AgentCards-BU9G3s11.js"),__vite__mapDeps([557,187,188,189,190,544,215,133,152,274,75,246,513]))),m6t=C.lazy(()=>Fe(()=>import("./Marketplace-Bzb2oux3.js"),__vite__mapDeps([558,158,215,80]))),p6t=C.lazy(()=>Fe(()=>import("./RewardStore-hPRoflrv.js"),__vite__mapDeps([559,560,80,95,81]))),g6t=C.lazy(()=>Fe(()=>import("./Integrations-BVlbwjeL.js"),__vite__mapDeps([561,156,228,30,227,229,269,546,98,69]))),y6t=C.lazy(()=>Fe(()=>import("./SocialConnections-DMkJMEHV.js"),__vite__mapDeps([562,156]))),x6t=C.lazy(()=>Fe(()=>import("./SocialAutopilot-xmzlZwFM.js"),__vite__mapDeps([563,156,230,231,232,81]))),v6t=C.lazy(()=>Fe(()=>import("./McpUpdates-D8CY_EE8.js"),__vite__mapDeps([564,156]))),_6t=C.lazy(()=>Fe(()=>import("./RefreshMcpTools-B_fHl19K.js"),[])),b6t=C.lazy(()=>Fe(()=>import("./NotificationSettings-Bx2i1C6j.js"),__vite__mapDeps([565,156]))),w6t=C.lazy(()=>Fe(()=>import("./PresentationAnalytics-DPjrpxY2.js"),__vite__mapDeps([566,273,152,274,160]))),S6t=C.lazy(()=>Fe(()=>import("./ListingPresentationStudioAdmin-CbF3HMJB.js"),__vite__mapDeps([567,156]))),T6t=C.lazy(()=>Fe(()=>import("./ListingRevivalAdmin-BTOtZ3Rj.js"),__vite__mapDeps([568,156,569]))),E6t=C.lazy(()=>Fe(()=>import("./GuestBookAnalytics-BWK0XwbU.js"),__vite__mapDeps([570,69]))),j6t=C.lazy(()=>Fe(()=>import("./IntegrationsCallback-Dl7WeLK-.js"),__vite__mapDeps([571,69,84]))),A6t=C.lazy(()=>Fe(()=>import("./Prospector-DL_JfQcR.js"),[])),k6t=C.lazy(()=>Fe(()=>import("./AdminRecruiting-UP_86DEI.js"),__vite__mapDeps([572,573,133,137,410,161,411,412,413,414,314,7,383,81,303,217,152,274,84,483,88,340,167,221,213,547,98,178,179,311,574,183,329,475,181,182,491,184,185,186,95,313,160,497,11,38,5,141,142,69,510]))),C6t=C.lazy(()=>Fe(()=>import("./BrokerageRecruiting-B7g8ZWpV.js"),__vite__mapDeps([575,573,133,137,410,161,411,412,413,414,314,7,383,81,303,217,152,274,84,483,88,340,167,221,213,547,98,178,179,311,574,183,329,475,181,182,491,184,185,186,95,313,160,497,11,38,5,141,142,69,519,477,363,518,241,576]))),N6t=C.lazy(()=>Fe(()=>import("./BrokerageOnboarding-D1L1AgSi.js"),__vite__mapDeps([577,319,320,84,81,169,519,477,481,517,152,274,576]))),I6t=C.lazy(()=>Fe(()=>import("./BrokerageTransactions-D8PgsjQi.js"),__vite__mapDeps([578,521,201,485,84,579,530,481,80]))),P6t=C.lazy(()=>Fe(()=>import("./BrokerageOperations-DIkH5D8l.js"),__vite__mapDeps([580,581,530,319,495]))),R6t=C.lazy(()=>Fe(()=>import("./WebsitesHub-Byw3zjBO.js"),__vite__mapDeps([582,583]))),L6t=C.lazy(()=>Fe(()=>import("./SiteGrade-iE3ogpqW.js"),__vite__mapDeps([584,583,417,84]))),D6t=C.lazy(()=>Fe(()=>import("./TeamWebsite-DxZj13Oh.js"),__vite__mapDeps([585,586,59,75,587,583]))),M6t=C.lazy(()=>Fe(()=>import("./BrokerageWebsite-BTrvFlJH.js"),__vite__mapDeps([588,586,59,75,587,583]))),O6t=C.lazy(()=>Fe(()=>import("./BrokerageAgentWebsites-BwP2VdeU.js"),__vite__mapDeps([589,88]))),F6t=C.lazy(()=>Fe(()=>import("./BrokerageCommissionPlans-BmFF9V3g.js"),__vite__mapDeps([590,520,530,417,483,581,493,105,367,161,112,579,389]))),B6t=C.lazy(()=>Fe(()=>import("./BrokerageContentActivity-2kphvxFa.js"),__vite__mapDeps([591,156]))),$6t=C.lazy(()=>Fe(()=>import("./BetaSocialPostGenerator-DdVE6fVt.js"),__vite__mapDeps([592,156,171,253,254,215]))),z6t=C.lazy(()=>Fe(()=>import("./AdminLMS-CZ6-n2Cz.js"),__vite__mapDeps([593,594,184,512,75]))),U6t=C.lazy(()=>Fe(()=>import("./AdminCourseDetail-BVXMmMJ0.js"),__vite__mapDeps([595,594,184,512,75,158,81]))),V6t=C.lazy(()=>Fe(()=>import("./AdminLMSStats-BoiddAMW.js"),[])),q6t=C.lazy(()=>Fe(()=>import("./LevelUpU-B2SJzzLH.js"),__vite__mapDeps([596,594,184,512]))),G6t=C.lazy(()=>Fe(()=>import("./LevelUpUCourse-B0fdGALn.js"),__vite__mapDeps([597,594]))),H6t=C.lazy(()=>Fe(()=>import("./MobileAgentApp-CyusgRdM.js"),__vite__mapDeps([598,88,168,334,138,137,139,140,141,142,143,144,145,97,98,146,215,36,38,281]))),W6t=C.lazy(()=>Fe(()=>import("./StagingStudio-fXXJNsTF.js"),__vite__mapDeps([599,212,213,600,478,455,49,158,601,602,35,603,192,193,235,80,447]))),K6t=C.lazy(()=>Fe(()=>import("./StagingLibrary-aOjj4nTg.js"),__vite__mapDeps([604,600,478,455,49,601,192,486,80,447]))),Y6t=C.lazy(()=>Fe(()=>import("./StagingCredits-Oj0tnJl5.js"),__vite__mapDeps([605,603,192,193,90]))),Z6t=C.lazy(()=>Fe(()=>import("./AgentWallet-LdZW9bBw.js"),__vite__mapDeps([606,402,192,607,269,193,292]))),X6t=C.lazy(()=>Fe(()=>import("./StagingSharePage-ChGCbJeo.js"),__vite__mapDeps([608,602]))),Q6t=C.lazy(()=>Fe(()=>import("./StagingStudioAdmin-CX8e7EYK.js"),__vite__mapDeps([609,600,478,455,49,4,192,602,447,86]))),J6t=C.lazy(()=>Fe(()=>import("./ContactFinderAdmin-po0oW8Oc.js"),__vite__mapDeps([610,402]))),eUt=C.lazy(()=>Fe(()=>import("./PostcardManager-1Ra-iLOj.js"),__vite__mapDeps([611,612,250,251,613,234,185,81]))),tUt=C.lazy(()=>Fe(()=>import("./MailStudioTemplates-Ck05pGYj.js"),__vite__mapDeps([614,612,250,251,613,234,185,81,152,274]))),rUt=C.lazy(()=>Fe(()=>import("./HomeReelManager-Ag8Yp9QC.js"),__vite__mapDeps([615,607,269,616,51,7,340,314,132,504,234,449,133,279,450,81,270,267,430,342]))),nUt=C.lazy(()=>Fe(()=>import("./AdminMusicVideos-Ckd_TvRe.js"),__vite__mapDeps([617,51]))),iUt=C.lazy(()=>Fe(()=>import("./AdminVideoLab-D7v90RiJ.js"),__vite__mapDeps([618,616,51,449,7,158,508]))),sUt=C.lazy(()=>Fe(()=>import("./BoostPreview-B12VI4-p.js"),__vite__mapDeps([619,1,2,3,4,5]))),aUt=C.lazy(()=>Fe(()=>import("./AdminCredits-7N2XOzli.js"),__vite__mapDeps([620,156,201,476]))),oUt=C.lazy(()=>Fe(()=>import("./AdminCleanup-DayAIn1S.js"),[])),lUt=C.lazy(()=>Fe(()=>import("./MailStudio-D7XoXqFN.js"),__vite__mapDeps([621,613,250,251,417,81,234,158,423,185,186,469,385,386,622,361,283,12,461,623,191,440,215,121,229,420,421,360,161,148,201,624]))),cUt=()=>{const t=ki();return s.jsx(ci,{to:`/mission-control/direct-mail${t.search}`,replace:!0})},uUt=C.lazy(()=>Fe(()=>import("./InnerCirclePopbyMap-DDN1w81f.js"),__vite__mapDeps([625,370,425,426,69]))),dUt=C.lazy(()=>Fe(()=>import("./SphereMap-BqygAVt3.js"),__vite__mapDeps([626,386,137,448,388,360,622,426,334,376,377,378,379,380,256,234,336,381,314,296,382,383,195,152,274,95,138,139,140,141,142,143,144,145,97,98,146,168,215,390,220,402,372,333,434,494]))),hUt=C.lazy(()=>Fe(()=>import("./PropertyIntelligenceDashboard-ZE1fgtg7.js"),__vite__mapDeps([627,399,471,270,400]))),fUt=C.lazy(()=>Fe(()=>import("./LiveVisitorFeed-BqkdE3HI.js"),__vite__mapDeps([628,280]))),mUt=C.lazy(()=>Fe(()=>import("./LeadSites-KehlkHfV.js"),__vite__mapDeps([629,507,506]))),Xue=C.lazy(()=>Fe(()=>import("./LeadSiteEditor-CKvC-7FK.js"),__vite__mapDeps([630,631,105,379,380,46,464,113,186,185,465,401,436,466,467,274,86,279,152,468,469,161,470,8,29,48,183,342,434,381,471,122,400,285,93,472,36,473,474,475,57,306,69,476,84,449,477,478,479,120,336,312,123,267,368,283,480,90,284,270,121,281,241,455,35,75,481,482,483,175,484,147,217,485,264,269,411,80,486,487,488,489,133,490,282,462,11,181,182,491,492,201,493,233,158,447,88,108,372,494,218,340,95,337,184,495,362,425,496,116,100,363,497,498,196,390,12,199,499,500,246,501,502,442,414,456,206,413,314,26,503,160,303,504,423,231,51,426,505,448,304,146,7,358,405,114,454,261,151,50,506,507,148,112,508,367,290,260,189,220,81,450,509,235,292,510,511,268,512,67,207,38,154,387,280,5,451,513,215,461,71,514,37,515,25,49,21,441,516,234,329,333,229,65,204,87,517,518,195,389,519,313,39,109,188,632,132,633,54,408]))),pUt=C.lazy(()=>Fe(()=>import("./AdminLeadSiteThemes-BhDxFO4r.js"),__vite__mapDeps([634,631,633,304,234,284,489]))),gUt=C.lazy(()=>Fe(()=>import("./AdminFreeWebsiteOffers-BX0mpK3q.js"),[])),yUt=C.lazy(()=>Fe(()=>import("./AdminPartnerships-DZDjAHYP.js"),[])),xUt=C.lazy(()=>Fe(()=>import("./MyPartnership-DgdLVdLx.js"),[])),vUt=C.lazy(()=>Fe(()=>import("./UpgradeFeature-CWEvakkL.js"),[])),_Ut=C.lazy(()=>Fe(()=>import("./CoachingOnboarding-DLmJhezJ.js"),[])),bUt=C.lazy(()=>Fe(()=>import("./AdminFreeWebsiteOfferStudio-Beq0nwDX.js"),__vite__mapDeps([635,631,632,132,633,11,12,26,304,133,75,234,121,25,81]))),wUt=C.lazy(()=>Fe(()=>import("./AdminMlsFeeds-DgnNXUTL.js"),__vite__mapDeps([636,270]))),SUt=C.lazy(()=>Fe(()=>import("./AdminLeadSiteAnalytics-CZSpgkxl.js"),[])),TUt=C.lazy(()=>Fe(()=>import("./AdminWebsiteInterests-BqlgaxGk.js"),[])),EUt=C.lazy(()=>Fe(()=>import("./AdminWebsiteRequests-DWu-_g8Y.js"),__vite__mapDeps([637,84]))),jUt=C.lazy(()=>Fe(()=>import("./NeedAWebsite-D7tqwMaF.js"),__vite__mapDeps([638,194,218,160,468]))),AUt=C.lazy(()=>Fe(()=>import("./AdminMlsFeeTracker-DK1c4SVr.js"),[])),kUt=C.lazy(()=>Fe(()=>import("./MLSListings-BFtS-sDI.js"),__vite__mapDeps([639,408,11,430,429,334,385,386,384,141,142,215,235,75,342,51]))),CUt=C.lazy(()=>Fe(()=>import("./MLSListingDetail-C3CuXAaX.js"),__vite__mapDeps([640,168,139,140,334,215,75,296,40,137,136,417,148,516]))),NUt=C.lazy(()=>Fe(()=>import("./MarketReportPage-CQz-uky8.js"),[]));C.lazy(()=>Fe(()=>import("./WebsiteActivityPage-DVEIN3_e.js"),__vite__mapDeps([641,168,138,137,139,140,141,142,143,144,145,97,98,146,12])));const IUt=C.lazy(()=>Fe(()=>import("./PublicRecruitForm-Caa6Z4a7.js"),__vite__mapDeps([642,24,483]))),PUt=C.lazy(()=>Fe(()=>import("./PublicRecruitVideo-CyjkZ9Qj.js"),[])),RUt=C.lazy(()=>Fe(()=>import("./PublicRecruitUnsubscribe-fZLZK_2W.js"),[])),LUt=C.lazy(()=>Fe(()=>import("./PublicEventInviteUnsubscribe-DOmoU3AX.js"),__vite__mapDeps([643,472]))),DUt=C.lazy(()=>Fe(()=>import("./SocialConnections-IbODS_z7.js"),__vite__mapDeps([644,238,65,158,69,231,269,84]))),MUt=C.lazy(()=>Fe(()=>import("./SocialConnectionsCallback-BSbskEOj.js"),__vite__mapDeps([645,69,84]))),OUt=C.lazy(()=>Fe(()=>import("./SocialConnectionsGoogleCallback-BFAmwR4d.js"),[])),FUt=C.lazy(()=>Fe(()=>import("./LinkedInCallback-B71CMmGf.js"),__vite__mapDeps([646,69,84]))),BUt=C.lazy(()=>Fe(()=>import("./TikTokCallback-De3mcM2F.js"),__vite__mapDeps([647,242,69,84,231]))),$Ut=C.lazy(()=>Fe(()=>import("./MarketplaceProductDetail-CXS-RPP7.js"),[])),zUt=C.lazy(()=>Fe(()=>import("./MarketplaceCart-Amx4J-1x.js"),__vite__mapDeps([648,137,268]))),UUt=C.lazy(()=>Fe(()=>import("./MarketplaceOrders-DIw1rvNQ.js"),[])),VUt=C.lazy(()=>Fe(()=>import("./MarketplaceOrderDetail-oIm1nX9Q.js"),__vite__mapDeps([649,137,175,515,21]))),qUt=C.lazy(()=>Fe(()=>import("./MarketplaceSuccess-DDLxX-vp.js"),[])),GUt=C.lazy(()=>Fe(()=>import("./RewardStore-DEdjn1dn.js"),__vite__mapDeps([650,560,221,213,268]))),HUt=C.lazy(()=>Fe(()=>import("./ReferFriends-BwTQ2QeD.js"),__vite__mapDeps([651,137,168]))),WUt=C.lazy(()=>Fe(()=>import("./SmartPresentations-Cg8GeEXc.js"),__vite__mapDeps([652,653,401]))),Que=C.lazy(()=>Fe(()=>import("./SmartPresentationCreate-C1AGE_y7.js"),__vite__mapDeps([654,177,178,179,180,181,182,183,184,185,186,95,410,161,411,412,413,414,314,7,655,75,383,69,296,653,168,138,137,139,140,141,142,143,144,145,97,98,146,133,158]))),KUt=C.lazy(()=>Fe(()=>import("./PublicPresentation-_LEXL3S8.js"),[])),YUt=C.lazy(()=>Fe(()=>import("./GuestBook-CeBsSx6v.js"),__vite__mapDeps([656,137,136,377,387,133,446,447,296,88,401,168,141,95,215,148,374,360,158,201,75]))),ZUt=C.lazy(()=>Fe(()=>Promise.resolve().then(()=>kQe),void 0)),XUt=C.lazy(()=>Fe(()=>Promise.resolve().then(()=>PQe),void 0)),QUt=C.lazy(()=>Fe(()=>import("./PublicResourceLanding-DWs350Ng.js"),[])),JUt=C.lazy(()=>Fe(()=>import("./SignDocument-BHYTghE4.js"),__vite__mapDeps([657,421,84,234,514,455]))),eVt=C.lazy(()=>Fe(()=>import("./Blog-Bed3pjxD.js"),__vite__mapDeps([658,659]))),tVt=C.lazy(()=>Fe(()=>import("./BlogPost-CNWxafYE.js"),__vite__mapDeps([660,659,480,516]))),rVt=C.lazy(()=>Fe(()=>import("./AdminBlog-B-01j6th.js"),__vite__mapDeps([661,137,178,180,574,183,329,182,491,184,312,185,186,95,158,75]))),nVt=C.lazy(()=>Fe(()=>import("./ReviewLanding-BpPM1oOg.js"),__vite__mapDeps([662,663,410,161,411,412,413,414,314,7]))),iVt=C.lazy(()=>Fe(()=>import("./PublicReviewsPage-B5vF9llo.js"),__vite__mapDeps([664,468,501]))),sVt=C.lazy(()=>Fe(()=>import("./PublicReviewSubmit-y9wBElQW.js"),__vite__mapDeps([665,663,410,161,411,412,413,414,314,7]))),aVt=C.lazy(()=>Fe(()=>import("./Reviews-CKg4u-V7.js"),__vite__mapDeps([666,136,129,236,237,239,230,231,235,468,151,260,75,65,336,148,372]))),oVt=C.lazy(()=>Fe(()=>import("./PublicNetSheet-3Wsc7GoL.js"),[])),Jue=C.lazy(()=>Fe(()=>import("./NetSheets-C7JhI87-.js"),__vite__mapDeps([667,81]))),lVt=C.lazy(()=>Fe(()=>import("./ClientPortalPage-BcaAp_gx.js"),[])),cVt=C.lazy(()=>Fe(()=>Promise.resolve().then(()=>_it),void 0)),uVt=C.lazy(()=>Fe(()=>import("./LenderHub-DrQ60Heq.js"),__vite__mapDeps([668,528,669,204]))),dVt=C.lazy(()=>Fe(()=>import("./LendersLanding-CMXyBLBS.js"),__vite__mapDeps([670,669,468,473]))),hVt=C.lazy(()=>Fe(()=>import("./LendingPartners-BDLahxGz.js"),__vite__mapDeps([671,669,468,317,392,527,528,393,497,466]))),fVt=C.lazy(()=>Fe(()=>import("./AdminLenders-BhT0EAFC.js"),__vite__mapDeps([672,669,468,75]))),mVt=C.lazy(()=>Fe(()=>import("./CardStudio-ClkrCWsW.js"),__vite__mapDeps([673,383,525,410,161,411,412,413,414,314,7,296,237,168,144]))),pVt=C.lazy(()=>Fe(()=>import("./ListingStudio-QhZYQMv3.js"),__vite__mapDeps([674,158,284,121,482,105,414,50,363,29]))),gVt=C.lazy(()=>Fe(()=>Promise.resolve().then(()=>pRt),void 0)),yVt=C.lazy(()=>Fe(()=>import("./SmartDrips-BxR9BmLh.js"),__vite__mapDeps([675,137,168,507,405,296,525,410,161,411,412,413,414,314,7,383,377,378,379,380,256,234,336,381,382,195,152,274,95,397,334,215,372,285]))),xVt=C.lazy(()=>Fe(()=>import("./WeeklyReels-DrOr3AqK.js"),__vite__mapDeps([676,212,213,677,137,221,678,449,243,235]))),vVt=C.lazy(()=>Fe(()=>import("./WeeklyReelsOnboarding-DU47GCow.js"),__vite__mapDeps([679,678]))),_Vt=C.lazy(()=>Fe(()=>import("./WeeklyReelsAdmin-BI-zcnDW.js"),__vite__mapDeps([680,243,678,677,137,221,213,449]))),bVt=C.lazy(()=>Fe(()=>import("./AttractLayout-CULD9gBD.js"),__vite__mapDeps([681,682,683,684,154,5,241]))),wVt=C.lazy(()=>Fe(()=>import("./AttractToday-DkZddU48.js"),__vite__mapDeps([685,221,213,683,686,687,688,689,690,372,340,492,691,692,519,285,502,693,511]))),SVt=C.lazy(()=>Fe(()=>import("./AttractRelationships-BNvClaPE.js"),__vite__mapDeps([694,695,691,687,692,217,696,401,688,683,686,519]))),TVt=C.lazy(()=>Fe(()=>import("./AttractFollowUp-DOcqjDZv.js"),__vite__mapDeps([697,695,688,687,123]))),EVt=C.lazy(()=>Fe(()=>import("./AttractResources-BuE5iROu.js"),[])),jVt=C.lazy(()=>Fe(()=>import("./AttractTemplates-DbR_VSFn.js"),__vite__mapDeps([698,123,290]))),AVt=C.lazy(()=>Fe(()=>import("./AttractReports-Cn4jG2wt.js"),__vite__mapDeps([699,695,687,689,692,305]))),kVt=C.lazy(()=>Fe(()=>import("./AttractSettings-_PLHYmri.js"),__vite__mapDeps([700,695,682]))),CVt=C.lazy(()=>Fe(()=>import("./AttractToolkit-DvMivc8A.js"),__vite__mapDeps([701,695,246,511,285,340]))),NVt=C.lazy(()=>Fe(()=>import("./Objections-MONbHh0T.js"),__vite__mapDeps([702,511]))),IVt=C.lazy(()=>Fe(()=>import("./AttractCalculator-MHJN8JeY.js"),__vite__mapDeps([703,695,704]))),PVt=C.lazy(()=>Fe(()=>import("./AttractEventList-CTDVAdgV.js"),__vite__mapDeps([705,693]))),ede=C.lazy(()=>Fe(()=>import("./AttractEventBuilder-tt3FyuHf.js"),__vite__mapDeps([706,137,693,707,95,81]))),RVt=C.lazy(()=>Fe(()=>import("./AttractEventDetail-BD5uW4Mm.js"),__vite__mapDeps([708,693,687,148,246]))),LVt=C.lazy(()=>Fe(()=>import("./AttractEventCheckIn-BBfAXUAd.js"),__vite__mapDeps([709,440,693,148]))),DVt=C.lazy(()=>Fe(()=>import("./AttractOnboarding-CR-S5GfU.js"),__vite__mapDeps([710,682,154,490,285]))),MVt=C.lazy(()=>Fe(()=>import("./ContentStudio-Df5AOye4.js"),__vite__mapDeps([711,695,509]))),OVt=C.lazy(()=>Fe(()=>import("./KitList-BdejGJkW.js"),__vite__mapDeps([712,707,340,114]))),tde=C.lazy(()=>Fe(()=>import("./KitBuilder-ClY1X-Qz.js"),__vite__mapDeps([713,707,687,695,714,95,246,152,274,314,161]))),FVt=C.lazy(()=>Fe(()=>import("./KitAnalytics-DOGaXLb1.js"),__vite__mapDeps([715,707,695,160,305]))),BVt=C.lazy(()=>Fe(()=>import("./KitTemplates-Co9FHKAG.js"),__vite__mapDeps([716,707,695]))),$Vt=C.lazy(()=>Fe(()=>import("./AttractAgentDetail-DkCpFW1h.js"),__vite__mapDeps([717,696,687,401,138,137,139,140,141,142,143,144,145,97,98,146,168,683,688,684,690,372,340,492,692,5,280,279,519,38]))),zVt=C.lazy(()=>Fe(()=>import("./AttractOpportunities-DMybbah_.js"),__vite__mapDeps([718,683,686,690,372,340,492]))),UVt=C.lazy(()=>Fe(()=>import("./AttractIntelligenceDebug-COnxtcBA.js"),__vite__mapDeps([719,683,684,470]))),VVt=C.lazy(()=>Fe(()=>import("./AttractToolsQA-BSLBSKnM.js"),[])),qVt=C.lazy(()=>Fe(()=>import("./PublicAttractKit-DYEOKuY_.js"),__vite__mapDeps([720,714,95,246]))),GVt=C.lazy(()=>Fe(()=>import("./PublicAttractEvent-DAMRSerC.js"),__vite__mapDeps([721,693]))),HVt=C.lazy(()=>Fe(()=>import("./PublicAttractEventCheckIn-Lf6WjmTv.js"),[])),WVt=C.lazy(()=>Fe(()=>import("./PublicAttractionPage-2nQrcWtc.js"),__vite__mapDeps([722,723,212,213]))),KVt=C.lazy(()=>Fe(()=>import("./RevivalLanding-BWAvUGCa.js"),__vite__mapDeps([724,725]))),rde=C.lazy(()=>Fe(()=>import("./RevivalPlan-Di26h3L5.js"),__vite__mapDeps([726,727,136,725,417,440]))),YVt=C.lazy(()=>Fe(()=>import("./ListingRevival-BIR1oGkk.js"),__vite__mapDeps([728,729,725,569,479,217,148,730,218,235,401,465]))),ZVt=C.lazy(()=>Fe(()=>import("./RevivalCampaignWizard-C3G4lBGQ.js"),__vite__mapDeps([731,422,416,417,158,729,725,732,253,623]))),XVt=C.lazy(()=>Fe(()=>import("./RevivalCampaignDetail-DGQyqLhz.js"),__vite__mapDeps([733,136,732,253,417,623,734,195,488,81,374,360,729,725,727,440,410,161,411,412,413,414,314,7,383,69,422,416,158,75,148,220,483,29]))),QVt=C.lazy(()=>Fe(()=>import("./FsboBreakthrough-asc8qN42.js"),__vite__mapDeps([735,736,737,738,422,416,417,158,148,730,218,235,401,465]))),JVt=C.lazy(()=>Fe(()=>import("./FsboCampaignWizard-DTZ2nUmH.js"),__vite__mapDeps([739,422,416,417,158,736,737,732,253,623]))),e8t=C.lazy(()=>Fe(()=>import("./FsboCampaignDetail-DsHLc3br.js"),__vite__mapDeps([740,136,732,253,417,623,734,195,488,81,736,737,374,360,738,422,416,158,191,483]))),t8t=C.lazy(()=>Fe(()=>import("./FsboLanding-C1pI9vfI.js"),__vite__mapDeps([741,737,742]))),r8t=C.lazy(()=>Fe(()=>import("./FsboGuide-kIgR0N69.js"),__vite__mapDeps([743,742]))),n8t=C.lazy(()=>Fe(()=>import("./FsboBreakthroughAdmin-DkNFhwlj.js"),__vite__mapDeps([744,736,148,730]))),i8t=C.lazy(()=>Fe(()=>import("./AttractLandingPageBuilder-aZcf96JX.js"),__vite__mapDeps([745,704,723,212,213,81]))),s8t=C.lazy(()=>Fe(()=>import("./AttractAccess-CbOdgL6K.js"),__vite__mapDeps([746,156,201,84]))),a8t=C.lazy(()=>Fe(()=>import("./Teams-Dg6feFOs.js"),__vite__mapDeps([747,275,284,276,277,278,279,280,201,281,282,283,80,87]))),o8t=C.lazy(()=>Fe(()=>import("./MyTeam-Bce6n08E.js"),__vite__mapDeps([748,275,278,279,280,201,281,282,277,749,284,283,80]))),l8t=C.lazy(()=>Fe(()=>import("./TeamHub-uHgkN3T9.js"),__vite__mapDeps([750,275,278,279,280,201,281,282,277,749,586,59,75,284,283,80]))),c8t=C.lazy(()=>Fe(()=>import("./SchedulerSettings-BhzFe0uM.js"),__vite__mapDeps([751,92,93,94,65,137,499,84,548,97,98,235]))),u8t=C.lazy(()=>Fe(()=>import("./MyCalendar-CNMgJ5uC.js"),__vite__mapDeps([752,94,237,240,239,241]))),d8t=C.lazy(()=>Fe(()=>Promise.resolve().then(()=>_Rt),void 0)),h8t=C.lazy(()=>Fe(()=>import("./BookingManagePage-BJkZgWd9.js"),__vite__mapDeps([753,84]))),f8t=C.lazy(()=>Fe(()=>import("./LandingPages-BswntYeF.js"),__vite__mapDeps([754,136,148]))),m8t=C.lazy(()=>Fe(()=>import("./BuyerMatch-DcMCxHYK.js"),__vite__mapDeps([755,756,327,256,328,183,329,184,95,160,314,152,274,330,139,140,334,385,386,215,7,401]))),p8t=C.lazy(()=>Fe(()=>import("./BuyerMatchEditor-SHpctJOf.js"),__vite__mapDeps([757,136,756,327,256,328,183,329,184,95,160,314,152,274,330,139,140,334,385,386,215,138,137,141,142,143,144,145,97,98,146,758,81]))),g8t=C.lazy(()=>Fe(()=>import("./PublicBuyerMatch-CyBp2KB3.js"),__vite__mapDeps([759,758,496,84]))),y8t=C.lazy(()=>Fe(()=>import("./LandingPageEditor-Dd6MR42e.js"),__vite__mapDeps([760,136,160,132,148,81,133]))),x8t=C.lazy(()=>Fe(()=>import("./LandingPageDefaults-C-HPjxB5.js"),__vite__mapDeps([761,81]))),v8t=C.lazy(()=>Fe(()=>Promise.resolve().then(()=>URt),void 0)),_8t=C.lazy(()=>Fe(()=>import("./WebsiteAppsHub-BMCkUnop.js"),__vite__mapDeps([762,763,284,764,464,113,186,185,465,401,436,466,467,274,86,279,152,468,469,161,470,8,29,48,183,342,434,381,471,122,400,285,93,472,36,473,474,475,57,306,69,476,84,449,477,478,479,120,336,312,123,267,368,283,480,90,270,121,281,241,455,35,75,481,482,483,175,484,147,217,485,264,269,411,80,486,487,488,489,133,490,282,462,11,181,182,491,492,201,493,233,158,447,88,108,372,494,218,340,95,337,184,495,362,425,496,116,100,363,497,498,196,390,12,199,499,500,246,501,502,442,414,456,206,413,314,26,503,160,303,504,423,231,51,426,505,448,304,146,105,7,358,405,114,454,261,151,50,506,507,148,112,508,367,290,260,189,220,81,450,509,235,292,510,511,268,512,67,207,38,154,387,280,5,451,513,215,461,71,514,37,515,25,49,21,441,516,234,329,333,229,65,204,87,517,518,195,389,519,313,39,109,188]))),b8t=C.lazy(()=>Fe(()=>import("./ClaimWebsite-CO_ckbsB.js"),__vite__mapDeps([765,763,284]))),w8t=C.lazy(()=>Fe(()=>import("./VideoGreeterEditor-BB2K8GZT.js"),__vite__mapDeps([766,764,296,633,410,161,411,412,413,414,314,7,655,75,383,69]))),S8t=C.lazy(()=>Fe(()=>import("./ExitIntentEditor-Bx8ewHQ8.js"),__vite__mapDeps([767,764,768]))),T8t=C.lazy(()=>Fe(()=>import("./LeadMagnetEditor-DK6Y1Hdt.js"),__vite__mapDeps([769,764,768]))),E8t=C.lazy(()=>Fe(()=>import("./EmbedVideoGreeter-D0KVXycx.js"),[])),j8t=C.lazy(()=>Fe(()=>import("./EmbedLeadMagnet-B8pd9TpP.js"),[])),A8t=C.lazy(()=>Fe(()=>import("./RelationshipScorecard-CuCvgDl9.js"),__vite__mapDeps([770,373,174,467,358,167]))),k8t=C.lazy(()=>Fe(()=>import("./SphereGaps-DBtgVxsx.js"),__vite__mapDeps([771,143,168,138,137,139,140,141,142,144,145,97,98,146,334,505,215,81]))),C8t=C.lazy(()=>Fe(()=>import("./Signals-DeukVb5H.js"),[])),N8t=C.lazy(()=>Fe(()=>import("./ConnectPageSettings-XjNwhXim.js"),__vite__mapDeps([772,143]))),I8t=C.lazy(()=>Fe(()=>import("./WebsiteActivityPage-DVEIN3_e.js"),__vite__mapDeps([641,168,138,137,139,140,141,142,143,144,145,97,98,146,12]))),P8t=C.lazy(()=>Fe(()=>import("./EmailCampaigns-BHeF4Xwi.js"),__vite__mapDeps([773,774,98,139,69]))),R8t=C.lazy(()=>Fe(()=>import("./EmailCompliance-D51gNi6S.js"),__vite__mapDeps([775,498]))),L8t=C.lazy(()=>Fe(()=>import("./EmailCampaignComposer-jgJTAmlw.js"),__vite__mapDeps([776,774,98,140,777,178,180,311,179,183,181,182,184,185,186,95,461,400,218,330,342,80,296,331,312,146]))),D8t=C.lazy(()=>Fe(()=>import("./EmailCampaignDetail-Ol87jW6C.js"),__vite__mapDeps([778,303,161]))),M8t=C.lazy(()=>Fe(()=>import("./SharedCampaignTemplates-DHok-wNG.js"),__vite__mapDeps([779,780,777,178,180,311,179,183,181,182,184,185,186,95,461,400,218,342,312]))),O8t=C.lazy(()=>Fe(()=>import("./AgentTemplates-C0CEy5IF.js"),__vite__mapDeps([781,780,777,178,180,311,179,183,181,182,184,185,186,95,461,400,218,342,312,80]))),nde=C.lazy(()=>Fe(()=>import("./TheLocalMoveHome-BnuzWJ0Y.js"),__vite__mapDeps([782,783,283,474,122]))),ide=C.lazy(()=>Fe(()=>import("./TheLocalMoveGetStarted-2q9BHPYl.js"),__vite__mapDeps([784,783]))),sde=C.lazy(()=>Fe(()=>import("./TheLocalMoveCheckout-DlRQwVa5.js"),__vite__mapDeps([785,241]))),ade=C.lazy(()=>Fe(()=>import("./TheLocalMoveCheckoutSuccess-Ds5R0M5C.js"),[])),F8t=C.lazy(()=>Fe(()=>import("./AdminWebsiteOrders-BLeniFss.js"),__vite__mapDeps([786,215]))),B8t=new M5e({defaultOptions:{queries:{refetchOnWindowFocus:!1,staleTime:5*60*1e3}}}),$8t=()=>{const t=window.location.hostname;return t==="listings.relevelup.com"||t.startsWith("listings.")},z8t=()=>{const t=window.location.hostname;return t==="commercial.relevelup.com"||t.startsWith("commercial.")},U8t=()=>{const t=window.location.hostname;return t==="cards.relevelup.com"||t.startsWith("cards.")},V8t=()=>{const t=window.location.hostname;return t==="presentations.relevelup.com"||t.startsWith("presentations.")},q8t=()=>{const t=window.location.hostname;return t==="guestbook.relevelup.com"||t.startsWith("guestbook.")},G8t=()=>{const t=window.location.hostname;return t==="clients.relevelup.com"||t.startsWith("clients.")},H8t=()=>{const t=window.location.hostname;return t==="cma.relevelup.com"||t.startsWith("cma.")},W8t=()=>{const t=window.location.hostname;return t==="cardstudio.relevelup.com"||t.startsWith("cardstudio.")},K8t=()=>{const t=window.location.hostname;return t==="booking.relevelup.com"||t.startsWith("booking.")},Y8t=()=>{const t=window.location.hostname;return t==="contacts.relevelup.com"||t.startsWith("contacts.")},Z8t=()=>{const t=window.location.hostname;return t==="pages.relevelup.com"||t.startsWith("pages.")},HAe=()=>{const t=window.location.hostname;return t==="thelocalmove.com"||t==="www.thelocalmove.com"},X8t=new Set(["app","www","api","admin","embed","cdn","static","assets"]),Q8t=()=>{const t=window.location.hostname;if(new URLSearchParams(window.location.search).get("previewSlug"))return!0;if(Ife(t))return!(window.location.pathname.startsWith("/embed/")||window.location.pathname.startsWith("/widgets/"));if(!t.endsWith(".thelocalmove.com")||HAe())return!1;const e=t.replace(/\.thelocalmove\.com$/,"").split(".").pop()||"";return!(X8t.has(e.toLowerCase())||window.location.pathname.startsWith("/embed/")||window.location.pathname.startsWith("/widgets/"))};if(typeof window<"u")try{const e=new URLSearchParams(window.location.search).get("ref");e&&/^[a-z0-9]{2,32}$/i.test(e)&&localStorage.setItem("levelup_referral_code",e.toLowerCase())}catch{}const J8t=()=>s.jsx(z5e,{client:B8t,children:s.jsx(Nge,{children:s.jsxs(Qpe,{children:[s.jsx(QMe,{}),s.jsx(NOe,{}),s.jsx(Y3e,{}),s.jsx(Z4e,{future:{v7_startTransition:!0},children:s.jsx(Wze,{children:s.jsx(Qze,{children:s.jsx(e6e,{children:s.jsxs(Xze,{children:[s.jsx(Jze,{}),s.jsx(zUe,{}),s.jsx(EZe,{}),W8t()?s.jsx(gRt,{}):U8t()?s.jsx(tQe,{}):z8t()?s.jsx(AXe,{}):$8t()?s.jsx(EXe,{}):V8t()?s.jsx(sQe,{}):q8t()?s.jsx(Mnt,{}):G8t()?s.jsx(bit,{}):H8t()?s.jsx(Cit,{}):K8t()?s.jsx(bRt,{}):Y8t()?s.jsx(IRt,{}):Z8t()?s.jsx(VRt,{}):HAe()?s.jsxs(Cy,{children:[s.jsx(xe,{path:"/get-started",element:s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(ide,{})})}),s.jsx(xe,{path:"/checkout",element:s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(sde,{})})}),s.jsx(xe,{path:"/checkout/success",element:s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(ade,{})})}),s.jsx(xe,{path:"/privacy-policy",element:s.jsx(Oue,{})}),s.jsx(xe,{path:"/terms-of-service",element:s.jsx(Fue,{})}),s.jsx(xe,{path:"/mcp-data-use",element:s.jsx(Bue,{})}),s.jsx(xe,{path:"*",element:s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(nde,{})})})]}):Q8t()?s.jsx(uBt,{}):s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsxs(Cy,{children:[s.jsx(xe,{path:"/",element:s.jsx(Hit,{})}),s.jsx(xe,{path:"/the-local-move",element:s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(nde,{})})}),s.jsx(xe,{path:"/get-started",element:s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(ide,{})})}),s.jsx(xe,{path:"/local-move/checkout",element:s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(sde,{})})}),s.jsx(xe,{path:"/local-move/checkout/success",element:s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(ade,{})})}),s.jsx(xe,{path:"/privacy-policy",element:s.jsx(Oue,{})}),s.jsx(xe,{path:"/terms-of-service",element:s.jsx(Fue,{})}),s.jsx(xe,{path:"/data-deletion",element:s.jsx(gBt,{})}),s.jsx(xe,{path:"/mcp-data-use",element:s.jsx(Bue,{})}),s.jsx(xe,{path:"/canva-support",element:s.jsx(pBt,{})}),s.jsx(xe,{path:"/sms-opt-in",element:s.jsx($ue,{})}),s.jsx(xe,{path:"/sms-consent",element:s.jsx($ue,{memberOnly:!0})}),s.jsx(xe,{path:"/oauth-connect",element:s.jsx(D6,{})}),s.jsx(xe,{path:"/.lovable/oauth/consent",element:s.jsx(D6,{})}),s.jsx(xe,{path:"/oauth/consent",element:s.jsx(D6,{})}),s.jsx(xe,{path:"/mcp",element:s.jsx(zue,{})}),s.jsx(xe,{path:"/connect-chatgpt",element:s.jsx(zue,{})}),s.jsx(xe,{path:"/connect-chatgpt/classic",element:s.jsx(yBt,{})}),s.jsx(xe,{path:"/public/listings",element:s.jsx(qBt,{})}),s.jsx(xe,{path:"/public/commercial",element:s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(mBt,{})})}),s.jsx(xe,{path:"/public/listing/:slugOrId",element:s.jsx(GBt,{})}),s.jsx(xe,{path:"/listing/:slugOrId",element:s.jsx(eqt,{})}),s.jsx(xe,{path:"/private-listing",element:s.jsx(YBt,{})}),s.jsx(xe,{path:"/commercial-pitch/:token",element:s.jsx(KBt,{})}),s.jsx(xe,{path:"/card/:slug",element:s.jsx(ZBt,{})}),s.jsx(xe,{path:"/join-brokerage/:slug",element:s.jsx(IUt,{})}),s.jsx(xe,{path:"/recruit-unsubscribe",element:s.jsx(RUt,{})}),s.jsx(xe,{path:"/event-invite-unsubscribe",element:s.jsx(LUt,{})}),s.jsx(xe,{path:"/recruit-video/:shareToken",element:s.jsx(PUt,{})}),s.jsx(xe,{path:"/connect/:slug",element:s.jsx(XBt,{})}),s.jsx(xe,{path:"/home-value",element:s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(Hue,{})})}),s.jsx(xe,{path:"/whats-my-home-worth",element:s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(Hue,{})})}),s.jsx(xe,{path:"/live/:slug",element:s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(QBt,{})})}),s.jsx(xe,{path:"/auth",element:s.jsx(Bie,{})}),s.jsx(xe,{path:"/login",element:s.jsx(Bie,{})}),s.jsx(xe,{path:"/subscription-success",element:s.jsx(xBt,{})}),s.jsx(xe,{path:"/subscription",element:s.jsx(lt,{children:s.jsx(vBt,{})})}),s.jsxs(xe,{path:"/share/video",element:s.jsx(UBt,{}),children:[s.jsx(xe,{path:":shareToken",element:s.jsx(que,{})}),s.jsx(xe,{path:":shareToken/r/:recipientToken",element:s.jsx(que,{})})]}),s.jsx(xe,{path:"/p/:shareToken",element:s.jsx(KUt,{})}),s.jsx(xe,{path:"/net-sheet/:slug",element:s.jsx(oVt,{})}),s.jsx(xe,{path:"/portal/:slug",element:s.jsx(lVt,{})}),s.jsx(xe,{path:"/portal/:slug/refer",element:s.jsx(cVt,{})}),s.jsx(xe,{path:"/lender/:token",element:s.jsx(uVt,{})}),s.jsx(xe,{path:"/lenders",element:s.jsx(C.Suspense,{fallback:null,children:s.jsx(dVt,{})})}),s.jsx(xe,{path:"/og/video/:token",element:s.jsx(VBt,{})}),s.jsx(xe,{path:"/setup-brokerage",element:s.jsx(lt,{children:s.jsx(_Bt,{})})}),s.jsx(xe,{path:"/claim-account",element:s.jsx(Uue,{})}),s.jsx(xe,{path:"/claim",element:s.jsx(Uue,{})}),s.jsx(xe,{path:"/activate",element:s.jsx(bBt,{})}),s.jsx(xe,{path:"/auth/confirm-reset",element:s.jsx(Vue,{})}),s.jsx(xe,{path:"/auth/continue",element:s.jsx(Vue,{})}),s.jsx(xe,{path:"/join",element:s.jsx(wBt,{})}),s.jsx(xe,{path:"/trial",element:s.jsx(DBt,{})}),s.jsx(xe,{path:"/trial/success",element:s.jsx(MBt,{})}),s.jsx(xe,{path:"/labor-day",element:s.jsx(OBt,{})}),s.jsx(xe,{path:"/brokerage-labor-day",element:s.jsx(FBt,{})}),s.jsx(xe,{path:"/brokerage-solutions",element:s.jsx(BBt,{})}),s.jsx(xe,{path:"/upgrade",element:s.jsx($Bt,{})}),s.jsx(xe,{path:"/instagram",element:s.jsx(zBt,{})}),s.jsx(xe,{path:"/dashboard",element:s.jsx(lt,{children:s.jsx(t$t,{})})}),s.jsx(xe,{path:"/coaching",element:s.jsx(lt,{children:s.jsx(SBt,{})})}),s.jsx(xe,{path:"/coaching/billing",element:s.jsx(lt,{children:s.jsx(ABt,{})})}),s.jsx(xe,{path:"/coaching/settings",element:s.jsx(lt,{children:s.jsx(kBt,{})})}),s.jsx(xe,{path:"/coaching/waitlist",element:s.jsx(lt,{children:s.jsx(IBt,{})})}),s.jsx(xe,{path:"/coaching/agent/:id",element:s.jsx(lt,{children:s.jsx(TBt,{})})}),s.jsx(xe,{path:"/my-coach",element:s.jsx(lt,{children:s.jsx(EBt,{})})}),s.jsx(xe,{path:"/admin/coaching",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(jBt,{})})}),s.jsx(xe,{path:"/oauth/google-calendar/return",element:s.jsx(CBt,{})}),s.jsx(xe,{path:"/oauth/microsoft-365/return",element:s.jsx(NBt,{})}),s.jsxs(xe,{path:"/attract",element:s.jsx(lt,{children:s.jsx(fBt,{children:s.jsx(bVt,{})})}),children:[s.jsx(xe,{index:!0,element:s.jsx(wVt,{})}),s.jsx(xe,{path:"agents",element:s.jsx(SVt,{})}),s.jsx(xe,{path:"agents/:agentId",element:s.jsx($Vt,{})}),s.jsx(xe,{path:"attract-page",element:s.jsx(i8t,{})}),s.jsx(xe,{path:"calculator",element:s.jsx(IVt,{})}),s.jsx(xe,{path:"results",element:s.jsx(AVt,{})}),s.jsx(xe,{path:"onboarding",element:s.jsx(DVt,{})}),s.jsx(xe,{path:"opportunities",element:s.jsx(zVt,{})}),s.jsx(xe,{path:"follow-up",element:s.jsx(TVt,{})}),s.jsx(xe,{path:"settings",element:s.jsx(kVt,{})}),s.jsxs(xe,{path:"toolkit",element:s.jsx(CVt,{}),children:[s.jsx(xe,{index:!0,element:s.jsx(ci,{to:"/attract/toolkit/kits",replace:!0})}),s.jsx(xe,{path:"kits",element:s.jsx(OVt,{})}),s.jsx(xe,{path:"scripts",element:s.jsx(jVt,{})}),s.jsx(xe,{path:"objections",element:s.jsx(NVt,{})}),s.jsx(xe,{path:"events",element:s.jsx(PVt,{})}),s.jsx(xe,{path:"content",element:s.jsx(MVt,{})}),s.jsx(xe,{path:"resources",element:s.jsx(EVt,{})})]}),s.jsx(xe,{path:"toolkit/kits/templates",element:s.jsx(BVt,{})}),s.jsx(xe,{path:"toolkit/kits/new",element:s.jsx(tde,{})}),s.jsx(xe,{path:"toolkit/kits/:kitId/edit",element:s.jsx(tde,{})}),s.jsx(xe,{path:"toolkit/kits/:kitId/analytics",element:s.jsx(FVt,{})}),s.jsx(xe,{path:"events/new",element:s.jsx(ede,{})}),s.jsx(xe,{path:"events/:eventId",element:s.jsx(RVt,{})}),s.jsx(xe,{path:"events/:eventId/edit",element:s.jsx(ede,{})}),s.jsx(xe,{path:"events/:eventId/checkin",element:s.jsx(LVt,{})}),s.jsx(xe,{path:"relationships",element:s.jsx(ci,{to:"/attract/agents",replace:!0})}),s.jsx(xe,{path:"pipeline",element:s.jsx(ci,{to:"/attract/agents",replace:!0})}),s.jsx(xe,{path:"plan",element:s.jsx(ci,{to:"/attract/settings",replace:!0})}),s.jsx(xe,{path:"digest",element:s.jsx(ci,{to:"/attract/results",replace:!0})}),s.jsx(xe,{path:"reports",element:s.jsx(ci,{to:"/attract/results",replace:!0})}),s.jsx(xe,{path:"dashboard-legacy",element:s.jsx(ci,{to:"/attract",replace:!0})}),s.jsx(xe,{path:"share",element:s.jsx(ci,{to:"/attract/toolkit/kits",replace:!0})}),s.jsx(xe,{path:"create",element:s.jsx(ci,{to:"/attract/toolkit/content",replace:!0})}),s.jsx(xe,{path:"templates",element:s.jsx(ci,{to:"/attract/toolkit/scripts",replace:!0})}),s.jsx(xe,{path:"resources",element:s.jsx(ci,{to:"/attract/toolkit/resources",replace:!0})}),s.jsx(xe,{path:"events",element:s.jsx(ci,{to:"/attract/toolkit/events",replace:!0})}),s.jsx(xe,{path:"landing-page",element:s.jsx(ci,{to:"/attract/attract-page",replace:!0})}),s.jsx(xe,{path:"provide/kits",element:s.jsx(ci,{to:"/attract/toolkit/kits",replace:!0})}),s.jsx(xe,{path:"provide/kits/templates",element:s.jsx(ci,{to:"/attract/toolkit/kits/templates",replace:!0})}),s.jsx(xe,{path:"provide/*",element:s.jsx(ci,{to:"/attract/toolkit/kits",replace:!0})}),s.jsx(xe,{path:"influence/content-studio",element:s.jsx(ci,{to:"/attract/toolkit/content",replace:!0})}),s.jsx(xe,{path:"influence/*",element:s.jsx(ci,{to:"/attract/toolkit/content",replace:!0})}),s.jsx(xe,{path:"produce/*",element:s.jsx(ci,{to:"/attract/results",replace:!0})}),s.jsx(xe,{path:"connect/*",element:s.jsx(ci,{to:"/attract/toolkit/events",replace:!0})}),s.jsx(xe,{path:"connect",element:s.jsx(ci,{to:"/attract/toolkit/events",replace:!0})}),s.jsx(xe,{path:"pillars/*",element:s.jsx(ci,{to:"/attract",replace:!0})})]}),s.jsx(xe,{path:"/weekly-reels",element:s.jsx(lt,{children:s.jsx(Mue,{children:s.jsx(xVt,{})})})}),s.jsx(xe,{path:"/weekly-reels/onboarding",element:s.jsx(lt,{children:s.jsx(Mue,{children:s.jsx(vVt,{})})})}),s.jsx(xe,{path:"/admin/weekly-reels",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(_Vt,{})})}),s.jsx(xe,{path:"/admin/attract-access",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(s8t,{})})}),s.jsx(xe,{path:"/admin/attract-intelligence",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(UVt,{})})}),s.jsx(xe,{path:"/admin/attract-tools",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(VVt,{})})}),s.jsx(xe,{path:"/attract-kit/:shareToken",element:s.jsx(qVt,{})}),s.jsx(xe,{path:"/attract-event/:slug",element:s.jsx(GVt,{})}),s.jsx(xe,{path:"/attract-event-checkin/:token",element:s.jsx(HVt,{})}),s.jsx(xe,{path:"/join/:slug",element:s.jsx(WVt,{})}),s.jsx(xe,{path:"/revival/:slug",element:s.jsx(KVt,{})}),s.jsx(xe,{path:"/revival/:slug/plan",element:s.jsx(rde,{})}),s.jsx(xe,{path:"/fsbo/:slug",element:s.jsx(t8t,{})}),s.jsx(xe,{path:"/fsbo/:slug/guide",element:s.jsx(r8t,{})}),s.jsx(xe,{path:"/revival/:slug/plan",element:s.jsx(rde,{})}),s.jsx(xe,{path:"/coaches",element:s.jsx(PBt,{})}),s.jsx(xe,{path:"/coaches/apply",element:s.jsx(LBt,{})}),s.jsx(xe,{path:"/coaches/:slug",element:s.jsx(RBt,{})}),s.jsx(xe,{path:"/credits",element:s.jsx(lt,{children:s.jsx(Z6t,{})})}),s.jsx(xe,{path:"/wallet",element:s.jsx(ci,{to:"/credits",replace:!0})}),s.jsx(xe,{path:"/profile",element:s.jsx(lt,{children:s.jsx(r$t,{})})}),s.jsx(xe,{path:"/apps/*",element:s.jsx(lt,{children:s.jsx(s$t,{})})}),s.jsx(xe,{path:"/admin",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(Wue,{})})}),s.jsx(xe,{path:"/admin/dashboard",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(Wue,{})})}),s.jsx(xe,{path:"/admin/apps",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(N$t,{})})}),s.jsx(xe,{path:"/admin/members",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(I$t,{})})}),s.jsx(xe,{path:"/admin/unassigned-members",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(P$t,{})})}),s.jsx(xe,{path:"/admin/invite-codes",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(R$t,{})})}),s.jsx(xe,{path:"/admin/events",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(L$t,{})})}),s.jsx(xe,{path:"/admin/live",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(JBt,{})})})}),s.jsx(xe,{path:"/admin/live/:id",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(e$t,{})})})}),s.jsx(xe,{path:"/admin/mcp-audit",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(D$t,{})})}),s.jsx(xe,{path:"/events",element:s.jsx(lt,{children:s.jsx(n$t,{})})}),s.jsx(xe,{path:"/events/:eventId",element:s.jsx(lt,{children:s.jsx(i$t,{})})}),s.jsx(xe,{path:"/templates",element:s.jsx(lt,{children:s.jsx(a$t,{})})}),s.jsx(xe,{path:"/templates/:templateId",element:s.jsx(lt,{children:s.jsx(o$t,{})})}),s.jsx(xe,{path:"/admin/templates",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(M$t,{})})}),s.jsx(xe,{path:"/programs",element:s.jsx(lt,{children:s.jsx(l$t,{})})}),s.jsx(xe,{path:"/programs/:slug",element:s.jsx(lt,{children:s.jsx(c$t,{})})}),s.jsx(xe,{path:"/programs/:slug/enroll",element:s.jsx(lt,{children:s.jsx(u$t,{})})}),s.jsx(xe,{path:"/programs/:slug/workspace",element:s.jsx(lt,{children:s.jsx(d$t,{})})}),s.jsx(xe,{path:"/admin/programs",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(h$t,{})})}),s.jsx(xe,{path:"/watch/:slug",element:s.jsx(p$t,{})}),s.jsx(xe,{path:"/academy",element:s.jsx(lt,{children:s.jsx(f$t,{})})}),s.jsx(xe,{path:"/academy/:videoId",element:s.jsx(lt,{children:s.jsx(m$t,{})})}),s.jsx(xe,{path:"/admin/academy",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(O$t,{})})}),s.jsx(xe,{path:"/toolbox",element:s.jsx(lt,{children:s.jsx(g$t,{})})}),s.jsx(xe,{path:"/toolbox/:kitId",element:s.jsx(lt,{children:s.jsx(y$t,{})})}),s.jsx(xe,{path:"/admin/toolbox",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(F$t,{})})}),s.jsx(xe,{path:"/admin/blog",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(rVt,{})})}),s.jsx(xe,{path:"/social-swag",element:s.jsx(lt,{children:s.jsx(x$t,{})})}),s.jsx(xe,{path:"/social-studio",element:s.jsx(lt,{children:s.jsx(v$t,{})})}),s.jsx(xe,{path:"/social-swag-2",element:s.jsx(ci,{to:"/social-studio?tab=gallery",replace:!0})}),s.jsx(xe,{path:"/marketing-studio",element:s.jsx(lt,{children:s.jsx(_$t,{})})}),s.jsx(xe,{path:"/marketing-studio/brand-kit",element:s.jsx(lt,{children:s.jsx(b$t,{})})}),s.jsx(xe,{path:"/marketing-studio/branding-bar",element:s.jsx(lt,{children:s.jsx(w$t,{})})}),s.jsx(xe,{path:"/marketing-studio/listing-templates",element:s.jsx(lt,{children:s.jsx(S$t,{})})}),s.jsx(xe,{path:"/marketing-studio/personal-branding",element:s.jsx(lt,{children:s.jsx(T$t,{})})}),s.jsx(xe,{path:"/social-swag/:swagId",element:s.jsx(lt,{children:s.jsx(E$t,{})})}),s.jsx(xe,{path:"/social-connections",element:s.jsx(lt,{children:s.jsx(DUt,{})})}),s.jsx(xe,{path:"/social-connections/callback",element:s.jsx(lt,{children:s.jsx(MUt,{})})}),s.jsx(xe,{path:"/social-connections/linkedin-callback",element:s.jsx(lt,{children:s.jsx(FUt,{})})}),s.jsx(xe,{path:"/social-connections/tiktok-callback",element:s.jsx(lt,{children:s.jsx(BUt,{})})}),s.jsx(xe,{path:"/social-connections/google-callback",element:s.jsx(lt,{children:s.jsx(OUt,{})})}),s.jsx(xe,{path:"/admin/social-swag",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(B$t,{})})}),s.jsx(xe,{path:"/admin/social-swag-2",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx($$t,{})})}),s.jsx(xe,{path:"/community",element:s.jsx(lt,{children:s.jsx(j$t,{})})}),s.jsx(xe,{path:"/support",element:s.jsx(lt,{children:s.jsx(A$t,{})})}),s.jsx(xe,{path:"/admin/community",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(z$t,{})})}),s.jsx(xe,{path:"/admin/support-tickets",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(G$t,{})})}),s.jsx(xe,{path:"/admin/email-templates",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(H$t,{})})}),s.jsx(xe,{path:"/admin/agent-email-templates",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(W$t,{})})}),s.jsx(xe,{path:"/admin/analytics",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(U$t,{})})}),s.jsx(xe,{path:"/admin/brokerage-resources",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(V$t,{})})}),s.jsx(xe,{path:"/admin/dashboard-management",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(q$t,{})})}),s.jsx(xe,{path:"/brokerage/dashboard",element:s.jsx(lt,{requireBrokerageManager:!0,children:s.jsx(K$t,{})})}),s.jsx(xe,{path:"/brokerage/teams",element:s.jsx(lt,{requireBrokerageManager:!0,children:s.jsx(a8t,{})})}),s.jsx(xe,{path:"/brokerage/recruiting",element:s.jsx(lt,{requireBrokerageManager:!0,children:s.jsx(C6t,{})})}),s.jsx(xe,{path:"/brokerage/onboarding",element:s.jsx(lt,{requireBrokerageManager:!0,children:s.jsx(N6t,{})})}),s.jsx(xe,{path:"/brokerage/commission-plans",element:s.jsx(lt,{children:s.jsx(F6t,{})})}),s.jsx(xe,{path:"/brokerage/operations",element:s.jsx(lt,{children:s.jsx(P6t,{})})}),s.jsx(xe,{path:"/brokerage/website",element:s.jsx(lt,{children:s.jsx(M6t,{})})}),s.jsx(xe,{path:"/brokerage/agent-websites",element:s.jsx(lt,{children:s.jsx(O6t,{})})}),s.jsx(xe,{path:"/websites/grade",element:s.jsx(lt,{children:s.jsx(L6t,{})})}),s.jsx(xe,{path:"/websites",element:s.jsx(lt,{children:s.jsx(R6t,{})})}),s.jsx(xe,{path:"/team/website",element:s.jsx(lt,{children:s.jsx(D6t,{})})}),s.jsx(xe,{path:"/brokerage/transactions",element:s.jsx(lt,{children:s.jsx(I6t,{})})}),s.jsx(xe,{path:"/team",element:s.jsx(lt,{children:s.jsx(l8t,{})})}),s.jsx(xe,{path:"/my-team",element:s.jsx(lt,{children:s.jsx(o8t,{})})}),s.jsx(xe,{path:"/my-brokerage",element:s.jsx(lt,{children:s.jsx(Y$t,{})})}),s.jsx(xe,{path:"/brokerage/help-board",element:s.jsx(lt,{children:s.jsx(Q$t,{})})}),s.jsx(xe,{path:"/brokerage/help-board/new",element:s.jsx(lt,{children:s.jsx(J$t,{})})}),s.jsx(xe,{path:"/brokerage/help-board/:id",element:s.jsx(lt,{children:s.jsx(ezt,{})})}),s.jsx(xe,{path:"/brokerage-content",element:s.jsx(lt,{children:s.jsx(Z$t,{})})}),s.jsx(xe,{path:"/brokerage-content/:contentId",element:s.jsx(lt,{children:s.jsx(X$t,{})})}),s.jsx(xe,{path:"/brokerage-resources",element:s.jsx(lt,{requireBrokerageManager:!0,children:s.jsx(k$t,{})})}),s.jsx(xe,{path:"/brokerage-resources/:resourceId",element:s.jsx(lt,{requireBrokerageManager:!0,children:s.jsx(C$t,{})})}),s.jsx(xe,{path:"/newsletters",element:s.jsx(lt,{children:s.jsx(tzt,{})})}),s.jsx(xe,{path:"/newsletters/:id",element:s.jsx(lt,{children:s.jsx(rzt,{})})}),s.jsx(xe,{path:"/wishlist",element:s.jsx(lt,{children:s.jsx(ozt,{})})}),s.jsx(xe,{path:"/wishlist/:itemId",element:s.jsx(lt,{children:s.jsx(lzt,{})})}),s.jsx(xe,{path:"/admin/wishlist",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(czt,{})})}),s.jsx(xe,{path:"/admin/levelup-brief",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(uzt,{})})}),s.jsx(xe,{path:"/admin/boost-announcements",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(szt,{})})}),s.jsx(xe,{path:"/admin/broadcasts",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(izt,{})})}),s.jsx(xe,{path:"/admin/newsletters",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(nzt,{})})}),s.jsx(xe,{path:"/admin/newsletter-graphics",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(azt,{})})}),s.jsx(xe,{path:"/admin/additional-services",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(dzt,{})})}),s.jsx(xe,{path:"/admin/discounts",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(hzt,{})})}),s.jsx(xe,{path:"/admin/subscriptions",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(fzt,{})})}),s.jsx(xe,{path:"/admin/instagram-gift-emails",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(mzt,{})})}),s.jsx(xe,{path:"/admin/referrals",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(pzt,{})})}),s.jsx(xe,{path:"/admin/prospector",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(A6t,{})})}),s.jsx(xe,{path:"/admin/recruiting",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(k6t,{})})}),s.jsx(xe,{path:"/admin/beta/social-post-generator",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx($6t,{})})}),s.jsx(xe,{path:"/admin/credits",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(aUt,{})})})}),s.jsx(xe,{path:"/admin/cleanup",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(oUt,{})})})}),s.jsx(xe,{path:"/admin/beta/postcard-manager",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(eUt,{})})})}),s.jsx(xe,{path:"/admin/mail-studio/templates",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(tUt,{})})})}),s.jsx(xe,{path:"/admin/beta/homereel",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(rUt,{})})})}),s.jsx(xe,{path:"/admin/beta/boost",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(sUt,{})})})}),s.jsx(xe,{path:"/admin/video-lab",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(iUt,{})})})}),s.jsx(xe,{path:"/admin/music-videos",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(nUt,{})})})}),s.jsx(xe,{path:"/admin/lms",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(z6t,{})})}),s.jsx(xe,{path:"/admin/lms/stats",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(V6t,{})})}),s.jsx(xe,{path:"/admin/lms/:courseId",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(U6t,{})})}),s.jsx(xe,{path:"/levelup-u",element:s.jsx(lt,{children:s.jsx(q6t,{})})}),s.jsx(xe,{path:"/levelup-u/:courseId",element:s.jsx(lt,{children:s.jsx(G6t,{})})}),s.jsx(xe,{path:"/admin/brokerage-content-activity",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(B6t,{})})}),s.jsx(xe,{path:"/admin/onboarding-checklist",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(gzt,{})})}),s.jsx(xe,{path:"/admin/marketplace",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(m6t,{})})}),s.jsx(xe,{path:"/admin/agent-points",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(h6t,{})})}),s.jsx(xe,{path:"/admin/reward-store",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(p6t,{})})}),s.jsx(xe,{path:"/admin/integrations",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(g6t,{})})}),s.jsx(xe,{path:"/admin/mcp-updates",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(v6t,{})})}),s.jsx(xe,{path:"/help/refresh-mcp-tools",element:s.jsx(lt,{children:s.jsx(_6t,{})})}),s.jsx(xe,{path:"/admin/social-autopilot",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(x6t,{})})}),s.jsx(xe,{path:"/admin/social-connections",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(y6t,{})})}),s.jsx(xe,{path:"/admin/integrations/callback",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(j6t,{})})}),s.jsx(xe,{path:"/admin/email-compliance",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(R8t,{})})})}),s.jsx(xe,{path:"/admin/email-campaigns",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(P8t,{})})})}),s.jsx(xe,{path:"/admin/email-campaigns/templates",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(M8t,{})})})}),s.jsx(xe,{path:"/email-campaigns/templates",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(O8t,{})})})}),s.jsx(xe,{path:"/admin/email-campaigns/new",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(L8t,{})})})}),s.jsx(xe,{path:"/admin/email-campaigns/:id",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(D8t,{})})})}),s.jsx(xe,{path:"/reward-store",element:s.jsx(lt,{children:s.jsx(GUt,{})})}),s.jsx(xe,{path:"/refer-friends",element:s.jsx(lt,{children:s.jsx(HUt,{})})}),s.jsx(xe,{path:"/additional-services",element:s.jsx(lt,{children:s.jsx(xzt,{})})}),s.jsx(xe,{path:"/additional-services/:serviceId",element:s.jsx(lt,{children:s.jsx(vzt,{})})}),s.jsx(xe,{path:"/ai-toolkit",element:s.jsx(lt,{children:s.jsx(_zt,{})})}),s.jsx(xe,{path:"/ask-ai",element:s.jsx(lt,{children:s.jsx(bzt,{})})}),s.jsx(xe,{path:"/mission-control",element:s.jsx(lt,{children:s.jsx(wzt,{})})}),s.jsx(xe,{path:"/mission-control/contacts",element:s.jsx(lt,{children:s.jsx(Szt,{})})}),s.jsx(xe,{path:"/mission-control/sphere-map",element:s.jsx(lt,{children:s.jsx(dUt,{})})}),s.jsx(xe,{path:"/mission-control/property-intelligence",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(hUt,{})})}),s.jsx(xe,{path:"/mission-control/contacts/:contactId",element:s.jsx(lt,{children:s.jsx(Tzt,{})})}),s.jsx(xe,{path:"/mission-control/sent-emails",element:s.jsx(lt,{children:s.jsx(Ezt,{})})}),s.jsx(xe,{path:"/mission-control/plans",element:s.jsx(lt,{children:s.jsx(jzt,{})})}),s.jsx(xe,{path:"/mission-control/cma",element:s.jsx(lt,{children:s.jsx(Azt,{})})}),s.jsx(xe,{path:"/mission-control/cma/:id",element:s.jsx(lt,{children:s.jsx(kzt,{})})}),s.jsx(xe,{path:"/cma/:token",element:s.jsx(Izt,{})}),s.jsx(xe,{path:"/apps/listing-presentation-studio",element:s.jsx(lt,{children:s.jsx(Czt,{})})}),s.jsx(xe,{path:"/apps/listing-presentation-studio/:id",element:s.jsx(lt,{children:s.jsx(Nzt,{})})}),s.jsx(xe,{path:"/apps/listing-revival",element:s.jsx(lt,{children:s.jsx(YVt,{})})}),s.jsx(xe,{path:"/apps/listing-revival/new",element:s.jsx(lt,{children:s.jsx(ZVt,{})})}),s.jsx(xe,{path:"/apps/listing-revival/campaigns/:id",element:s.jsx(lt,{children:s.jsx(XVt,{})})}),s.jsx(xe,{path:"/staged/:token",element:s.jsx(X6t,{})}),s.jsx(xe,{path:"/apps/staging-studio",element:s.jsx(lt,{children:s.jsx(Z$,{children:s.jsx(W6t,{})})})}),s.jsx(xe,{path:"/apps/staging-studio/library",element:s.jsx(lt,{children:s.jsx(Z$,{children:s.jsx(K6t,{})})})}),s.jsx(xe,{path:"/apps/staging-studio/credits",element:s.jsx(lt,{children:s.jsx(Z$,{children:s.jsx(Y6t,{})})})}),s.jsx(xe,{path:"/apps/fsbo-breakthrough",element:s.jsx(lt,{children:s.jsx(QVt,{})})}),s.jsx(xe,{path:"/apps/fsbo-breakthrough/new",element:s.jsx(lt,{children:s.jsx(JVt,{})})}),s.jsx(xe,{path:"/apps/reviews",element:s.jsx(lt,{children:s.jsx(aVt,{})})}),s.jsx(xe,{path:"/apps/fsbo-breakthrough/campaigns/:id",element:s.jsx(lt,{children:s.jsx(e8t,{})})}),s.jsx(xe,{path:"/admin/fsbo-breakthrough",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(n8t,{})})}),s.jsx(xe,{path:"/mission-control/listing-presentations",element:s.jsx(ci,{to:"/apps/listing-presentation-studio",replace:!0})}),s.jsx(xe,{path:"/mission-control/popbys",element:s.jsx(lt,{children:s.jsx(Pzt,{})})}),s.jsx(xe,{path:"/mission-control/popbys/map",element:s.jsx(lt,{children:s.jsx(uUt,{})})}),s.jsx(xe,{path:"/admin/notification-settings",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(b6t,{})})}),s.jsx(xe,{path:"/admin/agent-os",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(yzt,{})})}),s.jsx(xe,{path:"/mission-control/listings",element:s.jsx(lt,{children:s.jsx(Rzt,{})})}),s.jsx(xe,{path:"/mission-control/listing-studio",element:s.jsx(lt,{children:s.jsx(pVt,{})})}),s.jsx(xe,{path:"/mission-control/listings/new",element:s.jsx(lt,{children:s.jsx(HBt,{})})}),s.jsx(xe,{path:"/mission-control/listings/new/residential",element:s.jsx(lt,{children:s.jsx(Kue,{})})}),s.jsx(xe,{path:"/mission-control/listings/new/commercial",element:s.jsx(lt,{children:s.jsx(Gue,{})})}),s.jsx(xe,{path:"/mission-control/listings/:listingId/commercial",element:s.jsx(lt,{children:s.jsx(WBt,{})})}),s.jsx(xe,{path:"/mission-control/listings/:listingId/commercial/edit",element:s.jsx(lt,{children:s.jsx(Gue,{})})}),s.jsx(xe,{path:"/mission-control/listings/:listingId",element:s.jsx(lt,{children:s.jsx(Lzt,{})})}),s.jsx(xe,{path:"/mission-control/listings/:listingId/edit",element:s.jsx(lt,{children:s.jsx(Kue,{})})}),s.jsx(xe,{path:"/mission-control/listings/:listingId/customize",element:s.jsx(lt,{children:s.jsx(Dzt,{})})}),s.jsx(xe,{path:"/admin/listing-exchange",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(a6t,{})})}),s.jsx(xe,{path:"/admin/listing-leads",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(o6t,{})})}),s.jsx(xe,{path:"/admin/public-site-leads",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(l6t,{})})}),s.jsx(xe,{path:"/mission-control/lenders",element:s.jsx(lt,{children:s.jsx(hVt,{})})}),s.jsx(xe,{path:"/mission-control/pipeline",element:s.jsx(lt,{children:s.jsx(Vzt,{})})}),s.jsx(xe,{path:"/mission-control/forms",element:s.jsx(lt,{children:s.jsx(qzt,{})})}),s.jsx(xe,{path:"/mission-control/tasks",element:s.jsx(lt,{children:s.jsx(sRt,{})})}),s.jsx(xe,{path:"/mission-control/transactions",element:s.jsx(lt,{children:s.jsx(Gzt,{})})}),s.jsx(xe,{path:"/mission-control/net-sheets",element:s.jsx(lt,{children:s.jsx(Jue,{})})}),s.jsx(xe,{path:"/mission-control/net-sheets/:id",element:s.jsx(lt,{children:s.jsx(Jue,{})})}),s.jsx(xe,{path:"/mission-control/client-portals",element:s.jsx(lt,{children:s.jsx(Zzt,{})})}),s.jsx(xe,{path:"/mission-control/client-portals/:portalId",element:s.jsx(lt,{children:s.jsx(Xzt,{})})}),s.jsx(xe,{path:"/mission-control/portal-referrals",element:s.jsx(lt,{children:s.jsx(Hzt,{})})}),s.jsx(xe,{path:"/mission-control/vendors",element:s.jsx(lt,{children:s.jsx(Wzt,{})})}),s.jsx(xe,{path:"/brokerage/forms",element:s.jsx(lt,{children:s.jsx(Kzt,{})})}),s.jsx(xe,{path:"/brokerage/vendors",element:s.jsx(lt,{children:s.jsx(Yzt,{})})}),s.jsx(xe,{path:"/mission-control/my-card",element:s.jsx(lt,{children:s.jsx(Qzt,{})})}),s.jsx(xe,{path:"/mission-control/integrations",element:s.jsx(lt,{children:s.jsx(Jzt,{})})}),s.jsx(xe,{path:"/mission-control/browser-extension",element:s.jsx(lt,{children:s.jsx(e6t,{})})}),s.jsx(xe,{path:"/mission-control/integrations/gmail/callback",element:s.jsx(lt,{children:s.jsx(t6t,{})})}),s.jsx(xe,{path:"/mission-control/integrations/canva/callback",element:s.jsx(r6t,{})}),s.jsx(xe,{path:"/mission-control/integrations/meta/callback",element:s.jsx(lt,{children:s.jsx(n6t,{})})}),s.jsx(xe,{path:"/mission-control/scorecard",element:s.jsx(lt,{children:s.jsx(eIt,{})})}),s.jsx(xe,{path:"/admin/scorecard",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(i6t,{})})}),s.jsx(xe,{path:"/admin/agent-activation",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(s6t,{})})}),s.jsx(xe,{path:"/admin/scorecard/:userId",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(Zue,{})})}),s.jsx(xe,{path:"/mission-control/scorecard/:userId",element:s.jsx(lt,{children:s.jsx(Zue,{})})}),s.jsx(xe,{path:"/mission-control/relationship-scorecard",element:s.jsx(lt,{children:s.jsx(A8t,{})})}),s.jsx(xe,{path:"/mission-control/sphere-gaps",element:s.jsx(lt,{children:s.jsx(k8t,{})})}),s.jsx(xe,{path:"/mission-control/signals",element:s.jsx(lt,{children:s.jsx(C8t,{})})}),s.jsx(xe,{path:"/mission-control/website-activity",element:s.jsx(lt,{children:s.jsx(I8t,{})})}),s.jsx(xe,{path:"/mission-control/connect-page",element:s.jsx(lt,{children:s.jsx(N8t,{})})}),s.jsx(xe,{path:"/admin/membership-reviews",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(c6t,{})})}),s.jsx(xe,{path:"/admin/lead-notifications",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(u6t,{})})}),s.jsx(xe,{path:"/admin/weekly-digest",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(d6t,{})})}),s.jsx(xe,{path:"/studio/join/:roomId",element:s.jsx(C.Suspense,{fallback:null,children:s.jsx(zzt,{})})}),s.jsx(xe,{path:"/main-stage",element:s.jsx(C.Suspense,{fallback:null,children:s.jsx(Yue,{})})}),s.jsx(xe,{path:"/main-stage/e/:eventId",element:s.jsx(C.Suspense,{fallback:null,children:s.jsx(Yue,{})})}),s.jsx(xe,{path:"/admin/main-stage",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:null,children:s.jsx(Bzt,{})})})}),s.jsx(xe,{path:"/admin/studio-kits",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:null,children:s.jsx($zt,{})})})}),s.jsx(xe,{path:"/desktop/studio",element:s.jsx(C.Suspense,{fallback:null,children:s.jsx(Fzt,{})})}),s.jsx(xe,{path:"/video-studio",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:null,children:s.jsx(Ozt,{})})})}),s.jsx(xe,{path:"/mission-control/video/record",element:s.jsx(Mzt,{})}),s.jsx(xe,{path:"/mission-control/video-library",element:s.jsx(lt,{children:s.jsx(Uzt,{})})}),s.jsx(xe,{path:"/my-partnership",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:null,children:s.jsx(xUt,{})})})}),s.jsx(xe,{path:"/upgrade/:featureKey",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:null,children:s.jsx(vUt,{})})})}),s.jsx(xe,{path:"/coaching/onboarding",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:null,children:s.jsx(_Ut,{})})})}),s.jsx(xe,{path:"/admin/lenders",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:null,children:s.jsx(fVt,{})})})}),s.jsx(xe,{path:"/admin/partnerships",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:null,children:s.jsx(yUt,{})})})}),s.jsx(xe,{path:"/website-apps",element:s.jsx(lt,{children:s.jsx(_8t,{})})}),s.jsx(xe,{path:"/get-my-website",element:s.jsx(lt,{children:s.jsx(b8t,{})})}),s.jsx(xe,{path:"/need-a-website",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(jUt,{})})})}),s.jsx(xe,{path:"/website-apps/video_greeter",element:s.jsx(lt,{children:s.jsx(w8t,{})})}),s.jsx(xe,{path:"/website-apps/exit_intent",element:s.jsx(lt,{children:s.jsx(S8t,{})})}),s.jsx(xe,{path:"/website-apps/lead_magnet",element:s.jsx(lt,{children:s.jsx(T8t,{})})}),s.jsx(xe,{path:"/embed/video-greeter/:slug",element:s.jsx(E8t,{})}),s.jsx(xe,{path:"/embed/lead-magnet/:slug",element:s.jsx(j8t,{})}),s.jsx(xe,{path:"/marketplace",element:s.jsx(lt,{children:s.jsx(lRt,{})})}),s.jsx(xe,{path:"/marketplace/:productId",element:s.jsx(lt,{children:s.jsx($Ut,{})})}),s.jsx(xe,{path:"/marketplace/cart",element:s.jsx(lt,{children:s.jsx(zUt,{})})}),s.jsx(xe,{path:"/marketplace/orders",element:s.jsx(lt,{children:s.jsx(UUt,{})})}),s.jsx(xe,{path:"/marketplace/orders/:orderId",element:s.jsx(lt,{children:s.jsx(VUt,{})})}),s.jsx(xe,{path:"/marketplace/success",element:s.jsx(lt,{children:s.jsx(qUt,{})})}),s.jsx(xe,{path:"/admin/agent-cards",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(f6t,{})})}),s.jsx(xe,{path:"/admin/presentation-analytics",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(w6t,{})})}),s.jsx(xe,{path:"/admin/listing-presentation-studio",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(S6t,{})})}),s.jsx(xe,{path:"/admin/listing-revival",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(T6t,{})})}),s.jsx(xe,{path:"/admin/contact-finder",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(J6t,{})})}),s.jsx(xe,{path:"/admin/staging-studio",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(Q6t,{})})}),s.jsx(xe,{path:"/admin/guest-book-analytics",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(E6t,{})})}),s.jsx(xe,{path:"/mission-control/smart-drips",element:s.jsx(lt,{children:s.jsx(yVt,{})})}),s.jsx(xe,{path:"/mission-control/mail-studio",element:s.jsx(cUt,{})}),s.jsx(xe,{path:"/mission-control/direct-mail",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(lUt,{})})})}),s.jsx(xe,{path:"/mission-control/presentations",element:s.jsx(lt,{children:s.jsx(WUt,{})})}),s.jsx(xe,{path:"/mission-control/presentations/new",element:s.jsx(lt,{children:s.jsx(Que,{})})}),s.jsx(xe,{path:"/mission-control/presentations/:id",element:s.jsx(lt,{children:s.jsx(Que,{})})}),s.jsx(xe,{path:"/mission-control/guest-book",element:s.jsx(lt,{children:s.jsx(YUt,{})})}),s.jsx(xe,{path:"/mission-control/guest-book/live/:id",element:s.jsx(lt,{children:s.jsx(fUt,{})})}),s.jsx(xe,{path:"/guestbook/:slug",element:s.jsx(ZUt,{})}),s.jsx(xe,{path:"/review/:token",element:s.jsx(nVt,{})}),s.jsx(xe,{path:"/reviews/:slug/new",element:s.jsx(sVt,{})}),s.jsx(xe,{path:"/reviews/:slug",element:s.jsx(iVt,{})}),s.jsx(xe,{path:"/rsvp/:slug",element:s.jsx(XUt,{})}),s.jsx(xe,{path:"/resources/:slug",element:s.jsx(QUt,{})}),s.jsx(xe,{path:"/sign/:token",element:s.jsx(JUt,{})}),s.jsx(xe,{path:"/blog",element:s.jsx(eVt,{})}),s.jsx(xe,{path:"/blog/:slug",element:s.jsx(tVt,{})}),s.jsx(xe,{path:"/mission-control/card-studio",element:s.jsx(lt,{children:s.jsx(mVt,{})})}),s.jsx(xe,{path:"/mission-control/scheduler",element:s.jsx(lt,{children:s.jsx(c8t,{})})}),s.jsx(xe,{path:"/mission-control/calendar",element:s.jsx(lt,{children:s.jsx(u8t,{})})}),s.jsx(xe,{path:"/c/:shareToken",element:s.jsx(gVt,{})}),s.jsx(xe,{path:"/book/:slug",element:s.jsx(d8t,{})}),s.jsx(xe,{path:"/booking/manage/:token",element:s.jsx(h8t,{})}),s.jsx(xe,{path:"/page/:slug",element:s.jsx(v8t,{})}),s.jsx(xe,{path:"/buyer-match/:slug",element:s.jsx(g8t,{})}),s.jsx(xe,{path:"/mission-control/buyer-match",element:s.jsx(lt,{children:s.jsx(m8t,{})})}),s.jsx(xe,{path:"/mission-control/buyer-match/:campaignId",element:s.jsx(lt,{children:s.jsx(p8t,{})})}),s.jsx(xe,{path:"/mission-control/landing-pages",element:s.jsx(lt,{children:s.jsx(f8t,{})})}),s.jsx(xe,{path:"/mission-control/landing-pages/defaults",element:s.jsx(lt,{children:s.jsx(x8t,{})})}),s.jsx(xe,{path:"/mission-control/landing-pages/:pageId",element:s.jsx(lt,{children:s.jsx(y8t,{})})}),s.jsx(xe,{path:"/my-website/:siteId/edit",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(Xue,{})})})}),s.jsx(xe,{path:"/my-website/mls-listings",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(kUt,{})})})}),s.jsx(xe,{path:"/my-website/mls-listings/:mlsId",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(CUt,{})})})}),s.jsx(xe,{path:"/my-website/market-report",element:s.jsx(lt,{children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(NUt,{})})})}),s.jsx(xe,{path:"/admin/lead-sites",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(mUt,{})})})}),s.jsx(xe,{path:"/admin/lead-sites/themes",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(pUt,{})})})}),s.jsx(xe,{path:"/admin/lead-sites/offers",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(gUt,{})})})}),s.jsx(xe,{path:"/admin/lead-sites/offers/:brokerageId",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(bUt,{})})})}),s.jsx(xe,{path:"/admin/lead-sites/:siteId/edit",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(Xue,{})})})}),s.jsx(xe,{path:"/admin/mls-feeds",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(wUt,{})})})}),s.jsx(xe,{path:"/admin/lead-site-analytics",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(SUt,{})})})}),s.jsx(xe,{path:"/admin/website-interests",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(TUt,{})})})}),s.jsx(xe,{path:"/admin/website-requests",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(EUt,{})})})}),s.jsx(xe,{path:"/admin/website-orders",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(F8t,{})})})}),s.jsx(xe,{path:"/admin/mls-fee-tracker",element:s.jsx(lt,{requireAdmin:!0,children:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(AUt,{})})})}),s.jsx(xe,{path:"/m/*",element:s.jsx(C.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(H6t,{})})}),s.jsx(xe,{path:"*",element:s.jsx(Gje,{})})]})})]})})})})})]})})});function eqt(){const t=ki(),e=t.pathname.replace(/^\/listing\//,"");return s.jsx(ci,{to:`/public/listing/${e}${t.search}`,replace:!0})}const WAe=window.location.hostname;/(\.lovable\.app|\.lovableproject\.com)$/.test(WAe)&&/[?&]authorization_id=/.test(window.location.search)&&window.location.replace(`https://dashboard.relevelup.com/oauth-connect${window.location.search}`);if(WAe==="tile-portal.lovable.app"){const{pathname:t,search:e,hash:r}=window.location;if(/access_token=|refresh_token=|token_hash=|[?&]code=|type=(magiclink|recovery|invite|signup|email_change)/.test(r+e)){const i=t==="/"||t===""?"/claim-account":t;window.location.replace(`https://dashboard.relevelup.com${i}${e}${r}`)}}"serviceWorker"in navigator&&navigator.serviceWorker.getRegistrations().then(t=>{t.forEach(e=>void e.unregister())}).catch(()=>{});"caches"in window&&caches.keys().then(t=>{t.forEach(e=>void caches.delete(e))}).catch(()=>{});const SG="levelup:chunk-reload",tqt=t=>!!t&&/Failed to fetch dynamically imported module|Importing a module script failed|error loading dynamically imported module/i.test(t),nY=t=>{tqt(t)&&(sessionStorage.getItem(SG)||(sessionStorage.setItem(SG,"1"),window.location.reload()))};window.addEventListener("vite:preloadError",t=>{t.preventDefault(),nY("Failed to fetch dynamically imported module")});window.addEventListener("error",t=>nY(t.message));window.addEventListener("unhandledrejection",t=>{var e;return nY((e=t.reason)==null?void 0:e.message)});window.setTimeout(()=>sessionStorage.removeItem(SG),15e3);Nfe(document.getElementById("root")).render(s.jsx(J8t,{}));export{Kn as $,GA as A,_o as B,z_e as C,Qre as D,b_ as E,Hs as F,fh as G,Zo as H,Br as I,$n as J,Mr as K,FDe as L,Es as M,WC as N,mg as O,f1e as P,Ai as Q,rM as R,xd as S,Nx as T,Vt as U,Hn as V,Px as W,ud as X,dd as Y,ak as Z,su as _,ba as a,CD as a$,hS as a0,EDe as a1,xs as a2,MU as a3,JS as a4,no as a5,eS as a6,Ds as a7,HA as a8,fl as a9,Xo as aA,Ad as aB,kD as aC,vxe as aD,iu as aE,Rl as aF,yx as aG,VC as aH,cf as aI,sA as aJ,Dl as aK,V3 as aL,Sd as aM,Cm as aN,jd as aO,lqt as aP,gxe as aQ,h$ as aR,t_ as aS,cme as aT,qt as aU,f1 as aV,$p as aW,gA as aX,YDe as aY,$U as aZ,sc as a_,ri as aa,KO as ab,WA as ac,pm as ad,fme as ae,vd as af,_d as ag,bd as ah,ss as ai,wve as aj,Pm as ak,Ar as al,dx as am,dH as an,Y3 as ao,zp as ap,oo as aq,UDe as ar,TC as as,_m as at,ix as au,gm as av,Ri as aw,lo as ax,qa as ay,xl as az,oa as b,ki as b$,ODe as b0,JO as b1,T9 as b2,gT as b3,Os as b4,iMe as b5,ZDe as b6,dme as b7,Dee as b8,C9 as b9,E3 as bA,C3 as bB,OU as bC,qv as bD,NDe as bE,JDe as bF,zU as bG,Lit as bH,YO as bI,sMe as bJ,DU as bK,SC as bL,M7 as bM,H7 as bN,ll as bO,Vo as bP,qo as bQ,Go as bR,lf as bS,O7 as bT,QDe as bU,RDe as bV,va as bW,pme as bX,wme as bY,hMe as bZ,mqt as b_,wd as ba,ND as bb,lc as bc,Oie as bd,KA as be,zee as bf,sne as bg,h1e as bh,Dit as bi,Mit as bj,Oit as bk,Fit as bl,Bit as bm,E9 as bn,XO as bo,J1 as bp,hf as bq,wC as br,pMe as bs,jDe as bt,bm as bu,or as bv,Sr as bw,S9 as bx,nMe as by,RBe as bz,Jre as c,Jpe as c$,$Gt as c0,zGt as c1,VGt as c2,PGt as c3,DGt as c4,UGt as c5,qGt as c6,Tpe as c7,oqt as c8,F9 as c9,nn as cA,Ml as cB,q_e as cC,XS as cD,__ as cE,kXe as cF,es as cG,eQe as cH,XXe as cI,ADe as cJ,vme as cK,gMe as cL,XH as cM,QH as cN,vk as cO,Yl as cP,JH as cQ,Zl as cR,ume as cS,yl as cT,D7t as cU,m7t as cV,R7t as cW,UKe as cX,Qpe as cY,_5e as cZ,b5e as c_,B9 as ca,z9 as cb,U9 as cc,$9 as cd,q9 as ce,V9 as cf,lXe as cg,RGt as ch,WGt as ci,HGt as cj,OGt as ck,FGt as cl,cXe as cm,Lee as cn,KGt as co,GGt as cp,MGt as cq,LGt as cr,X$ as cs,BGt as ct,hme as cu,x1e as cv,eW as cw,Lm as cx,Xe as cy,dg as cz,uXe as d,S_ as d$,lme as d0,XDe as d1,tIt as d2,cK as d3,TA as d4,l5 as d5,j9 as d6,HUe as d7,jD as d8,Y7 as d9,T7 as dA,wxe as dB,Sxe as dC,SGt as dD,TGt as dE,jGt as dF,AGt as dG,wGt as dH,dS as dI,PDe as dJ,pqt as dK,Oee as dL,xme as dM,cMe as dN,S7 as dO,Pqt as dP,DDe as dQ,Cy as dR,xe as dS,ci as dT,sqt as dU,BDe as dV,$ee as dW,vC as dX,Qo as dY,yd as dZ,Yn as d_,On as da,Li as db,ust as dc,v1e as dd,Jit as de,FKe as df,vHe as dg,Ts as dh,Xs as di,gme as dj,Q1 as dk,Rfe as dl,tZe as dm,KDe as dn,bC as dp,FU as dq,w1 as dr,Uee as ds,Cfe as dt,yxe as du,mZe as dv,A9 as dw,NV as dx,_xe as dy,tVe as dz,wa as e,nf as e$,Or as e0,Fl as e1,vl as e2,Do as e3,mme as e4,Z7 as e5,FC as e6,BC as e7,kDe as e8,dT as e9,uT as eA,f7 as eB,m7 as eC,ZS as eD,sk as eE,pxe as eF,Ix as eG,PC as eH,v_ as eI,u3 as eJ,d3 as eK,c3 as eL,Lqt as eM,ZUe as eN,Aqt as eO,CDe as eP,uHe as eQ,bme as eR,P9 as eS,$De as eT,iye as eU,uMe as eV,uk as eW,dk as eX,hk as eY,fk as eZ,Rp as e_,Nu as ea,o_e as eb,l_e as ec,Eje as ed,jje as ee,UL as ef,VL as eg,yA as eh,zje as ei,yme as ej,rc as ek,xKe as el,kve as em,BU as en,tc as eo,ds as ep,O5e as eq,yte as er,dqt as es,hqt as et,Q5e as eu,Fe as ev,TDe as ew,qDe as ex,tMe as ey,zDe as ez,la as f,QO as f$,CGt as f0,SDe as f1,LU as f2,$x as f3,hT as f4,zV as f5,Q8 as f6,FNt as f7,i5 as f8,s5 as f9,f$ as fA,cst as fB,dst as fC,ck as fD,rH as fE,g7t as fF,L7t as fG,I7t as fH,hst as fI,P7t as fJ,lst as fK,_7t as fL,YH as fM,Txe as fN,iVe as fO,Zc as fP,th as fQ,Qit as fR,i7t as fS,s7t as fT,gS as fU,aMe as fV,$a as fW,kst as fX,y7t as fY,v7t as fZ,x7t as f_,Qh as fa,N_ as fb,BNt as fc,xg as fd,RF as fe,_i as ff,$i as fg,JW as fh,uh as fi,Vs as fj,fi as fk,_q as fl,og as fm,Sy as fn,VF as fo,zi as fp,O7t as fq,ax as fr,Vp as fs,ec as ft,F7t as fu,rN as fv,HF as fw,vje as fx,$At as fy,MDe as fz,mn as g,ZH as g$,Nje as g0,J9t as g1,i1e as g2,p7t as g3,RU as g4,Q9t as g5,w7t as g6,C7t as g7,b7t as g8,N7t as g9,EGt as gA,kGt as gB,Unt as gC,T2 as gD,G7t as gE,F9t as gF,Jqt as gG,gGt as gH,SYe as gI,pGt as gJ,Kf as gK,wYe as gL,B9t as gM,D9t as gN,M9t as gO,O9t as gP,dit as gQ,G2 as gR,Z9t as gS,X9t as gT,e7t as gU,K7t as gV,Z7t as gW,Y7t as gX,Q7t as gY,X7t as gZ,W7t as g_,S7t as ga,E7t as gb,j7t as gc,A7t as gd,k7t as ge,T7t as gf,LHt as gg,T8 as gh,Sit as gi,sf as gj,iXe as gk,eHt as gl,lIt as gm,cIt as gn,V7t as go,tHt as gp,rHt as gq,q7t as gr,eVe as gs,ZO as gt,GDe as gu,HDe as gv,kue as gw,fMe as gx,K2 as gy,mMe as gz,lMe as h,Aje as h$,B7t as h0,$7t as h1,z7t as h2,J7t as h3,H7t as h4,Fxe as h5,t7t as h6,r7t as h7,n7t as h8,Mee as h9,q9t as hA,G9t as hB,Pie as hC,Wnt as hD,V9t as hE,$9t as hF,z9t as hG,K9t as hH,Znt as hI,Xnt as hJ,W9t as hK,ZGt as hL,XGt as hM,QGt as hN,JGt as hO,e9t as hP,t9t as hQ,r9t as hR,n9t as hS,zXe as hT,a7t as hU,p1e as hV,sst as hW,rst as hX,Cst as hY,R1e as hZ,Tje as h_,IDe as ha,LDe as hb,VDe as hc,QS as hd,WDe as he,eMe as hf,rMe as hg,oMe as hh,_me as hi,N9 as hj,dMe as hk,I9 as hl,wDe as hm,Iie as hn,nGt as ho,tGt as hp,iGt as hq,Fqt as hr,sGt as hs,aGt as ht,oGt as hu,lGt as hv,Oqt as hw,aHe as hx,U9t as hy,H9t as hz,Bt as i,Rwe as i$,YGt as i0,aRt as i1,sHt as i2,aHt as i3,oHt as i4,oRt as i5,cHt as i6,uHt as i7,dHt as i8,hHt as i9,Kqt as iA,Yqt as iB,Wqt as iC,Zqt as iD,Xqt as iE,qqt as iF,Gqt as iG,zqt as iH,Uqt as iI,Vqt as iJ,VKe as iK,vVe as iL,ZYe as iM,Gee as iN,Rqt as iO,oZe as iP,c7t as iQ,l7t as iR,o7t as iS,u7t as iT,f7t as iU,qNt as iV,s9t as iW,a9t as iX,N9t as iY,I9t as iZ,P9t as i_,fHt as ia,mHt as ib,pHt as ic,gHt as id,yHt as ie,xHt as ig,bHt as ih,wHt as ii,iHt as ij,nHt as ik,V$ as il,lh as im,hGt as io,uGt as ip,fGt as iq,eGt as ir,Hqt as is,rGt as it,Bqt as iu,$qt as iv,ije as iw,cGt as ix,dGt as iy,Qqt as iz,s as j,QPt as j$,fr as j0,CHt as j1,qRt as j2,yK as j3,Jje as j4,PHt as j5,jHt as j6,AHt as j7,kHt as j8,sMt as j9,S9t as jA,l9t as jB,d9t as jC,T9t as jD,E9t as jE,A9t as jF,k9t as jG,C9t as jH,i9t as jI,o9t as jJ,c9t as jK,TYe as jL,Ont as jM,yGt as jN,xGt as jO,vGt as jP,mGt as jQ,vYe as jR,xit as jS,dN as jT,Xte as jU,X7 as jV,yve as jW,zF as jX,Kr as jY,tN as jZ,U7t as j_,w7 as ja,Iqt as jb,KUe as jc,YUe as jd,ewe as je,Lfe as jf,lHt as jg,c_e as jh,vHt as ji,_Ht as jj,SHt as jk,THt as jl,XYe as jm,iQe as jn,u9t as jo,h9t as jp,f9t as jq,m9t as jr,p9t as js,g9t as jt,y9t as ju,w9t as jv,x9t as jw,v9t as jx,_9t as jy,b9t as jz,ml as k,Cve as k0,x4t as k1,w4t as k2,E4t as k3,YA as k4,kRt as k5,a6 as k6,EHt as k7,wx as k8,DHt as k9,aMt as kA,zHt as kB,bLt as kC,cLt as kD,$Ht as kE,TK as kF,VHt as kG,qHt as kH,owe as kI,utt as kJ,y8 as kK,d7t as kL,h7t as kM,jqt as kN,Hp as ka,RHt as kb,u5 as kc,FHt as kd,oDt as ke,BHt as kf,_K as kg,OHt as kh,NHt as ki,Hx as kj,f5 as kk,c5 as kl,UHt as km,HHt as kn,GHt as ko,lg as kp,IHt as kq,wG as kr,GAe as ks,I4t as kt,MHt as ku,WHt as kv,KHt as kw,oMt as kx,lMt as ky,AK as kz,hx as l,dXe as m,ene as n,Re as o,U_e as p,Wr as q,C as r,XV as s,Fee as t,mr as u,AD as v,Bee as w,k9 as x,mi as y,oc as z};