nubot-lite 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -5
- package/lib/api.mjs +6 -2
- package/lib/cloudflare.mjs +13 -12
- package/lib/commands/init.mjs +260 -251
- package/package.json +1 -1
- package/template/.claude/skills/nubot-lite/SKILL.md +7 -1
- package/template/panel/PANEL.md +1 -1
- package/template/panel/assets/AgendarDemoPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/{AgentDatasetsPage-D8vQhRWO.js → AgentDatasetsPage-wLtBtSB2.js} +2 -2
- package/template/panel/assets/AgentKnowledgeGroupsPage-BGHNFj-e.js +1 -0
- package/template/panel/assets/AgentListPage-F3ja9_o_.js +1 -0
- package/template/panel/assets/AgentQaTrainingPage-CojiU8_W.js +1 -0
- package/template/panel/assets/AiAgentWhatsappPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/BlogPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/BlogPostPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/CalculadoraTiempoRespuestaPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/{CampaignDetailPage-DFMctNEj.js → CampaignDetailPage-DUNnckvn.js} +1 -1
- package/template/panel/assets/CampaignsPage-CS60yZBd.js +1 -0
- package/template/panel/assets/ChannelSelector-C7R9zqrt.js +1 -0
- package/template/panel/assets/ChatbotParaWhatsappPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/ConfirmModal-B27OBQdm.js +1 -0
- package/template/panel/assets/ContactsPage-CvoDlFUN.js +14 -0
- package/template/panel/assets/CreateAgentPage-CbhikMY1.js +19 -0
- package/template/panel/assets/CreditLimitBanner-j72L7jgK.js +1 -0
- package/template/panel/assets/CrmParaWhatsappPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/DashboardPage-BGWkXY7W.js +1 -0
- package/template/panel/assets/{EmojiPicker-BToAe-MT.js → EmojiPicker-ByTMSXTj.js} +1 -1
- package/template/panel/assets/{EventTypesSettingsPage-DCedeQzM.js → EventTypesSettingsPage-CLpO1VBL.js} +1 -1
- package/template/panel/assets/GeneradorEnlacesPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/GeneradorQrWhatsappPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/{GeneralSettingsPage-B04ozcHb.js → GeneralSettingsPage-CY-5aGgL.js} +1 -1
- package/template/panel/assets/GoogleCalendarManagePage-oX7DuErV.js +1 -0
- package/template/panel/assets/{InvitationAcceptancePage-BPgtBFl5.js → InvitationAcceptancePage-BYllrAYs.js} +1 -1
- package/template/panel/assets/IrAlSitioPublico-Bn_BvTp1.js +1 -0
- package/template/panel/assets/LiteAiUsagePage-Dzm8jBL2.js +1 -0
- package/template/panel/assets/{LiteSetupPage-42rgAdnG.js → LiteSetupPage-CMSAur_e.js} +1 -1
- package/template/panel/assets/MarkdownRenderer-C3TD9KYa.js +3 -0
- package/template/panel/assets/MediaProcessingService-CG2DdSyN.js +1 -0
- package/template/panel/assets/NewCampaignPage-BfSEd075.js +1 -0
- package/template/panel/assets/OrdersConfigPage-BAKKaX0L.js +1 -0
- package/template/panel/assets/OrdersPage-CXiPOCXP.js +1 -0
- package/template/panel/assets/{PasswordStrengthIndicator-HZK_oU0W.js → PasswordStrengthIndicator-4h-Y0s2r.js} +1 -1
- package/template/panel/assets/PlantillaDetailPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/PlantillasIndexPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/PrivacyPolicy-Bn_BvTp1.js +1 -0
- package/template/panel/assets/{ProductManagementPage-DNM7DEgt.js → ProductManagementPage-CRkNTicv.js} +4 -4
- package/template/panel/assets/PublicFormPage-BxPxJ3Pq.js +1 -0
- package/template/panel/assets/QaForm-Px-cmakA.js +5 -0
- package/template/panel/assets/SelectPlanPage-Gyo5C1Hq.js +1 -0
- package/template/panel/assets/SignatureEditor-DIhmrXow.js +1 -0
- package/template/panel/assets/{TagSelector-ChoKzvjW.js → TagSelector-o6tVpRs9.js} +1 -1
- package/template/panel/assets/TagsSettingsPage-DT8MfW1H.js +2 -0
- package/template/panel/assets/TeamsPage-BuWuGxZo.js +1 -0
- package/template/panel/assets/WhatsappBusinessApiPage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/WhatsappMultiagentePage-Bn_BvTp1.js +1 -0
- package/template/panel/assets/{account-D2ltXC_U.js → account-G3WXxisG.js} +1 -1
- package/template/panel/assets/{admin-lEgqZTsa.js → admin-CSMlOMR8.js} +1 -1
- package/template/panel/assets/{agent.service-BcAkMU7j.js → agent.service-BE2rJG_o.js} +1 -1
- package/template/panel/assets/{alert-dialog-D8P69s-m.js → alert-dialog-gzZZoAiu.js} +2 -2
- package/template/panel/assets/{alert-DI3GBLi1.js → alert-seLKo73M.js} +1 -1
- package/template/panel/assets/api-keys-BF33GS2N.js +1 -0
- package/template/panel/assets/{archive-LUe5bKi5.js → archive-CxUKRJwu.js} +1 -1
- package/template/panel/assets/{arrow-left-BeDdBs_Q.js → arrow-left-CI7mH7bD.js} +1 -1
- package/template/panel/assets/{arrow-up-BiBq8Pvx.js → arrow-up-DJzXCc8_.js} +1 -1
- package/template/panel/assets/{arrow-up-down-CaG2BONN.js → arrow-up-down-DkSCsCjR.js} +1 -1
- package/template/panel/assets/audit-slljESxh.js +1 -0
- package/template/panel/assets/{authService-Cbm8LdlJ.js → authService-CtvlzCDa.js} +1 -1
- package/template/panel/assets/{avatar-CILB1zwS.js → avatar-BXhSKQGY.js} +1 -1
- package/template/panel/assets/{billing-IVLNopU2.js → billing-Cy2XUBeY.js} +1 -1
- package/template/panel/assets/{brain-B9z7jZ7A.js → brain-BmrjUpsb.js} +1 -1
- package/template/panel/assets/{calendar-CIHhMjNy.js → calendar-Bu0aDtW1.js} +1 -1
- package/template/panel/assets/{calendar-days-BwJfOz8M.js → calendar-days-CXtOZxOF.js} +1 -1
- package/template/panel/assets/{card-DcKsxjXK.js → card-DdbmSh-v.js} +1 -1
- package/template/panel/assets/{checkbox-pcbjC0d3.js → checkbox-CuJh5AMO.js} +1 -1
- package/template/panel/assets/{chevrons-up-down-DC-BWTrj.js → chevrons-up-down-DNNdNhV8.js} +1 -1
- package/template/panel/assets/{circle-check-big-DzPo5zZX.js → circle-check-big-BOZQ_2Kv.js} +1 -1
- package/template/panel/assets/{circle-x-BwMKIs8b.js → circle-x-decmm7ip.js} +1 -1
- package/template/panel/assets/cloud-B3m0_VpL.js +1 -0
- package/template/panel/assets/{code-BMAyHFJe.js → code-C-UH-ZD-.js} +1 -1
- package/template/panel/assets/{cog-M7j64wa2.js → cog-BS-_-U4F.js} +1 -1
- package/template/panel/assets/{collapsible-B22t1J-V.js → collapsible-Ce_8EeFJ.js} +1 -1
- package/template/panel/assets/{command-COdSmSIB.js → command-aHRTWaYV.js} +1 -1
- package/template/panel/assets/connectionsService-BJg4S1e9.js +1 -0
- package/template/panel/assets/contactsApi-DI5dcMLo.js +1 -0
- package/template/panel/assets/creditErrors-DSbswjsG.js +1 -0
- package/template/panel/assets/{database-C1qvt3Py.js → database-Brb7Omak.js} +1 -1
- package/template/panel/assets/{datapath-C12uI_pT.js → datapath-CHeKabeh.js} +1 -1
- package/template/panel/assets/{datetime-BuZosCVk.js → datetime-D72Uxhjs.js} +1 -1
- package/template/panel/assets/{download-CiVQHPeB.js → download-CyfdxFCW.js} +1 -1
- package/template/panel/assets/{ellipsis-CMEJnUfK.js → ellipsis-GLu0u4ze.js} +1 -1
- package/template/panel/assets/{ellipsis-vertical-DTqbEYYp.js → ellipsis-vertical-CskGwbgN.js} +1 -1
- package/template/panel/assets/email-inbox-kyJ2qML5.js +1 -0
- package/template/panel/assets/es-BDgg6unH.js +1 -0
- package/template/panel/assets/external-link-w7K66ae2.js +1 -0
- package/template/panel/assets/{eye-HfQCUjxJ.js → eye-CR5C6hVv.js} +1 -1
- package/template/panel/assets/{eye-off-v1Z_lKS0.js → eye-off-CBiJXw4j.js} +1 -1
- package/template/panel/assets/facebook-D0SQMea2.js +1 -0
- package/template/panel/assets/{file-DMzjdlTL.js → file-CTZ8-xmL.js} +1 -1
- package/template/panel/assets/file-braces-54MsOnzo.js +1 -0
- package/template/panel/assets/file-spreadsheet-DpekIaV8.js +1 -0
- package/template/panel/assets/{folder-D0GKakGp.js → folder-DxTHNhQ_.js} +1 -1
- package/template/panel/assets/{folder-open-DQFc4qTJ.js → folder-open-BM4rA96e.js} +1 -1
- package/template/panel/assets/format-BG1mN6C0.js +1 -0
- package/template/panel/assets/{grip-vertical-FN-eTC2C.js → grip-vertical-CS-dU0tJ.js} +1 -1
- package/template/panel/assets/{hash-BoTE56iw.js → hash-ByrjK6gt.js} +1 -1
- package/template/panel/assets/{help-center-B1MAIBWA.js → help-center-fmvvoAkD.js} +1 -1
- package/template/panel/assets/{history-DhHayxUg.js → history-97D1GT_9.js} +1 -1
- package/template/panel/assets/house-CXew5LB-.js +1 -0
- package/template/panel/assets/{index-DsyZ_FlA.js → index-43NA2pdZ.js} +23 -23
- package/template/panel/assets/index-BG59-Kyv.js +6 -0
- package/template/panel/assets/{index-DUnioqCT.js → index-BGvtgHY3.js} +1 -1
- package/template/panel/assets/index-BL76lyPt.js +2 -0
- package/template/panel/assets/index-BUA9lP4J.js +1 -0
- package/template/panel/assets/index-Bfvq4Q3v.js +1 -0
- package/template/panel/assets/index-CK793Wzl.css +1 -0
- package/template/panel/assets/{index-BTxe6gLJ.js → index-ChrvveQm.js} +1 -1
- package/template/panel/assets/index-CoJIvJ6y.js +1 -0
- package/template/panel/assets/{index-CMEeV9dO.js → index-CsV1u-Y7.js} +2 -2
- package/template/panel/assets/{index-BiSc3WD9.js → index-DIxON2Dm.js} +1 -1
- package/template/panel/assets/index-DtoSJTyl.js +1 -0
- package/template/panel/assets/index-FBuxpbGF.js +36 -0
- package/template/panel/assets/index-YR5X3nd4.js +1 -0
- package/template/panel/assets/{instagram-CC7iYt7V.js → instagram-Bm17x-Fs.js} +1 -1
- package/template/panel/assets/interactiveLimits-C7Sx7s9W.js +1 -0
- package/template/panel/assets/landing-CEUFhLJ9.js +1 -0
- package/template/panel/assets/{layout-grid-Cm6hfBWZ.js → layout-grid-DN-t2Wjd.js} +1 -1
- package/template/panel/assets/{list-BKc6EXnV.js → list-B0uLKf1b.js} +1 -1
- package/template/panel/assets/{map-pin-CPmcofD3.js → map-pin-COYHwobx.js} +1 -1
- package/template/panel/assets/{maximize-2-WdbM7Kdx.js → maximize-2-SbmXBBYe.js} +1 -1
- package/template/panel/assets/mediaLimits-CAYdWqeQ.js +1 -0
- package/template/panel/assets/mediaValidation-Bg0xHQrv.js +1 -0
- package/template/panel/assets/message-circle-tNSzOeOW.js +1 -0
- package/template/panel/assets/{message-square-Dfn16oHc.js → message-square-B1_OirdW.js} +1 -1
- package/template/panel/assets/{meta-templates-C7yEjSOI.js → meta-templates-hhDdxBOR.js} +1 -1
- package/template/panel/assets/metadataSchemasApi-BmJko2eC.js +1 -0
- package/template/panel/assets/{mic-CT4vyzLZ.js → mic-ClFq9hMZ.js} +1 -1
- package/template/panel/assets/minus-vh4a51Mn.js +1 -0
- package/template/panel/assets/{music-Cu8AQMFp.js → music-CgtkroYi.js} +1 -1
- package/template/panel/assets/{page-components-o2TF52HV.js → page-components-DXOKtt_M.js} +1 -1
- package/template/panel/assets/{pages-Cj5Qd1QO.js → pages-BcYbyh_-.js} +1 -1
- package/template/panel/assets/{pages-B7digtXi.js → pages-BuibyrnC.js} +1 -1
- package/template/panel/assets/{pages-Dw7dvmaS.js → pages-CGXCBdff.js} +1 -1
- package/template/panel/assets/paperclip-DVRbzE7C.js +1 -0
- package/template/panel/assets/{pen-line-DLnhkIuw.js → pen-line-Cr0YFjAs.js} +1 -1
- package/template/panel/assets/{pencil-Cx8u1N8t.js → pencil-aqjc7AWb.js} +1 -1
- package/template/panel/assets/{popover-MyuU-yAK.js → popover-cWIhNmod.js} +1 -1
- package/template/panel/assets/{power-CdR2OkIX.js → power-CVFzhVJx.js} +1 -1
- package/template/panel/assets/{product.service-CRLZOQsr.js → product.service-FClit10f.js} +1 -1
- package/template/panel/assets/products.types-nZIsk2w8.js +1 -0
- package/template/panel/assets/proxy-CvX2KM2u.js +1 -0
- package/template/panel/assets/{save-Dua2yhWl.js → save-mwkHDnDL.js} +1 -1
- package/template/panel/assets/scroll-area-CSCo4HHB.js +1 -0
- package/template/panel/assets/{select-DlB_BbfM.js → select-DCY_lg9j.js} +1 -1
- package/template/panel/assets/{send-Dxmdupsl.js → send-DBQH77K9.js} +1 -1
- package/template/panel/assets/{separator-CPT3uVRM.js → separator-DznqP68l.js} +1 -1
- package/template/panel/assets/{settings-2-C-c8ECWW.js → settings-2-PhKPMrsj.js} +1 -1
- package/template/panel/assets/shield-alert-Fv3j9Wbv.js +1 -0
- package/template/panel/assets/{skeleton-B0zh8s_y.js → skeleton-CN6xlRXP.js} +1 -1
- package/template/panel/assets/{slider-CY71MXOW.js → slider-D0QB_Lme.js} +1 -1
- package/template/panel/assets/{square-BuGqLxJB.js → square-Dm5VC71z.js} +1 -1
- package/template/panel/assets/{square-pen-CJajoyrm.js → square-pen-Dbn7xmc-.js} +1 -1
- package/template/panel/assets/{star-Cuegk1GF.js → star-BMD3HmS6.js} +1 -1
- package/template/panel/assets/stat-card-W7s_-fHW.js +1 -0
- package/template/panel/assets/storage.api-C0ZJBoSz.js +20 -0
- package/template/panel/assets/{switch-ODBa0fCT.js → switch-C7XmAU1c.js} +1 -1
- package/template/panel/assets/{table-CvSELOPi.js → table-7NGq0kRw.js} +1 -1
- package/template/panel/assets/{tabs-DqXhuAr6.js → tabs-BGCKrmVw.js} +1 -1
- package/template/panel/assets/{tags-By_tlh_r.js → tags-HU2fuPFH.js} +1 -1
- package/template/panel/assets/{target-DEuCdeUI.js → target-CG_g4_Fj.js} +1 -1
- package/template/panel/assets/{textarea-BYtcLsMD.js → textarea-B1anutjq.js} +1 -1
- package/template/panel/assets/{ticket-CWba7G1i.js → ticket-CHs1Xojr.js} +1 -1
- package/template/panel/assets/{trash-2-Du2vmQCH.js → trash-2-D_kmHMwn.js} +1 -1
- package/template/panel/assets/{trending-up-Ba4HSvuW.js → trending-up-BnHeLWFs.js} +1 -1
- package/template/panel/assets/{upload-C7TwpdyA.js → upload-CQg4_W5r.js} +1 -1
- package/template/panel/assets/{useAiAgentsQuery-Bm6aRHKj.js → useAiAgentsQuery-CXo6TmU6.js} +1 -1
- package/template/panel/assets/useFunnelStats-Bk8wTET5.js +1 -0
- package/template/panel/assets/useFunnelsQuery-vDrahaDr.js +1 -0
- package/template/panel/assets/{useInfiniteQuery-BXUM1Z9V.js → useInfiniteQuery-D0sFT2K2.js} +1 -1
- package/template/panel/assets/{useMutation-a5tIBvQY.js → useMutation-0ypmz8SO.js} +1 -1
- package/template/panel/assets/useOrgSyncedFetch-FSgwRhpR.js +1 -0
- package/template/panel/assets/usePipelineBoardQuery-BysscZXI.js +9 -0
- package/template/panel/assets/{useUploadConfig-BuiF0X-3.js → useUploadConfig-CvVmSc6S.js} +1 -1
- package/template/panel/assets/{user-DwCALzIG.js → user-l48WDfDH.js} +1 -1
- package/template/panel/assets/{user-plus-BiUjcHil.js → user-plus-CWaaUP-O.js} +1 -1
- package/template/panel/assets/{video-VfwKgB6z.js → video-CILE66CA.js} +1 -1
- package/template/panel/assets/{volume-2-C5DMdOVq.js → volume-2-DfFqN0dw.js} +1 -1
- package/template/panel/assets/wrench-Dcbk4scY.js +1 -0
- package/template/panel/index.html +2 -2
- package/template/panel/version.json +2 -2
- package/template/worker/migrations/0006_ai_usage.sql +33 -0
- package/template/worker/migrations/0007_channels.sql +18 -0
- package/template/worker/src/agent/pricing.ts +37 -0
- package/template/worker/src/agent/prompt.ts +137 -134
- package/template/worker/src/agent/run.ts +350 -243
- package/template/worker/src/agent/sandbox.ts +2 -2
- package/template/worker/src/agent/tools.ts +463 -463
- package/template/worker/src/channels/accounts.ts +177 -0
- package/template/worker/src/channels/zernio.ts +161 -148
- package/template/worker/src/inbox/contacts.ts +2 -0
- package/template/worker/src/inbox/store.ts +199 -187
- package/template/worker/src/index.ts +2 -0
- package/template/worker/src/nubot/account.ts +163 -178
- package/template/worker/src/nubot/ai-usage.ts +197 -0
- package/template/worker/src/nubot/channels.ts +159 -0
- package/template/worker/src/nubot/contacts.ts +387 -386
- package/template/worker/src/nubot/funnels.ts +672 -670
- package/template/worker/src/nubot/inbox.ts +623 -616
- package/template/worker/src/nubot/index.ts +127 -122
- package/template/worker/src/nubot/mappers.ts +12 -5
- package/template/worker/src/routes/channels.ts +13 -0
- package/template/worker/src/routes/system.ts +110 -100
- package/template/worker/src/webhooks/zernio.ts +154 -125
- package/template/panel/assets/AgendarDemoPage-DOiS40FL.js +0 -1
- package/template/panel/assets/AgentKnowledgeGroupsPage-DEPS1lsk.js +0 -1
- package/template/panel/assets/AgentListPage-DqY9rze5.js +0 -1
- package/template/panel/assets/AgentQaTrainingPage-Ecis7xoc.js +0 -1
- package/template/panel/assets/AiAgentWhatsappPage-DOiS40FL.js +0 -1
- package/template/panel/assets/AiMetricsPage-DEPS1lsk.js +0 -1
- package/template/panel/assets/BlogPage-DOiS40FL.js +0 -1
- package/template/panel/assets/BlogPostPage-DOiS40FL.js +0 -1
- package/template/panel/assets/CalculadoraTiempoRespuestaPage-DOiS40FL.js +0 -1
- package/template/panel/assets/CampaignsPage-CLRaXGlj.js +0 -1
- package/template/panel/assets/ChannelSelector-q9tTirNo.js +0 -1
- package/template/panel/assets/ChatbotParaWhatsappPage-DOiS40FL.js +0 -1
- package/template/panel/assets/ConfirmModal-W7VUI3Z_.js +0 -1
- package/template/panel/assets/ContactsPage-CsOFsOPw.js +0 -14
- package/template/panel/assets/CreateAgentPage-Ifxx6_UX.js +0 -19
- package/template/panel/assets/CreditLimitBanner-J49rSVEn.js +0 -1
- package/template/panel/assets/CrmParaWhatsappPage-DOiS40FL.js +0 -1
- package/template/panel/assets/DashboardPage-3Viy83dd.js +0 -1
- package/template/panel/assets/GeneradorEnlacesPage-DOiS40FL.js +0 -1
- package/template/panel/assets/GeneradorQrWhatsappPage-DOiS40FL.js +0 -1
- package/template/panel/assets/IrAlSitioPublico-DOiS40FL.js +0 -1
- package/template/panel/assets/MediaProcessingService-glHGiE_o.js +0 -1
- package/template/panel/assets/NewCampaignPage-Cw99m3W8.js +0 -1
- package/template/panel/assets/OrdersConfigPage-B6BfM3lf.js +0 -1
- package/template/panel/assets/OrdersPage-Du7CJjty.js +0 -1
- package/template/panel/assets/PlantillaDetailPage-DOiS40FL.js +0 -1
- package/template/panel/assets/PlantillasIndexPage-DOiS40FL.js +0 -1
- package/template/panel/assets/PrivacyPolicy-DOiS40FL.js +0 -1
- package/template/panel/assets/PublicFormPage-DDb4OXEM.js +0 -1
- package/template/panel/assets/QaForm-BDboHNKo.js +0 -5
- package/template/panel/assets/SelectPlanPage-DALaf8E5.js +0 -1
- package/template/panel/assets/TagsSettingsPage-DYCKveQq.js +0 -2
- package/template/panel/assets/TeamsPage-DPUcRdlh.js +0 -1
- package/template/panel/assets/WhatsappBusinessApiPage-DOiS40FL.js +0 -1
- package/template/panel/assets/WhatsappMultiagentePage-DOiS40FL.js +0 -1
- package/template/panel/assets/api-keys-B0UQNR5E.js +0 -1
- package/template/panel/assets/audit-BrdHcTNl.js +0 -1
- package/template/panel/assets/connections-Dqwd01UI.js +0 -1
- package/template/panel/assets/connectionsService-BsJf8pFz.js +0 -3
- package/template/panel/assets/contactsApi-B851NME_.js +0 -1
- package/template/panel/assets/creditErrors-CrpkwwUI.js +0 -1
- package/template/panel/assets/email-inbox-LbGeQCty.js +0 -1
- package/template/panel/assets/es-BG480iA5.js +0 -1
- package/template/panel/assets/facebook-RxMBweMB.js +0 -1
- package/template/panel/assets/index-B183O0S5.js +0 -1
- package/template/panel/assets/index-BJCPaymI.css +0 -1
- package/template/panel/assets/index-BtxJGfLL.js +0 -6
- package/template/panel/assets/index-Bz-ixwph.js +0 -1
- package/template/panel/assets/index-CjQSv8hF.js +0 -2
- package/template/panel/assets/index-D3vkHHjD.js +0 -9
- package/template/panel/assets/index-D4WhIkMN.js +0 -1
- package/template/panel/assets/interactiveLimits-CfLJ1O4_.js +0 -1
- package/template/panel/assets/landing-If3oVsS0.js +0 -1
- package/template/panel/assets/mediaValidation-BR-ZOj5w.js +0 -1
- package/template/panel/assets/minus-CyVEzdqL.js +0 -1
- package/template/panel/assets/products.types-46xSxBS8.js +0 -1
- package/template/panel/assets/scroll-area-CavEOIyz.js +0 -1
- package/template/panel/assets/shield-alert-04pSYngI.js +0 -1
- package/template/panel/assets/storage.api-CFU3KJNp.js +0 -20
- package/template/panel/assets/useFunnelStats-tvjpmWIC.js +0 -1
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import{c as Dt,j as e,B as L,n as ze,I as He,a1 as es,a2 as ss,a3 as ts,a4 as as,a5 as gs,az as ks,t as D,d as Ja,o as ke,l as M,aE as ba,r as me,al as Ws,am as Ks,an as Qs,ao as Gs,ap as ja,aq as Qe,Z as cs,T as Cs,s as Ss,v as Es,ar as va,J as Se,as as Na,G as ms,a8 as mt,aa as Ls,u as Ya,i as Rs,O as Be,a9 as st,aC as Xa,a7 as ya,F as Za,C as yt,R as Js,A as tt,y as at,aF as er,x as fs,aG as sr,a0 as wa,g as rs,w as ve,a as bs,ad as tr,ae as ar,af as rr,ag as nr,ah as lr,X as us,ai as Mt,a6 as wt,S as kt,aB as Ct,k as ir,aj as or,Y as Lt,au as Ys,V as dr,U as $e,E as As,_ as Kt,aw as cr,P as mr,aA as ur,aH as Qt}from"./index-43NA2pdZ.js";import{b as m,k as xr,g as hr,A as pr,C as fr,X as gr,Y as br,T as jr,h as vr}from"./recharts-DrC5kNsx.js";import{P as Nr,a as yr,b as wr}from"./page-components-DXOKtt_M.js";import{S as Ye}from"./scroll-area-CSCo4HHB.js";import{F as ka}from"./file-braces-54MsOnzo.js";import{C as Gt}from"./checkbox-CuJh5AMO.js";import{A as xs,a as hs,b as ps}from"./avatar-BXhSKQGY.js";import{T as kr,a as Cr,b as Jt,c as qs,d as Sr,e as Bs}from"./table-7NGq0kRw.js";import{a as Ne,c as Er}from"./datetime-D72Uxhjs.js";import{E as Ar}from"./ellipsis-GLu0u4ze.js";import{E as St}from"./external-link-w7K66ae2.js";import{M as Te}from"./message-square-B1_OirdW.js";import{G as _r,g as se,M as Tr,e as Ca,b as Ir,c as Dr,d as Mr,f as Lr,a as Rt,S as $s,C as Rr,h as Or,B as Yt}from"./contactsApi-DI5dcMLo.js";import{t as Ze,c as Pr,n as ut,s as Xt,g as Fr,e as zr,a as Zt,m as ea,b as Us,f as Sa}from"./format-BG1mN6C0.js";import{P as qe,a as qr}from"./index-YR5X3nd4.js";import{e as rt}from"./es-BDgg6unH.js";import{S as sa}from"./separator-DznqP68l.js";import{C as ta,b as aa,a as Br}from"./collapsible-Ce_8EeFJ.js";import{T as Ot,a as Pt,b as Xe,c as Ue}from"./tabs-BGCKrmVw.js";import{A as Ea,a as Aa,b as _a,c as Ta,d as Ia,e as Da,f as Ma,g as $r}from"./alert-dialog-gzZZoAiu.js";import{A as Ge,a as Xs,b as Je}from"./alert-seLKo73M.js";import{C as Ur,a as Vr,b as Hr,c as Wr,d as Kr,e as ra}from"./command-aHRTWaYV.js";import{P as Ft,a as zt,b as qt}from"./popover-cWIhNmod.js";import{M as Os}from"./message-circle-tNSzOeOW.js";import{C as Qr}from"./chevrons-up-down-DNNdNhV8.js";import{I as Bt}from"./instagram-Bm17x-Fs.js";import{T as La,M as Gr}from"./TagSelector-o6tVpRs9.js";import{S as we}from"./skeleton-CN6xlRXP.js";import{U as Ve}from"./user-l48WDfDH.js";import{u as Jr}from"./useInfiniteQuery-D0sFT2K2.js";import{C as Yr}from"./cog-BS-_-U4F.js";import{F as Xr}from"./facebook-D0SQMea2.js";import{U as Ds}from"./user-plus-CWaaUP-O.js";import{T as Ms}from"./trending-up-BnHeLWFs.js";import{E as Et}from"./eye-CR5C6hVv.js";import{u as Zr}from"./useMutation-0ypmz8SO.js";import{S as nt,a as lt,b as it,c as ot,d as Fe,C as en}from"./select-DCY_lg9j.js";import{T as sn}from"./textarea-B1anutjq.js";import{m as Ra}from"./metadataSchemasApi-BmJko2eC.js";import{P as tn}from"./pen-line-Cr0YFjAs.js";import{T as At}from"./trash-2-D_kmHMwn.js";import{M as xt,T as na,A as an}from"./tags-HU2fuPFH.js";import{C as Oa}from"./calendar-Bu0aDtW1.js";import{S as Pa,L as rn}from"./star-BMD3HmS6.js";import{u as Fa,C as nn,p as ln}from"./ChannelSelector-C7R9zqrt.js";import{u as on,P as dn}from"./useCountryFromLocale-BavmL9FK.js";import{u as za,h as la}from"./creditErrors-DSbswjsG.js";import{C as cn}from"./CreditLimitBanner-j72L7jgK.js";import{u as mn,C as _t,a as un}from"./index-ChrvveQm.js";import{M as xn}from"./maximize-2-SbmXBBYe.js";import{D as _s}from"./download-CyfdxFCW.js";import{D as gt}from"./database-Brb7Omak.js";import{C as bt}from"./circle-check-big-BOZQ_2Kv.js";import{S as ia}from"./shield-alert-Fv3j9Wbv.js";import{A as hn}from"./arrow-left-CI7mH7bD.js";import{A as pn}from"./archive-CxUKRJwu.js";import{u as fn}from"./useDebounce-Bfcb_jpD.js";import{C as Ts,a as Is}from"./card-DdbmSh-v.js";import{H as gn}from"./hash-ByrjK6gt.js";import{T as bn}from"./target-CG_g4_Fj.js";import{L as jn}from"./list-B0uLKf1b.js";import"./index-KbFmSzBE.js";import"./switch-C7XmAU1c.js";import"./house-CXew5LB-.js";import"./save-mwkHDnDL.js";import"./history-97D1GT_9.js";import"./code-C-UH-ZD-.js";import"./eye-off-CBiJXw4j.js";import"./index-BGvtgHY3.js";import"./folder-DxTHNhQ_.js";import"./index-CEYKqxbU.js";const vn=[["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"}]],dt=Dt("clipboard-list",vn);const Nn=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]],yn=Dt("columns-2",Nn);const wn=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],kn=Dt("link",wn);function Zs(s,l){const n=+Ze(s)-+Ze(l);return n<0?-1:n>0?1:n}function Cn(s){return Pr(s,Date.now())}function Sn(s,l,n){const[i,r]=ut(n?.in,s,l);return+Xt(i)==+Xt(r)}function En(s,l,n){const[i,r]=ut(n?.in,s,l),f=i.getFullYear()-r.getFullYear(),u=i.getMonth()-r.getMonth();return f*12+u}function An(s){return l=>{const i=(s?Math[s]:Math.trunc)(l);return i===0?0:i}}function _n(s,l){return+Ze(s)-+Ze(l)}function Tn(s,l){const n=Ze(s,l?.in);return n.setHours(23,59,59,999),n}function In(s,l){const n=Ze(s,l?.in),i=n.getMonth();return n.setFullYear(n.getFullYear(),i+1,0),n.setHours(23,59,59,999),n}function Dn(s,l){const n=Ze(s,l?.in);return+Tn(n,l)==+In(n,l)}function Mn(s,l,n){const[i,r,f]=ut(n?.in,s,s,l),u=Zs(r,f),g=Math.abs(En(r,f));if(g<1)return 0;r.getMonth()===1&&r.getDate()>27&&r.setDate(30),r.setMonth(r.getMonth()-u*g);let b=Zs(r,f)===-u;Dn(i)&&g===1&&Zs(i,f)===1&&(b=!1);const h=u*(g-+b);return h===0?0:h}function Ln(s,l,n){const i=_n(s,l)/1e3;return An(n?.roundingMethod)(i)}function Rn(s,l,n){const i=Fr(),r=n?.locale??i.locale??zr,f=2520,u=Zs(s,l);if(isNaN(u))throw new RangeError("Invalid time value");const g=Object.assign({},n,{addSuffix:n?.addSuffix,comparison:u}),[b,h]=ut(n?.in,...u>0?[l,s]:[s,l]),c=Ln(h,b),I=(Zt(h)-Zt(b))/1e3,T=Math.round((c-I)/60);let x;if(T<2)return n?.includeSeconds?c<5?r.formatDistance("lessThanXSeconds",5,g):c<10?r.formatDistance("lessThanXSeconds",10,g):c<20?r.formatDistance("lessThanXSeconds",20,g):c<40?r.formatDistance("halfAMinute",0,g):c<60?r.formatDistance("lessThanXMinutes",1,g):r.formatDistance("xMinutes",1,g):T===0?r.formatDistance("lessThanXMinutes",1,g):r.formatDistance("xMinutes",T,g);if(T<45)return r.formatDistance("xMinutes",T,g);if(T<90)return r.formatDistance("aboutXHours",1,g);if(T<ea){const N=Math.round(T/60);return r.formatDistance("aboutXHours",N,g)}else{if(T<f)return r.formatDistance("xDays",1,g);if(T<Us){const N=Math.round(T/ea);return r.formatDistance("xDays",N,g)}else if(T<Us*2)return x=Math.round(T/Us),r.formatDistance("aboutXMonths",x,g)}if(x=Mn(h,b),x<12){const N=Math.round(T/Us);return r.formatDistance("xMonths",N,g)}else{const N=x%12,y=Math.trunc(x/12);return N<3?r.formatDistance("aboutXYears",y,g):N<9?r.formatDistance("overXYears",y,g):r.formatDistance("almostXYears",y+1,g)}}function Tt(s,l){return Rn(s,Cn(s),l)}const On=({startDate:s,endDate:l,onStartDateChange:n,onEndDateChange:i,disabled:r=!1,className:f=""})=>{const[u,g]=m.useState(!1),b=s||l,h=()=>!s&&!l?"Rango de fechas":s&&l?`${Ne(s,{style:"date-only"})} - ${Ne(l,{style:"date-only"})}`:s?`Desde ${Ne(s,{style:"date-only"})}`:`Hasta ${Ne(l,{style:"date-only"})}`;return e.jsxs(Ft,{open:u,onOpenChange:g,children:[e.jsx(zt,{asChild:!0,children:e.jsxs(L,{variant:"outline",size:"sm",className:`h-9 gap-2 ${b?"border-primary":""} ${f}`,disabled:r,children:[e.jsx(Oa,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:h()})]})}),e.jsx(qt,{className:"w-80 p-4",align:"start",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ze,{className:"text-xs text-muted-foreground",children:"Desde"}),e.jsx(He,{type:"datetime-local",value:s,onChange:c=>n(c.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ze,{className:"text-xs text-muted-foreground",children:"Hasta"}),e.jsx(He,{type:"datetime-local",value:l,onChange:c=>i(c.target.value),className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-between pt-2",children:[e.jsx(L,{variant:"ghost",size:"sm",onClick:()=>{n(""),i("")},children:"Limpiar"}),e.jsx(L,{size:"sm",onClick:()=>g(!1),children:"Aplicar"})]})]})})]})},Pn=({isOpen:s,onClose:l,data:n,title:i})=>{const r=()=>{try{const u=typeof n=="string"?n:JSON.stringify(n,null,2);navigator.clipboard.writeText(u),D.success("JSON copiado al portapapeles")}catch{D.error("Error al copiar JSON")}};let f="";try{typeof n=="string"?n.trim().startsWith("{")||n.trim().startsWith("[")?f=JSON.stringify(JSON.parse(n),null,2):f=n:f=JSON.stringify(n,null,2)}catch{f=String(n)}return e.jsx(es,{open:s,onOpenChange:u=>!u&&l(),children:e.jsxs(ss,{className:"sm:max-w-xl max-h-[85vh] flex flex-col p-6 rounded-3xl gap-0 overflow-hidden border-none shadow-2xl bg-white dark:bg-slate-900",children:[e.jsx(ts,{className:"pb-4 flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-indigo-50 dark:bg-indigo-900/30 flex items-center justify-center text-indigo-500",children:e.jsx(ka,{className:"w-5 h-5"})}),e.jsxs("div",{className:"space-y-1 text-left",children:[e.jsx(as,{className:"text-xl font-black tracking-tight text-slate-900 dark:text-white",children:i}),e.jsx(gs,{className:"text-sm font-medium text-slate-500",children:"Visualización estructurada de metadata"})]})]})}),e.jsxs("div",{className:"flex-1 min-h-0 relative rounded-xl bg-slate-50 dark:bg-slate-950 border border-slate-100 dark:border-slate-800 overflow-hidden group",children:[e.jsx(Ye,{className:"h-full w-full",children:e.jsx("div",{className:"p-4",children:e.jsx("pre",{className:"text-xs font-mono text-slate-600 dark:text-slate-300 whitespace-pre-wrap leading-relaxed",children:f})})}),e.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(L,{size:"icon",variant:"secondary",className:"h-8 w-8 rounded-lg shadow-sm bg-white dark:bg-slate-800",onClick:r,children:e.jsx(ks,{className:"h-3.5 w-3.5"})})})]}),e.jsx("div",{className:"pt-4 flex justify-end",children:e.jsx(L,{onClick:l,className:"rounded-xl font-bold px-6",children:"Cerrar"})})]})})},Fn=[{key:"phone",label:"Teléfono",type:"contact",sortable:!0},{key:"email",label:"Email",type:"contact",sortable:!0},{key:"tags",label:"Etiquetas",type:"standard",sortable:!1},{key:"lastSeenAt",label:"Última Actividad",type:"date",sortable:!0},{key:"createdAt",label:"Creado",type:"date",sortable:!0},{key:"updatedAt",label:"Actualizado",type:"date",sortable:!0},{key:"otherMetadata",label:"Info Adicional",type:"standard",sortable:!1}],zn="otherMetadata",oa={page:1,limit:20,sortOrder:"DESC",sortBy:"updatedAt"},qn=["phone","email","tags","lastSeenAt"],$t=Ja((s,l)=>({filters:oa,visibleColumns:qn,selectAllMode:!1,selectAllCount:0,setFilters:n=>{s(i=>({filters:{...i.filters,...n,page:n.page??1},selectAllMode:!1,selectAllCount:0}))},clearFilters:()=>{s({filters:oa,selectAllMode:!1,selectAllCount:0})},toggleColumn:n=>{s(i=>{const r=i.visibleColumns;return r.includes(n)?{visibleColumns:r.filter(f=>f!==n)}:{visibleColumns:[...r,n]}})},setSelectAllMode:(n,i)=>{s({selectAllMode:n,selectAllCount:n?i??0:0})},clearSelectAll:()=>{s({selectAllMode:!1,selectAllCount:0})},setVisibleColumns:n=>s({visibleColumns:n}),initializeColumnsFromSchemas:n=>{const i=l().visibleColumns,r=n.map(f=>f.key).filter(f=>!i.includes(f));r.length>0&&s({visibleColumns:[...i,...r]})}})),Bn=m.memo(({contacts:s,isLoading:l,selectedIds:n,onSelect:i,onSelectAll:r,onViewDetail:f,onOpenChat:u,onMerge:g,visibleColumns:b=["phone","email","tags","lastSeenAt"],availableFields:h=[],page:c=1,total:I=0,limit:T=20,onPageChange:x,density:N="comfortable",selectAllMode:y=!1})=>{const[w,E]=m.useState({open:!1,data:null,title:""}),H=C=>C.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),Z=C=>{const t=h.find(a=>a.key===C);return t?t.label:C},X=(C,t)=>{switch(t){case"phone":return e.jsxs("div",{className:"flex items-center gap-2 group/phone",children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-slate-50 dark:bg-slate-800 flex items-center justify-center group-hover/phone:bg-primary/10 transition-colors",children:e.jsx(qe,{className:"w-3.5 h-3.5 text-slate-400 group-hover/phone:text-primary transition-colors"})}),e.jsx("span",{className:M("text-[13px] text-slate-700 dark:text-slate-200",N==="compact"?"font-medium":"font-bold"),children:C.phone})]});case"email":return C.email?e.jsxs("div",{className:"flex items-center gap-2 group/email",children:[e.jsx("div",{className:"w-7 h-7 rounded-lg bg-slate-50 dark:bg-slate-800 flex items-center justify-center group-hover/email:bg-blue-500/10 transition-colors",children:e.jsx(Se,{className:"w-3.5 h-3.5 text-slate-400 group-hover/email:text-blue-500 transition-colors"})}),e.jsx("span",{className:"text-[13px] text-slate-600 dark:text-slate-400 truncate max-w-[180px] font-medium",children:C.email})]}):e.jsx("span",{className:"text-slate-300 text-xs italic font-medium",children:"Sin email"});case"tags":return e.jsxs("div",{className:"flex flex-wrap gap-1.5 max-w-[220px]",children:[C.tags&&C.tags.length>0?C.tags.slice(0,3).map(ae=>e.jsxs(me,{variant:"outline",className:"text-[10px] font-bold px-2.5 py-0.5 rounded-full border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 shadow-sm flex items-center gap-1.5",title:ae.readOnly?"Etiqueta del sistema":void 0,children:[ae.readOnly?e.jsx(va,{className:"w-2.5 h-2.5 text-slate-500 shrink-0"}):e.jsx("div",{className:"w-1.5 h-1.5 rounded-full",style:{backgroundColor:ae.color||"#64748b"}}),ae.name]},ae.id)):e.jsx("span",{className:"text-slate-300 text-xs",children:"-"}),C.tags&&C.tags.length>3&&e.jsxs(me,{variant:"secondary",className:"text-[10px] font-black px-2 py-0.5 rounded-full bg-slate-100 text-slate-500 border-none shadow-none",children:["+",C.tags.length-3]})]});case"lastSeenAt":return e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[12px] text-slate-600 dark:text-slate-300 font-bold",children:C.lastSeenAt?Tt(new Date(C.lastSeenAt),{addSuffix:!0,locale:rt}):"-"}),C.lastSeenAt&&e.jsx("span",{className:"text-[9px] text-slate-400 uppercase font-black tracking-widest mt-0.5",children:"Última actividad"})]});case"createdAt":case"updatedAt":const a=t==="createdAt"?C.createdAt:C.updatedAt;if(!a)return e.jsx("span",{className:"text-slate-300 text-xs",children:"-"});const o=new Date(a);return e.jsx(cs,{children:e.jsxs(Cs,{children:[e.jsx(Ss,{asChild:!0,children:e.jsx("span",{className:"text-sm text-slate-500 font-medium cursor-help border-b border-dotted border-slate-300 dark:border-slate-600",children:Ne(o,{style:"date-only"})})}),e.jsx(Es,{children:e.jsxs("div",{className:"text-xs text-center",children:[e.jsx("p",{className:"font-semibold capitalize",children:Ne(o,{style:"chart-tooltip"})}),e.jsx("p",{className:"text-slate-400",children:Ne(o,{style:"time-only"})})]})})]})});default:const j=t===zn,v=j?C.metadata:C.metadata?.[t];if(v==null||j&&Object.keys(v||{}).length===0)return e.jsx("span",{className:"text-slate-300 dark:text-slate-600 text-xs",children:"—"});if(typeof v=="object"||t==="otherMetadata")return e.jsxs(L,{variant:"outline",size:"sm",className:"h-7 text-xs font-bold rounded-lg border-slate-200 bg-slate-50 text-slate-600 hover:bg-slate-100 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300 gap-1.5",onClick:ae=>{ae.stopPropagation(),E({open:!0,data:v,title:Z(t)})},children:[e.jsx(ka,{className:"h-3 w-3"}),"Ver JSON"]});if(typeof v=="string"&&(v.startsWith("http")||v.startsWith("www")))return e.jsxs("a",{href:v.startsWith("www")?`https://${v}`:v,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-primary/5 hover:bg-primary/10 text-primary text-[12px] font-bold transition-colors",onClick:ae=>ae.stopPropagation(),children:[e.jsx(St,{className:"w-3 h-3"}),"Ver enlace"]});if(typeof v=="boolean")return e.jsx(me,{variant:"outline",className:M("text-[10px] font-bold px-2 py-0.5 rounded-md",v?"bg-emerald-50 text-emerald-600 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-800":"bg-slate-50 text-slate-500 border-slate-200 dark:bg-slate-800 dark:text-slate-400 dark:border-slate-700"),children:v?"Sí":"No"});if(typeof v=="number")return e.jsx("span",{className:"inline-flex items-center px-2 py-0.5 rounded-md bg-indigo-50 dark:bg-indigo-900/20 text-indigo-600 dark:text-indigo-400 text-[12px] font-bold tabular-nums",children:v.toLocaleString()});const Y=String(v),te=Y.length>20;return e.jsx("div",{className:"group/meta relative",children:e.jsx("span",{className:M("inline-block px-2.5 py-1 rounded-lg bg-slate-50 dark:bg-slate-800 text-slate-700 dark:text-slate-300 text-[12px] font-semibold",te&&"max-w-[140px] truncate"),title:te?Y:void 0,children:Y})})}};if(l)return e.jsxs("div",{className:"w-full bg-white dark:bg-slate-900 rounded-[32px] border border-slate-100 dark:border-slate-800 p-16 flex flex-col items-center justify-center gap-6 animate-pulse",children:[e.jsx("div",{className:"w-16 h-16 bg-slate-50 dark:bg-slate-800 rounded-2xl flex items-center justify-center",children:e.jsx(ke,{className:"w-8 h-8 animate-spin text-primary"})}),e.jsxs("div",{className:"space-y-2 text-center",children:[e.jsx("p",{className:"text-slate-900 dark:text-white font-black text-lg",children:"Preparando tu audiencia"}),e.jsx("p",{className:"text-slate-500 text-sm",children:"Organizando contactos y segmentos..."})]})]});if(s.length===0)return e.jsxs("div",{className:"w-full bg-white dark:bg-slate-900 rounded-[32px] border border-dashed border-slate-200 dark:border-slate-800 p-20 flex flex-col items-center justify-center text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-slate-50 dark:bg-slate-800 rounded-[24px] flex items-center justify-center mb-6",children:e.jsx($n,{className:"w-10 h-10 text-slate-300"})}),e.jsx("h3",{className:"text-2xl font-black text-slate-900 dark:text-white mb-2 tracking-tight",children:"Sin resultados"}),e.jsx("p",{className:"text-slate-500 max-w-sm mx-auto text-sm leading-relaxed",children:"No encontramos ningún contacto que coincida con tus criterios de búsqueda. Intenta ajustar los filtros."}),e.jsx(L,{variant:"outline",className:"mt-8 rounded-full px-8 font-bold border-slate-200",onClick:()=>window.location.reload(),children:"Resetear Filtros"})]});const q=y||s.length>0&&n.length===s.length,le=Math.ceil(I/T);return e.jsxs("div",{className:"bg-white dark:bg-slate-900 rounded-[32px] border border-slate-100 dark:border-slate-800 shadow-sm overflow-hidden flex flex-col animate-in fade-in slide-in-from-bottom-2 duration-500",children:[e.jsx("div",{className:"overflow-x-auto no-scrollbar",children:e.jsxs(kr,{children:[e.jsx(Cr,{children:e.jsxs(Jt,{className:"bg-slate-50/30 dark:bg-slate-800/20 hover:bg-slate-50/30 dark:hover:bg-slate-800/20 border-slate-100 dark:border-slate-800",children:[e.jsx(qs,{className:M("w-[60px] pl-6",N==="compact"?"py-3":"py-6"),children:e.jsx(Gt,{checked:q,onCheckedChange:C=>r(!!C),className:"data-[state=checked]:bg-primary data-[state=checked]:border-primary rounded-[6px]"})}),e.jsx(qs,{className:M("font-black uppercase text-[10px] tracking-widest pl-2 w-[320px] text-slate-400",N==="compact"?"py-3":"py-6"),children:"Contacto"}),b.map(C=>e.jsx(qs,{className:M("font-black uppercase text-[10px] tracking-widest text-slate-400",N==="compact"?"py-3":"py-6"),children:Z(C)},C)),e.jsx(qs,{className:"w-[80px] pr-6"})]})}),e.jsx(Sr,{children:s.map((C,t)=>{const a=n.includes(C.id),o=C.isBlacklisted;return e.jsxs(Jt,{className:M("group cursor-pointer hover:bg-slate-50/80 dark:hover:bg-slate-800/50 border-slate-50/50 dark:border-slate-800/50 transition-all duration-300",a&&"bg-primary/5 dark:bg-primary/10 hover:bg-primary/10",N==="compact"&&"h-12"),onClick:()=>f(C),children:[e.jsx(Bs,{className:M("pl-6",N==="compact"?"py-1.5":"py-4"),onClick:j=>j.stopPropagation(),children:e.jsx(Gt,{checked:a,onCheckedChange:j=>i(C.id,!!j),className:"data-[state=checked]:bg-primary rounded-[6px]"})}),e.jsx(Bs,{className:M("pl-2",N==="compact"?"py-1.5":"py-4"),children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"relative group-hover:scale-105 transition-transform duration-300",children:[e.jsxs(xs,{className:M("border-2 border-white dark:border-slate-800 shadow-md",N==="compact"?"h-9 w-9":"h-12 w-12"),children:[e.jsx(hs,{src:C.profilePicUrl}),e.jsx(ps,{className:"bg-indigo-50 text-indigo-500 font-black text-xs dark:bg-indigo-900/30",children:H(C.name||C.phone)})]}),C.hasActiveTickets&&e.jsx("span",{className:M("absolute top-0 -right-0.5 border-2 border-white dark:border-slate-900 rounded-full shadow-sm animate-pulse bg-blue-500",N==="compact"?"w-2.5 h-2.5":"w-3.5 h-3.5")}),o&&e.jsx("div",{className:"absolute -bottom-1 -right-1 bg-rose-500 text-white rounded-full p-0.5 border-2 border-white dark:border-slate-900 shadow-sm",children:e.jsx(ba,{className:"w-2.5 h-2.5"})})]}),e.jsxs("div",{className:"min-w-0 flex flex-col",children:[e.jsx("span",{className:M("text-slate-900 dark:text-white truncate leading-tight group-hover:text-primary transition-colors",N==="compact"?"text-[13px] font-semibold":"text-sm font-black"),children:C.name||"Sin Nombre"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx("span",{className:M("text-[10px] text-slate-400 tracking-tight uppercase",N==="compact"?"font-medium":"font-bold"),children:C.email?C.email:C.phone}),o&&e.jsx(me,{className:"h-4 px-1.5 py-0 text-[8px] bg-rose-500/10 text-rose-500 border-none uppercase font-black",children:"Bloqueado"})]})]})]})}),b.map(j=>e.jsx(Bs,{className:N==="compact"?"py-1.5":"py-4",children:X(C,j)},j)),e.jsx(Bs,{className:M("text-right pr-6",N==="compact"?"py-1.5":"py-4"),onClick:j=>j.stopPropagation(),children:e.jsx("div",{className:"flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity translate-x-4 group-hover:translate-x-0 duration-300",children:e.jsxs(Ws,{children:[e.jsx(Ks,{asChild:!0,children:e.jsx(L,{variant:"ghost",size:"icon",className:"h-8 w-8 rounded-full hover:bg-slate-200/50",children:e.jsx(Ar,{className:"h-4 w-4 text-slate-400"})})}),e.jsxs(Qs,{align:"end",className:"w-52 p-2 rounded-2xl shadow-2xl border-slate-100",children:[e.jsx(Gs,{className:"text-[10px] uppercase font-black tracking-widest text-slate-400 p-2",children:"Opciones"}),e.jsx(ja,{className:"bg-slate-50"}),e.jsxs(Qe,{onClick:()=>f(C),className:"rounded-xl p-2.5 font-bold text-sm",children:[e.jsx(St,{className:"mr-3 h-4 w-4 text-slate-400"})," Ver Detalles"]}),e.jsxs(Qe,{onClick:()=>u(C),className:"rounded-xl p-2.5 font-bold text-sm",children:[e.jsx(Te,{className:"mr-3 h-4 w-4 text-slate-400"})," Iniciar Chat"]}),e.jsxs(Qe,{onClick:()=>navigator.clipboard.writeText(C.phone),className:"rounded-xl p-2.5 font-bold text-sm",children:[e.jsx(ks,{className:"mr-3 h-4 w-4 text-slate-400"})," Copiar Teléfono"]}),g&&e.jsxs(Qe,{onClick:()=>g(C),className:"rounded-xl p-2.5 font-bold text-sm text-amber-600 focus:text-amber-700 focus:bg-amber-50",children:[e.jsx(_r,{className:"mr-3 h-4 w-4"})," Fusionar Contacto"]})]})]})})})]},C.id)})})]})}),x&&e.jsxs("div",{className:"px-8 py-4 bg-[#F8FAFC] dark:bg-slate-900/50 border-t border-slate-100 dark:border-slate-800 flex items-center justify-between",children:[e.jsx("div",{children:e.jsxs("span",{className:"text-[11px] font-black text-slate-400 uppercase tracking-widest",children:["PÁGINA ",e.jsx("span",{className:"text-slate-600 dark:text-slate-200",children:c})," DE ",e.jsx("span",{className:"text-slate-600 dark:text-slate-200",children:le||1})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(L,{variant:"outline",size:"sm",disabled:c<=1,onClick:()=>x(c-1),className:"h-9 px-4 rounded-xl font-bold text-[12px] text-slate-600 border-slate-200 bg-white hover:bg-slate-50 transition-all shadow-sm",children:"Anterior"}),e.jsx(L,{variant:"outline",size:"sm",disabled:c>=le,onClick:()=>x(c+1),className:"h-9 px-4 rounded-xl font-bold text-[12px] text-slate-600 border-slate-200 bg-white hover:bg-slate-50 transition-all shadow-sm",children:"Siguiente"})]})]}),e.jsx(Pn,{isOpen:w.open,onClose:()=>E(C=>({...C,open:!1})),data:w.data,title:w.title})]})}),$n=({className:s})=>e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("line",{x1:"17",y1:"8",x2:"22",y2:"13"}),e.jsx("line",{x1:"22",y1:"8",x2:"17",y2:"13"})]}),Un=s=>s.disconnectedFromMetaAt||s.deactivatedAt||!s.isActive?{label:"Inactivo",colorClass:"bg-slate-100 text-slate-500 border-slate-200 dark:bg-slate-800 dark:text-slate-400 dark:border-slate-700",showDot:!1,isActive:!1}:{label:"ACTIVO",colorClass:"bg-emerald-50 text-emerald-700 border-none dark:bg-emerald-500/10 dark:text-emerald-400",showDot:!0,isActive:!0},Vn=s=>{switch(s?.toLowerCase()){case"whatsapp":return{icon:e.jsx(qr,{className:"w-4 h-4 text-[#25D366]"}),bg:"bg-emerald-50 dark:bg-emerald-500/10"};case"web":return{icon:e.jsx(ms,{className:"w-4 h-4 text-violet-500"}),bg:"bg-violet-50 dark:bg-violet-500/10"};default:return{icon:e.jsx(Os,{className:"w-4 h-4 text-slate-500"}),bg:"bg-slate-100 dark:bg-slate-800"}}};function Hn({value:s,onChange:l,allowAllOption:n=!0,disableInactive:i=!1,showSelectionIndicator:r=!0,filterTypes:f,compact:u=!1}){const{channels:g,fetchChannels:b}=Na(),[h,c]=m.useState(!1);m.useEffect(()=>{g.length===0&&b()},[b,g.length]),m.useEffect(()=>{h&&b()},[h,b]);const I=m.useMemo(()=>[...f?.length?g.filter(N=>f.includes(N.type)):g].sort((N,y)=>N.isActive&&!y.isActive?-1:!N.isActive&&y.isActive?1:N.name.localeCompare(y.name)),[g,f]),T=I.find(x=>x.id===s);return e.jsxs(Ft,{open:h,onOpenChange:c,children:[e.jsx(zt,{asChild:!0,children:e.jsxs(L,{variant:"outline",role:"combobox","aria-expanded":h,className:M("w-full justify-between rounded-xl border border-slate-200 bg-white px-4 text-sm focus:ring-2 focus:ring-primary/20 text-slate-700 shadow-sm transition-all hover:bg-slate-50 dark:bg-slate-900 dark:border-slate-800 dark:text-slate-300 font-normal",u?"h-9 text-xs":"h-12"),children:[e.jsxs("div",{className:"flex items-center gap-2 truncate",children:[e.jsx(Os,{className:"w-4 h-4 text-slate-400 shrink-0"}),T?e.jsxs("span",{className:"truncate font-medium",children:[T.name," (",T.type,")"]}):e.jsx("span",{className:n?"text-slate-500":"text-slate-400",children:n?"Todos los canales":"Selecciona un canal..."})]}),e.jsx(Qr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(qt,{className:"w-[var(--radix-popover-trigger-width)] p-0 rounded-xl",align:"start",children:e.jsxs(Ur,{children:[e.jsx(Vr,{placeholder:"Buscar canal...",className:"h-11"}),e.jsxs(Hr,{children:[e.jsx(Wr,{children:"No se encontraron canales."}),e.jsxs(Kr,{children:[n&&e.jsx(ra,{value:"all_channels_special_value",onSelect:()=>{l(void 0),c(!1)},className:M("py-2.5 cursor-pointer mb-2 rounded-lg transition-colors font-medium text-sm flex items-center justify-center",!s||s==="all"||s===""?"bg-slate-100 text-slate-900 dark:bg-slate-800 dark:text-white":"hover:bg-slate-50 text-slate-600 dark:hover:bg-slate-800/50 dark:text-slate-400"),children:"Todos los canales"}),I.map(x=>{const N=Un(x),y=Vn(x.type),w=i&&!N.isActive;return e.jsx(ra,{value:`${x.name} ${x.type}`,disabled:w,onSelect:()=>{w||(l(x.id===s?void 0:x.id),c(!1))},className:M("flex items-center p-2.5 transition-all duration-200 border-b border-slate-50/50 last:border-0",w?"opacity-50 grayscale cursor-not-allowed":"cursor-pointer hover:bg-slate-50"),children:e.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[r&&e.jsx("div",{className:M("w-4 h-4 rounded-full border flex flex-shrink-0 items-center justify-center transition-all",s===x.id?"border-primary":"border-slate-300 dark:border-slate-600"),children:s===x.id&&e.jsx("div",{className:"w-2.5 h-2.5 bg-primary rounded-full"})}),e.jsx("div",{className:M("w-8 h-8 rounded-lg flex items-center justify-center shrink-0",y.bg),children:y.icon}),e.jsxs("div",{className:"flex flex-col flex-1 min-w-0 justify-center",children:[e.jsx("span",{className:M("text-[13px] font-semibold text-slate-900 dark:text-white truncate leading-tight",!N.isActive&&"opacity-70"),children:x.name}),e.jsx("span",{className:"text-[9px] font-bold text-slate-400 py-0 px-1.5 bg-slate-100 dark:bg-slate-800 rounded w-fit uppercase tracking-tight mt-0.5 inline-block",children:x.type})]}),e.jsxs("div",{className:M("flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-tight shrink-0",N.colorClass),children:[N.showDot&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500"}),N.label]})]})},x.id)})]})]})]})})]})}const Wn=s=>s.credentials?.phoneNumber||s.config?.phoneNumber||s.providerId||"",Kn=s=>{switch(s?.toUpperCase()){case"WHATSAPP":return e.jsx(Te,{className:"h-4 w-4 text-emerald-500"});case"EMAIL":return e.jsx(Se,{className:"h-4 w-4 text-amber-500"});case"INSTAGRAM":return e.jsx(Bt,{className:"h-4 w-4 text-pink-500"});default:return e.jsx(ms,{className:"h-4 w-4 text-blue-500"})}},Qn=({open:s,onOpenChange:l,onAdd:n})=>{const{channels:i}=Na(),[r,f]=m.useState(void 0),[u,g]=m.useState(!1),b=m.useMemo(()=>i.find(T=>T.id===r),[i,r]),h=b?.type?.toUpperCase()||"",c=b?Wn(b):"";m.useEffect(()=>{s&&f(void 0)},[s]);const I=async()=>{if(!(!r||!c||!h)){g(!0);try{await n(h,c,r),f(void 0),l(!1)}finally{g(!1)}}};return e.jsx(es,{open:s,onOpenChange:l,children:e.jsxs(ss,{className:"sm:max-w-[480px]",children:[e.jsxs(ts,{children:[e.jsx(as,{children:"Vincular Nueva Cuenta"}),e.jsx(gs,{children:"Asocia una identidad adicional a este contacto para unificar sus canales de comunicación."})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs(Ge,{className:"bg-primary/5 border-primary/20",children:[e.jsx(mt,{className:"h-4 w-4 text-primary"}),e.jsx(Xs,{className:"text-primary font-semibold",children:"Nota informativa"}),e.jsx(Je,{className:"text-primary/80 text-xs",children:"Al vincular una cuenta, el sistema reconocerá automáticamente a este cliente si escribe desde el canal seleccionado, permitiendo mantener un historial unificado."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ze,{children:"Conexión"}),e.jsx(Hn,{value:r,onChange:T=>f(T),allowAllOption:!1,disableInactive:!0,showSelectionIndicator:!0})]}),b&&c&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ze,{children:"Número de la conexión"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute left-3 top-3 opacity-50",children:Kn(h)}),e.jsx("div",{className:"absolute right-3 top-3 opacity-40",children:e.jsx(va,{className:"h-4 w-4"})}),e.jsx(He,{value:c,readOnly:!0,disabled:!0,className:"pl-10 pr-10 bg-muted/50 cursor-not-allowed font-mono"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"El número se obtiene automáticamente de la conexión seleccionada."})]})]})]}),e.jsxs(Ls,{children:[e.jsx(L,{variant:"secondary",onClick:()=>l(!1),disabled:u,children:"Cancelar"}),e.jsxs(L,{onClick:I,disabled:u||!r||!c,children:[u?e.jsx(ke,{className:"h-4 w-4 animate-spin mr-2"}):null,"Vincular Cuenta"]})]})]})})},da=s=>!["RESOLVED","ARCHIVED"].includes(s),Gn=s=>{switch(s){case"WAITING_ASSIGNMENT":return"En espera";case"IN_PROGRESS_AI":return"Bot IA";case"IN_PROGRESS_HUMAN":return"Agente";case"RESOLVED":return"Resuelto";case"ARCHIVED":return"Archivado";default:return s}},Jn=s=>{switch(s){case"WAITING_ASSIGNMENT":return"bg-amber-100 text-amber-700 border-amber-200";case"IN_PROGRESS_AI":return"bg-purple-100 text-purple-700 border-purple-200";case"IN_PROGRESS_HUMAN":return"bg-blue-100 text-blue-700 border-blue-200";case"RESOLVED":return"bg-green-100 text-green-700 border-green-200";default:return"bg-gray-100 text-gray-700 border-gray-200"}},Yn=s=>Sa(new Date(s),"HH:mm"),qa=m.memo(({message:s})=>{const l=s.senderType==="AGENT"||s.senderType==="BOT",n=s.senderType==="BOT";if(s.senderType==="SYSTEM"||s.contentType==="SYSTEM"){let r=s.metadata?.systemType||"default";if(!s.metadata?.systemType){const u=s.content||"";u.includes("bloqueado")||u.includes("blocked")||u.includes("Intento de envío")?r="error":u.includes("Advertencia")||u.includes("inactividad")||u.includes("Cierre")||u.includes("cerrado")?r="warning":(u.includes("📩")||u.includes("Respuesta automática"))&&(r="info")}const f={default:"text-gray-500 dark:text-gray-400 bg-gray-100/50 dark:bg-gray-800/50",info:"text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/30",success:"text-green-600 dark:text-green-400 bg-green-50 dark:bg-green-900/30",warning:"text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/30",error:"text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-900/30"};return e.jsx("div",{className:"flex justify-center my-2",children:e.jsx("span",{className:M("text-[10px] px-2.5 py-1 rounded-md font-medium max-w-[300px] truncate",f[r]),title:s.content,children:s.content})})}return e.jsx("div",{className:M("flex w-full mb-1 group",l?"justify-end":"justify-start"),children:e.jsxs("div",{className:M("flex flex-col max-w-[80%] min-w-[60px] relative transition-all",l?"items-end":"items-start"),children:[e.jsxs("div",{className:M("px-3 py-2 text-sm shadow-sm relative break-words whitespace-pre-wrap",l?"bg-primary text-primary-foreground rounded-2xl rounded-tr-none":"bg-white border border-gray-100 text-gray-800 rounded-2xl rounded-tl-none",s.content.length<5&&"text-center"),children:[s.contentType==="IMAGE"&&s.mediaUrl&&e.jsx("div",{className:"mb-1 rounded-lg overflow-hidden",children:e.jsx("img",{src:s.mediaUrl,alt:"Adjunto",className:"max-w-full h-auto object-cover",loading:"lazy"})}),s.content&&!(["IMAGE","VIDEO","AUDIO","DOCUMENT"].includes(s.contentType)&&(s.content.startsWith("http")||s.content.startsWith("gs://")))&&e.jsx("span",{className:M("leading-relaxed block",!l&&"text-gray-700"),children:s.content})]}),e.jsxs("div",{className:M("flex items-center gap-1 mt-0.5 text-[10px] text-muted-foreground/60 px-1 opacity-0 group-hover:opacity-100 transition-opacity select-none"),children:[n&&e.jsx(Za,{className:"h-3 w-3"}),l&&!n&&e.jsx(Ve,{className:"h-3 w-3"}),e.jsx("span",{children:Yn(s.createdAt)})]})]})})});qa.displayName="SimpleChatBubble";const Ba=m.memo(({contactId:s,className:l})=>{const n=Ya(),i=Rs(),[r,f]=m.useState(!1),[u,g]=m.useState([]),[b,h]=m.useState(null),[c,I]=m.useState([]),[T,x]=m.useState(!1),[N,y]=m.useState(!1),w=m.useMemo(()=>u.some(t=>da(t.status)),[u]),E=m.useRef(null),H=m.useCallback(async()=>{if(s){f(!0);try{const t=await Be.getContactTickets(s),a=Array.isArray(t)?t:Array.isArray(t?.data)?t.data:[];g(a),a.length>0&&h(a[0].id)}catch(t){console.error("Error loading tickets:",t)}finally{f(!1)}}},[s]),Z=m.useCallback(async t=>{if(t){x(!0);try{const o=((await Be.getMessages(t)).data||[]).sort((j,v)=>{const F=new Date(j.channelTimestamp||j.createdAt).getTime(),Y=new Date(v.channelTimestamp||v.createdAt).getTime();return F-Y});I(o)}catch(a){console.error("Error loading messages:",a),I([])}finally{x(!1)}}},[]);m.useEffect(()=>{!T&&c.length>0&&setTimeout(()=>{E.current?.scrollIntoView({behavior:"auto"})},100)},[c,T,b]),m.useEffect(()=>{H()},[H]),m.useEffect(()=>{b&&Z(b)},[b,Z]);const X=u.find(t=>t.id===b),q=()=>{b&&n(`/bandeja?ticket=${b}`)},le=m.useCallback(async()=>{y(!0);try{const t=await Be.createTicketForContact(s);await H(),await i.invalidateQueries({queryKey:["inbox","conversations"]}),i.invalidateQueries({queryKey:["inbox","counts"]}),n(`/bandeja?ticket=${t.id}`)}catch(t){t?.response?.status===409?(D.error("Este contacto ya tiene un ticket abierto"),await H()):D.error("Error al crear el ticket")}finally{y(!1)}},[s,H,n,i]),C=m.useMemo(()=>{const t=[];let a=null,o=[];return c.forEach(j=>{const v=new Date(j.createdAt);!a||!Sn(a,v)?(o.length>0&&a&&t.push({date:a,showDate:!0,msgs:[...o]}),o=[j],a=v):o.push(j)}),o.length>0&&a&&t.push({date:a,showDate:!0,msgs:[...o]}),t},[c]);return!r&&u.length===0?e.jsxs("div",{className:M("flex flex-col items-center justify-center h-full text-center p-8 bg-muted/5",l),children:[e.jsx("div",{className:"w-12 h-12 bg-muted/50 rounded-full flex items-center justify-center mb-3",children:e.jsx(Te,{className:"w-6 h-6 text-muted-foreground/40"})}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Sin historial de conversaciones"}),e.jsxs(L,{size:"sm",onClick:le,disabled:N,className:"gap-1",children:[e.jsx(st,{className:"h-3.5 w-3.5"}),N?"Creando...":"Crear conversación"]})]}):r?e.jsxs("div",{className:"flex flex-col h-full gap-4 p-4",children:[e.jsx(we,{className:"h-10 w-full"}),e.jsx(we,{className:"h-full w-full rounded-xl"})]}):e.jsxs("div",{className:M("flex flex-col h-full bg-[#f8f9fa] dark:bg-background/50 overflow-hidden",l),children:[" ",e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-white dark:bg-card border-b shadow-sm z-10 shrink-0",children:[" ",e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Ticket"}),e.jsxs("div",{className:"flex items-center bg-muted/30 rounded-md border border-border/50",children:[e.jsx(L,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:!u.length||u.findIndex(t=>t.id===b)<=0,onClick:()=>{const t=u.findIndex(a=>a.id===b);t>0&&h(u[t-1].id)},children:e.jsx(Xa,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-xs font-mono px-1 min-w-[20px] text-center",children:u.findIndex(t=>t.id===b)+1}),e.jsx(L,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:!u.length||u.findIndex(t=>t.id===b)>=u.length-1,onClick:()=>{const t=u.findIndex(a=>a.id===b);t<u.length-1&&h(u[t+1].id)},children:e.jsx(ya,{className:"h-3 w-3"})})]})]}),X&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(me,{variant:"outline",className:M("text-[10px] px-2 h-5 font-normal border-0",Jn(X.status)),children:Gn(X.status)}),da(X.status)&&e.jsxs(L,{size:"sm",variant:"default",className:"h-6 text-[10px] px-2 gap-1 ml-1",onClick:q,children:["Responder",e.jsx(St,{className:"h-3 w-3 opacity-70"})]}),!w&&e.jsxs(L,{size:"sm",variant:"default",className:"h-6 text-[10px] px-2 gap-1 ml-1",onClick:le,disabled:N,children:[e.jsx(st,{className:"h-3 w-3"}),N?"Creando...":"Nuevo Ticket"]})]})]}),e.jsxs(Ye,{className:"flex-1 w-full h-px",children:[" ",e.jsxs("div",{className:"p-4 flex flex-col justify-end min-h-0 pb-6",children:[T?e.jsxs("div",{className:"space-y-6 pt-8 px-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(we,{className:"h-8 w-1/3 rounded-lg rounded-tl-none"}),e.jsx(we,{className:"h-8 w-1/2 rounded-lg rounded-tl-none"})]}),e.jsx("div",{className:"space-y-2 flex flex-col items-end",children:e.jsx(we,{className:"h-10 w-1/3 rounded-lg rounded-tr-none"})})]}):e.jsxs(e.Fragment,{children:[C.map(({date:t,showDate:a,msgs:o},j)=>e.jsxs("div",{className:"mb-4",children:[a&&e.jsx("div",{className:"flex justify-center mb-4 sticky top-0 py-2 z-10",children:e.jsx("span",{className:"text-[10px] font-medium text-muted-foreground bg-muted/50 backdrop-blur-sm px-3 py-0.5 rounded-full border border-border/40 shadow-sm",children:Sa(t,"d 'de' MMMM",{locale:rt})})}),e.jsx("div",{className:"space-y-0.5",children:o.map(v=>e.jsx(qa,{message:v},v.id))})]},`group-${j}`)),e.jsx("div",{ref:E})]}),!T&&c.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 opacity-50",children:[e.jsx(Te,{className:"h-12 w-12 text-muted-foreground mb-3 opacity-20"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Conversación vacía"})]})]})]})]})});Ba.displayName="ConversationHistory";const ws={label:"API",icon:er,color:"text-violet-600 dark:text-violet-400",bgColor:"bg-violet-100 dark:bg-violet-900/30",borderColor:"border-violet-300 dark:border-violet-800"},Pe={label:"WhatsApp",icon:Te,color:"text-emerald-600 dark:text-emerald-400",bgColor:"bg-emerald-100 dark:bg-emerald-900/30",borderColor:"border-emerald-300 dark:border-emerald-800"},It={label:"Email",icon:Se,color:"text-blue-600 dark:text-blue-400",bgColor:"bg-blue-100 dark:bg-blue-900/30",borderColor:"border-blue-300 dark:border-blue-800"},Ut={label:"Chat",icon:Os,color:"text-fuchsia-600 dark:text-fuchsia-400",bgColor:"bg-fuchsia-100 dark:bg-fuchsia-900/30",borderColor:"border-fuchsia-300 dark:border-fuchsia-800"},Ke={label:"Formulario",icon:dt,color:"text-orange-600 dark:text-orange-400",bgColor:"bg-orange-100 dark:bg-orange-900/30",borderColor:"border-orange-300 dark:border-orange-800"},ds={label:"Sistema",icon:Yr,color:"text-slate-600 dark:text-slate-400",bgColor:"bg-slate-100 dark:bg-slate-800",borderColor:"border-slate-300 dark:border-slate-700"},Xn={api:ws,whatsapp:Pe,email:It,chat:Ut,formulario:Ke,sistema:ds,event:ws,events:ws,integration:ws,ticket:Pe,tickets:Pe,conversation:Pe,conversations:Pe,inbox:Pe,message:Pe,messages:Pe,correo:It,form:Ke,forms:Ke,formularios:Ke,submission:Ke,form_submission:Ke,system:ds,lifecycle:ds,internal:ds,nubot:ds},Zn=new Set([Pe,It,Ut]),el={event:ws,conversation:Ut,form:Ke},sl={whatsapp:{label:"WhatsApp",icon:Te},email:{label:"Email",icon:Se},gmail:{label:"Email",icon:Se},outlook:{label:"Email",icon:Se},instagram:{label:"Instagram",icon:Bt},messenger:{label:"Messenger",icon:Te},facebook:{label:"Facebook",icon:Xr},webchat:{label:"Web",icon:ms},web:{label:"Web",icon:ms},widget:{label:"Web",icon:ms}},Vt=s=>{const l=s.replace(/[_.-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").trim();return l?l.charAt(0).toUpperCase()+l.slice(1).toLowerCase():""},tl=s=>{const l=typeof s?.channelType=="string"?s.channelType:typeof s?.channel=="string"?s.channel:null;return l?l.toLowerCase().trim():null},al=s=>{const l=String(s.source||"").toLowerCase().trim(),n=Xn[l];if(n&&Zn.has(n)){const f=tl(s.meta),u=f?sl[f]:void 0;if(u)return{...n,...u}}if(n)return n;const r=(typeof s.kind=="string"?el[s.kind.toLowerCase()]:void 0)??ds;return{...r,label:Vt(l)||r.label}},rl={event:"los eventos de tus integraciones",conversation:"las conversaciones",form:"las respuestas de formulario"},nl=s=>s.map(l=>rl[l.toLowerCase().trim()]??Vt(l)??"").filter(Boolean).join(", "),ca={lifecycle_stage_changed:Ms,contact_created:Ds,lead_created:Ds,ticket_opened:Te,ticket_created:Te,conversation_started:Te,ticket_closed:fs,conversation_closed:fs,form_submission:dt,form_submitted:dt},ll=[[/(purchase|order|compra|pedido|venta|checkout|cart|carrito)/i,sr],[/(paid|pago|payment|cobro)/i,fs],[/(stage|etapa|lifecycle|upgrade)/i,Ms],[/(view|visit|visita|page|pagina|página)/i,Et],[/(click|clic|tap)/i,Tr],[/(mail|email|correo|newsletter)/i,Se],[/(form|formulario|survey|encuesta|lead)/i,dt],[/(abandon|abandonad|fail|error|cancel)/i,yt],[/(trigger|automation|workflow|automatiz)/i,wa]],il=(s,l)=>{const n=String(s.type||"").toLowerCase();if(ca[n])return ca[n];for(const[i,r]of ll)if(i.test(n))return r;return l.icon},ol={from:"De",to:"A",fromLabel:"De",toLabel:"A",trigger:"Disparo",status:"Estado",channel:"Canal",channelType:"Canal",form:"Formulario",formName:"Formulario",stage:"Etapa",agent:"Agente",assignee:"Responsable",resolution:"Resolución",messages:"Mensajes",messageCount:"Mensajes",unread:"Sin leer",unreadCount:"Sin leer",fields:"Campos",amount:"Monto",total:"Total",currency:"Moneda",value:"Valor",campaign:"Campaña"},dl=/(^|_)(id|ids|uuid|url|href|link|token|secret|raw|payload|body|hash)$/i,cl=s=>{if(typeof s=="boolean")return s?"Sí":"No";if(typeof s=="number")return Number.isFinite(s)?String(s):null;if(typeof s=="string"){const l=s.trim();return l?l.length>42?`${l.slice(0,41)}…`:l:null}return null},ma=(s,l=3)=>{if(!s)return[];const n=[];for(const[i,r]of Object.entries(s)){if(n.length>=l)break;if(dl.test(i)||/Id$/.test(i))continue;const f=cl(r);f!==null&&n.push({key:i,label:ol[i]??Vt(i),value:f})}return n},ml=s=>s?Ne(s,{style:"date-numeric"}):"sin-fecha",ul=s=>{const l=Ne(new Date,{style:"date-numeric"}),n=Ne(new Date(Date.now()-864e5),{style:"date-numeric"}),i=[];for(const r of s){const f=ml(r.occurredAt),u=i[i.length-1];if(u&&u.key===f){u.items.push(r);continue}let g;f==="sin-fecha"?g="Sin fecha":f===l?g="Hoy":f===n?g="Ayer":g=Ne(r.occurredAt,{style:"date-long"}),i.push({key:f,label:g,items:[r]})}return i},xl=20,hl=25,$a=s=>["contacts","activity",s];function pl(s,l=!0){return Jr({queryKey:$a(s),queryFn:({pageParam:n})=>se.getContactActivity(s,{limit:xl,cursor:n}),initialPageParam:null,getNextPageParam:(n,i,r)=>{if(n.hasMore&&n.nextCursor&&!(i.length>=hl)&&n.nextCursor!==r)return n.nextCursor},enabled:!!s&&l,staleTime:30*1e3})}const Ua=m.memo(({item:s,isLast:l})=>{const n=al(s),i=il(s,n),r=typeof s.detail=="string"?s.detail:null,f=typeof s.detail=="string"?[]:ma(s.detail,3),u=ma(s.meta,f.length>0?2:3),g=[...f,...u].slice(0,4);return e.jsxs("div",{className:"flex gap-3","data-testid":"activity-item",children:[e.jsxs("div",{className:"flex flex-col items-center shrink-0",children:[e.jsx("div",{className:M("relative z-10 w-7 h-7 rounded-full flex items-center justify-center border-2 shadow-sm",n.bgColor,n.borderColor),children:e.jsx(i,{className:M("w-3.5 h-3.5",n.color)})}),!l&&e.jsx("div",{className:"w-0.5 flex-1 bg-border min-h-[16px]"})]}),e.jsxs("div",{className:"flex-1 min-w-0 pb-4",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-foreground leading-snug flex-1 min-w-0 break-words",children:s.title}),e.jsx(me,{variant:"outline",className:M("shrink-0 h-5 px-1.5 text-[9px] font-semibold uppercase tracking-wide border-0",n.bgColor,n.color),children:n.label})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[e.jsx(at,{className:"w-3 h-3 text-muted-foreground/70 shrink-0"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",title:s.occurredAt?Ne(s.occurredAt,{style:"full"}):void 0,children:s.occurredAt?Er(s.occurredAt,"short"):"Fecha desconocida"})]}),r&&e.jsx("p",{className:"mt-1.5 text-[12px] text-muted-foreground leading-snug line-clamp-3 break-words",children:r}),g.length>0&&e.jsx("div",{className:"flex flex-wrap items-center gap-1 mt-1.5",children:g.map(b=>e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-muted/70 dark:bg-muted/40 text-muted-foreground max-w-full truncate",children:[e.jsxs("span",{className:"opacity-60",children:[b.label,":"]})," ",b.value]},b.key))})]})]})});Ua.displayName="ActivityRow";const fl=()=>e.jsx("div",{className:"p-4 space-y-4","data-testid":"activity-skeleton",children:Array.from({length:5}).map((s,l)=>e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center shrink-0",children:[e.jsx(we,{className:"w-7 h-7 rounded-full"}),l<4&&e.jsx("div",{className:"w-0.5 flex-1 bg-border/50 min-h-[16px]"})]}),e.jsxs("div",{className:"flex-1 space-y-2 pb-4",children:[e.jsx(we,{className:"h-4 w-2/3 rounded"}),e.jsx(we,{className:"h-3 w-1/3 rounded"})]})]},l))}),Va=m.memo(({contactId:s,className:l})=>{const{data:n,isLoading:i,isError:r,error:f,refetch:u,isFetching:g,fetchNextPage:b,hasNextPage:h,isFetchingNextPage:c}=pl(s),I=m.useMemo(()=>[...(n?.pages??[]).flatMap(E=>E.data)].sort((E,H)=>{const Z=E.occurredAt?Date.parse(E.occurredAt):NaN,X=H.occurredAt?Date.parse(H.occurredAt):NaN;return Number.isNaN(Z)&&Number.isNaN(X)?0:Number.isNaN(Z)?1:Number.isNaN(X)?-1:X-Z}),[n]),T=m.useMemo(()=>ul(I),[I]),x=m.useMemo(()=>{const w=new Set;for(const E of n?.pages??[])for(const H of E.unavailable)w.add(H);return Array.from(w)},[n]),N=m.useCallback(()=>{u()},[u]),y=m.useCallback(()=>{b()},[b]);return r&&I.length===0?e.jsxs("div",{className:M("flex flex-col items-center justify-center h-full text-center p-8 bg-muted/5",l),children:[e.jsx("div",{className:"w-12 h-12 bg-destructive/10 rounded-full flex items-center justify-center mb-3",children:e.jsx(yt,{className:"w-6 h-6 text-destructive/70"})}),e.jsx("p",{className:"text-sm font-medium text-foreground/80",children:"No pudimos cargar la actividad"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5 max-w-[280px] leading-relaxed",children:f?.message?`El servidor respondió: ${f.message}`:"Revisa tu conexión e inténtalo de nuevo."}),e.jsxs(L,{size:"sm",variant:"outline",className:"mt-4 gap-1.5",onClick:N,children:[e.jsx(Js,{className:"h-3.5 w-3.5"}),"Reintentar"]})]}):i?e.jsx("div",{className:M("flex flex-col h-full bg-muted/5 overflow-hidden",l),children:e.jsx(fl,{})}):I.length===0&&x.length===0?e.jsxs("div",{className:M("flex flex-col items-center justify-center h-full text-center p-8 bg-muted/5",l),children:[e.jsx("div",{className:"w-12 h-12 bg-muted/50 rounded-full flex items-center justify-center mb-3",children:e.jsx(tt,{className:"w-6 h-6 text-muted-foreground/40"})}),e.jsx("p",{className:"text-sm font-medium text-foreground/80",children:"Todavía no hay actividad"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5 max-w-[290px] leading-relaxed",children:"Aquí aparecerán, en orden cronológico, los eventos que envíen tus integraciones, las conversaciones de este contacto y las respuestas que deje en tus formularios."}),e.jsxs(L,{size:"sm",variant:"ghost",className:"mt-4 gap-1.5 text-xs",onClick:N,children:[e.jsx(Js,{className:M("h-3.5 w-3.5",g&&"animate-spin")}),"Actualizar"]})]}):e.jsxs("div",{className:M("flex flex-col h-full bg-muted/5 dark:bg-background/50 overflow-hidden",l),children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-white dark:bg-card border-b shadow-sm z-10 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Actividad"}),e.jsxs(me,{variant:"secondary",className:"h-5 px-1.5 text-[10px] font-mono font-normal",children:[I.length,h?"+":""]})]}),e.jsx(L,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:N,disabled:g,title:"Actualizar actividad","aria-label":"Actualizar actividad",children:e.jsx(Js,{className:M("h-3.5 w-3.5 text-muted-foreground",g&&"animate-spin")})})]}),(x.length>0||r)&&e.jsxs("div",{className:"flex items-start gap-2 px-4 py-2 bg-amber-50 dark:bg-amber-900/15 border-b border-amber-200 dark:border-amber-900/40 shrink-0",role:"status","data-testid":"activity-degraded-warning",children:[e.jsx(yt,{className:"h-3.5 w-3.5 text-amber-600 dark:text-amber-400 mt-[1px] shrink-0"}),e.jsx("p",{className:"text-[11px] leading-snug text-amber-700 dark:text-amber-300",children:x.length>0?`Esta línea de tiempo está incompleta: no se pudo leer ${nl(x)}.`:"No se pudo actualizar la actividad; estás viendo datos anteriores."})]}),e.jsx(Ye,{className:"flex-1 w-full h-px",children:e.jsxs("div",{className:"p-4",children:[T.map((w,E)=>e.jsxs("div",{className:M(E>0&&"mt-2"),children:[e.jsx("div",{className:"flex justify-center mb-3",children:e.jsx("span",{className:"text-[10px] font-medium text-muted-foreground bg-muted/50 backdrop-blur-sm px-3 py-0.5 rounded-full border border-border/40 shadow-sm",children:w.label})}),w.items.map((H,Z)=>e.jsx(Ua,{item:H,isLast:E===T.length-1&&Z===w.items.length-1},H.id))]},w.key)),h&&e.jsx("div",{className:"flex justify-center pt-1 pb-2",children:e.jsx(L,{variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs",onClick:y,disabled:c,children:c?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"h-3.5 w-3.5 animate-spin"}),"Cargando…"]}):"Cargar más"})})]})})]})});Va.displayName="ContactActivityTab";const gl={all:["lifecycle-stages"]},bl=[{level:1,key:"subscriber",label:"Suscriptor"},{level:2,key:"interested",label:"Interesado"},{level:3,key:"evaluating",label:"Evaluando"},{level:4,key:"purchase_attempt",label:"Intento de compra"},{level:5,key:"customer",label:"Cliente"}];function jl(){return rs({queryKey:gl.all,queryFn:()=>se.getLifecycleStages(),staleTime:1/0,gcTime:1/0,retry:1})}const ct=s=>typeof s=="object"&&s!==null?s:null,vl=s=>{if(typeof s=="number"&&Number.isFinite(s))return Math.trunc(s);if(typeof s=="string"&&s.trim()!==""){const l=Number(s);if(Number.isFinite(l))return Math.trunc(l)}return null};function Nl(s){const l=ct(s);if(!l)return null;const n=ct(l.lifecycleStage);return vl(n?.level??l.lifecycleStageLevel??l.lifecycle_stage_level)}function yl(s){const l=ct(s);if(!l)return null;const i=ct(l.lifecycleStage)?.updatedAt??l.lifecycleStageUpdatedAt??l.lifecycle_stage_updated_at;return typeof i=="string"&&i.trim()!==""?i:null}const jt="none",ua=500,wl={1:"bg-slate-500/10 text-slate-600 dark:text-slate-300 border-slate-500/25",2:"bg-sky-500/10 text-sky-700 dark:text-sky-300 border-sky-500/25",3:"bg-violet-500/10 text-violet-700 dark:text-violet-300 border-violet-500/25",4:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/25",5:"bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/25"},kl=s=>{const l=s?.response,n=l?.status;if(n===403)return"No tienes permiso para cambiar la etapa. Solo el propietario o un administrador puede hacerlo.";const i=l?.data?.message;return typeof i=="string"&&i.trim()!==""?i:Array.isArray(i)&&typeof i[0]=="string"?i[0]:n===404?"No se encontró el contacto o el servidor todavía no admite la corrección de etapa.":"No se pudo guardar la etapa. Vuelve a intentarlo."},Ha=m.memo(({contactId:s,level:l,updatedAt:n,canEdit:i,isLoading:r=!1,onUpdated:f})=>{const[u,g]=m.useState(void 0),[b,h]=m.useState(""),[c,I]=m.useState(null),T=Rs(),x=Ca(),N=jl(),y=m.useMemo(()=>[...N.data?.length?N.data:bl].sort((o,j)=>o.level-j.level),[N.data]),w=m.useCallback(a=>a===null?null:y.find(o=>o.level===a)?.label??`Nivel ${a}`,[y]),E=w(l),H=u===void 0?null:w(u),Z=u!==void 0&&l!==null&&(u===null||u<l),X=m.useCallback(()=>{g(void 0),h(""),I(null)},[]),q=Zr({mutationFn:a=>se.setContactLifecycleStage(s,a),onSuccess:(a,o)=>{const j=a?.level!==void 0?a.level:o.level;x(s),T.invalidateQueries({queryKey:$a(s)}),a?.changed===!1?D.info("La etapa ya estaba en ese nivel."):j==null?D.success("Etapa borrada. El cambio queda en su actividad."):D.success(`Etapa corregida a "${w(j)}". El cambio queda en su actividad.`),f?.(j??null),X()},onError:a=>{const o=kl(a);I(o),D.error(o)}}),le=m.useCallback(a=>{const o=a===jt?null:Number(a);o!==l&&(I(null),h(""),g(o))},[l]),C=m.useCallback(()=>{u===void 0||q.isPending||(I(null),q.mutate({level:u,reason:b}))},[q,u,b]),t=l===null?jt:String(l);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between px-1",children:[e.jsx("h3",{className:"text-sm font-semibold tracking-tight text-foreground/90 uppercase text-[11px]",children:"Etapa del Ciclo de Vida"}),e.jsx(cs,{children:e.jsxs(Cs,{children:[e.jsx(Ss,{asChild:!0,children:e.jsx("span",{className:"text-muted-foreground/70 hover:text-muted-foreground transition-colors","aria-label":"Cómo funciona la etapa del ciclo de vida",children:e.jsx(mt,{className:"h-3.5 w-3.5"})})}),e.jsxs(Es,{className:"max-w-[260px] text-xs leading-snug",children:["La etapa avanza sola con los eventos que recibe esta persona y nunca retrocede por su cuenta.",i?" Desde aquí puedes corregirla a mano si quedó mal.":""]})]})})]}),e.jsxs("div",{className:"p-4 rounded-xl border bg-card/50 shadow-sm hover:shadow-md transition-shadow duration-300 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-[24px_1fr] items-start gap-2",children:[e.jsx(Ms,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground uppercase mb-1",children:"Etapa actual"}),r?e.jsx(we,{className:"h-6 w-32 rounded-full"}):l!==null?e.jsx(me,{variant:"outline",className:M("text-xs font-medium h-6 py-0.5 border",wl[l]),children:E}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sin etapa asignada"}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1.5 leading-snug",children:n?`Cambió el ${Ne(n,{style:"short"})}`:"Avanza sola cuando llegan eventos de esta persona."})]})]}),i&&e.jsxs("div",{className:"pt-3 border-t border-border/50 space-y-1.5",children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground uppercase",children:"Corregir etapa"}),e.jsxs(nt,{value:t,onValueChange:le,disabled:r||q.isPending,children:[e.jsx(lt,{size:"sm",className:"w-full","aria-label":"Corregir la etapa del ciclo de vida",children:e.jsx(it,{placeholder:"Elegir etapa"})}),e.jsxs(ot,{children:[e.jsx(Fe,{value:jt,children:"Sin etapa"}),y.map(a=>e.jsxs(Fe,{value:String(a.level),children:[a.level,". ",a.label]},a.level))]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:"Úsalo solo para arreglar un error: el cambio queda registrado en la pestaña Actividad."})]})]}),e.jsx(Ea,{open:u!==void 0,onOpenChange:a=>{!a&&!q.isPending&&X()},children:e.jsxs(Aa,{children:[e.jsxs(_a,{children:[e.jsxs(Ta,{className:"flex items-center gap-2",children:[Z?e.jsx(ve,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"}):e.jsx(Ms,{className:"h-5 w-5 text-primary"}),Z?u===null?"¿Quitarle la etapa a esta persona?":"¿Bajar la etapa de esta persona?":"¿Cambiar la etapa?"]}),e.jsx(Ia,{className:"space-y-3",asChild:!0,children:e.jsxs("div",{children:[e.jsxs("p",{children:["Pasará de"," ",e.jsx("strong",{children:E??"sin etapa"})," ","a"," ",e.jsx("strong",{children:H??"sin etapa"}),"."]}),Z&&e.jsx("div",{className:"rounded-lg border border-amber-300/60 dark:border-amber-500/30 bg-amber-50 dark:bg-amber-500/10 px-3 py-2 text-[12px] leading-snug text-amber-700 dark:text-amber-300",children:"Normalmente la etapa solo sube sola, a medida que llegan los eventos de esta persona. Bajarla o quitarla es una corrección manual y quedará registrada en su historia."})]})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ze,{htmlFor:"lifecycle-stage-reason",className:"text-xs",children:"Motivo (opcional)"}),e.jsx(sn,{id:"lifecycle-stage-reason",value:b,onChange:a=>h(a.target.value),maxLength:ua,disabled:q.isPending,placeholder:"Ej.: el evento de newsletter estaba mapeado a Cliente por error.",className:"min-h-[72px] text-sm"}),e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:"Es lo que leerá dentro de tres meses quien vea este cambio en su actividad."}),b.length>0&&e.jsxs("span",{className:"text-[11px] text-muted-foreground tabular-nums shrink-0",children:[b.length,"/",ua]})]})]}),c&&e.jsx(Ge,{variant:"destructive",className:"py-2",children:e.jsx(Je,{className:"text-[12px] leading-snug",children:c})}),e.jsxs(Da,{children:[e.jsx(Ma,{disabled:q.isPending,children:"Cancelar"}),e.jsx(L,{onClick:C,disabled:q.isPending,className:M(Z&&"bg-amber-600 hover:bg-amber-700 text-white dark:bg-amber-600 dark:hover:bg-amber-700"),children:q.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ke,{className:"h-4 w-4 mr-2 animate-spin"}),"Guardando..."]}):"Guardar cambio"})]})]})})]})});Ha.displayName="ContactLifecycleStage";const Cl=()=>["inbox","metadata-schemas","first-active","with-system"];function Sl(s=!0){return rs({queryKey:Cl(),queryFn:async()=>{const l=await Ra.listSchemas({entityType:"contact",includeSystem:!0});return l.length>0?l[0]:null},enabled:s,staleTime:600*1e3,gcTime:1800*1e3})}const El={profile:"Perfil de Contacto",conversations:"Historial de Conversaciones",activity:"Actividad del Contacto"},Wa=m.memo(({contact:s,open:l,onOpenChange:n,onContactUpdated:i,initialTab:r})=>{const f=Ir(l?s?.id:void 0),u=Dr(),g=Mr(),b=Ca(),h=m.useCallback(()=>{s?.id&&b(s.id)},[s?.id,b]),c=f.data??s??null,I=f.isLoading,T=Lr(),x=Rt(k=>k.fetchFolders);m.useEffect(()=>{l&&x()},[l,x]);const y=Sl(l).data??null,w=c?.tags||[],E=!!c?.isBlacklisted,[H,Z]=m.useState(r??"profile"),X=bs(k=>k.user),q=X?.role==="OWNER"||X?.role==="ADMIN",le=X?.role==="OWNER"||X?.role==="ADMIN",[C,t]=m.useState({personalInfo:!0,tags:!0,metadata:!0}),[a,o]=m.useState(!1),[j,v]=m.useState(!1),[F,Y]=m.useState(null),te=m.useCallback(async k=>{const B=s?.id;if(!B)return;const S=g(B)?.tags||[],P=S.some(K=>K.id===k.id);try{if(P){await Be.removeTag(B,k.id);const K=S.filter(R=>R.id!==k.id);u(B,R=>R&&{...R,tags:K}),i({...c,tags:K})}else{await Be.assignTag(B,k.id);const K=[...S,k];u(B,R=>R&&{...R,tags:K}),i({...c,tags:K})}}catch(K){console.error("Error toggling tag:",K),D.error("Error al actualizar etiqueta")}},[s?.id,g,u,c,i]),ae=m.useCallback(async(k,B)=>{const S=s?.id;try{const P=await Be.createTag({name:k,folderId:B});if(S){await Be.assignTag(S,P.id);const R=[...g(S)?.tags||[],P];u(S,U=>U&&{...U,tags:R}),c&&i({...c,tags:R})}await x(!0),D.success("Etiqueta creada")}catch(P){throw console.error("Error creating tag:",P),D.error("Error al crear etiqueta"),P}},[s?.id,g,u,c,i,x]),Q=m.useCallback(async(k,B)=>{try{await Be.createFolder({name:k,color:B}),await x(!0),D.success("Carpeta creada")}catch(S){throw console.error("Error creating folder:",S),D.error("Error al crear carpeta"),S}},[x]),re=m.useCallback(async k=>{const B=s?.id;if(B)try{const S=await se.updateContact(B,k);u(B,P=>P?{...P,...S}:S),i(S),D.success("Perfil actualizado correctamente")}catch(S){throw console.error("Error saving contact info:",S),D.error("Error al guardar información"),S}},[s?.id,u,i]),z=m.useCallback(async k=>{const B=s?.id;if(B)try{const S=await se.updateContact(B,{metadata:k});u(B,P=>P?{...P,...S}:S),i(S)}catch(S){throw console.error("Error saving metadata:",S),D.error("Error al guardar información"),S}},[s?.id,u,i]),ue=m.useCallback(async()=>{const k=s?.id;if(!k)return;const B=!!g(k)?.isBlacklisted;try{B?(await se.unblockContact(k),u(k,S=>S&&{...S,isBlacklisted:!1}),i({...c,isBlacklisted:!1}),D.success("Contacto desbloqueado globalmente")):(await se.blockContact(k,"Manual global block from panel"),u(k,S=>S&&{...S,isBlacklisted:!0}),i({...c,isBlacklisted:!0}),D.success("Contacto bloqueado globalmente (todas sus cuentas)")),h()}catch(S){console.error("Error toggling blacklist:",S),D.error("Error al actualizar bloqueo")}},[s?.id,g,u,c,i,h]),W=m.useCallback(async k=>{const B=c?.orgId;if(B)try{k.isBlacklisted?(await se.unblockIdentifier(B,k.identifierValue),D.success(`Cuenta ${k.type} desbloqueada`)):(await se.blockIdentifier(B,k.identifierValue,"Blocked from contact identities list"),D.success(`Cuenta ${k.type} bloqueada`)),h()}catch(S){console.error("Error toggling identity blacklist:",S),D.error("Error al actualizar bloqueo de cuenta")}},[c,h]),G=k=>{t(B=>({...B,[k]:!B[k]}))},O=(k,B)=>{navigator.clipboard.writeText(k),D.success(`${B} copiado`)};if(!s)return null;const ie=c?.name||c?.phone||"Sin nombre",oe=ie.split(" ").slice(0,2).map(k=>k[0]).join("").toUpperCase();return e.jsx(tr,{open:l,onOpenChange:n,children:e.jsxs(ar,{className:"w-full sm:w-[480px] p-0 flex flex-col gap-0 border-l shadow-2xl bg-background/95 backdrop-blur-sm",children:[e.jsxs(rr,{className:"sr-only",children:[e.jsx(nr,{children:"Detalle del contacto"}),e.jsx(lr,{children:"Información detallada y acciones disponibles para el contacto."})]}),e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b bg-muted/20",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsx("span",{className:"text-sm font-medium text-muted-foreground/80",children:El[H]})}),e.jsx("div",{className:"flex items-center gap-2"})]}),e.jsxs(Ot,{value:H,onValueChange:k=>Z(k),className:"flex-1 flex flex-col min-h-0",children:[e.jsx("div",{className:"px-6 border-b bg-background sticky top-0 z-10",children:e.jsxs(Pt,{className:"w-full h-auto p-0 bg-transparent gap-6 justify-start border-none rounded-none overflow-x-auto no-scrollbar",children:[e.jsx(Xe,{value:"profile",className:"relative h-12 rounded-none bg-transparent px-2 pb-3 pt-2 font-medium text-muted-foreground data-[state=active]:text-primary data-[state=active]:shadow-none after:absolute after:bottom-0 after:left-0 after:right-0 after:h-[2px] after:bg-primary after:scale-x-0 data-[state=active]:after:scale-x-100 after:transition-transform",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ve,{className:"hidden sm:block h-4 w-4"}),e.jsx("span",{children:"General"})]})}),e.jsx(Xe,{value:"conversations",className:"relative h-12 rounded-none bg-transparent px-2 pb-3 pt-2 font-medium text-muted-foreground data-[state=active]:text-primary data-[state=active]:shadow-none after:absolute after:bottom-0 after:left-0 after:right-0 after:h-[2px] after:bg-primary after:scale-x-0 data-[state=active]:after:scale-x-100 after:transition-transform",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Te,{className:"hidden sm:block h-4 w-4"}),e.jsx("span",{children:"Conversaciones"})]})}),e.jsx(Xe,{value:"activity",className:"relative h-12 rounded-none bg-transparent px-2 pb-3 pt-2 font-medium text-muted-foreground data-[state=active]:text-primary data-[state=active]:shadow-none after:absolute after:bottom-0 after:left-0 after:right-0 after:h-[2px] after:bg-primary after:scale-x-0 data-[state=active]:after:scale-x-100 after:transition-transform",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tt,{className:"hidden sm:block h-4 w-4"}),e.jsx("span",{children:"Actividad"})]})})]})}),e.jsx(Ue,{value:"profile",className:"flex-1 m-0 overflow-hidden bg-muted/10 focus-visible:ring-0",children:e.jsx(Ye,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-8 pb-20",children:[e.jsxs("div",{className:"flex flex-col items-center text-center animate-in fade-in slide-in-from-bottom-2 duration-300",children:[e.jsxs("div",{className:"relative group cursor-pointer",children:[e.jsx("div",{className:"absolute inset-0 rounded-full bg-primary/20 scale-105 group-hover:scale-110 transition-transform duration-500"}),e.jsxs(xs,{className:"h-24 w-24 border-4 border-background shadow-xl ring-2 ring-primary/10",children:[e.jsx(hs,{src:c?.profilePicUrl}),e.jsx(ps,{className:"bg-gradient-to-tr from-primary to-primary/80 text-primary-foreground text-3xl font-bold",children:oe})]}),E&&e.jsx(cs,{children:e.jsxs(Cs,{children:[e.jsx(Ss,{asChild:!0,children:e.jsx("div",{className:"absolute -bottom-1 -right-1 bg-destructive text-destructive-foreground rounded-full p-1.5 shadow-md ring-2 ring-background",children:e.jsx($s,{className:"h-4 w-4"})})}),e.jsx(Es,{children:"Contacto Bloqueado"})]})})]}),e.jsxs("div",{className:"mt-4 space-y-1",children:[e.jsx("h2",{className:"text-xl font-bold text-foreground leading-tight tracking-tight",children:ie}),c?.email&&e.jsx("p",{className:"text-sm text-muted-foreground",children:c.email}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-3",children:[c?.lastSeenAt?e.jsxs(me,{variant:"outline",className:"text-xs font-normal text-muted-foreground gap-1.5 py-0.5 h-6 bg-background/50 border-dashed",children:[e.jsx(at,{className:"h-3 w-3 opacity-70"}),"Activo ",Ne(c.lastSeenAt,{style:"day-month"})]}):e.jsxs(me,{variant:"outline",className:"text-xs font-normal text-muted-foreground gap-1.5 py-0.5 h-6 bg-background/50",children:[e.jsx(at,{className:"h-3 w-3 opacity-70"}),"Sin actividad"]}),e.jsx(cs,{children:e.jsxs(Cs,{children:[e.jsx(Ss,{asChild:!0,children:e.jsxs(me,{variant:"secondary",className:"text-xs font-normal h-6 py-0.5 cursor-pointer hover:bg-muted-foreground/20 transition-colors",onClick:()=>O(s.id,"ID"),children:["ID: ",s.id.slice(0,6),"...",e.jsx(ks,{className:"h-3 w-3 ml-1 opacity-50"})]})}),e.jsxs(Es,{children:["Copiar ID: ",s.id]})]})})]})]})]}),e.jsx(sa,{className:"bg-border/60"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between px-1",children:[e.jsx("h3",{className:"text-sm font-semibold tracking-tight text-foreground/90 uppercase text-[11px]",children:"Información Personal"}),e.jsx(L,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted",onClick:()=>G("personalInfo"),children:e.jsx(tn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]}),e.jsxs("div",{className:"grid gap-3 p-4 rounded-xl border bg-card/50 shadow-sm hover:shadow-md transition-shadow duration-300",children:[e.jsxs("div",{className:"grid grid-cols-[24px_1fr] items-start gap-2",children:[e.jsx(Ve,{className:"h-4 w-4 text-primary mt-1"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground uppercase mb-0.5",children:"Nombre Completo"}),e.jsx("p",{className:"text-sm font-medium",children:c?.name||"-"})]})]}),e.jsxs("div",{className:"grid grid-cols-[24px_1fr] items-start gap-2",children:[e.jsx(Se,{className:"h-4 w-4 text-primary mt-1"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground uppercase mb-0.5",children:"Email"}),e.jsxs("div",{className:"flex items-center justify-between group/copy",children:[e.jsx("p",{className:"text-sm font-medium truncate max-w-[200px]",children:c?.email||"-"}),c?.email&&e.jsx(L,{variant:"ghost",size:"icon",className:"h-5 w-5 opacity-0 group-hover/copy:opacity-100 transition-opacity",onClick:()=>O(c.email,"Email"),children:e.jsx(ks,{className:"h-3 w-3"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-[24px_1fr] items-start gap-2",children:[e.jsx(qe,{className:"h-4 w-4 text-primary mt-1"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground uppercase mb-0.5",children:"Teléfono"}),e.jsxs("div",{className:"flex items-center justify-between group/copy",children:[e.jsx("p",{className:"text-sm font-medium font-mono",children:c?.phone||"-"}),c?.phone&&e.jsx(L,{variant:"ghost",size:"icon",className:"h-5 w-5 opacity-0 group-hover/copy:opacity-100 transition-opacity",onClick:()=>O(c.phone,"Teléfono"),children:e.jsx(ks,{className:"h-3 w-3"})})]})]})]}),e.jsx(ta,{open:C.personalInfo,children:e.jsx(aa,{children:e.jsx("div",{className:"pt-4 mt-2 border-t border-border/50",children:e.jsx(Rr,{name:c?.name,email:c?.email,phone:c?.phone,onSave:re})})})})]})]}),e.jsx(Ha,{contactId:s.id,level:Nl(c),updatedAt:yl(c),canEdit:le,isLoading:I}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between px-1",children:[e.jsx("h3",{className:"text-sm font-semibold tracking-tight text-foreground/90 uppercase text-[11px]",children:"Etiquetas"}),e.jsx(me,{variant:"outline",className:"text-[10px] h-5",children:w.length})]}),e.jsxs("div",{className:"p-4 rounded-xl border bg-card/50 shadow-sm space-y-4",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:w.length>0?w.map(k=>{const S=T.find(P=>P.tags?.some(K=>K.id===k.id))?.color||k.color||"#64748b";return e.jsxs(me,{variant:"secondary",className:"text-xs group hover:opacity-90 transition-all pl-2 font-medium shadow-sm border-0 gap-1.5 py-1",style:{backgroundColor:`${S}15`,color:S,border:`1px solid ${S}40`},children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{backgroundColor:S}}),k.name,e.jsx("button",{onClick:P=>{P.stopPropagation(),te(k)},className:"ml-0.5 rounded-full hover:bg-black/10 p-0.5 transition-colors",children:e.jsx(us,{className:"h-3 w-3 opacity-60 group-hover:opacity-100"})})]},k.id)}):e.jsx("div",{className:"w-full text-center py-4 bg-muted/20 rounded-lg border border-dashed",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"No hay etiquetas asignadas"})})}),e.jsx(sa,{className:"bg-border/60"}),e.jsx("div",{className:"pt-1",children:I?e.jsx("div",{className:"flex justify-center p-2",children:e.jsx(ke,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsx(La,{selectedTags:w,folders:T,onToggleTag:te,onCreateTag:q?ae:void 0,onCreateFolder:q?Q:void 0})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between px-1",children:e.jsx("h3",{className:"text-sm font-semibold tracking-tight text-foreground/90 uppercase text-[11px]",children:"Información Adicional"})}),e.jsx("div",{className:"p-1 rounded-xl border bg-card/50 shadow-sm overflow-hidden",children:e.jsxs(ta,{open:C.metadata,onOpenChange:()=>G("metadata"),children:[e.jsxs(Br,{className:"flex items-center justify-between w-full p-3 hover:bg-muted/50 transition-colors rounded-t-lg",children:[e.jsx("span",{className:"text-sm text-foreground/80",children:"Ver campos personalizados"}),e.jsx(Mt,{className:M("h-4 w-4 transition-transform text-muted-foreground",C.metadata&&"rotate-180")})]}),e.jsx(aa,{children:e.jsx("div",{className:"p-4 pt-0 border-t border-border/50 bg-background/50",children:e.jsx(Or,{metadata:c?.metadata,schema:y,onSave:z,isLoading:I})})})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between px-1",children:[e.jsx("h3",{className:"text-sm font-semibold tracking-tight text-foreground/90 uppercase text-[11px]",children:"Cuentas Vinculadas"}),e.jsxs(L,{variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-[10px] hover:bg-primary/10 hover:text-primary transition-colors",onClick:()=>o(!0),children:[e.jsx(st,{className:"h-3 w-3"}),"Vincular"]})]}),e.jsx("div",{className:"grid gap-2",children:c?.identities&&c.identities.length>0?c.identities.map(k=>{const B=k.type.toUpperCase();let S=ms,P="text-blue-500",K="bg-blue-500/10";return B==="WHATSAPP"&&(S=Te,P="text-emerald-500",K="bg-emerald-500/10"),B==="EMAIL"&&(S=Se,P="text-amber-500",K="bg-amber-500/10"),B==="INSTAGRAM"&&(S=Bt,P="text-pink-500",K="bg-pink-500/10"),e.jsxs("div",{className:M("flex items-center justify-between p-3 rounded-lg border bg-card/40 group/id transition-all shadow-sm",k.isBlacklisted?"border-destructive/30 bg-destructive/5":"hover:border-primary/30"),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:M("p-2 rounded-md relative",K),children:[e.jsx(S,{className:M("h-4 w-4",P)}),k.isBlacklisted&&e.jsx("div",{className:"absolute -top-1 -right-1 bg-destructive rounded-full p-0.5 shadow-sm",children:e.jsx($s,{className:"h-2 w-2 text-white"})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-[10px] font-bold text-muted-foreground uppercase leading-none mb-0.5",children:k.channel?.name||k.type}),k.isBlacklisted&&e.jsx(me,{variant:"outline",className:"h-4 px-1 text-[8px] border-destructive/30 text-destructive bg-destructive/5 font-bold",children:"BLOQUEADO"})]}),k.channel?.phone&&e.jsxs("p",{className:"text-[10px] text-muted-foreground/70 leading-tight mb-0.5 truncate",children:["Conexión: ",k.channel.phone]}),e.jsx("p",{className:"text-sm font-mono tracking-tight",children:k.identifierValue})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(cs,{children:e.jsxs(Cs,{children:[e.jsx(Ss,{asChild:!0,children:e.jsx(L,{variant:"ghost",size:"icon",className:M("h-8 w-8 opacity-0 group-hover/id:opacity-100 transition-opacity",k.isBlacklisted?"text-emerald-600 hover:bg-emerald-50":"text-destructive hover:bg-destructive/10"),onClick:()=>W(k),children:k.isBlacklisted?e.jsx(wt,{className:"h-4 w-4"}):e.jsx($s,{className:"h-4 w-4"})})}),e.jsx(Es,{children:k.isBlacklisted?`Desbloquear canal ${k.type}`:`Bloquear canal ${k.type}`})]})}),e.jsx(L,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground opacity-0 group-hover/id:opacity-100 transition-opacity hover:bg-muted",onClick:()=>{Y({id:k.id,type:k.type,value:k.identifierValue}),v(!0)},children:e.jsx(At,{className:"h-4 w-4"})})]})]},k.id)}):e.jsx("div",{className:"text-center py-6 px-4 rounded-xl border border-dashed bg-muted/5",children:e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No hay cuentas adicionales vinculadas"})})})]})]})})}),e.jsx(Ue,{value:"conversations",className:"flex-1 m-0 overflow-hidden bg-muted/10 h-full",children:s?.id?e.jsx(Ba,{contactId:s.id,className:"h-full border-none"}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-muted-foreground p-8 text-center",children:[e.jsx(Te,{className:"h-10 w-10 mb-4 opacity-20"}),e.jsx("p",{children:"Selecciona un contacto válido"})]})}),e.jsx(Ue,{value:"activity",className:"flex-1 m-0 overflow-hidden bg-muted/10 h-full",children:s?.id?e.jsx(Va,{contactId:s.id,className:"h-full border-none"}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-muted-foreground p-8 text-center",children:[e.jsx(tt,{className:"h-10 w-10 mb-4 opacity-20"}),e.jsx("p",{children:"Selecciona un contacto válido"})]})})]}),e.jsx(Qn,{open:a,onOpenChange:o,onAdd:async(k,B,S)=>{if(c)try{await se.addIdentity(c.id,k,B,S),D.success("Identidad vinculada correctamente"),h()}catch(P){throw D.error(P.response?.data?.message||"Error al vincular identidad"),P}}}),e.jsx(Ea,{open:j,onOpenChange:v,children:e.jsxs(Aa,{children:[e.jsxs(_a,{children:[e.jsxs(Ta,{className:"flex items-center gap-2",children:[e.jsx(At,{className:"h-5 w-5 text-destructive"}),"¿Desvincular cuenta?"]}),e.jsx(Ia,{className:"space-y-3",asChild:!0,children:e.jsxs("div",{children:[e.jsxs("p",{children:["Estás a punto de desvincular la cuenta ",e.jsxs("strong",{children:[F?.type,": ",F?.value]}),"."]}),e.jsx(Ge,{className:"bg-destructive/5 border-destructive/20 py-2",children:e.jsx(Je,{className:"text-destructive/80 text-[11px] leading-tight",children:"Si desvinculas esta cuenta, el sistema dejará de reconocer automáticamente a este contacto cuando escriba desde este identificador específico."})})]})})]}),e.jsxs(Da,{children:[e.jsx(Ma,{onClick:()=>Y(null),children:"Cancelar"}),e.jsx($r,{className:"bg-destructive hover:bg-destructive/90",onClick:async()=>{if(c&&F)try{await se.removeIdentity(c.id,F.id),D.success("Cuenta desvinculada"),h()}catch{D.error("Error al desvincular")}finally{Y(null)}},children:"Desvincular de todos modos"})]})]})}),e.jsx("div",{className:"p-4 border-t bg-background sticky bottom-0 z-20",children:e.jsx(L,{variant:E?"default":"outline",className:M("w-full shadow-sm",E&&"bg-destructive hover:bg-destructive/90 text-destructive-foreground"),onClick:ue,disabled:!s?.id&&!s?.phone,children:E?e.jsxs(e.Fragment,{children:[e.jsx(wt,{className:"h-4 w-4 mr-2"}),"Desbloquear Todo"]}):e.jsxs(e.Fragment,{children:[e.jsx($s,{className:"h-4 w-4 mr-2"}),"Bloquear Todo"]})})})]})})});Wa.displayName="ContactDetailPanel";const Al=({targetContact:s,open:l,onOpenChange:n,onMerged:i})=>{const[r,f]=m.useState(""),[u,g]=m.useState([]),[b,h]=m.useState(!1),[c,I]=m.useState(null),[T,x]=m.useState(!1),N=async()=>{if(r.trim()){h(!0);try{const w=await se.getContacts({search:r,limit:5});g(w.data.filter(E=>E.id!==s?.id))}catch{D.error("Error al buscar contactos")}finally{h(!1)}}},y=async()=>{if(!(!s||!c)){x(!0);try{const w=await se.mergeContacts(s.id,c.id);D.success("Contactos fusionados correctamente"),i(w),n(!1),I(null),f(""),g([])}catch(w){D.error(w.response?.data?.message||"Error al fusionar contactos")}finally{x(!1)}}};return e.jsx(es,{open:l,onOpenChange:n,children:e.jsxs(ss,{className:"sm:max-w-[550px]",children:[e.jsxs(ts,{children:[e.jsxs(as,{className:"flex items-center gap-2",children:[e.jsx(ve,{className:"h-5 w-5 text-amber-500"}),"Fusionar Contactos"]}),e.jsxs(gs,{children:["Esta acción unirá toda la información del contacto seleccionado en ",e.jsx("strong",{children:s?.name||s?.phone}),". El contacto original será eliminado."]})]}),e.jsx("div",{className:"space-y-6 py-4",children:c?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-center gap-6 p-6 rounded-xl bg-muted/30 border border-dashed",children:[e.jsxs("div",{className:"text-center space-y-2 w-1/3",children:[e.jsxs(xs,{className:"h-12 w-12 mx-auto ring-2 ring-destructive/20 shadow-lg",children:[e.jsx(hs,{src:c.profilePicUrl}),e.jsx(ps,{children:e.jsx(Ve,{className:"h-6 w-6"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-destructive truncate",children:c.name||"Origen"}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:"Se eliminará"})]})]}),e.jsx(Ct,{className:"h-8 w-8 text-muted-foreground animate-pulse"}),e.jsxs("div",{className:"text-center space-y-2 w-1/3",children:[e.jsxs(xs,{className:"h-12 w-12 mx-auto ring-2 ring-primary/20 shadow-lg border-2 border-primary/20",children:[e.jsx(hs,{src:s?.profilePicUrl}),e.jsx(ps,{children:e.jsx(Ve,{className:"h-6 w-6"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-bold text-primary truncate",children:s?.name||"Destino"}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase",children:"Conservar"})]})]})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-amber-50 dark:bg-amber-900/10 border border-amber-200 dark:border-amber-800 text-xs space-y-2",children:[e.jsxs("p",{className:"font-bold text-amber-800 dark:text-amber-500 flex items-center gap-1",children:[e.jsx(ve,{className:"h-3 w-3"}),"¿Qué pasará después de la fusión?"]}),e.jsxs("ul",{className:"list-disc pl-4 space-y-1 text-amber-700 dark:text-amber-400",children:[e.jsxs("li",{children:["Se transferirán todas las ",e.jsx("strong",{children:"etiquetas"}),"."]}),e.jsxs("li",{children:["Se transferirán todos los ",e.jsx("strong",{children:"tickets e historial de chat"}),"."]}),e.jsxs("li",{children:["Se vincularán las ",e.jsx("strong",{children:"identidades"})," (WhatsApp, Web, etc.)."]}),e.jsx("li",{children:"El contacto origen dejará de existir."})]})]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(kt,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(He,{placeholder:"Buscar contacto a fusionar (nombre, email o ID)...",value:r,onChange:w=>f(w.target.value),onKeyDown:w=>w.key==="Enter"&&N(),className:"pl-9"})]}),e.jsx(L,{onClick:N,disabled:b,children:b?e.jsx(ke,{className:"h-4 w-4 animate-spin"}):"Buscar"})]}),e.jsxs("div",{className:"space-y-2 max-h-[200px] overflow-auto pr-2",children:[u.map(w=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/50 cursor-pointer transition-colors",onClick:()=>I(w),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(xs,{className:"h-8 w-8",children:[e.jsx(hs,{src:w.profilePicUrl}),e.jsx(ps,{children:e.jsx(Ve,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:w.name||"Sin nombre"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:w.phone||w.email||w.id})]})]}),e.jsx(L,{variant:"ghost",size:"sm",children:"Seleccionar"})]},w.id)),r&&!b&&u.length===0&&e.jsx("p",{className:"text-center py-4 text-sm text-muted-foreground",children:"No se encontraron resultados"})]})]})}),e.jsx(Ls,{className:"gap-2 sm:gap-0",children:c?e.jsxs(e.Fragment,{children:[e.jsx(L,{variant:"ghost",onClick:()=>I(null),disabled:T,children:"Elegir otro"}),e.jsxs(L,{variant:"destructive",onClick:y,disabled:T,children:[T?e.jsx(ke,{className:"h-4 w-4 animate-spin mr-2"}):null,"Confirmar Fusión"]})]}):e.jsx(L,{variant:"secondary",onClick:()=>n(!1),children:"Cancelar"})})]})})},_e={all:["contacts"],list:(s,l)=>[..._e.all,"list",s,l],schemas:s=>[..._e.all,"schemas",s]},_l=s=>{const{user:l}=bs(),n=$t(f=>f.filters),i=l?.organizationId;return rs({queryKey:_e.list(i||"",n),queryFn:()=>se.getContacts(n),enabled:!!i,placeholderData:ir,staleTime:1e3*60,select:s})},Tl=()=>{const{user:s}=bs(),l=s?.organizationId;return rs({queryKey:_e.schemas(l||""),queryFn:()=>Ra.listSchemas(),enabled:!!l,staleTime:1e3*60*60})},Ka=()=>{const{user:s}=bs(),l=s?.organizationId;return rs({queryKey:[..._e.all,"stats",l],queryFn:()=>se.getStats(),enabled:!!l,staleTime:1e3*60*5})},Il=()=>{const{user:s}=bs(),l=s?.organizationId;return rs({queryKey:[..._e.all,"analytics",l],queryFn:()=>se.getAnalytics(),enabled:!1,staleTime:1e3*60*5})},Qa=()=>{const{user:s}=bs(),l=s?.organizationId;return rs({queryKey:[..._e.all,"duplicates",l],queryFn:()=>se.getDuplicates(),enabled:!!l,staleTime:0})},xa=({value:s,ids:l,count:n,type:i,onMerge:r})=>{const[f,u]=m.useState(!1),[g,b]=m.useState(!1),[h,c]=m.useState([]),[I,T]=m.useState(!1),x=l[0],N=l.slice(1);m.useEffect(()=>{g&&h.length===0&&w()},[g]);const y=t=>{let a=0;if(t.name&&t.name.length>0&&(a+=2),t.email&&t.email.length>0&&(a+=1),t.phone&&t.phone.length>0&&(a+=1),t.tags&&t.tags.length>0&&(a+=1),t.profilePicUrl&&(a+=1),t.lastSeenAt){const o=new Date(t.lastSeenAt).getTime(),v=(new Date().getTime()-o)/(1e3*3600*24);v<30?a+=2:v<90&&(a+=1)}return a},w=async()=>{T(!0);try{const a=(await se.getContacts({ids:l,limit:100})).data||[];a.sort((o,j)=>{const v=y(o),F=y(j);if(v!==F)return F-v;const Y=o.lastSeenAt?new Date(o.lastSeenAt).getTime():0,te=j.lastSeenAt?new Date(j.lastSeenAt).getTime():0;if(Y!==te)return te-Y;const ae=o.createdAt?new Date(o.createdAt).getTime():0,Q=j.createdAt?new Date(j.createdAt).getTime():0;return ae-Q}),c(a)}catch(t){console.error("Error loading contact details:",t)}finally{T(!1)}},E=async()=>{if(h.length===0){u(!0);try{for(const o of N)await r(x,o);D.success(`Fusiones completadas para ${s}`)}catch(o){console.error(o),D.error("Error al fusionar algunos contactos")}finally{u(!1)}return}const t=h[0].id,a=h.slice(1).map(o=>o.id);u(!0);try{for(const o of a)await r(t,o);D.success(`Fusiones completadas para ${s}`),c([])}catch(o){console.error(o),D.error("Error al fusionar algunos contactos")}finally{u(!1)}},H=i==="Phone"?qe:Se,Z=i==="Phone"?"bg-blue-50 dark:bg-blue-950/30":"bg-purple-50 dark:bg-purple-950/30",X=i==="Phone"?"text-blue-500":"text-purple-500",q=i==="Phone"?"border-blue-100 dark:border-blue-900/50":"border-purple-100 dark:border-purple-900/50",le=t=>t.split(" ").map(a=>a[0]).slice(0,2).join("").toUpperCase(),C=t=>{const a=[...h],o=a.findIndex(j=>j.id===t);if(o>0){const[j]=a.splice(o,1);a.unshift(j),c(a),D.success("Contacto principal actualizado")}};return e.jsxs("div",{className:M("rounded-xl border-2 mb-3 transition-all overflow-hidden",Z,q),children:[e.jsxs("div",{className:"flex items-center justify-between p-4 cursor-pointer hover:bg-white/50 dark:hover:bg-slate-900/20 transition-colors",onClick:()=>b(!g),children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:M("w-10 h-10 rounded-full flex items-center justify-center",i==="Phone"?"bg-blue-100 dark:bg-blue-900/50":"bg-purple-100 dark:bg-purple-900/50"),children:e.jsx(H,{className:M("h-5 w-5",X)})}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-sm text-slate-800 dark:text-slate-200",children:s}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[n," contactos comparten este ",i==="Phone"?"teléfono":"email"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(L,{size:"sm",variant:"ghost",className:"h-8 w-8 p-0",onClick:t=>{t.stopPropagation(),b(!g)},children:g?e.jsx(en,{className:"h-4 w-4"}):e.jsx(Mt,{className:"h-4 w-4"})}),e.jsx(L,{size:"sm",onClick:t=>{t.stopPropagation(),E()},disabled:f,className:"bg-slate-900 hover:bg-slate-800 text-white dark:bg-slate-100 dark:text-slate-900 dark:hover:bg-slate-200 rounded-lg shadow-sm",children:f?e.jsx(ke,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(xt,{className:"h-4 w-4 mr-2"}),"Unificar"]})})]})]}),g&&e.jsxs("div",{className:"px-4 pb-4 pt-0 border-t border-slate-200/50 dark:border-slate-700/50",children:[e.jsx("div",{className:"pt-3 space-y-2",children:I?e.jsx("div",{className:"space-y-2",children:l.map(t=>e.jsx(we,{className:"h-16 w-full rounded-lg"},t))}):h.map((t,a)=>{const o=a===0;return e.jsxs("div",{className:M("flex items-center gap-3 p-3 rounded-lg border transition-all group",o?"bg-emerald-50 dark:bg-emerald-950/20 border-emerald-200 dark:border-emerald-800":"bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-700 hover:border-slate-300 dark:hover:border-slate-600"),children:[e.jsxs(xs,{className:"h-10 w-10 border-2 border-white dark:border-slate-800 shadow-sm",children:[e.jsx(hs,{src:t.profilePicUrl}),e.jsx(ps,{className:M("text-xs font-bold",o?"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/50 dark:text-emerald-400":"bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400"),children:le(t.name||t.phone)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:M("font-semibold text-sm truncate",o?"text-emerald-800 dark:text-emerald-300":"text-slate-800 dark:text-slate-200"),children:t.name||"Sin nombre"}),o&&e.jsxs(me,{className:"h-5 px-1.5 text-[9px] bg-emerald-500 text-white border-none",children:[e.jsx(fs,{className:"h-2.5 w-2.5 mr-0.5"}),"PRINCIPAL"]})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[t.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qe,{className:"h-3 w-3"}),t.phone]}),t.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate max-w-[150px]",children:[e.jsx(Se,{className:"h-3 w-3"}),t.email]})]}),t.tags&&t.tags.length>0&&e.jsxs("div",{className:"flex items-center gap-1 mt-1.5 flex-wrap",children:[t.tags.slice(0,3).map(j=>e.jsxs(me,{variant:"outline",className:"text-[9px] h-4 px-1.5 bg-white dark:bg-slate-800",children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full mr-1",style:{backgroundColor:j.color||"#64748b"}}),j.name]},j.id)),t.tags.length>3&&e.jsxs(me,{variant:"outline",className:"text-[9px] h-4 px-1.5",children:["+",t.tags.length-3]})]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[t.lastSeenAt?e.jsxs("div",{className:"text-[10px] text-muted-foreground whitespace-nowrap",children:[e.jsx(Oa,{className:"h-3 w-3 inline mr-1"}),Tt(new Date(t.lastSeenAt),{addSuffix:!0,locale:rt})]}):t.createdAt?e.jsxs("div",{className:"text-[10px] text-muted-foreground whitespace-nowrap",children:["Creado ",Tt(new Date(t.createdAt),{addSuffix:!0,locale:rt})]}):null,!o&&e.jsxs(L,{size:"sm",variant:"secondary",onClick:()=>C(t.id),className:"h-6 px-2 text-[10px] opacity-0 group-hover:opacity-100 transition-opacity bg-slate-100 hover:bg-slate-200 dark:bg-slate-800 dark:hover:bg-slate-700 border border-slate-200 dark:border-slate-700",children:[e.jsx(Pa,{className:"h-3 w-3 mr-1 text-amber-500"}),"Hacer Principal"]})]})]},t.id)})}),e.jsx("div",{className:"mt-3 p-2 rounded-lg bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-800",children:e.jsxs("p",{className:"text-[11px] text-amber-700 dark:text-amber-400 flex items-start gap-1.5",children:[e.jsx(mt,{className:"h-3.5 w-3.5 mt-0.5 flex-shrink-0"}),e.jsxs("span",{children:["Al unificar, el contacto ",e.jsx("strong",{children:"PRINCIPAL"})," conservará sus datos y absorberá las etiquetas e historial de conversaciones de los demás contactos."]})]})})]})]})},Dl=({pair:s,onMerge:l})=>{const[n,i]=m.useState(!1),[r,f]=m.useState([]),[u,g]=m.useState(!0);m.useEffect(()=>{h()},[s]);const b=N=>{let y=0;if(N.name?.length>0&&(y+=2),N.email&&N.email.length>0&&(y+=1),N.phone&&N.phone.length>0&&(y+=1),N.tags&&N.tags.length>0&&(y+=1),N.profilePicUrl&&(y+=1),N.lastSeenAt){const w=(Date.now()-new Date(N.lastSeenAt).getTime())/864e5;w<30?y+=2:w<90&&(y+=1)}return y},h=async()=>{g(!0);try{const y=(await se.getContacts({ids:[s.id1,s.id2]})).data||[];y.sort((w,E)=>{const H=b(w),Z=b(E);if(H!==Z)return Z-H;const X=w.lastSeenAt?new Date(w.lastSeenAt).getTime():0;return(E.lastSeenAt?new Date(E.lastSeenAt).getTime():0)-X}),f(y)}catch(N){console.error(N)}finally{g(!1)}},c=N=>{const y=[...r],w=y.findIndex(E=>E.id===N);if(w>0){const[E]=y.splice(w,1);y.unshift(E),f(y),D.success("Principal actualizado")}},I=async()=>{if(!(r.length<2)){i(!0);try{await l(r[0].id,r[1].id),D.success("Contactos fusionados correctamente")}catch{D.error("Error al fusionar")}finally{i(!1)}}},T=Math.round(s.score*100),x=T>=90?"text-red-600 bg-red-50 border-red-200":T>=80?"text-amber-600 bg-amber-50 border-amber-200":"text-blue-600 bg-blue-50 border-blue-200";return u?e.jsx(we,{className:"h-40 w-full mb-3 rounded-xl"}):r.length<2?null:e.jsxs("div",{className:"p-4 rounded-xl border-2 border-orange-100 dark:border-orange-900/50 bg-orange-50/50 dark:bg-orange-950/20 mb-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(me,{className:M("text-xs font-medium border",x),children:[e.jsx(Lt,{className:"h-3 w-3 mr-1"}),T,"% similitud"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Revisa quién debe ser el principal"})]}),e.jsxs(L,{size:"sm",onClick:I,disabled:n,className:"h-8 rounded-lg bg-slate-900 text-white hover:bg-slate-800 dark:bg-slate-100 dark:text-slate-900",children:[n?e.jsx(ke,{className:"h-4 w-4 animate-spin"}):e.jsx(xt,{className:"h-4 w-4 mr-2"}),"Fusionar"]})]}),e.jsxs("div",{className:"grid grid-cols-[1fr,40px,1fr] gap-2 items-stretch",children:[r.map((N,y)=>{const w=y===0;return e.jsxs("div",{className:M("flex flex-col p-3 rounded-lg border text-center transition-all relative",w?"bg-emerald-50 dark:bg-emerald-950/30 border-emerald-200 dark:border-emerald-800 shadow-sm":"bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-700 opacity-80 hover:opacity-100"),children:[w&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsx(me,{className:"text-[9px] h-4 px-1 bg-emerald-500 border-emerald-600 text-white",children:"PRINCIPAL"})}),e.jsx("div",{className:"w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center mx-auto mb-2 border-2 border-white dark:border-slate-700 shadow-sm overflow-hidden",children:N.profilePicUrl?e.jsx("img",{src:N.profilePicUrl,alt:"",className:"w-full h-full object-cover"}):e.jsx(Ve,{className:M("h-5 w-5",w?"text-emerald-600":"text-slate-400")})}),e.jsx("div",{className:"font-semibold text-sm truncate px-1 text-slate-800 dark:text-slate-200",children:N.name||"Sin nombre"}),e.jsxs("div",{className:"mt-1 space-y-0.5 mb-3",children:[N.phone&&e.jsxs("div",{className:"text-[10px] text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(qe,{className:"h-2.5 w-2.5"})," ",N.phone]}),N.email&&e.jsxs("div",{className:"text-[10px] text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Se,{className:"h-2.5 w-2.5"})," ",N.email.substring(0,15),"..."]})]}),e.jsx("div",{className:"mt-auto pt-2 border-t border-slate-100 dark:border-slate-800",children:w?e.jsx("div",{className:"text-[10px] text-emerald-600 font-medium py-1",children:"Se mantendrá"}):e.jsxs(L,{size:"sm",variant:"ghost",className:"w-full h-6 text-[10px] hover:bg-emerald-50 hover:text-emerald-600 dark:hover:bg-emerald-950/30",onClick:()=>c(N.id),children:[e.jsx(Pa,{className:"h-3 w-3 mr-1"}),"Hacer Principal"]})})]},N.id)}),e.jsx("div",{className:"flex items-center justify-center self-center h-full",children:e.jsx("div",{className:"w-8 h-8 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center",children:e.jsx("span",{className:"text-xs font-bold text-slate-400",children:"VS"})})})]}),e.jsx("div",{className:"mt-3 p-2 bg-orange-50 dark:bg-orange-950/30 rounded border border-orange-100 dark:border-orange-800/50",children:e.jsx("p",{className:"text-[10px] text-orange-800 dark:text-orange-300 text-center",children:"Similitud detectada por nombre. Verifica si son la misma persona."})})]})},vt=({type:s})=>e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-50 dark:bg-emerald-950/30 flex items-center justify-center mb-4",children:e.jsx(fs,{className:"h-8 w-8 text-emerald-500"})}),e.jsxs("h4",{className:"font-medium text-slate-700 dark:text-slate-300 mb-1",children:["Sin duplicados por ",s]}),e.jsxs("p",{className:"text-sm text-muted-foreground max-w-xs",children:["No encontramos contactos que compartan el mismo ",s.toLowerCase()]})]}),Ml=({open:s,onOpenChange:l})=>{const{data:n,isLoading:i}=Qa(),r=Rs(),f=async(E,H)=>{await se.mergeContacts(E,H),r.invalidateQueries({queryKey:_e.all})},u=n?.byPhone?.length||0,g=n?.byEmail?.length||0,b=n?.byFuzzy?.length||0,h=u+g+b,c=n?.hasResults!==!1,I=!i&&n?.hasResults===!1,T=!i&&c&&h===0,x=n?.meta?.analyzedAt?Ne(n.meta.analyzedAt,{style:"short"}):null,N=n?.meta?.isStale,y=n?.meta?.contactCount,w=u>0?"phone":g>0?"email":"fuzzy";return e.jsx(es,{open:s,onOpenChange:l,children:e.jsxs(ss,{className:"max-w-2xl max-h-[90vh] flex flex-col p-0 gap-0 overflow-hidden",children:[e.jsx(ts,{className:"px-6 pt-6 pb-4 border-b bg-gradient-to-r from-slate-50 to-white dark:from-slate-900 dark:to-slate-900/50",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gradient-to-br from-primary/20 to-primary/5 flex items-center justify-center",children:e.jsx(xt,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(as,{className:"text-xl font-bold",children:"Gestión de Duplicados"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:"Mantén tu base de datos limpia y organizada"})]})]}),c&&h>0&&e.jsxs(me,{variant:"secondary",className:"bg-amber-100 text-amber-700 border-amber-200 text-sm px-3 py-1",children:[e.jsx(ve,{className:"h-3.5 w-3.5 mr-1.5"}),h," duplicado",h!==1?"s":""]})]})}),c&&x&&e.jsxs("div",{className:"px-6 py-3 bg-slate-50 dark:bg-slate-900/50 border-b flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(at,{className:"h-4 w-4"}),e.jsxs("span",{children:["Último análisis: ",e.jsx("span",{className:"font-medium text-slate-700 dark:text-slate-300",children:x})]})]}),y&&e.jsxs(me,{variant:"outline",className:"text-xs",children:[y.toLocaleString()," contactos analizados"]})]}),N&&e.jsxs(me,{variant:"outline",className:"bg-amber-50 text-amber-700 border-amber-200 text-xs",children:[e.jsx(ve,{className:"h-3 w-3 mr-1"}),"Datos antiguos (",">","7 días)"]})]}),e.jsx("div",{className:"flex-1 overflow-hidden px-6 py-4",children:i?e.jsxs("div",{className:"flex flex-col items-center justify-center h-64",children:[e.jsx(ke,{className:"h-10 w-10 animate-spin text-primary mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Cargando análisis de duplicados..."})]}):I?e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-center",children:[e.jsx("div",{className:"w-20 h-20 rounded-2xl bg-blue-50 dark:bg-blue-950/30 flex items-center justify-center mb-4",children:e.jsx(or,{className:"h-10 w-10 text-blue-500"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-800 dark:text-slate-200 mb-2",children:"No hay análisis disponible"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-sm mb-4",children:"El análisis de duplicados es ejecutado por el administrador del sistema para detectar contactos que podrían estar repetidos."}),e.jsxs(Ge,{className:"max-w-md bg-blue-50/50 dark:bg-blue-950/20 border-blue-200 dark:border-blue-800",children:[e.jsx(mt,{className:"h-4 w-4 text-blue-500"}),e.jsx(Je,{className:"text-sm text-blue-700 dark:text-blue-300",children:"Contacta a soporte si necesitas que se realice un análisis de tus contactos."})]})]}):T?e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-center",children:[e.jsx("div",{className:"w-20 h-20 rounded-2xl bg-emerald-50 dark:bg-emerald-950/30 flex items-center justify-center mb-4",children:e.jsx(wt,{className:"h-10 w-10 text-emerald-500"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-800 dark:text-slate-200 mb-2",children:"¡Tu base de datos está limpia!"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-sm",children:"No encontramos contactos duplicados obvios. Tu información está bien organizada."})]}):e.jsxs(Ot,{defaultValue:w,className:"h-full flex flex-col",children:[e.jsxs(Pt,{className:"grid w-full grid-cols-3 p-1 bg-slate-100 dark:bg-slate-800 rounded-xl mb-4",children:[e.jsxs(Xe,{value:"phone",className:"rounded-lg data-[state=active]:bg-white dark:data-[state=active]:bg-slate-900 data-[state=active]:shadow-sm flex items-center gap-2",children:[e.jsx(qe,{className:"h-4 w-4"}),e.jsx("span",{children:"Teléfono"}),u>0&&e.jsx(me,{variant:"secondary",className:"h-5 px-1.5 text-[10px] bg-blue-100 text-blue-700",children:u})]}),e.jsxs(Xe,{value:"email",className:"rounded-lg data-[state=active]:bg-white dark:data-[state=active]:bg-slate-900 data-[state=active]:shadow-sm flex items-center gap-2",children:[e.jsx(Se,{className:"h-4 w-4"}),e.jsx("span",{children:"Email"}),g>0&&e.jsx(me,{variant:"secondary",className:"h-5 px-1.5 text-[10px] bg-purple-100 text-purple-700",children:g})]}),e.jsxs(Xe,{value:"fuzzy",className:"rounded-lg data-[state=active]:bg-white dark:data-[state=active]:bg-slate-900 data-[state=active]:shadow-sm flex items-center gap-2",children:[e.jsx(Ve,{className:"h-4 w-4"}),e.jsx("span",{children:"Nombres"}),b>0&&e.jsx(me,{variant:"secondary",className:"h-5 px-1.5 text-[10px] bg-orange-100 text-orange-700",children:b})]})]}),e.jsx(Ue,{value:"phone",className:"flex-1 overflow-hidden mt-0",children:e.jsx(Ye,{className:"h-[350px] pr-2",children:u>0?e.jsxs(e.Fragment,{children:[e.jsxs(Ge,{className:"mb-4 bg-blue-50/50 dark:bg-blue-950/20 border-blue-200 dark:border-blue-800",children:[e.jsx(qe,{className:"h-4 w-4 text-blue-500"}),e.jsx(Xs,{className:"text-sm font-medium text-blue-800 dark:text-blue-300",children:"Duplicados por teléfono"}),e.jsx(Je,{className:"text-xs text-blue-700/80 dark:text-blue-400/80",children:"Haz clic en cada grupo para ver los detalles de los contactos antes de unificar."})]}),n?.byPhone?.map(E=>e.jsx(xa,{value:E.phone,ids:E.ids,count:E.count,type:"Phone",onMerge:f},E.phone))]}):e.jsx(vt,{type:"teléfono"})})}),e.jsx(Ue,{value:"email",className:"flex-1 overflow-hidden mt-0",children:e.jsx(Ye,{className:"h-[350px] pr-2",children:g>0?e.jsxs(e.Fragment,{children:[e.jsxs(Ge,{className:"mb-4 bg-purple-50/50 dark:bg-purple-950/20 border-purple-200 dark:border-purple-800",children:[e.jsx(Se,{className:"h-4 w-4 text-purple-500"}),e.jsx(Xs,{className:"text-sm font-medium text-purple-800 dark:text-purple-300",children:"Duplicados por email"}),e.jsx(Je,{className:"text-xs text-purple-700/80 dark:text-purple-400/80",children:"Haz clic en cada grupo para ver los detalles de los contactos antes de unificar."})]}),n?.byEmail?.map(E=>e.jsx(xa,{value:E.email,ids:E.ids,count:E.count,type:"Email",onMerge:f},E.email))]}):e.jsx(vt,{type:"email"})})}),e.jsx(Ue,{value:"fuzzy",className:"flex-1 overflow-hidden mt-0",children:e.jsx(Ye,{className:"h-[350px] pr-2",children:b>0?e.jsxs(e.Fragment,{children:[e.jsxs(Ge,{className:"mb-4 bg-orange-50/50 dark:bg-orange-950/20 border-orange-200 dark:border-orange-800",children:[e.jsx(Lt,{className:"h-4 w-4 text-orange-500"}),e.jsx(Xs,{className:"text-sm font-medium text-orange-800 dark:text-orange-300",children:"Nombres similares detectados"}),e.jsx(Je,{className:"text-xs text-orange-700/80 dark:text-orange-400/80",children:"Estos contactos tienen nombres muy parecidos. Revisa cuidadosamente antes de fusionar ya que podrían ser personas diferentes."})]}),n?.byFuzzy?.map((E,H)=>e.jsx(Dl,{pair:E,onMerge:f},H))]}):e.jsx(vt,{type:"nombre similar"})})})]})})]})})},Ll=({open:s,onOpenChange:l,onSuccess:n})=>{const[i,r]=m.useState(""),[f,u]=m.useState(""),[g,b]=m.useState(""),[h,c]=m.useState(""),[I,T]=m.useState(!1),{channels:x}=Fa(),N=on(),{pool:y,limitReached:w,blocked:E,refetch:H}=za({resourceType:"CONTACTS",enabled:s}),Z=async()=>{if(w||E){la({creditError:E?"RESOURCE_BLOCKED":"CREDIT_ERROR"},{title:"Limite de Contactos Alcanzado",fallbackDescription:E?"La creacion de contactos esta temporalmente bloqueada.":"Tu plan no permite crear mas contactos."});return}if(i.trim()){T(!0);try{const q=await se.createContact({name:i.trim(),phone:f?f.replace(/\+/g,"").trim():void 0,email:g.trim()||void 0,channelId:h||void 0});D.success("Contacto creado con exito"),H(),n(q),X(),l(!1)}catch(q){console.error(q),la(q,{title:"Limite de Contactos Alcanzado",fallbackDescription:"Tu plan no permite crear mas contactos."})||D.error("Error al crear contacto",{description:q.message||"Ocurrio un error inesperado."})}finally{T(!1)}}},X=()=>{r(""),u(""),b(""),c("")};return e.jsx(es,{open:s,onOpenChange:q=>{q||X(),l(q)},children:e.jsxs(ss,{className:"sm:max-w-[450px]",children:[e.jsxs(ts,{children:[e.jsx(as,{children:"Nuevo Contacto"}),e.jsx(gs,{children:"Crea un nuevo contacto manualmente en tu base de datos."})]}),e.jsx(cn,{pool:y,lowThreshold:10}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ze,{htmlFor:"name",children:"Nombre Completo *"}),e.jsx(He,{id:"name",placeholder:"Ej: Juan Perez",value:i,onChange:q=>r(q.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ze,{htmlFor:"phone",children:"Telefono (Opcional)"}),e.jsx("div",{className:"phone-input-container",children:e.jsx(dn,{international:!0,defaultCountry:N,value:f,onChange:q=>u(q||""),className:"flex h-11 w-full rounded-md border border-border bg-card px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium 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",placeholder:"Ingresa el numero de telefono"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ze,{htmlFor:"email",children:"Correo Electronico (Opcional)"}),e.jsx(He,{id:"email",type:"email",placeholder:"Ej: juan@ejemplo.com",value:g,onChange:q=>b(q.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ze,{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"w-3 h-3 text-primary"}),"Canal de Origen"]}),e.jsxs(nt,{value:h,onValueChange:c,children:[e.jsx(lt,{children:e.jsx(it,{placeholder:"Seleccionar un canal..."})}),e.jsx(ot,{children:x.filter(q=>q.isActive&&!q.deletedAt&&!q.disconnectedFromMetaAt).map(q=>e.jsxs(Fe,{value:q.id,children:[q.name," (",q.type,")"]},q.id))})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Vincular un canal permitira que este contacto sea visible en los filtros de campanas."})]})]}),e.jsxs(Ls,{children:[e.jsx(L,{variant:"outline",onClick:()=>l(!1),disabled:I,children:"Cancelar"}),e.jsxs(L,{onClick:Z,disabled:I||!i.trim(),children:[I&&e.jsx(ke,{className:"mr-2 h-4 w-4 animate-spin"}),"Crear Contacto"]})]})]})})},ha=3e4;function Rl(s=!0){const[l,n]=m.useState(null),i=m.useRef(0);m.useEffect(()=>{s&&se.getImportStatus().then(u=>{u&&(u.status==="queued"||u.status==="processing"||u.status==="completed"||u.status==="failed")&&n(u)}).catch(()=>{})},[s]),m.useEffect(()=>s?Ys.onContactsImportProgress(g=>{i.current=Date.now(),n(b=>({jobId:g.jobId,status:g.status,phase:g.phase,progress:g.progress,processedRows:g.processedRows,totalRows:g.totalRows,message:g.message,...g.result?{result:g.result}:{},...b?.startedAt?{startedAt:b.startedAt}:{},...b?.result&&!g.result?{result:b.result}:{}}))}):void 0,[s]),m.useEffect(()=>{if(!s)return;const u=setInterval(()=>{!(l?.status==="queued"||l?.status==="processing")||Date.now()-i.current<ha||se.getImportStatus().then(h=>{h&&n(c=>c?.progress===h.progress&&c?.status===h.status?c:{...c,...h})}).catch(()=>{})},ha);return()=>clearInterval(u)},[s,l?.status]);const r=m.useCallback(()=>n(null),[]),f=m.useCallback(u=>{i.current=Date.now(),n({jobId:u,status:"queued",progress:0,processedRows:0,totalRows:0,message:"En cola de procesamiento...",startedAt:new Date().toISOString()})},[]);return{importStatus:l,resetImportStatus:r,setJobQueued:f}}var et={exports:{}};var Ol=et.exports,pa;function Pl(){return pa||(pa=1,(function(s,l){((n,i)=>{s.exports=i()})(Ol,function n(){var i=typeof self<"u"?self:typeof window<"u"?window:i!==void 0?i:{},r,f=!i.document&&!!i.postMessage,u=i.IS_PAPA_WORKER||!1,g={},b=0,h={};function c(t){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},(function(a){var o=q(a);o.chunkSize=parseInt(o.chunkSize),a.step||a.chunk||(o.chunkSize=null),this._handle=new y(o),(this._handle.streamer=this)._config=o}).call(this,t),this.parseChunk=function(a,o){var j=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0<j){let F=this._config.newline;F||(v=this._config.quoteChar||'"',F=this._handle.guessLineEndings(a,v)),a=[...a.split(F).slice(j)].join(F)}this.isFirstChunk&&C(this._config.beforeFirstChunk)&&(v=this._config.beforeFirstChunk(a))!==void 0&&(a=v),this.isFirstChunk=!1,this._halted=!1;var j=this._partialLine+a,v=(this._partialLine="",this._handle.parse(j,this._baseIndex,!this._finished));if(!this._handle.paused()&&!this._handle.aborted()){if(a=v.meta.cursor,j=(this._finished||(this._partialLine=j.substring(a-this._baseIndex),this._baseIndex=a),v&&v.data&&(this._rowCount+=v.data.length),this._finished||this._config.preview&&this._rowCount>=this._config.preview),u)i.postMessage({results:v,workerId:h.WORKER_ID,finished:j});else if(C(this._config.chunk)&&!o){if(this._config.chunk(v,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=v=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(v.data),this._completeResults.errors=this._completeResults.errors.concat(v.errors),this._completeResults.meta=v.meta),this._completed||!j||!C(this._config.complete)||v&&v.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),j||v&&v.meta.paused||this._nextChunk(),v}this._halted=!0},this._sendError=function(a){C(this._config.error)?this._config.error(a):u&&this._config.error&&i.postMessage({workerId:h.WORKER_ID,error:a,finished:!1})}}function I(t){var a;(t=t||{}).chunkSize||(t.chunkSize=h.RemoteChunkSize),c.call(this,t),this._nextChunk=f?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(o){this._input=o,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(a=new XMLHttpRequest,this._config.withCredentials&&(a.withCredentials=this._config.withCredentials),f||(a.onload=le(this._chunkLoaded,this),a.onerror=le(this._chunkError,this)),a.open(this._config.downloadRequestBody?"POST":"GET",this._input,!f),this._config.downloadRequestHeaders){var o,j=this._config.downloadRequestHeaders;for(o in j)a.setRequestHeader(o,j[o])}var v;this._config.chunkSize&&(v=this._start+this._config.chunkSize-1,a.setRequestHeader("Range","bytes="+this._start+"-"+v));try{a.send(this._config.downloadRequestBody)}catch(F){this._chunkError(F.message)}f&&a.status===0&&this._chunkError()}},this._chunkLoaded=function(){a.readyState===4&&(a.status<200||400<=a.status?this._chunkError():(this._start+=this._config.chunkSize||a.responseText.length,this._finished=!this._config.chunkSize||this._start>=(o=>(o=o.getResponseHeader("Content-Range"))!==null?parseInt(o.substring(o.lastIndexOf("/")+1)):-1)(a),this.parseChunk(a.responseText)))},this._chunkError=function(o){o=a.statusText||o,this._sendError(new Error(o))}}function T(t){(t=t||{}).chunkSize||(t.chunkSize=h.LocalChunkSize),c.call(this,t);var a,o,j=typeof FileReader<"u";this.stream=function(v){this._input=v,o=v.slice||v.webkitSlice||v.mozSlice,j?((a=new FileReader).onload=le(this._chunkLoaded,this),a.onerror=le(this._chunkError,this)):a=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount<this._config.preview)||this._readChunk()},this._readChunk=function(){var v=this._input,F=(this._config.chunkSize&&(F=Math.min(this._start+this._config.chunkSize,this._input.size),v=o.call(v,this._start,F)),a.readAsText(v,this._config.encoding));j||this._chunkLoaded({target:{result:F}})},this._chunkLoaded=function(v){this._start+=this._config.chunkSize,this._finished=!this._config.chunkSize||this._start>=this._input.size,this.parseChunk(v.target.result)},this._chunkError=function(){this._sendError(a.error)}}function x(t){var a;c.call(this,t=t||{}),this.stream=function(o){return a=o,this._nextChunk()},this._nextChunk=function(){var o,j;if(!this._finished)return o=this._config.chunkSize,a=o?(j=a.substring(0,o),a.substring(o)):(j=a,""),this._finished=!a,this.parseChunk(j)}}function N(t){c.call(this,t=t||{});var a=[],o=!0,j=!1;this.pause=function(){c.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){c.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(v){this._input=v,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){j&&a.length===1&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),a.length?this.parseChunk(a.shift()):o=!0},this._streamData=le(function(v){try{a.push(typeof v=="string"?v:v.toString(this._config.encoding)),o&&(o=!1,this._checkIsFinished(),this.parseChunk(a.shift()))}catch(F){this._streamError(F)}},this),this._streamError=le(function(v){this._streamCleanUp(),this._sendError(v)},this),this._streamEnd=le(function(){this._streamCleanUp(),j=!0,this._streamData("")},this),this._streamCleanUp=le(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function y(t){var a,o,j,v,F=Math.pow(2,53),Y=-F,te=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,ae=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,Q=this,re=0,z=0,ue=!1,W=!1,G=[],O={data:[],errors:[],meta:{}};function ie(S){return t.skipEmptyLines==="greedy"?S.join("").trim()==="":S.length===1&&S[0].length===0}function oe(){if(O&&j&&(B("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+h.DefaultDelimiter+"'"),j=!1),t.skipEmptyLines&&(O.data=O.data.filter(function(R){return!ie(R)})),k()){let R=function(U,xe){C(t.transformHeader)&&(U=t.transformHeader(U,xe)),G.push(U)};if(O)if(Array.isArray(O.data[0])){for(var S=0;k()&&S<O.data.length;S++)O.data[S].forEach(R);O.data.splice(0,1)}else O.data.forEach(R)}function P(R,U){for(var xe=t.header?{}:[],ne=0;ne<R.length;ne++){var ee=ne,J=R[ne],J=((ge,$)=>(de=>(t.dynamicTypingFunction&&t.dynamicTyping[de]===void 0&&(t.dynamicTyping[de]=t.dynamicTypingFunction(de)),(t.dynamicTyping[de]||t.dynamicTyping)===!0))(ge)?$==="true"||$==="TRUE"||$!=="false"&&$!=="FALSE"&&((de=>{if(te.test(de)&&(de=parseFloat(de),Y<de&&de<F))return 1})($)?parseFloat($):ae.test($)?new Date($):$===""?null:$):$)(ee=t.header?ne>=G.length?"__parsed_extra":G[ne]:ee,J=t.transform?t.transform(J,ee):J);ee==="__parsed_extra"?(xe[ee]=xe[ee]||[],xe[ee].push(J)):xe[ee]=J}return t.header&&(ne>G.length?B("FieldMismatch","TooManyFields","Too many fields: expected "+G.length+" fields but parsed "+ne,z+U):ne<G.length&&B("FieldMismatch","TooFewFields","Too few fields: expected "+G.length+" fields but parsed "+ne,z+U)),xe}var K;O&&(t.header||t.dynamicTyping||t.transform)&&(K=1,!O.data.length||Array.isArray(O.data[0])?(O.data=O.data.map(P),K=O.data.length):O.data=P(O.data,0),t.header&&O.meta&&(O.meta.fields=G),z+=K)}function k(){return t.header&&G.length===0}function B(S,P,K,R){S={type:S,code:P,message:K},R!==void 0&&(S.row=R),O.errors.push(S)}C(t.step)&&(v=t.step,t.step=function(S){O=S,k()?oe():(oe(),O.data.length!==0&&(re+=S.data.length,t.preview&&re>t.preview?o.abort():(O.data=O.data[0],v(O,Q))))}),this.parse=function(S,P,K){var R=t.quoteChar||'"',R=(t.newline||(t.newline=this.guessLineEndings(S,R)),j=!1,t.delimiter?C(t.delimiter)&&(t.delimiter=t.delimiter(S),O.meta.delimiter=t.delimiter):((R=((U,xe,ne,ee,J)=>{var ge,$,de,be;J=J||[","," ","|",";",h.RECORD_SEP,h.UNIT_SEP];for(var je=0;je<J.length;je++){for(var Ee,Re=J[je],he=0,Ce=0,pe=0,fe=(de=void 0,new E({comments:ee,delimiter:Re,newline:xe,preview:10}).parse(U)),Ae=0;Ae<fe.data.length;Ae++)ne&&ie(fe.data[Ae])?pe++:(Ee=fe.data[Ae].length,Ce+=Ee,de===void 0?de=Ee:0<Ee&&(he+=Math.abs(Ee-de),de=Ee));0<fe.data.length&&(Ce/=fe.data.length-pe),($===void 0||he<=$)&&(be===void 0||be<Ce)&&1.99<Ce&&($=he,ge=Re,be=Ce)}return{successful:!!(t.delimiter=ge),bestDelimiter:ge}})(S,t.newline,t.skipEmptyLines,t.comments,t.delimitersToGuess)).successful?t.delimiter=R.bestDelimiter:(j=!0,t.delimiter=h.DefaultDelimiter),O.meta.delimiter=t.delimiter),q(t));return t.preview&&t.header&&R.preview++,a=S,o=new E(R),O=o.parse(a,P,K),oe(),ue?{meta:{paused:!0}}:O||{meta:{paused:!1}}},this.paused=function(){return ue},this.pause=function(){ue=!0,o.abort(),a=C(t.chunk)?"":a.substring(o.getCharIndex())},this.resume=function(){Q.streamer._halted?(ue=!1,Q.streamer.parseChunk(a,!0)):setTimeout(Q.resume,3)},this.aborted=function(){return W},this.abort=function(){W=!0,o.abort(),O.meta.aborted=!0,C(t.complete)&&t.complete(O),a=""},this.guessLineEndings=function(U,R){U=U.substring(0,1048576);var R=new RegExp(w(R)+"([^]*?)"+w(R),"gm"),K=(U=U.replace(R,"")).split("\r"),R=U.split(`
|
|
2
|
+
`),U=1<R.length&&R[0].length<K[0].length;if(K.length===1||U)return`
|
|
3
|
+
`;for(var xe=0,ne=0;ne<K.length;ne++)K[ne][0]===`
|
|
4
|
+
`&&xe++;return xe>=K.length/2?`\r
|
|
5
|
+
`:"\r"}}function w(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function E(t){var a=(t=t||{}).delimiter,o=t.newline,j=t.comments,v=t.step,F=t.preview,Y=t.fastMode,te=null,ae=!1,Q=t.quoteChar==null?'"':t.quoteChar,re=Q;if(t.escapeChar!==void 0&&(re=t.escapeChar),(typeof a!="string"||-1<h.BAD_DELIMITERS.indexOf(a))&&(a=","),j===a)throw new Error("Comment character same as delimiter");j===!0?j="#":(typeof j!="string"||-1<h.BAD_DELIMITERS.indexOf(j))&&(j=!1),o!==`
|
|
6
|
+
`&&o!=="\r"&&o!==`\r
|
|
7
|
+
`&&(o=`
|
|
8
|
+
`);var z=0,ue=!1;this.parse=function(W,G,O){if(typeof W!="string")throw new Error("Input must be a string");var ie=W.length,oe=a.length,k=o.length,B=j.length,S=C(v),P=[],K=[],R=[],U=z=0;if(!W)return he();if(Y||Y!==!1&&W.indexOf(Q)===-1){for(var xe=W.split(o),ne=0;ne<xe.length;ne++){if(R=xe[ne],z+=R.length,ne!==xe.length-1)z+=o.length;else if(O)return he();if(!j||R.substring(0,B)!==j){if(S){if(P=[],be(R.split(a)),Ce(),ue)return he()}else be(R.split(a));if(F&&F<=ne)return P=P.slice(0,F),he(!0)}}return he()}for(var ee=W.indexOf(a,z),J=W.indexOf(o,z),ge=new RegExp(w(re)+w(Q),"g"),$=W.indexOf(Q,z);;)if(W[z]===Q)for($=z,z++;;){if(($=W.indexOf(Q,$+1))===-1)return O||K.push({type:"Quotes",code:"MissingQuotes",message:"Quoted field unterminated",row:P.length,index:z}),Ee();if($===ie-1)return Ee(W.substring(z,$).replace(ge,Q));if(Q===re&&W[$+1]===re)$++;else if(Q===re||$===0||W[$-1]!==re){ee!==-1&&ee<$+1&&(ee=W.indexOf(a,$+1));var de=je((J=J!==-1&&J<$+1?W.indexOf(o,$+1):J)===-1?ee:Math.min(ee,J));if(W.substr($+1+de,oe)===a){R.push(W.substring(z,$).replace(ge,Q)),W[z=$+1+de+oe]!==Q&&($=W.indexOf(Q,z)),ee=W.indexOf(a,z),J=W.indexOf(o,z);break}if(de=je(J),W.substring($+1+de,$+1+de+k)===o){if(R.push(W.substring(z,$).replace(ge,Q)),Re($+1+de+k),ee=W.indexOf(a,z),$=W.indexOf(Q,z),S&&(Ce(),ue))return he();if(F&&P.length>=F)return he(!0);break}K.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:P.length,index:z}),$++}}else if(j&&R.length===0&&W.substring(z,z+B)===j){if(J===-1)return he();z=J+k,J=W.indexOf(o,z),ee=W.indexOf(a,z)}else if(ee!==-1&&(ee<J||J===-1))R.push(W.substring(z,ee)),z=ee+oe,ee=W.indexOf(a,z);else{if(J===-1)break;if(R.push(W.substring(z,J)),Re(J+k),S&&(Ce(),ue))return he();if(F&&P.length>=F)return he(!0)}return Ee();function be(pe){P.push(pe),U=z}function je(pe){var fe=0;return fe=pe!==-1&&(pe=W.substring($+1,pe))&&pe.trim()===""?pe.length:fe}function Ee(pe){return O||(pe===void 0&&(pe=W.substring(z)),R.push(pe),z=ie,be(R),S&&Ce()),he()}function Re(pe){z=pe,be(R),R=[],J=W.indexOf(o,z)}function he(pe){if(t.header&&!G&&P.length&&!ae){var fe=P[0],Ae=Object.create(null),We=new Set(fe);let ns=!1;for(let Le=0;Le<fe.length;Le++){let ye=fe[Le];if(Ae[ye=C(t.transformHeader)?t.transformHeader(ye,Le):ye]){let Ie,ls=Ae[ye];for(;Ie=ye+"_"+ls,ls++,We.has(Ie););We.add(Ie),fe[Le]=Ie,Ae[ye]++,ns=!0,(te=te===null?{}:te)[Ie]=ye}else Ae[ye]=1,fe[Le]=ye;We.add(ye)}ns&&console.warn("Duplicate headers found and renamed."),ae=!0}return{data:P,errors:K,meta:{delimiter:a,linebreak:o,aborted:ue,truncated:!!pe,cursor:U+(G||0),renamedHeaders:te}}}function Ce(){v(he()),P=[],K=[]}},this.abort=function(){ue=!0},this.getCharIndex=function(){return z}}function H(t){var a=t.data,o=g[a.workerId],j=!1;if(a.error)o.userError(a.error,a.file);else if(a.results&&a.results.data){var v={abort:function(){j=!0,Z(a.workerId,{data:[],errors:[],meta:{aborted:!0}})},pause:X,resume:X};if(C(o.userStep)){for(var F=0;F<a.results.data.length&&(o.userStep({data:a.results.data[F],errors:a.results.errors,meta:a.results.meta},v),!j);F++);delete a.results}else C(o.userChunk)&&(o.userChunk(a.results,v,a.file),delete a.results)}a.finished&&!j&&Z(a.workerId,a.results)}function Z(t,a){var o=g[t];C(o.userComplete)&&o.userComplete(a),o.terminate(),delete g[t]}function X(){throw new Error("Not implemented.")}function q(t){if(typeof t!="object"||t===null)return t;var a,o=Array.isArray(t)?[]:{};for(a in t)o[a]=q(t[a]);return o}function le(t,a){return function(){t.apply(a,arguments)}}function C(t){return typeof t=="function"}return h.parse=function(t,a){var o=(a=a||{}).dynamicTyping||!1;if(C(o)&&(a.dynamicTypingFunction=o,o={}),a.dynamicTyping=o,a.transform=!!C(a.transform)&&a.transform,!a.worker||!h.WORKERS_SUPPORTED)return o=null,h.NODE_STREAM_INPUT,typeof t=="string"?(t=(j=>j.charCodeAt(0)!==65279?j:j.slice(1))(t),o=new(a.download?I:x)(a)):t.readable===!0&&C(t.read)&&C(t.on)?o=new N(a):(i.File&&t instanceof File||t instanceof Object)&&(o=new T(a)),o.stream(t);(o=(()=>{var j;return!!h.WORKERS_SUPPORTED&&(j=(()=>{var v=i.URL||i.webkitURL||null,F=n.toString();return h.BLOB_URL||(h.BLOB_URL=v.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",F,")();"],{type:"text/javascript"})))})(),(j=new i.Worker(j)).onmessage=H,j.id=b++,g[j.id]=j)})()).userStep=a.step,o.userChunk=a.chunk,o.userComplete=a.complete,o.userError=a.error,a.step=C(a.step),a.chunk=C(a.chunk),a.complete=C(a.complete),a.error=C(a.error),delete a.worker,o.postMessage({input:t,config:a,workerId:o.id})},h.unparse=function(t,a){var o=!1,j=!0,v=",",F=`\r
|
|
9
|
+
`,Y='"',te=Y+Y,ae=!1,Q=null,re=!1,z=((()=>{if(typeof a=="object"){if(typeof a.delimiter!="string"||h.BAD_DELIMITERS.filter(function(G){return a.delimiter.indexOf(G)!==-1}).length||(v=a.delimiter),typeof a.quotes!="boolean"&&typeof a.quotes!="function"&&!Array.isArray(a.quotes)||(o=a.quotes),typeof a.skipEmptyLines!="boolean"&&typeof a.skipEmptyLines!="string"||(ae=a.skipEmptyLines),typeof a.newline=="string"&&(F=a.newline),typeof a.quoteChar=="string"&&(Y=a.quoteChar),typeof a.header=="boolean"&&(j=a.header),Array.isArray(a.columns)){if(a.columns.length===0)throw new Error("Option columns is empty");Q=a.columns}a.escapeChar!==void 0&&(te=a.escapeChar+Y),a.escapeFormulae instanceof RegExp?re=a.escapeFormulae:typeof a.escapeFormulae=="boolean"&&a.escapeFormulae&&(re=/^[=+\-@\t\r].*$/)}})(),new RegExp(w(Y),"g"));if(typeof t=="string"&&(t=JSON.parse(t)),Array.isArray(t)){if(!t.length||Array.isArray(t[0]))return ue(null,t,ae);if(typeof t[0]=="object")return ue(Q||Object.keys(t[0]),t,ae)}else if(typeof t=="object")return typeof t.data=="string"&&(t.data=JSON.parse(t.data)),Array.isArray(t.data)&&(t.fields||(t.fields=t.meta&&t.meta.fields||Q),t.fields||(t.fields=Array.isArray(t.data[0])?t.fields:typeof t.data[0]=="object"?Object.keys(t.data[0]):[]),Array.isArray(t.data[0])||typeof t.data[0]=="object"||(t.data=[t.data])),ue(t.fields||[],t.data||[],ae);throw new Error("Unable to serialize unrecognized input");function ue(G,O,ie){var oe="",k=(typeof G=="string"&&(G=JSON.parse(G)),typeof O=="string"&&(O=JSON.parse(O)),Array.isArray(G)&&0<G.length),B=!Array.isArray(O[0]);if(k&&j){for(var S=0;S<G.length;S++)0<S&&(oe+=v),oe+=W(G[S],S);0<O.length&&(oe+=F)}for(var P=0;P<O.length;P++){var K=(k?G:O[P]).length,R=!1,U=k?Object.keys(O[P]).length===0:O[P].length===0;if(ie&&!k&&(R=ie==="greedy"?O[P].join("").trim()==="":O[P].length===1&&O[P][0].length===0),ie==="greedy"&&k){for(var xe=[],ne=0;ne<K;ne++){var ee=B?G[ne]:ne;xe.push(O[P][ee])}R=xe.join("").trim()===""}if(!R){for(var J=0;J<K;J++){0<J&&!U&&(oe+=v);var ge=k&&B?G[J]:J;oe+=W(O[P][ge],J)}P<O.length-1&&(!ie||0<K&&!U)&&(oe+=F)}}return oe}function W(G,O){var ie,oe;return G==null?"":G.constructor===Date?JSON.stringify(G).slice(1,25):(oe=!1,re&&typeof G=="string"&&re.test(G)&&(G="'"+G,oe=!0),ie=G.toString().replace(z,te),(oe=oe||o===!0||typeof o=="function"&&o(G,O)||Array.isArray(o)&&o[O]||((k,B)=>{for(var S=0;S<B.length;S++)if(-1<k.indexOf(B[S]))return!0;return!1})(ie,h.BAD_DELIMITERS)||-1<ie.indexOf(v)||ie.charAt(0)===" "||ie.charAt(ie.length-1)===" ")?Y+ie+Y:ie)}},h.RECORD_SEP="",h.UNIT_SEP="",h.BYTE_ORDER_MARK="\uFEFF",h.BAD_DELIMITERS=["\r",`
|
|
10
|
+
`,'"',h.BYTE_ORDER_MARK],h.WORKERS_SUPPORTED=!f&&!!i.Worker,h.NODE_STREAM_INPUT=1,h.LocalChunkSize=10485760,h.RemoteChunkSize=5242880,h.DefaultDelimiter=",",h.Parser=E,h.ParserHandle=y,h.NetworkStreamer=I,h.FileStreamer=T,h.StringStreamer=x,h.ReadableStreamStreamer=N,i.jQuery&&((r=i.jQuery).fn.parse=function(t){var a=t.config||{},o=[];return this.each(function(F){if(!(r(this).prop("tagName").toUpperCase()==="INPUT"&&r(this).attr("type").toLowerCase()==="file"&&i.FileReader)||!this.files||this.files.length===0)return!0;for(var Y=0;Y<this.files.length;Y++)o.push({file:this.files[Y],inputElem:this,instanceConfig:r.extend({},a)})}),j(),this;function j(){if(o.length===0)C(t.complete)&&t.complete();else{var F,Y,te,ae,Q=o[0];if(C(t.before)){var re=t.before(Q.file,Q.inputElem);if(typeof re=="object"){if(re.action==="abort")return F="AbortError",Y=Q.file,te=Q.inputElem,ae=re.reason,void(C(t.error)&&t.error({name:F},Y,te,ae));if(re.action==="skip")return void v();typeof re.config=="object"&&(Q.instanceConfig=r.extend(Q.instanceConfig,re.config))}else if(re==="skip")return void v()}var z=Q.instanceConfig.complete;Q.instanceConfig.complete=function(ue){C(z)&&z(ue,Q.file,Q.inputElem),v()},h.parse(Q.file,Q.instanceConfig)}}function v(){o.splice(0,1),j()}}),u&&(i.onmessage=function(t){t=t.data,h.WORKER_ID===void 0&&t&&(h.WORKER_ID=t.workerId),typeof t.input=="string"?i.postMessage({workerId:h.WORKER_ID,results:h.parse(t.input,t.config),finished:!0}):(i.File&&t.input instanceof File||t.input instanceof Object)&&(t=h.parse(t.input,t.config))&&i.postMessage({workerId:h.WORKER_ID,results:t,finished:!0})}),(I.prototype=Object.create(c.prototype)).constructor=I,(T.prototype=Object.create(c.prototype)).constructor=T,(x.prototype=Object.create(x.prototype)).constructor=x,(N.prototype=Object.create(c.prototype)).constructor=N,h})})(et)),et.exports}var Fl=Pl();const fa=xr(Fl);function zl(s){if(!s)return!1;const l=s.replace(/[^0-9]/g,"");return l.length>=8&&l.length<=20}function ql(s){return!s||s.trim()===""?!0:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim())}function Bl(s){const l=String(s);return(l.includes(".")?l.split(".")[0]:l).replace(/[^0-9]/g,"")}function $l(s){const l=s.replace(/[^0-9]/g,"");return l.length===9&&l.startsWith("9")}function Ul(s){if(!s||s.trim()===""||s.trim()==="null")return!0;try{const l=JSON.parse(s);return typeof l=="object"&&l!==null}catch{return!1}}const os=50;function Ns(s,l=50){return s?s.length>l?s.substring(0,l)+"...":s:"-"}function Nt(s,l){const n={totalRows:s.length,validRows:0,skippedNoIdentifier:0,skippedInvalidPhone:0,skippedInvalidEmail:0,skippedDuplicateInCsv:0,invalidMetadataCells:0,phonesWithoutCountryCode:0,uniqueTags:[],extraColumns:[],errorDetails:[]},i=new Set,r=new Set,f=new Set,u={},g=[],b=[];for(const[h,c]of Object.entries(l))c&&(c==="metadata_json"?g.push(h):c==="metadata_extra"?b.push(h):u[c]=h);n.extraColumns=b;for(let h=0;h<s.length;h++){const c=s[h],I=h+2,T=u.phone,x=u.email,N=u.tags,y=T?c[T]?.trim():"",w=x?c[x]?.trim():"";if(!y&&!w){n.skippedNoIdentifier++,n.errorDetails.length<os&&n.errorDetails.push({row:I,reason:"no_identifier",field:[T,x].filter(Boolean).join(" / ")||"phone/email",value:"-"});continue}if(y){const E=Bl(y);if(!zl(E)){n.skippedInvalidPhone++,n.errorDetails.length<os&&n.errorDetails.push({row:I,reason:"invalid_phone",field:T,value:Ns(y)});continue}if($l(E)&&n.phonesWithoutCountryCode++,i.has(E)){n.skippedDuplicateInCsv++,n.errorDetails.length<os&&n.errorDetails.push({row:I,reason:"duplicate",field:T,value:Ns(E)});continue}i.add(E)}if(!y&&w){const E=w.toLowerCase();if(r.has(E)){n.skippedDuplicateInCsv++,n.errorDetails.length<os&&n.errorDetails.push({row:I,reason:"duplicate",field:x,value:Ns(w)});continue}r.add(E)}else w&&r.add(w.toLowerCase());if(w&&!ql(w)){n.skippedInvalidEmail++,n.errorDetails.length<os&&n.errorDetails.push({row:I,reason:"invalid_email",field:x,value:Ns(w)});continue}for(const E of g){const H=c[E]?.trim();H&&!Ul(H)&&(n.invalidMetadataCells++,n.errorDetails.length<os&&n.errorDetails.push({row:I,reason:"invalid_json",field:E,value:Ns(H)}))}N&&c[N]&&c[N].split(/[,;]/).map(E=>E.trim()).filter(Boolean).forEach(E=>f.add(E)),n.validRows++}return n.uniqueTags=Array.from(f),n}const Vl=[{value:"name",label:"Nombre Completo"},{value:"phone",label:"Telefono"},{value:"email",label:"Correo Electronico"},{value:"tags",label:"Etiquetas (sep. por , o ;)"}],Hl=5*1024*1024,Wl=({open:s,onOpenChange:l,onImportSuccess:n})=>{const[i,r]=m.useState("upload"),[f,u]=m.useState(null),[g,b]=m.useState([]),[h,c]=m.useState([]),[I,T]=m.useState({}),[x,N]=m.useState(null),[y,w]=m.useState(null),[E,H]=m.useState(""),[Z,X]=m.useState(!1),[q,le]=m.useState(!1),[C,t]=m.useState(null),[a,o]=m.useState("skip"),[j,v]=m.useState(new Set),[F,Y]=m.useState([]),[te,ae]=m.useState(""),[Q,re]=m.useState(!1),[z,ue]=m.useState(null),[W,G]=m.useState(!1),[O,ie]=m.useState(""),[oe,k]=m.useState(null),[B,S]=m.useState(!1),{channels:P}=Fa(),{folders:K,fetchFolders:R}=Rt(),{importStatus:U,resetImportStatus:xe,setJobQueued:ne}=Rl(s);m.useEffect(()=>{if(!U||!s)return;const{status:p}=U;(p==="queued"||p==="processing")&&i!=="uploading"&&r("uploading"),p==="completed"&&U.result&&i!=="result"&&(w(U.result),r("result"),i==="uploading"&&(ge(),n(),D.success(a==="skip"?`Importacion completada: ${U.result.newContactsInserted} nuevos, ${U.result.existingContactsSkipped} omitidos`:`Importacion completada: ${U.result.newContactsInserted} nuevos, ${U.result.existingContactsUpdated} actualizados`))),p==="failed"&&i!=="result"&&(r("result"),w(U.result||null),i==="uploading"&&D.error("La importacion falló",{description:U.message||"Error desconocido durante la importacion",duration:8e3}))},[U?.status,U?.result,s,i,a]);const{pool:ee,blocked:J,refetch:ge}=za({resourceType:"CONTACTS",enabled:s});m.useEffect(()=>{R()},[R]);const $=m.useMemo(()=>K.flatMap(p=>(p.tags||[]).map(d=>({id:d.id,name:d.name,color:d.color}))),[K]),de=m.useMemo(()=>F.map(p=>$.find(d=>d.id===p)?.name).filter(Boolean),[F,$]),be=m.useMemo(()=>$.filter(p=>F.includes(p.id)),[$,F]),je=m.useMemo(()=>$.filter(p=>!F.includes(p.id)&&p.name.toLowerCase().includes(te.toLowerCase())),[$,F,te]),Ee=m.useCallback(async p=>{const d=p[0];if(d){if(d.size>Hl){D.error("El archivo excede el limite de 10MB");return}u(d),await We(d)}},[]),{getRootProps:Re,getInputProps:he,isDragActive:Ce}=mn({onDrop:Ee,accept:{"text/csv":[".csv"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":[".xlsx"]},maxFiles:1}),pe=p=>{p.stopPropagation();const d=`Nombre,Telefono,Email,Etiquetas
|
|
11
|
+
Juan Perez,51987654321,juan@email.com,"Lima; Cliente"
|
|
12
|
+
Maria Lopez,51912345678,maria@email.com,"Arequipa"`,A=new Blob([d],{type:"text/csv"}),_=document.createElement("a");_.href=URL.createObjectURL(A),_.download="plantilla_importacion_contactos.csv",_.click(),URL.revokeObjectURL(_.href)},fe=p=>{const d={};return p.forEach(A=>{const _=A.toLowerCase();_.includes("name")||_.includes("nombre")||_.includes("apellido")?d[A]="name":_.includes("phone")||_.includes("tel")||_.includes("celular")||_.includes("numero")?d[A]="phone":_.includes("email")||_.includes("correo")||_.includes("mail")?d[A]="email":(_.includes("tag")||_.includes("etiqueta"))&&(d[A]="tags")}),d},Ae=async p=>{try{const d=await Kt(()=>import("./xlsx-BvJTHLik.js"),[]),A=await p.arrayBuffer(),_=d.read(A,{type:"array",cellFormula:!1,cellStyles:!1});if(!_.SheetNames||_.SheetNames.length===0){D.error("El archivo Excel no contiene hojas.");return}const V=_.Sheets[_.SheetNames[0]];if(!V||!V["!ref"]){D.error("La primera hoja del Excel esta vacia.");return}if(V["!merges"]&&V["!merges"].length>0){D.error("El Excel contiene celdas combinadas. Eliminalas antes de importar.");return}const ce=d.utils.decode_range(V["!ref"]),Me=ce.e.c-ce.s.c+1;if(Me>30){D.error(`El archivo tiene ${Me} columnas. Maximo permitido: 30.`);return}const vs=d.utils.sheet_to_json(V,{defval:"",raw:!1});if(vs.length===0){D.error("La hoja no contiene datos.");return}const Ht=Object.keys(vs[0]||{}).filter(ft=>ft.trim()?vs.slice(0,20).some(Wt=>Wt[ft]&&String(Wt[ft]).trim()!==""):!1);k(vs),b(Ht),c(vs.slice(0,5)),T(fe(Ht)),ie(""),r("mapping")}catch(d){D.error("Error al leer Excel: "+(d.message||"archivo corrupto o formato no soportado"))}},We=async p=>{if(p.name.toLowerCase().endsWith(".xlsx")){await Ae(p);return}try{const A=await p.slice(0,4).arrayBuffer(),_=new Uint8Array(A);_[0]===255&&_[1]===254?ie("El archivo parece estar en UTF-16 LE. La vista previa podria mostrar caracteres incorrectos, pero la importacion final convertira el archivo correctamente."):_[0]===254&&_[1]===255?ie("El archivo parece estar en UTF-16 BE. La vista previa podria mostrar caracteres incorrectos, pero la importacion final convertira el archivo correctamente."):ie("")}catch{}fa.parse(p,{header:!0,preview:5,skipEmptyLines:!0,complete:A=>{const _=A.meta.fields||[];b(_),c(A.data),T(fe(_)),r("mapping")},error:A=>{D.error("Error al leer CSV: "+A.message)}})},ns=()=>{if(!f)return;if(N(null),ue(null),X(!0),r("validation"),f.name.toLowerCase().endsWith(".xlsx")){if(oe){const d=Nt(oe,I);N(d),X(!1);return}Kt(()=>import("./xlsx-BvJTHLik.js"),[]).then(d=>{f.arrayBuffer().then(A=>{try{const _=d.read(A,{type:"array",cellFormula:!1,cellStyles:!1}),V=_.Sheets[_.SheetNames[0]],ce=d.utils.sheet_to_json(V,{defval:"",raw:!1}),Me=Nt(ce,I);N(Me),X(!1)}catch(_){D.error("Error al validar Excel: "+(_.message||"error desconocido")),X(!1),r("mapping")}})});return}fa.parse(f,{header:!0,skipEmptyLines:!0,complete:d=>{const A=Nt(d.data,I);N(A),X(!1)},error:d=>{D.error("Error al validar CSV: "+d.message),X(!1),r("mapping")}})},Le=async()=>{if(f){G(!0),ue(null);try{const p={};for(const[A,_]of Object.entries(I))_&&_!=="__ignore__"&&(p[A]=_);const d=await se.importContacts(f,p,E||void 0,a,Array.from(j),de,!0,B);ue(d)}catch{D.error("Error al generar vista previa")}finally{G(!1)}}},ye=async()=>{if(f){r("uploading");try{const p={};for(const[A,_]of Object.entries(I))_&&_!=="__ignore__"&&(p[A]=_);const d=await se.importContacts(f,p,E||void 0,a,Array.from(j),de,!1,B);"jobId"in d?ne(d.jobId):(w(d),r("result"))}catch(p){console.error(p);const d=(p?.response?.data?.message||p?.message||"").toLowerCase();d.includes("límite")||d.includes("limite")||d.includes("créditos")||d.includes("creditos")?D.error("Limite de Contactos Alcanzado",{description:p?.response?.data?.message||"Tu plan no permite importar mas contactos. Actualiza tu plan o contacta al administrador.",duration:8e3}):d.includes("importación en curso")||d.includes("importacion en curso")?D.error("Importacion en curso",{description:"Ya hay una importacion activa. Espera a que termine.",duration:5e3}):D.error("Error al importar archivo"),r("validation")}}},Ie=()=>{u(null),b([]),c([]),T({}),N(null),w(null),H(""),X(!1),le(!1),t(null),o("skip"),v(new Set),Y([]),ae(""),re(!1),k(null),S(!1),ue(null),G(!1),ie(""),xe(),se.dismissImportStatus().catch(()=>{}),r("upload")},ls=(p,d)=>{d==="__ignore__"?T(A=>{const _={...A};return delete _[p],_}):["phone","email","name","metadata_json"].includes(d)?T(_=>{const V={..._};for(const[ce,Me]of Object.entries(V))Me===d&&ce!==p&&delete V[ce];return V[p]=d,V}):T(_=>({..._,[p]:d}))},Ps=p=>{v(d=>{const A=new Set(d);return A.has(p)?A.delete(p):A.add(p),A})},De=p=>{if(!p.length)return;const d=`Fila,Campo,Valor,Razon
|
|
13
|
+
`,A=p.map(Me=>`${Me.row},"${(Me.field||"").replace(/"/g,'""')}","${(Me.value||"").replace(/"/g,'""')}","${(Me.reason||"").replace(/"/g,'""')}"`).join(`
|
|
14
|
+
`),_=new Blob([d+A],{type:"text/csv"}),V=URL.createObjectURL(_),ce=document.createElement("a");ce.href=V,ce.download=`errores_importacion_${new Date().toISOString().slice(0,10)}.csv`,document.body.appendChild(ce),ce.click(),document.body.removeChild(ce),URL.revokeObjectURL(V)},js=Object.values(I).some(p=>p==="phone"||p==="email"),is=p=>{const d=new Set(Object.values(I)),A=Vl.map(V=>({...V,disabled:d.has(V.value)&&V.value!=="tags"&&I[p]!==V.value})),_=d.has("metadata_json")&&I[p]!=="metadata_json";return{coreOptions:A,metadataJsonUsed:_}},ht={upload:"Subir",mapping:"Mapear",validation:"Validar",uploading:"Progreso",result:"Resultado"},Fs=["upload","mapping","validation","uploading","result"],zs=Fs.indexOf(i),Oe=x?x.skippedNoIdentifier+x.skippedInvalidPhone+x.skippedInvalidEmail+x.skippedDuplicateInCsv:0,pt=x?x.uniqueTags.length-j.size:0;return e.jsx(es,{open:s,onOpenChange:p=>{p||(i==="uploading"?le(!1):Ie()),l(p)},children:e.jsxs(ss,{className:`overflow-y-auto transition-all duration-200 ${q?"sm:max-w-[95vw] max-h-[95vh] h-[95vh]":"sm:max-w-[750px] max-h-[90vh]"}`,children:[e.jsxs("button",{type:"button",onClick:()=>le(p=>!p),className:"ring-offset-background focus:ring-ring absolute top-4 right-12 h-8 w-8 rounded-md flex items-center justify-center text-muted-foreground opacity-70 transition-all hover:opacity-100 hover:bg-muted focus:ring-2 focus:ring-offset-2 focus:outline-hidden",children:[q?e.jsx(Gr,{className:"h-4 w-4"}):e.jsx(xn,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:q?"Restaurar":"Maximizar"})]}),e.jsxs(ts,{children:[e.jsx(as,{className:"text-lg tracking-tight",children:"Importar Contactos"}),e.jsxs(gs,{children:[i==="upload"&&"Sube tu archivo CSV para comenzar.",i==="mapping"&&"Mapea las columnas de tu CSV a los campos de Nubot.",i==="validation"&&"Revisa el resumen de validacion antes de importar.",i==="uploading"&&"La importacion se procesa en segundo plano. Puedes cerrar este dialogo.",i==="result"&&"Resultado de la importacion."]})]}),e.jsx("div",{className:"flex items-center gap-2",children:Fs.map((p,d)=>e.jsx("div",{className:"flex items-center gap-2 flex-1",children:e.jsxs("div",{className:"flex flex-col items-center gap-1 flex-1",children:[e.jsx("div",{className:`h-1 w-full rounded-full transition-all duration-300 ${d<=zs?"bg-primary":"bg-muted"}`}),e.jsx("span",{className:`text-[10px] font-medium transition-colors ${d<=zs?"text-primary":"text-muted-foreground/50"}`,children:ht[p]})]})},p))}),e.jsxs("div",{className:"py-1 flex-1",children:[i==="upload"&&e.jsxs("div",{...Re(),className:`border-2 border-dashed rounded-xl p-12 flex flex-col items-center justify-center text-center cursor-pointer transition-all duration-200 ${Ce?"border-primary bg-primary/5 scale-[1.01]":"border-border hover:border-primary/40 hover:bg-muted/30"}`,children:[e.jsx("input",{...he()}),e.jsx("div",{className:`w-14 h-14 rounded-xl flex items-center justify-center mb-5 transition-colors ${Ce?"bg-primary/10 text-primary":"bg-muted text-muted-foreground"}`,children:e.jsx(_t,{className:"w-7 h-7"})}),e.jsx("h3",{className:"text-base font-semibold tracking-tight mb-1",children:"Arrastra tu archivo aqui"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-5",children:"o haz clic para seleccionar un archivo CSV o Excel"}),e.jsx(L,{variant:"outline",size:"sm",className:"rounded-lg",children:"Seleccionar Archivo"}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-3",children:"CSV o Excel (.xlsx) hasta 5MB"}),e.jsxs(L,{variant:"link",size:"sm",className:"mt-1 text-[11px] text-primary/70 hover:text-primary h-auto p-0",onClick:pe,children:[e.jsx(_s,{className:"w-3 h-3 mr-1"}),"Descargar plantilla"]})]}),i==="mapping"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 bg-muted/40 rounded-lg border",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:e.jsx(dr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 overflow-hidden",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:f?.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.length," columnas detectadas"]})]}),e.jsx(L,{variant:"ghost",size:"sm",onClick:Ie,className:"text-xs text-muted-foreground",children:"Cambiar"})]}),e.jsxs("div",{className:"space-y-2 px-4 py-3 bg-muted/20 rounded-lg border",children:[e.jsxs("label",{className:"text-xs font-medium text-foreground flex items-center gap-2",children:[e.jsx("div",{className:"p-1 rounded bg-primary/10",children:e.jsx(Os,{className:"w-3 h-3 text-primary"})}),"Canal de Origen",e.jsx("span",{className:"text-muted-foreground font-normal",children:"(opcional)"})]}),e.jsxs(nt,{value:E,onValueChange:H,children:[e.jsx(lt,{className:"bg-background h-9",children:e.jsx(it,{placeholder:"Seleccionar un canal..."})}),e.jsxs(ot,{children:[e.jsx(Fe,{value:"none",children:"Ninguno"}),P.map(p=>e.jsxs(Fe,{value:p.id,children:[p.name," (",p.type,")"]},p.id))]})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground leading-relaxed",children:"Vincula contactos a un canal para usarlos en campanas."})]}),e.jsxs("div",{className:"space-y-2 px-4 py-3 bg-muted/20 rounded-lg border",children:[e.jsxs("label",{className:"text-xs font-medium text-foreground flex items-center gap-2",children:[e.jsx("div",{className:"p-1 rounded bg-primary/10",children:e.jsx(gt,{className:"w-3 h-3 text-primary"})}),"Modo de Importacion"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>o("skip"),className:`flex flex-col items-start gap-1.5 p-3 rounded-lg border text-left transition-all ${a==="skip"?"border-primary bg-primary/5 ring-1 ring-primary/20":"border-border hover:border-primary/30 hover:bg-muted/30"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`p-1 rounded ${a==="skip"?"bg-primary/10":"bg-muted"}`,children:e.jsx(Ds,{className:`w-3.5 h-3.5 ${a==="skip"?"text-primary":"text-muted-foreground"}`})}),e.jsx("span",{className:"text-xs font-semibold",children:"Omitir existentes"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground leading-relaxed",children:"Solo agrega contactos nuevos. Los existentes no se modifican."})]}),e.jsxs("button",{type:"button",onClick:()=>o("enrich"),className:`flex flex-col items-start gap-1.5 p-3 rounded-lg border text-left transition-all ${a==="enrich"?"border-primary bg-primary/5 ring-1 ring-primary/20":"border-border hover:border-primary/30 hover:bg-muted/30"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`p-1 rounded ${a==="enrich"?"bg-primary/10":"bg-muted"}`,children:e.jsx(Lt,{className:`w-3.5 h-3.5 ${a==="enrich"?"text-primary":"text-muted-foreground"}`})}),e.jsx("span",{className:"text-xs font-semibold",children:"Enriquecer"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground leading-relaxed",children:"Actualiza campos vacios y agrega etiquetas a contactos existentes."})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/50 border-b",children:[e.jsx("th",{className:"px-4 py-2.5 text-left text-xs font-medium text-muted-foreground w-[30%]",children:"Columna CSV"}),e.jsx("th",{className:"px-4 py-2.5 text-left text-xs font-medium text-muted-foreground w-[40%]",children:"Campo Destino"}),e.jsx("th",{className:"px-4 py-2.5 text-left text-xs font-medium text-muted-foreground w-[30%]",children:"Vista previa"})]})}),e.jsx("tbody",{className:"divide-y",children:g.map((p,d)=>{const{coreOptions:A,metadataJsonUsed:_}=is(p),V=I[p];return e.jsxs("tr",{className:`transition-colors ${V&&V!=="__ignore__"?"bg-primary/[0.02]":"bg-card"}`,children:[e.jsx("td",{className:"px-4 py-2.5",children:e.jsx("span",{className:"text-xs font-medium font-mono bg-muted px-1.5 py-0.5 rounded",children:p})}),e.jsx("td",{className:"px-4 py-2.5",children:e.jsxs(nt,{value:V||"__ignore__",onValueChange:ce=>ls(p,ce),children:[e.jsx(lt,{className:"h-8 w-full bg-background",children:e.jsx(it,{placeholder:"Ignorar"})}),e.jsxs(ot,{children:[e.jsx(Fe,{value:"__ignore__",children:e.jsx("span",{className:"text-muted-foreground",children:"Ignorar Columna"})}),A.map(ce=>e.jsx(Fe,{value:ce.value,disabled:ce.disabled,children:ce.label},ce.value)),e.jsx(Fe,{value:"metadata_json",disabled:_,children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Yt,{className:"w-3 h-3"}),"Metadata (JSON)"]})}),e.jsx(Fe,{value:"metadata_extra",children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(gt,{className:"w-3 h-3"}),"Info. Adicional"]})})]})]})}),e.jsx("td",{className:"px-4 py-2.5",children:e.jsx("span",{className:"text-xs text-muted-foreground truncate block max-w-[180px]",children:h[0]?.[p]||e.jsx("span",{className:"italic",children:"vacio"})})})]},d)})})]})})]}),i==="validation"&&e.jsxs("div",{className:"space-y-4",children:[Z?e.jsxs("div",{className:"py-16 flex flex-col items-center justify-center text-center space-y-3",children:[e.jsx("div",{className:"p-3 rounded-xl bg-primary/10",children:e.jsx(ke,{className:"h-8 w-8 animate-spin text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Validando archivo..."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Esto solo toma unos segundos"})]})]}):x?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-xl border bg-card p-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-1",children:"Contactos validos"}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-4xl font-bold tracking-tight text-foreground",children:x.validRows}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["de ",x.totalRows]})]})]}),e.jsx("div",{className:"p-3 rounded-xl bg-emerald-500/10",children:e.jsx(bt,{className:"h-7 w-7 text-emerald-500"})})]}),e.jsx("div",{className:"mt-4 h-2 w-full rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-emerald-500 transition-all duration-500",style:{width:`${x.totalRows>0?x.validRows/x.totalRows*100:0}%`}})}),e.jsxs("div",{className:"mt-2 flex justify-between text-[10px] text-muted-foreground",children:[e.jsxs("span",{children:[x.totalRows>0?Math.round(x.validRows/x.totalRows*100):0,"% listos para importar"]}),Oe>0&&e.jsxs("span",{children:[Oe," se omitiran"]})]})]}),x.phonesWithoutCountryCode>0&&e.jsx("div",{className:"rounded-xl border p-4 bg-amber-50 border-amber-200 dark:bg-amber-950/20 dark:border-amber-800",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ve,{className:"h-5 w-5 shrink-0 text-amber-500"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"text-sm font-semibold text-amber-700 dark:text-amber-400",children:[x.phonesWithoutCountryCode," numeros sin codigo de pais"]}),e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400/80",children:"Se detectaron numeros de 9 digitos sin el prefijo 51 (ej: 951708151 en vez de 51951708151)."}),e.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:B,onChange:p=>S(p.target.checked),className:"rounded border-amber-400 text-amber-600 focus:ring-amber-500"}),e.jsxs("span",{className:"text-xs font-medium text-amber-700 dark:text-amber-400",children:["Agregar prefijo 51 automaticamente a los ",x.phonesWithoutCountryCode," numeros detectados"]})]})]})]})}),J&&e.jsx("div",{className:"rounded-xl border p-4 bg-rose-50 border-rose-200 dark:bg-rose-950/20 dark:border-rose-800",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ba,{className:"h-5 w-5 shrink-0 text-rose-500"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-rose-700 dark:text-rose-400",children:"Contactos Bloqueados"}),e.jsx("p",{className:"text-xs text-rose-600 dark:text-rose-400/80",children:"La importacion de contactos esta bloqueada por el administrador."})]})]})}),ee&&ee.limitEnabled&&e.jsxs("div",{className:`rounded-xl border p-4 ${ee.totalCredits<x.validRows?"bg-rose-50 border-rose-200 dark:bg-rose-950/20 dark:border-rose-800":"bg-blue-50 border-blue-200 dark:bg-blue-950/20 dark:border-blue-800"}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($e,{className:`h-5 w-5 shrink-0 ${ee.totalCredits<x.validRows?"text-rose-500":"text-blue-500"}`}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700 dark:text-slate-200",children:"Limite de Contactos"}),e.jsxs("p",{className:"text-xs text-slate-500 dark:text-slate-400",children:["Disponibles: ",e.jsx("span",{className:"font-bold",children:ee.totalCredits.toLocaleString()})," "," | Requiere: ",e.jsx("span",{className:"font-bold",children:x.validRows.toLocaleString()})]})]}),ee.totalCredits<x.validRows&&e.jsx(ve,{className:"h-5 w-5 text-rose-500 shrink-0"})]}),ee.totalCredits<x.validRows&&e.jsxs("p",{className:"mt-2 text-[11px] text-rose-600 dark:text-rose-400 font-medium",children:["El backend podria rechazar la importacion. Faltan ",(x.validRows-ee.totalCredits).toLocaleString()," contactos de capacidad."]})]}),Oe>0&&e.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsx("div",{className:"px-4 py-2.5 border-b bg-muted/30",children:e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Filas que se omitiran"})}),e.jsx("div",{className:"p-2 space-y-0.5",children:[{count:x.skippedNoIdentifier,label:"Sin telefono ni email",icon:ia,reason:"no_identifier"},{count:x.skippedInvalidPhone,label:"Telefono invalido",icon:ve,reason:"invalid_phone"},{count:x.skippedInvalidEmail,label:"Email invalido",icon:ve,reason:"invalid_email"},{count:x.skippedDuplicateInCsv,label:"Duplicados en CSV",icon:$e,reason:"duplicate"}].filter(p=>p.count>0).map(p=>{const d=C===p.reason,A=x.errorDetails.filter(V=>V.reason===p.reason),_=A.length>0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>_&&t(d?null:p.reason),className:`w-full flex items-center justify-between px-3 py-2 rounded-lg transition-colors ${_?"cursor-pointer hover:bg-muted/30":"cursor-default"} ${d?"bg-muted/30":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[_&&(d?e.jsx(Mt,{className:"w-3 h-3 text-muted-foreground"}):e.jsx(ya,{className:"w-3 h-3 text-muted-foreground"})),e.jsx("div",{className:"p-1 rounded bg-amber-500/10",children:e.jsx(p.icon,{className:"w-3 h-3 text-amber-500"})}),e.jsx("span",{className:"text-xs text-foreground",children:p.label})]}),e.jsx("span",{className:"text-xs font-semibold tabular-nums text-muted-foreground",children:p.count})]}),d&&A.length>0&&e.jsxs("div",{className:"mx-3 mb-2 mt-1 rounded-lg border bg-muted/10 overflow-hidden",children:[e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/30",children:[e.jsx("th",{className:"px-3 py-1.5 text-left text-[10px] font-medium text-muted-foreground uppercase tracking-wider w-[60px]",children:"Fila"}),e.jsx("th",{className:"px-3 py-1.5 text-left text-[10px] font-medium text-muted-foreground uppercase tracking-wider",children:"Columna"}),e.jsx("th",{className:"px-3 py-1.5 text-left text-[10px] font-medium text-muted-foreground uppercase tracking-wider",children:"Valor"})]})}),e.jsx("tbody",{className:"divide-y divide-border/50",children:A.slice(0,20).map((V,ce)=>e.jsxs("tr",{className:"hover:bg-muted/20",children:[e.jsx("td",{className:"px-3 py-1.5 text-[11px] tabular-nums text-muted-foreground",children:V.row}),e.jsx("td",{className:"px-3 py-1.5 text-[11px] font-mono text-foreground",children:V.field}),e.jsx("td",{className:"px-3 py-1.5 text-[11px] font-mono text-muted-foreground max-w-[200px] truncate",children:V.value==="-"?e.jsx("span",{className:"italic text-muted-foreground/50",children:"vacio"}):V.value})]},ce))})]}),A.length>20&&e.jsxs("div",{className:"px-3 py-1.5 border-t bg-muted/20 text-[10px] text-muted-foreground text-center",children:["y"," ",A.length-20," ","mas..."]})]})]},p.reason)})}),x.errorDetails.length>0&&e.jsx("div",{className:"px-4 py-2 border-t",children:e.jsxs("button",{type:"button",onClick:()=>De(x.errorDetails),className:"inline-flex items-center gap-1.5 text-[11px] text-primary hover:underline",children:[e.jsx(_s,{className:"w-3 h-3"}),"Descargar reporte de errores (",x.errorDetails.length,")"]})})]}),(x.invalidMetadataCells>0||x.extraColumns.length>0||x.uniqueTags.length>0)&&e.jsxs("div",{className:"space-y-2",children:[x.invalidMetadataCells>0&&e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg border bg-card",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-amber-500/10",children:e.jsx(Yt,{className:"w-3.5 h-3.5 text-amber-500"})}),e.jsxs("div",{className:"flex-1 text-xs",children:[e.jsx("span",{className:"font-semibold",children:x.invalidMetadataCells})," ",e.jsx("span",{className:"text-muted-foreground",children:"celdas con JSON invalido (se omitiran solo esas celdas)"})]})]}),x.extraColumns.length>0&&e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg border bg-card",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-violet-500/10",children:e.jsx(gt,{className:"w-3.5 h-3.5 text-violet-500"})}),e.jsxs("div",{className:"flex-1 text-xs",children:[e.jsxs("span",{className:"font-semibold",children:[x.extraColumns.length," columnas"]})," ",e.jsxs("span",{className:"text-muted-foreground",children:["como Info. Adicional:"," "]}),e.jsx("span",{className:"font-medium text-foreground",children:x.extraColumns.join(", ")})]})]}),x.uniqueTags.length>0&&e.jsxs("div",{className:"rounded-lg border bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-primary/10",children:e.jsx(As,{className:"w-3.5 h-3.5 text-primary"})}),e.jsxs("div",{className:"flex-1 text-xs",children:[e.jsxs("span",{className:"font-semibold",children:[pt," etiquetas"]})," ",e.jsx("span",{className:"text-muted-foreground",children:"se crearan o asignaran"}),j.size>0&&e.jsxs("span",{className:"text-muted-foreground/60 ml-1",children:["(",j.size," excluidas)"]})]})]}),e.jsx("div",{className:"px-4 pb-3 flex flex-wrap gap-1.5",children:x.uniqueTags.map(p=>{const d=j.has(p);return e.jsxs("button",{type:"button",onClick:()=>Ps(p),className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium transition-all ${d?"bg-muted text-muted-foreground line-through opacity-50":"bg-primary/10 text-primary hover:bg-primary/20"}`,children:[p,!d&&e.jsx(us,{className:"w-3 h-3 ml-0.5 opacity-60 hover:opacity-100"})]},p)})}),j.size>0&&e.jsx("div",{className:"px-4 pb-2",children:e.jsx("button",{type:"button",onClick:()=>v(new Set),className:"text-[10px] text-primary hover:underline",children:"Restaurar todas"})})]})]}),e.jsxs("div",{className:"rounded-lg border bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-emerald-500/10",children:e.jsx(st,{className:"w-3.5 h-3.5 text-emerald-500"})}),e.jsxs("div",{className:"flex-1 text-xs",children:[e.jsx("span",{className:"font-semibold",children:"Agregar etiquetas"})," ",e.jsx("span",{className:"text-muted-foreground",children:"a todos los contactos"})]})]}),e.jsx("div",{className:"px-4 pb-3",children:e.jsxs(Ft,{open:Q,onOpenChange:re,children:[e.jsx(zt,{asChild:!0,children:e.jsxs("div",{className:"min-h-[40px] p-2 bg-background border border-border rounded-lg flex flex-wrap gap-1.5 items-center focus-within:ring-2 focus-within:ring-primary/20 transition-all cursor-text",onClick:()=>document.getElementById("import-additional-tag-input")?.focus(),children:[be.map(p=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium bg-primary/10 text-primary",style:{borderLeft:`3px solid ${p.color||"#6366f1"}`},children:[p.name,e.jsx("button",{type:"button",onClick:d=>{d.stopPropagation(),Y(A=>A.filter(_=>_!==p.id))},className:"hover:bg-primary/20 p-0.5 rounded-full transition-colors",children:e.jsx(us,{className:"w-2.5 h-2.5"})})]},p.id)),e.jsx("div",{className:"flex-1 min-w-[100px]",children:e.jsx("input",{id:"import-additional-tag-input",className:"w-full bg-transparent border-none outline-none text-xs h-7 px-1 placeholder:text-muted-foreground/50",placeholder:be.length===0?"Buscar etiqueta...":"",value:te,onChange:p=>{ae(p.target.value),re(!0)},onFocus:()=>re(!0),onBlur:()=>setTimeout(()=>re(!1),150),onKeyDown:p=>{p.key==="Backspace"&&!te&&F.length>0&&Y(d=>d.slice(0,-1))}})})]})}),e.jsx(qt,{side:"top",align:"start",sideOffset:4,className:"w-[--radix-popover-trigger-width] p-1 max-h-48 overflow-y-auto",onOpenAutoFocus:p=>p.preventDefault(),children:je.length>0?je.slice(0,20).map(p=>e.jsxs("div",{className:"px-2.5 py-1.5 text-xs text-foreground hover:bg-muted rounded cursor-pointer flex items-center gap-2",onMouseDown:d=>d.preventDefault(),onClick:()=>{Y(d=>[...d,p.id]),ae("")},children:[e.jsx("div",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:p.color||"#6366f1"}}),p.name]},p.id)):te?e.jsx("div",{className:"px-2.5 py-2 text-[11px] text-muted-foreground text-center italic",children:"No se encontraron etiquetas"}):$.length===0?e.jsx("div",{className:"px-2.5 py-2 text-[11px] text-muted-foreground text-center italic",children:"No hay etiquetas disponibles"}):e.jsx("div",{className:"px-2.5 py-2 text-[11px] text-muted-foreground text-center italic",children:"Escribe para buscar..."})})]})})]}),z&&e.jsxs("div",{className:"rounded-xl border border-blue-200 dark:border-blue-900/30 bg-blue-50/50 dark:bg-blue-950/20 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-blue-200/50 dark:border-blue-900/20",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-blue-500/10",children:e.jsx(Et,{className:"w-3.5 h-3.5 text-blue-500"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-xs font-semibold text-foreground",children:"Vista previa del servidor"}),e.jsx("span",{className:"text-[10px] text-muted-foreground ml-1.5",children:"(sin modificar la base de datos)"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2 p-3",children:[e.jsxs("div",{className:"rounded-lg bg-background/80 border border-blue-100 dark:border-blue-900/30 p-3 text-center",children:[e.jsx("p",{className:"text-lg font-bold text-foreground tabular-nums",children:z.newContactsInserted}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:"Nuevos"})]}),e.jsxs("div",{className:"rounded-lg bg-background/80 border border-blue-100 dark:border-blue-900/30 p-3 text-center",children:[e.jsx("p",{className:"text-lg font-bold text-foreground tabular-nums",children:a==="skip"?z.existingContactsSkipped:z.existingContactsUpdated}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:a==="skip"?"Omitidos":"Actualizados"})]}),e.jsxs("div",{className:"rounded-lg bg-background/80 border border-blue-100 dark:border-blue-900/30 p-3 text-center",children:[e.jsx("p",{className:"text-lg font-bold text-foreground tabular-nums",children:z.newTagsCreated}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:"Tags nuevas"})]}),e.jsxs("div",{className:"rounded-lg bg-background/80 border border-blue-100 dark:border-blue-900/30 p-3 text-center",children:[e.jsx("p",{className:"text-lg font-bold text-foreground tabular-nums",children:z.tagAssignmentsCreated}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:"Asignaciones"})]})]}),z.phonesWithoutCountryCode>0&&e.jsxs("div",{className:"mx-3 mb-3 flex items-center gap-2 px-3 py-2 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-900/30",children:[e.jsx(ve,{className:"h-3.5 w-3.5 text-amber-500 shrink-0"}),e.jsxs("p",{className:"text-[10px] text-amber-700 dark:text-amber-400",children:[z.phonesWithoutCountryCode," numeros sin codigo de pais (51)"]})]})]})]}):null,e.jsxs("div",{className:"space-y-2",children:[f&&f.size>5*1024*1024&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-900/30",children:[e.jsx(ve,{className:"h-4 w-4 text-amber-500 shrink-0"}),e.jsxs("p",{className:"text-xs text-amber-700 dark:text-amber-400",children:["Archivo grande (",(f.size/(1024*1024)).toFixed(1)," MB). La importacion puede tomar varios minutos."]})]}),x&&x.totalRows>5e3&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-900/30",children:[e.jsx(ve,{className:"h-4 w-4 text-amber-500 shrink-0"}),e.jsxs("p",{className:"text-xs text-amber-700 dark:text-amber-400",children:[x.totalRows.toLocaleString()," filas detectadas. Importaciones grandes pueden demorar."]})]}),x&&Oe>x.totalRows*.3&&Oe>0&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-red-50 dark:bg-red-950/20 rounded-lg border border-red-200 dark:border-red-900/30",children:[e.jsx(ia,{className:"h-4 w-4 text-red-500 shrink-0"}),e.jsxs("p",{className:"text-xs text-red-700 dark:text-red-400",children:["Mas del 30% de las filas tienen errores (",Oe," de ",x.totalRows,"). Revisa tu archivo."]})]}),O&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-blue-50 dark:bg-blue-950/20 rounded-lg border border-blue-200 dark:border-blue-900/30",children:[e.jsx(ve,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("p",{className:"text-xs text-blue-700 dark:text-blue-400",children:O})]})]})]}),i==="uploading"&&e.jsxs("div",{className:"py-8 flex flex-col items-center justify-center text-center space-y-6",children:[e.jsx("div",{className:"p-4 rounded-2xl bg-primary/10",children:e.jsx(ke,{className:"h-8 w-8 animate-spin text-primary"})}),e.jsxs("div",{className:"w-full max-w-md space-y-3",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:U?.phase==="parsing"?"Analizando archivo...":U?.phase==="contacts"?"Insertando contactos...":U?.phase==="tags"?"Asignando etiquetas...":U?.phase==="identities"?"Vinculando identidades...":U?.phase==="finalizing"?"Finalizando...":"En cola de procesamiento..."}),e.jsxs("span",{className:"text-muted-foreground",children:[U?.progress||0,"%"]})]}),e.jsx("div",{className:"h-2.5 w-full rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary transition-all duration-500",style:{width:`${U?.progress||0}%`}})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:U?.message||"En cola de procesamiento..."})]})]}),i==="result"&&!y&&U?.status==="failed"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-xl border bg-destructive/5 border-destructive/20",children:[e.jsx("div",{className:"p-2 rounded-xl bg-destructive/10",children:e.jsx(ve,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"La importacion fallo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:U.message||"Ocurrio un error inesperado durante la importacion."})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground px-1",children:"Los creditos consumidos fueron reembolsados automaticamente. Puedes intentar importar nuevamente."})]}),i==="result"&&y&&e.jsxs("div",{className:"space-y-4",children:[y.failedBatches>0?e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-xl border bg-amber-500/5 border-amber-200 dark:border-amber-900/30",children:[e.jsx("div",{className:"p-2 rounded-xl bg-amber-500/10",children:e.jsx(ve,{className:"h-5 w-5 text-amber-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Importacion parcial"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.failedBatches," lote(s) fallaron durante el procesamiento"]})]})]}):e.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-xl border bg-emerald-500/5 border-emerald-200 dark:border-emerald-900/30",children:[e.jsx("div",{className:"p-2 rounded-xl bg-emerald-500/10",children:e.jsx(bt,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Importacion completada"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.totalRows," filas procesadas"]})]})]}),y.batchErrors&&y.batchErrors.length>0&&e.jsxs("div",{className:"space-y-2 px-4 py-3 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-900/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ve,{className:"h-4 w-4 text-amber-500"}),e.jsxs("p",{className:"text-xs font-medium text-amber-700 dark:text-amber-400",children:[y.batchErrors.length," lote(s) con errores"]})]}),e.jsx("div",{className:"space-y-1 max-h-32 overflow-y-auto",children:y.batchErrors.map((p,d)=>e.jsxs("p",{className:"text-[10px] text-amber-600 dark:text-amber-500",children:["Lote ",p.batchIndex," (filas ",p.startRow,"-",p.endRow,"): ",p.error]},d))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx("div",{className:"relative overflow-hidden rounded-xl border bg-card p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider",children:"Nuevos"}),e.jsx("p",{className:"text-2xl font-bold tracking-tight mt-0.5",children:y.newContactsInserted})]}),e.jsx("div",{className:"p-2 rounded-lg bg-emerald-500/10",children:e.jsx($e,{className:"h-4 w-4 text-emerald-500"})})]})}),e.jsx("div",{className:"relative overflow-hidden rounded-xl border bg-card p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider",children:a==="skip"?"Omitidos":"Actualizados"}),e.jsx("p",{className:"text-2xl font-bold tracking-tight mt-0.5",children:a==="skip"?y.existingContactsSkipped:y.existingContactsUpdated})]}),e.jsx("div",{className:`p-2 rounded-lg ${a==="skip"?"bg-amber-500/10":"bg-primary/10"}`,children:a==="skip"?e.jsx(Ds,{className:"h-4 w-4 text-amber-500"}):e.jsx($e,{className:"h-4 w-4 text-primary"})})]})})]}),(y.newTagsCreated>0||y.tagAssignmentsCreated>0||y.identitiesLinked>0)&&e.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsx("div",{className:"px-4 py-2.5 border-b bg-muted/30",children:e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Operaciones adicionales"})}),e.jsx("div",{className:"p-3 space-y-1",children:[{count:y.newTagsCreated,label:"Etiquetas creadas",icon:As,color:"text-violet-500",bg:"bg-violet-500/10"},{count:y.tagAssignmentsCreated,label:"Asignaciones de etiquetas",icon:As,color:"text-primary",bg:"bg-primary/10"},{count:y.identitiesLinked,label:"Identidades vinculadas",icon:kn,color:"text-cyan-500",bg:"bg-cyan-500/10"}].filter(p=>p.count>0).map(p=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:`p-1 rounded ${p.bg}`,children:e.jsx(p.icon,{className:`w-3 h-3 ${p.color}`})}),e.jsx("span",{className:"text-xs text-foreground",children:p.label})]}),e.jsx("span",{className:"text-xs font-semibold tabular-nums",children:p.count})]},p.label))})]}),(y.skippedNoIdentifier>0||y.skippedInvalidPhone>0||y.skippedInvalidEmail>0||y.skippedDuplicateInCsv>0||y.invalidMetadataCells>0)&&e.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsx("div",{className:"px-4 py-2.5 border-b bg-muted/30",children:e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Filas / Celdas omitidas"})}),e.jsx("div",{className:"p-3 space-y-1",children:[{count:y.skippedNoIdentifier,label:"Sin telefono ni email"},{count:y.skippedInvalidPhone,label:"Telefono invalido"},{count:y.skippedInvalidEmail,label:"Email invalido"},{count:y.skippedDuplicateInCsv,label:"Duplicados en CSV"},{count:y.invalidMetadataCells,label:"Celdas con JSON invalido"}].filter(p=>p.count>0).map(p=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 rounded-lg",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:p.label}),e.jsx("span",{className:"text-xs font-semibold tabular-nums text-muted-foreground",children:p.count})]},p.label))})]}),y.validationErrors&&y.validationErrors.length>0&&e.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-2.5 border-b bg-muted/30 flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Errores de validacion"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground/60",children:["Primeros ",y.validationErrors.length]})]}),e.jsx("div",{className:"max-h-[120px] overflow-auto p-3 text-xs space-y-1",children:y.validationErrors.map((p,d)=>e.jsxs("div",{className:"text-destructive font-mono text-[11px] px-2 py-1 rounded bg-destructive/5",children:["Fila ",p.row,": ",p.field,' = "',p.value,'" -'," ",p.reason]},d))}),e.jsx("div",{className:"px-4 py-2 border-t",children:e.jsxs("button",{type:"button",onClick:()=>De(y.validationErrors),className:"inline-flex items-center gap-1.5 text-[11px] text-primary hover:underline",children:[e.jsx(_s,{className:"w-3 h-3"}),"Descargar reporte (",y.validationErrors.length,")"]})})]})]})]}),e.jsxs(Ls,{className:"flex-row sm:justify-between items-center gap-2 pt-2 border-t",children:[i==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-muted-foreground mr-auto",children:js?e.jsxs("span",{className:"flex items-center gap-1.5 text-emerald-600 dark:text-emerald-400",children:[e.jsx(bt,{className:"w-3.5 h-3.5"}),"Telefono o Email mapeado"]}):e.jsx("span",{className:"text-muted-foreground/70",children:"Mapea al menos Telefono o Email"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(L,{variant:"outline",size:"sm",onClick:Ie,children:"Cancelar"}),e.jsxs(L,{size:"sm",onClick:ns,disabled:!js,children:["Validar",e.jsx(Ct,{className:"ml-1.5 h-3.5 w-3.5"})]})]})]}),i==="validation"&&!Z&&x&&e.jsxs(e.Fragment,{children:[e.jsxs(L,{variant:"outline",size:"sm",onClick:()=>r("mapping"),className:"mr-auto",children:[e.jsx(hn,{className:"mr-1.5 h-3.5 w-3.5"}),"Volver"]}),e.jsxs(L,{variant:"outline",size:"sm",onClick:Le,disabled:x.validRows===0||W,children:[W?e.jsx(ke,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}):e.jsx(Et,{className:"mr-1.5 h-3.5 w-3.5"}),"Vista previa"]}),e.jsxs(L,{size:"sm",onClick:ye,disabled:x.validRows===0||!!J,children:["Importar ",x.validRows," contactos",e.jsx(Ct,{className:"ml-1.5 h-3.5 w-3.5"})]})]}),i==="uploading"&&e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Puedes cerrar este dialogo. La importacion continuara en segundo plano."}),e.jsx(L,{variant:"ghost",size:"sm",onClick:()=>l(!1),className:"text-xs text-muted-foreground",children:"Cerrar"})]}),i==="result"&&e.jsx(L,{onClick:()=>{xe(),se.dismissImportStatus().catch(()=>{}),l(!1)},className:"w-full",size:"sm",children:"Cerrar"})]})]})})},Kl=({open:s,onOpenChange:l,count:n,onConfirm:i,isDeleting:r,selectedIds:f,selectAllMode:u,filters:g})=>{const[b,h]=m.useState(""),[c,I]=m.useState(null),[T,x]=m.useState(!1),N="ELIMINAR",y=b===N;m.useEffect(()=>{if(!s){h(""),I(null);return}(async()=>{x(!0);try{if(u&&g){const{page:H,limit:Z,sortBy:X,sortOrder:q,...le}=g,C=await se.bulkDeletePreview({filters:le});I(C)}else if(f&&f.length>0){const H=await se.bulkDeletePreview({ids:f});I(H)}}catch{I(null)}finally{x(!1)}})()},[s,f,u,g]);const w=()=>{y&&(i(),h(""))};return e.jsx(es,{open:s,onOpenChange:l,children:e.jsxs(ss,{className:"sm:max-w-[460px] border-l-4 border-l-rose-500",children:[e.jsxs(ts,{children:[e.jsxs("div",{className:"flex items-center gap-3 text-rose-600 mb-2",children:[e.jsx("div",{className:"p-2 bg-rose-50 dark:bg-rose-900/20 rounded-full",children:e.jsx(ve,{className:"h-5 w-5"})}),e.jsxs(as,{className:"text-xl",children:["Eliminar ",n.toLocaleString()," contacto",n!==1?"s":"","?"]})]}),e.jsx(gs,{asChild:!0,children:e.jsxs("div",{className:"pt-2 text-sm text-slate-600 dark:text-slate-300",children:["Esta accion es ",e.jsx("strong",{children:"irreversible"}),". Se eliminaran permanentemente:",e.jsxs("ul",{className:"list-disc pl-5 mt-2 mb-2 space-y-1 text-sm text-slate-500",children:[e.jsx("li",{children:"El perfil del contacto y sus metadatos."}),e.jsx("li",{children:"Todo el historial de conversaciones (Tickets y Mensajes)."}),e.jsx("li",{children:"La asociacion con campanas anteriores."})]})]})})]}),T&&e.jsxs("div",{className:"flex items-center gap-2 py-3 text-sm text-slate-500",children:[e.jsx(ke,{className:"w-4 h-4 animate-spin"}),"Analizando contactos..."]}),c&&c.softDelete>0&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-3.5 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-amber-800 font-semibold text-sm",children:[e.jsx(pn,{className:"w-4 h-4"}),c.softDelete," contacto",c.softDelete!==1?"s":""," seran archivados"]}),e.jsxs("p",{className:"text-xs text-amber-700",children:["Estos contactos tienen ",c.threshold,"+ conversaciones y seran archivados en vez de eliminados para preservar el historial."]}),c.softDeleteNames.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-1",children:[c.softDeleteNames.map((E,H)=>e.jsx("span",{className:"bg-amber-100 text-amber-800 text-[11px] font-medium px-2 py-0.5 rounded-full",children:E},H)),c.softDelete>c.softDeleteNames.length&&e.jsxs("span",{className:"text-[11px] text-amber-600",children:["+",c.softDelete-c.softDeleteNames.length," mas"]})]}),c.hardDelete>0&&e.jsxs("p",{className:"text-xs text-slate-600 mt-1 pt-1 border-t border-amber-200",children:["Los otros ",c.hardDelete.toLocaleString()," contactos seran eliminados permanentemente."]})]}),e.jsxs("div",{className:"py-4 space-y-3",children:[e.jsxs("p",{className:"text-sm font-medium text-slate-700 dark:text-slate-200",children:["Para confirmar, escribe ",e.jsx("span",{className:"font-mono bg-slate-100 px-1 py-0.5 rounded text-rose-600 select-all",children:N})," abajo:"]}),e.jsx(He,{value:b,onChange:E=>h(E.target.value),placeholder:"Escribe aqui...",className:"border-rose-200 focus-visible:ring-rose-500/20 font-bold tracking-widest uppercase text-center",autoFocus:!0})]}),e.jsxs(Ls,{children:[e.jsx(L,{variant:"outline",onClick:()=>l(!1),disabled:r,children:"Cancelar"}),e.jsx(L,{variant:"destructive",onClick:w,disabled:!y||r,className:"bg-rose-600 hover:bg-rose-700",children:r?"Eliminando...":"Si, eliminar contactos"})]})]})})},Ga=m.memo(({selectedCount:s,pageSize:l,totalMatching:n,selectAllMode:i,onSelectAllMatching:r,onClearSelection:f})=>{const u=s>=l&&l>0,g=n>l;if(!i)if(u){if(!g)return null}else return null;return e.jsxs("div",{className:"flex items-center justify-center gap-2 py-2.5 px-4 bg-amber-50 border border-amber-200 rounded-xl text-sm text-amber-800",children:[e.jsx(fs,{className:"w-4 h-4 text-amber-600 shrink-0"}),i?e.jsxs("span",{children:["Los ",e.jsx("strong",{children:n.toLocaleString()})," contactos que coinciden con los filtros estan seleccionados."," ",e.jsx("button",{onClick:f,className:"text-primary font-semibold hover:underline",children:"Limpiar seleccion"})]}):e.jsxs("span",{children:["Los ",s," contactos de esta pagina estan seleccionados."," ",e.jsxs("button",{onClick:r,className:"text-primary font-semibold hover:underline",children:["Seleccionar los ",n.toLocaleString()," contactos que coinciden"]})]})]})});Ga.displayName="SelectAllBanner";function Ql(){const s=Rs(),l=$t(n=>n.filters);m.useEffect(()=>{Ys.joinOrgRoom();const n=u=>{console.log("[useContactsSocket] New contact received:",u.id),s.invalidateQueries({queryKey:_e.all}),s.invalidateQueries({queryKey:[..._e.all,"stats"]}),D.success(`Nuevo contacto: ${u.name||u.phone}`,{description:"La lista se ha actualizado."})},i=u=>{u.newContactsInserted>0&&(console.log("[useContactsSocket] Import completed, refreshing lists"),s.invalidateQueries({queryKey:_e.all}),s.invalidateQueries({queryKey:[..._e.all,"stats"]}))},r=Ys.onContactNew(n),f=Ys.onContactsImportCompleted(i);return()=>{r(),f()}},[s,l])}const Gl=()=>{const{data:s,isLoading:l}=Il(),{data:n,isLoading:i}=Ka(),r=l||i,f=["#6366f1","#10b981","#f59e0b","#ef4444","#8b5cf6","#06b6d4"],u=m.useMemo(()=>{if(!n)return null;const b=n.total||0,h=b>0?Math.round(n.withEmail/b*100):0,c=b>0?Math.round(n.withPhone/b*100):0,I=b>0?Math.round(n.labeled/b*100):0,T=s?.channelDistribution?.[0],x=s?.tagDistribution?.[0];return{emailCoverage:h,phoneCoverage:c,labeledRatio:I,topChannelName:T?.type||"-",topChannelCount:T?.count||0,topTagName:x?.name||"-",topTagCount:x?.count||0}},[n,s]),g=m.useMemo(()=>s?.growthTrend?s.growthTrend.map(b=>({name:b.date,count:b.count})):[],[s]);return e.jsxs("div",{className:"space-y-6 animate-in fade-in duration-500",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4",children:[e.jsx(ys,{icon:e.jsx(gn,{className:"h-5 w-5"}),value:r?null:n?.total,label:"TOTAL",sublabel:"Contactos",color:"indigo",isLoading:r}),e.jsx(ys,{icon:e.jsx(qe,{className:"h-5 w-5"}),value:r?null:n?.withPhone,label:"TELÉFONOS",sublabel:"Identificados",color:"emerald",isLoading:r}),e.jsx(ys,{icon:e.jsx(Se,{className:"h-5 w-5"}),value:r?null:n?.withEmail,label:"EMAILS",sublabel:"Registrados",color:"amber",isLoading:r}),e.jsx(ys,{icon:e.jsx(na,{className:"h-5 w-5"}),value:r?null:n?.labeled,label:"ETIQUETADOS",sublabel:"Segmentados",color:"rose",isLoading:r}),e.jsx(ys,{icon:e.jsx(Ms,{className:"h-5 w-5"}),value:r?null:u?.emailCoverage,label:"COBERTURA",sublabel:"Email %",color:"violet",isLoading:r})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(Vs,{icon:e.jsx(an,{className:"h-5 w-5"}),title:"Top Etiqueta",value:u?.topTagName||"-",subtitle:`${u?.topTagCount||0} contactos`,color:"emerald",isLoading:r}),e.jsx(Vs,{icon:e.jsx(wa,{className:"h-5 w-5"}),title:"Canal Principal",value:u?.topChannelName||"-",subtitle:`${u?.topChannelCount||0} contactos`,color:"amber",isLoading:r}),e.jsx(Vs,{icon:e.jsx(bn,{className:"h-5 w-5"}),title:"Cobertura Teléfono",value:`${u?.phoneCoverage||0}%`,subtitle:"Salud de datos",color:"indigo",isLoading:r}),e.jsx(Vs,{icon:e.jsx(tt,{className:"h-5 w-5"}),title:"Segmentación",value:`${u?.labeledRatio||0}%`,subtitle:"Con etiquetas",color:"rose",isLoading:r})]}),e.jsx(Ts,{className:"border border-slate-200/60 dark:border-slate-800 shadow-sm rounded-2xl bg-white dark:bg-slate-900 overflow-hidden",children:e.jsxs(Is,{className:"p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-bold text-slate-900 dark:text-white",children:"Crecimiento de Audiencia"}),e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:"Tendencia de nuevos contactos"})]}),e.jsx(me,{variant:"outline",className:"rounded-lg px-3 py-1 text-xs font-medium bg-indigo-50 dark:bg-indigo-900/30 border-indigo-200 dark:border-indigo-800 text-indigo-600 dark:text-indigo-400",children:"Por día"})]}),e.jsx("div",{className:"h-[280px] w-full",children:r?e.jsx(we,{className:"h-full w-full rounded-xl"}):e.jsx(hr,{width:"100%",height:"100%",children:e.jsxs(pr,{data:g,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorGradientContacts",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#6366f1",stopOpacity:.3}),e.jsx("stop",{offset:"100%",stopColor:"#6366f1",stopOpacity:.05})]})}),e.jsx(fr,{strokeDasharray:"3 3",vertical:!1,stroke:"#e2e8f0",opacity:.5}),e.jsx(gr,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:"#94a3b8",fontSize:11,fontWeight:500},dy:10,tickFormatter:b=>Ne(b,{style:"chart-axis"})}),e.jsx(br,{axisLine:!1,tickLine:!1,tick:{fill:"#94a3b8",fontSize:11,fontWeight:500}}),e.jsx(jr,{contentStyle:{borderRadius:"12px",border:"1px solid #e2e8f0",boxShadow:"0 10px 40px -10px rgba(0, 0, 0, 0.1)",padding:"12px 16px",backgroundColor:"white"},cursor:{stroke:"#6366f1",strokeWidth:1,strokeDasharray:"4 4"},labelFormatter:b=>Ne(b,{style:"chart-tooltip"})}),e.jsx(vr,{type:"monotone",dataKey:"count",name:"Nuevos contactos",stroke:"#6366f1",strokeWidth:2.5,fillOpacity:1,fill:"url(#colorGradientContacts)",animationDuration:1500})]})})})]})}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-5",children:[e.jsx(Ts,{className:"lg:col-span-3 border border-slate-200/60 dark:border-slate-800 shadow-sm rounded-2xl bg-white dark:bg-slate-900 overflow-hidden",children:e.jsxs(Is,{className:"p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-bold text-slate-900 dark:text-white",children:"Distribución por Etiqueta"}),e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:"Top segmentos de clientes"})]}),e.jsx(me,{variant:"outline",className:"rounded-lg px-3 py-1 text-xs font-medium bg-slate-50 dark:bg-slate-800 border-slate-200 dark:border-slate-700",children:"TOP 10"})]}),r?e.jsx("div",{className:"space-y-4",children:Array.from({length:6}).map((b,h)=>e.jsx(we,{className:"h-10 w-full rounded-lg"},h))}):(s?.tagDistribution?.length||0)===0?e.jsx(ga,{icon:e.jsx(na,{className:"h-10 w-10"}),label:"Sin segmentos registrados"}):e.jsx("div",{className:"space-y-3",children:s?.tagDistribution.slice(0,10).map((b,h)=>{const c=s.tagDistribution[0]?.count||1,I=b.count/c*100,T=n?.total||1,x=Math.round(b.count/T*100);return e.jsxs("div",{className:"group",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shadow-sm",style:{backgroundColor:b.color||f[h%f.length]}}),e.jsx("span",{className:"text-sm font-semibold text-slate-700 dark:text-slate-200 group-hover:text-indigo-600 dark:group-hover:text-indigo-400 transition-colors",children:b.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-bold text-slate-900 dark:text-white",children:b.count}),e.jsxs("span",{className:"text-xs text-slate-400 font-medium",children:["(",x,"%)"]})]})]}),e.jsx("div",{className:"w-full h-2 bg-slate-100 dark:bg-slate-800 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all duration-700 ease-out",style:{width:`${I}%`,backgroundColor:b.color||f[h%f.length],opacity:.8}})})]},h)})})]})}),e.jsx(Ts,{className:"lg:col-span-2 border border-slate-200/60 dark:border-slate-800 shadow-sm rounded-2xl bg-white dark:bg-slate-900 overflow-hidden",children:e.jsxs(Is,{className:"p-6",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-base font-bold text-slate-900 dark:text-white",children:"Origen de Contactos"}),e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:"Distribución por canal"})]}),r?e.jsx("div",{className:"space-y-3",children:Array.from({length:4}).map((b,h)=>e.jsx(we,{className:"h-14 w-full rounded-xl"},h))}):(s?.channelDistribution?.length||0)===0?e.jsx(ga,{icon:e.jsx($e,{className:"h-10 w-10"}),label:"Sin datos de canales"}):e.jsx("div",{className:"space-y-2",children:s?.channelDistribution.map((b,h)=>e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-slate-50/80 dark:bg-slate-800/50 rounded-xl border border-slate-100 dark:border-slate-700/50 hover:bg-white dark:hover:bg-slate-800 hover:shadow-md hover:border-slate-200 dark:hover:border-slate-600 transition-all duration-200 group",children:[e.jsx("div",{className:M("w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold transition-all",h===0?"bg-indigo-100 text-indigo-600 dark:bg-indigo-900/30 dark:text-indigo-400":h===1?"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400":h===2?"bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400":"bg-slate-100 dark:bg-slate-700 text-slate-500 dark:text-slate-400"),children:h+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("span",{className:"text-sm font-semibold text-slate-800 dark:text-slate-100 block truncate",children:b.type})}),e.jsx("div",{className:"px-2.5 py-1 bg-indigo-50 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 rounded-lg text-xs font-bold",children:b.count})]},b.type))})]})})]})]})};function ys({icon:s,value:l,label:n,sublabel:i,color:r,isLoading:f}){const g={indigo:{bg:"bg-indigo-50 dark:bg-indigo-900/20",icon:"text-indigo-500 dark:text-indigo-400",border:"border-indigo-100 dark:border-indigo-800/50"},emerald:{bg:"bg-emerald-50 dark:bg-emerald-900/20",icon:"text-emerald-500 dark:text-emerald-400",border:"border-emerald-100 dark:border-emerald-800/50"},amber:{bg:"bg-amber-50 dark:bg-amber-900/20",icon:"text-amber-500 dark:text-amber-400",border:"border-amber-100 dark:border-amber-800/50"},rose:{bg:"bg-rose-50 dark:bg-rose-900/20",icon:"text-rose-500 dark:text-rose-400",border:"border-rose-100 dark:border-rose-800/50"},violet:{bg:"bg-violet-50 dark:bg-violet-900/20",icon:"text-violet-500 dark:text-violet-400",border:"border-violet-100 dark:border-violet-800/50"}}[r];return e.jsx(Ts,{className:"border border-slate-200/60 dark:border-slate-800 shadow-sm rounded-2xl bg-white dark:bg-slate-900 overflow-hidden hover:shadow-md transition-shadow",children:e.jsxs(Is,{className:"p-4",children:[e.jsx("div",{className:"flex items-start justify-between mb-3",children:e.jsx("div",{className:M("w-10 h-10 rounded-xl flex items-center justify-center",g.bg,g.border,"border"),children:e.jsx("span",{className:g.icon,children:s})})}),e.jsxs("div",{children:[f?e.jsx(we,{className:"h-8 w-16 mb-1"}):e.jsx("div",{className:"text-2xl font-bold text-slate-900 dark:text-white tracking-tight",children:l?.toLocaleString()??"-"}),e.jsx("div",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-wider mt-1",children:n}),e.jsx("div",{className:"text-xs text-slate-500 font-medium",children:i})]})]})})}function Vs({icon:s,title:l,value:n,subtitle:i,color:r,isLoading:f}){const u={indigo:"bg-indigo-50 dark:bg-indigo-900/20 text-indigo-500 dark:text-indigo-400",emerald:"bg-emerald-50 dark:bg-emerald-900/20 text-emerald-500 dark:text-emerald-400",amber:"bg-amber-50 dark:bg-amber-900/20 text-amber-500 dark:text-amber-400",rose:"bg-rose-50 dark:bg-rose-900/20 text-rose-500 dark:text-rose-400"};return e.jsx(Ts,{className:"border border-slate-200/60 dark:border-slate-800 shadow-sm rounded-2xl bg-white dark:bg-slate-900 overflow-hidden",children:e.jsx(Is,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:M("w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0",u[r]),children:s}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-wider",children:l}),f?e.jsx(we,{className:"h-5 w-24 mt-1"}):e.jsx("div",{className:"text-sm font-bold text-slate-900 dark:text-white truncate",children:n}),e.jsx("div",{className:"text-xs text-slate-500 font-medium",children:i})]})]})})})}function ga({icon:s,label:l}){return e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-slate-300 dark:text-slate-600",children:[e.jsx("div",{className:"mb-3 opacity-50",children:s}),e.jsx("p",{className:"text-xs font-semibold text-slate-400 dark:text-slate-500",children:l})]})}const fo=()=>{const s=Rs(),l=m.useRef(null),[n,i]=m.useState("directory"),{filters:r,setFilters:f,clearFilters:u,visibleColumns:g,toggleColumn:b,initializeColumnsFromSchemas:h,selectAllMode:c,selectAllCount:I,setSelectAllMode:T,clearSelectAll:x}=$t(),{data:N,isLoading:y,isFetching:w,refetch:E}=_l(),{data:H}=Tl(),{data:Z,isLoading:X}=Ka(),{data:q}=Qa();Ql();const{folders:le,fetchFolders:C}=Rt();m.useEffect(()=>{C()},[]);const t=m.useMemo(()=>{if(!H)return[];const d=H.flatMap(_=>_.fields),A=new Map;return d.forEach(_=>{A.has(_.key)||A.set(_.key,_)}),Array.from(A.values()).sort((_,V)=>_.order-V.order)},[H]);m.useEffect(()=>{t.length>0&&h(t)},[t.length]);const[a,o]=m.useState([]),[j,v]=m.useState(null),[F,Y]=m.useState(!1),[te,ae]=cr(),[Q,re]=m.useState(!1),[z,ue]=m.useState(!1),[W,G]=m.useState(null),{esAdmin:O}=mr(),[ie,oe]=m.useState(!1),[k,B]=m.useState(!1),[S,P]=m.useState(!1),[K,R]=m.useState(!1),[U,xe]=m.useState(!1),[ne,ee]=m.useState("comfortable"),[J,ge]=m.useState(r.search||""),$=fn(J,400);m.useEffect(()=>{$.length===0?r.search&&De("search",""):$.length>=2&&$!==r.search&&De("search",$)},[$]),m.useEffect(()=>{r.search!==J&&r.search===void 0&&ge("")},[r.search]);const de=m.useCallback(()=>{u(),x(),ge(""),o([]),D.success("Filtros reiniciados")},[u,x,o]),be=N?.data||[],je=N?.total||0,Ee=y||X,Re=(q?.byPhone?.length||0)+(q?.byEmail?.length||0)+(q?.byFuzzy?.length||0),he=m.useMemo(()=>({withEmail:Z?.withEmail||0,withPhone:Z?.withPhone||0,withTags:Z?.labeled||0,total:Z?.total||0}),[Z]),Ce=m.useCallback((d,A)=>{c?(x(),o(be.map(_=>_.id).filter(_=>_!==d))):o(_=>A?[..._,d]:_.filter(V=>V!==d))},[c,x,be]),pe=m.useCallback(d=>{d||x(),o(d?be.map(A=>A.id):[])},[be,x]),fe=m.useCallback(d=>{v(d),Y(!0)},[]),Ae=m.useRef(null),[We,ns]=m.useState("profile");m.useEffect(()=>{const d=te.get("contactId");if(!d||Ae.current===d)return;Ae.current=d;const A=te.get("tab");ns(A==="conversations"||A==="activity"?A:"profile"),se.getContact(d).then(_=>{v(_),Y(!0)}).catch(()=>D.error("No se pudo abrir el contacto (no existe o fue eliminado)")).finally(()=>{te.delete("contactId"),te.delete("tab"),ae(te,{replace:!0})})},[te,ae]);const Le=m.useCallback(d=>{const A=d.orgId||"";s.setQueryData(_e.list(A,r),_=>_&&{..._,data:_.data.map(V=>V.id===d.id?{...V,...d}:V)}),v(d)},[r,s]),ye=m.useCallback(()=>{E(),s.invalidateQueries({queryKey:_e.all}),D.success("Lista de contactos actualizada")},[E,s]),Ie=m.useCallback(d=>{G(d),re(!0)},[]),ls=m.useCallback(d=>{E(),o([]),v(d),D.success(`Contacto ${d.name||d.phone} actualizado tras la fusión`)},[E]),Ps=m.useCallback(async d=>{try{oe(!0);const A=await se.exportContacts(r,d),_=window.URL.createObjectURL(A),V=document.createElement("a");V.href=_;const ce=d==="reimport"?"contactos_reimport":"contactos_export";V.setAttribute("download",`${ce}_${new Date().toISOString().split("T")[0]}.csv`),document.body.appendChild(V),V.click(),V.parentNode?.removeChild(V),D.success("Exportación descargada con éxito")}catch(A){console.error(A),D.error("Error al exportar contactos")}finally{oe(!1)}},[r]),De=m.useCallback((d,A)=>{f({...r,[d]:A==="ALL"?void 0:A}),o([])},[r,f]),js=m.useMemo(()=>le.flatMap(d=>d.tags),[le]),is=m.useMemo(()=>js.filter(d=>r.tagIds?.includes(d.id)),[js,r.tagIds]),ht=m.useCallback(d=>{const A=r.tagIds||[],V=A.includes(d.id)?A.filter(ce=>ce!==d.id):[...A,d.id];f({...r,tagIds:V.length>0?V:void 0}),o([])},[r.tagIds,r,f]),Fs=m.useCallback(d=>{x(),De("page",d)},[De,x]),zs=()=>{R(!0)},Oe=m.useCallback(()=>{const{page:d,limit:A,sortBy:_,sortOrder:V,...ce}=r;return ce},[r]),pt=async()=>{try{xe(!0);let d;c?d=await se.bulkDeleteByFilter(Oe()):d=await se.bulkDelete(a);const A=[];d.hardDeleted>0&&A.push(`${d.hardDeleted} eliminados`),d.softDeleted>0&&A.push(`${d.softDeleted} archivados`),D.success(A.length>0?A.join(", "):`${d.count} contactos procesados`),o([]),x(),E(),R(!1)}catch(d){const A=d?.response?.data?.message||"Error al eliminar contactos";D.error(A)}finally{xe(!1)}},p=async d=>{try{if(c){const A=await se.bulkAssignTagsByFilter(Oe(),[d]);D.success(`Etiqueta asignada a ${A.count.toLocaleString()} contactos`)}else await se.bulkAssignTags(a,[d]),D.success(`Etiqueta asignada a ${a.length} contactos`);o([]),x(),E()}catch{D.error("Error al asignar etiquetas")}};return e.jsxs(cs,{children:[e.jsx(Nr,{children:e.jsxs("div",{className:"h-full overflow-y-auto no-scrollbar",ref:l,children:[e.jsx(yr,{title:"Audiencia & Contactos",description:"Gestiona y analiza tu base de clientes y prospectos de forma estratégica.",icon:$e,actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(L,{onClick:()=>B(!0),variant:"outline",className:"rounded-full shadow-sm hover:bg-slate-50 transition-all border-slate-200",children:[e.jsx(_t,{className:"mr-2 h-4 w-4 text-slate-500"}),e.jsx("span",{className:"hidden sm:inline",children:"Importar"})]}),e.jsxs(L,{onClick:()=>P(!0),className:"bg-primary hover:bg-primary/90 text-white shadow-lg shadow-primary/25 rounded-full px-5",children:[e.jsx(Ds,{className:"mr-2 h-4 w-4"}),"Nuevo Contacto"]})]})}),e.jsx(wr,{className:"space-y-6",children:e.jsxs(Ot,{value:n,onValueChange:i,className:"space-y-6",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx(Pt,{className:"bg-slate-100/50 dark:bg-slate-800/50 p-1 rounded-2xl h-11",children:e.jsxs(Xe,{value:"directory",className:"rounded-xl px-6 data-[state=active]:bg-white dark:data-[state=active]:bg-slate-900 data-[state=active]:shadow-sm transition-all",children:[e.jsx($e,{className:"w-4 h-4 mr-2"}),"Directorio"]})})}),e.jsxs(Ue,{value:"directory",className:"space-y-6 m-0 border-none p-0 outline-none",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4 px-1",children:[e.jsx(un,{className:"h-4 w-4 text-slate-400"}),e.jsx("h2",{className:"text-xs font-black uppercase tracking-widest text-slate-400",children:"Resumen Rápido"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(Hs,{icon:e.jsx($e,{className:"w-5 h-5 text-indigo-500"}),label:"Total",value:he.total,bgClass:"bg-indigo-50 dark:bg-indigo-900/10"}),e.jsx(Hs,{icon:e.jsx(qe,{className:"w-5 h-5 text-emerald-500"}),label:"Identificados",value:he.withPhone,bgClass:"bg-emerald-50 dark:bg-emerald-900/10"}),e.jsx(Hs,{icon:e.jsx(ur,{className:"w-5 h-5 text-violet-500"}),label:"Segmentados",value:he.withTags,bgClass:"bg-violet-50 dark:bg-violet-900/10"}),e.jsx(Hs,{icon:e.jsx(xt,{className:"w-5 h-5 text-amber-500"}),label:"Duplicados",value:Re,bgClass:"bg-amber-50 dark:bg-amber-900/10",onClick:()=>ue(!0),isInteractive:!0})]})]}),e.jsxs("div",{className:"bg-white dark:bg-slate-900 p-3 rounded-[24px] border border-slate-100 dark:border-slate-800 shadow-sm flex flex-col xl:flex-row items-center justify-between gap-3 sticky top-[72px] z-10 backdrop-blur-md bg-opacity-95",children:[e.jsxs("div",{className:"flex items-center gap-3 w-full xl:w-auto",children:[e.jsx(L,{variant:"ghost",size:"icon",onClick:ye,disabled:w,className:"rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 text-slate-400 hover:text-primary shrink-0 transition-colors",children:e.jsx(Js,{className:M("h-4 w-4",w&&"animate-spin")})}),e.jsx("div",{className:"h-6 w-[1px] bg-slate-100 dark:bg-slate-800 hidden md:block"}),e.jsxs("div",{className:"relative flex-1 xl:w-72",children:[w?e.jsx(ke,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-primary animate-spin"}):e.jsx(kt,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400"}),e.jsx(He,{placeholder:"Buscar por nombre, email, teléfono...",value:J,onChange:d=>ge(d.target.value),className:"h-11 pl-11 bg-slate-50 dark:bg-slate-950 border-none rounded-2xl text-sm focus-visible:ring-1 focus-visible:ring-primary/20 transition-all font-medium"}),J&&e.jsx(us,{className:"absolute right-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 cursor-pointer hover:text-slate-600 transition-colors bg-white/50 dark:bg-slate-800 rounded-lg p-0.5",onClick:()=>{ge(""),De("search","")}})]}),(r.search||r.channelType||r.channelId||r.tagIds&&r.tagIds.length>0||r.startDate||r.endDate)&&e.jsxs(L,{variant:"ghost",size:"sm",onClick:de,className:"text-[11px] font-bold uppercase tracking-tight text-rose-500 hover:text-rose-600 hover:bg-rose-50 dark:hover:bg-rose-900/10 whitespace-nowrap rounded-xl transition-all",children:[e.jsx(us,{className:"w-3.5 h-3.5 mr-1"}),"Limpiar"]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full xl:w-auto overflow-x-auto no-scrollbar pb-1 xl:pb-0",children:[e.jsx(nn,{value:r.channelId?`id:${r.channelId}`:r.channelType?`type:${r.channelType}`:"all",onChange:d=>{const A=ln(d);A.filterType==="all"?f({...r,channelType:void 0,channelId:void 0}):A.filterType==="type"?f({...r,channelType:A.value,channelId:void 0}):A.filterType==="id"&&f({...r,channelId:A.value,channelType:void 0}),o([])},showInactive:!1,className:"h-11 bg-slate-50 dark:bg-slate-950 border-none rounded-2xl text-[13px] font-medium w-full xl:w-[160px]"}),e.jsx(La,{selectedTags:is,folders:le,onToggleTag:ht,showUntaggedOption:!0,isUntaggedSelected:!!r.untagged,onToggleUntagged:d=>De("untagged",d||void 0),trigger:e.jsxs(L,{variant:"ghost",className:M("h-11 px-4 bg-slate-50 dark:bg-slate-950 rounded-2xl text-[13px] font-medium text-slate-500 border-none hover:bg-slate-100 transition-all",(is.length>0||r.untagged)&&"text-primary bg-primary/5 hover:bg-primary/10"),children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),is.length>0||r.untagged?e.jsxs("span",{children:[is.length+(r.untagged?1:0)," etiquetas"]}):"Etiquetas"]})}),e.jsx(On,{startDate:r.startDate||"",endDate:r.endDate||"",onStartDateChange:d=>De("startDate",d),onEndDateChange:d=>De("endDate",d),className:"h-11 rounded-2xl bg-slate-50 dark:bg-slate-950 border-none text-[13px] font-medium"}),e.jsx("div",{className:"h-6 w-[1px] bg-slate-100 dark:bg-slate-800 hidden md:block shrink-0 mx-1"}),e.jsxs(Ws,{children:[e.jsx(Ks,{asChild:!0,children:e.jsx(L,{variant:"ghost",size:"icon",className:"h-11 w-11 text-slate-400 hover:text-primary rounded-2xl hover:bg-slate-50 transition-all shrink-0",children:e.jsx(yn,{className:"h-5 w-5"})})}),e.jsxs(Qs,{align:"end",className:"w-56 p-2 rounded-2xl shadow-xl",children:[e.jsx(Gs,{className:"text-[10px] uppercase tracking-widest text-slate-400 font-bold mb-1",children:"Columnas Estándar"}),Fn.map(d=>e.jsx(Qt,{checked:g.includes(d.key),onCheckedChange:()=>b(d.key),className:"rounded-lg text-sm",children:d.label},d.key)),t.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(ja,{}),e.jsx(Gs,{className:"text-[10px] uppercase tracking-widest text-primary font-bold mb-1",children:"Campos Personalizados"}),t.map(d=>e.jsx(Qt,{checked:g.includes(d.key),onCheckedChange:()=>b(d.key),className:"rounded-lg text-sm",children:d.label},d.key))]})]})]}),O&&e.jsxs(Ws,{children:[e.jsx(Ks,{asChild:!0,children:e.jsx(L,{variant:"ghost",size:"icon",disabled:ie,className:"h-11 w-11 text-slate-400 hover:text-primary rounded-2xl hover:bg-slate-50 transition-all shrink-0",children:e.jsx(_s,{className:M("h-5 w-5",ie&&"animate-bounce")})})}),e.jsxs(Qs,{align:"end",children:[e.jsxs(Qe,{onClick:()=>Ps("default"),children:[e.jsx(_s,{className:"mr-2 h-4 w-4"}),"Exportar completo"]}),e.jsxs(Qe,{onClick:()=>Ps("reimport"),children:[e.jsx(_t,{className:"mr-2 h-4 w-4"}),"Exportar para re-importar"]})]})]}),e.jsx("div",{className:"h-6 w-[1px] bg-slate-100 dark:bg-slate-800 hidden md:block shrink-0 mx-1"}),e.jsxs("div",{className:"flex bg-slate-100/50 dark:bg-slate-800/50 p-1 rounded-xl shrink-0",children:[e.jsx(L,{variant:"ghost",size:"icon",onClick:()=>ee("comfortable"),className:M("h-8 w-8 rounded-lg transition-all",ne==="comfortable"?"bg-white dark:bg-slate-900 shadow-sm text-primary":"text-slate-400 hover:text-slate-600"),children:e.jsx(rn,{className:"h-4 w-4"})}),e.jsx(L,{variant:"ghost",size:"icon",onClick:()=>ee("compact"),className:M("h-8 w-8 rounded-lg transition-all",ne==="compact"?"bg-white dark:bg-slate-900 shadow-sm text-primary":"text-slate-400 hover:text-slate-600"),children:e.jsx(jn,{className:"h-4 w-4"})})]})]})]}),(r.search||r.channelType||r.channelId||r.tagIds&&r.tagIds.length>0||r.startDate||r.endDate||r.untagged)&&e.jsx("div",{className:"flex items-center gap-2 px-1",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-500 dark:text-slate-400",children:[e.jsx(kt,{className:"w-4 h-4"}),e.jsxs("span",{children:[e.jsx("span",{className:"font-bold text-slate-700 dark:text-slate-200",children:je.toLocaleString()})," ","contacto",je!==1?"s":""," encontrado",je!==1?"s":""]}),he.total>0&&je!==he.total&&e.jsxs("span",{className:"text-slate-400",children:["de ",he.total.toLocaleString()," total"]})]})}),e.jsx(Ga,{selectedCount:a.length,pageSize:be.length,totalMatching:je,selectAllMode:c,onSelectAllMatching:()=>T(!0,je),onClearSelection:()=>{o([]),x()}}),e.jsx(Bn,{contacts:be,isLoading:Ee,selectedIds:a,onSelect:Ce,onSelectAll:pe,onViewDetail:fe,onOpenChat:d=>console.log("Open Chat",d),onMerge:Ie,visibleColumns:g,availableFields:t,page:r.page||1,limit:r.limit||20,total:je,onPageChange:Fs,density:ne,selectAllMode:c})]}),e.jsx(Ue,{value:"analytics",className:"m-0 border-none p-0 outline-none",children:e.jsx(Gl,{})})]})})]})}),(a.length>0||c)&&e.jsx("div",{className:"fixed bottom-8 left-1/2 transform -translate-x-1/2 z-50 animate-in slide-in-from-bottom-5 fade-in duration-300",children:e.jsxs("div",{className:"bg-slate-900 text-white px-7 py-3.5 rounded-full shadow-[0_20px_50px_rgba(0,0,0,0.3)] flex items-center gap-7 border border-slate-800/50 backdrop-blur-xl bg-opacity-95",children:[e.jsxs("span",{className:"text-[13px] font-bold flex items-center gap-2.5",children:[e.jsx("div",{className:"bg-primary text-white w-6 h-6 rounded-full flex items-center justify-center text-[11px] font-black shadow-lg shadow-primary/40",children:c?I.toLocaleString():a.length}),c?"Todos seleccionados":"Seleccionados"]}),e.jsx("div",{className:"h-5 w-[1px] bg-white/10"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(L,{size:"sm",variant:"ghost",className:"h-9 hover:bg-white/10 text-white rounded-xl px-4 transition-all",onClick:()=>zs(),children:[e.jsx(At,{className:"w-4 h-4 mr-2 text-rose-400"}),"Eliminar"]}),e.jsxs(Ws,{children:[e.jsx(Ks,{asChild:!0,children:e.jsxs(L,{size:"sm",variant:"ghost",className:"h-9 hover:bg-white/10 text-white rounded-xl px-4 transition-all",children:[e.jsx(As,{className:"w-4 h-4 mr-2 text-indigo-400"}),"Etiquetar"]})}),e.jsxs(Qs,{className:"w-60 p-2 rounded-2xl shadow-2xl",align:"center",children:[e.jsx(Gs,{className:"text-[10px] uppercase font-bold tracking-widest text-slate-400 p-2",children:"Asignar Etiqueta"}),le.flatMap(d=>d.tags).map(d=>e.jsxs(Qe,{onClick:()=>p(d.id),className:"rounded-xl flex items-center gap-3 p-2",children:[e.jsx("div",{className:"w-2.5 h-2.5 rounded-full shadow-sm",style:{backgroundColor:d.color}}),e.jsx("span",{className:"text-sm font-medium",children:d.name})]},d.id))]})]})]}),e.jsx(L,{size:"icon",variant:"ghost",className:"h-7 w-7 rounded-full hover:bg-white/10 transition-all text-slate-400 hover:text-white",onClick:()=>{o([]),x()},children:e.jsx(us,{className:"w-4 h-4"})})]})}),e.jsx(Kl,{open:K,onOpenChange:R,count:c?I:a.length,onConfirm:pt,isDeleting:U,selectedIds:c?void 0:a,selectAllMode:c,filters:c?r:void 0}),e.jsx(Al,{open:Q,onOpenChange:re,targetContact:W,onMerged:ls}),e.jsx(Ml,{open:z,onOpenChange:ue}),e.jsx(Wl,{open:k,onOpenChange:B,onImportSuccess:ye}),e.jsx(Ll,{open:S,onOpenChange:P,onSuccess:ye}),j&&e.jsx(Wa,{contact:j,open:F,onOpenChange:Y,onContactUpdated:Le,initialTab:We})]})},Hs=({icon:s,label:l,value:n,bgClass:i,onClick:r,isInteractive:f})=>e.jsxs("div",{className:M("bg-white dark:bg-slate-900 p-5 rounded-[24px] border border-slate-100 dark:border-slate-800 shadow-sm flex items-center gap-5 transition-all duration-300 group",f?"cursor-pointer hover:shadow-xl hover:-translate-y-1 hover:border-amber-200 dark:hover:border-amber-900/50":"hover:shadow-lg"),onClick:r,children:[e.jsx("div",{className:M("w-14 h-14 rounded-2xl flex items-center justify-center shrink-0 shadow-inner group-hover:scale-110 transition-transform duration-300",i),children:s}),e.jsxs("div",{children:[e.jsx("div",{className:"flex items-baseline gap-1",children:e.jsx("p",{className:"text-3xl font-black text-slate-900 dark:text-white leading-none tracking-tighter",children:typeof n=="number"?n.toLocaleString():n})}),e.jsx("p",{className:"text-[11px] uppercase font-black text-slate-400 mt-2 tracking-widest",children:l})]})]});export{fo as ContactsPage};
|