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
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DsyZ_FlA.js","assets/recharts-DrC5kNsx.js","assets/index-BJCPaymI.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{c as $e,i as it,a as Ye,g as rt,w as Pe,s as hl,j as e,l as T,T as Oe,v as Ue,x as Re,y as ft,z as Za,D as bt,o as Se,r as De,M as Es,E as Rn,G as _n,F as Ie,W as pl,B as K,R as ys,b as he,H as Ln,h as Ft,J as It,U as Ws,K as fe,X as Ge,n as we,I as Te,O as Ja,P as er,_ as lt,k as gl,Q as Ce,S as fl,V as fr,Y as Bt,Z as tt,t as H,C as ct,$ as Is,a0 as rs,a1 as bl,a2 as La,a3 as yt,a4 as jt,a5 as Ut,a6 as vt,a7 as Rt,d as yl,a8 as Qs,a9 as Fn,aa as Fa,ab as dt,ac as tr,ad as fs,ae as Ks,u as Pn,af as jl,ag as vl,ah as Nl,ai as wl,aj as kl,L as Cl,ak as Zt,al as Tl,am as Sl,an as Vn,ao as Bn,ap as $n,aq as El,ar as zs,as as wt,at as As,au as sr,av as br,aw as Il,ax as Al,ay as Ml,az as Dl}from"./index-DsyZ_FlA.js";import{b as i,R as zn}from"./recharts-DrC5kNsx.js";import{u as qn}from"./index-CCTahcpv.js";import{A as ht,a as pt,b as gt}from"./avatar-CILB1zwS.js";import{f as Ol,a as is,b as Hn}from"./datetime-BuZosCVk.js";import{u as la}from"./useFunnelStats-tvjpmWIC.js";import{G as js,M as oa,u as Gn,a as Wn,m as ar,B as Ul,P as Qn,b as Rl,c as _l,d as Ll,e as Fl,f as Pl,g as Os,S as ja,C as Vl,h as yr,i as Bl}from"./contactsApi-B851NME_.js";import{F as $l,U as Pa,m as jr}from"./index-Bz-ixwph.js";import{S as zl,F as ql,C as Hl,c as Gl,P as Wl,a as Ql}from"./ChannelSelector-q9tTirNo.js";import{M as Ms}from"./message-square-Dfn16oHc.js";import{S as Ds}from"./send-Dxmdupsl.js";import{F as Kn,E as ca}from"./facebook-RxMBweMB.js";import{I as Yn}from"./instagram-CC7iYt7V.js";import{S as va}from"./switch-ODBa0fCT.js";import{P as Xe,a as Ze,b as Je}from"./popover-MyuU-yAK.js";import{S as kt,a as Ct,b as Tt,c as St,d as Me}from"./select-DlB_BbfM.js";import{C as At,a as Mt,b as Dt,c as Ot,d as Be,e as Le,f as Et}from"./command-COdSmSIB.js";import{C as Vt}from"./chevrons-up-down-DC-BWTrj.js";import{u as rr}from"./useAiAgentsQuery-Bm6aRHKj.js";import{t as Kl,c as Yl,g as Xl,f as Zl,e as Jl}from"./es-BG480iA5.js";import{S as Na,C as eo,M as Ys,a as Va,b as to,F as so}from"./products.types-46xSxBS8.js";import{C as Pt}from"./calendar-CIHhMjNy.js";import{M as ao,v as ro,P as no}from"./mediaValidation-BR-ZOj5w.js";import{S as gs}from"./skeleton-B0zh8s_y.js";import{u as da}from"./useInfiniteQuery-BXUM1Z9V.js";import{H as Xn}from"./history-DhHayxUg.js";import{R as vr}from"./index-DUnioqCT.js";import{D as ua}from"./download-CiVQHPeB.js";import{M as vs}from"./mic-CT4vyzLZ.js";import{S as mt,a as bs,H as Lt,b as Zn,M as ls,u as Nr,R as Ns,I as qs,c as Xs,d as Jn,e as ei,P as ws,f as io,g as nr,t as Ba,h as $a,i as lo,p as ti,j as wr,k as oo,l as kr,m as co}from"./interactiveLimits-CfLJ1O4_.js";import{M as os,c as ut}from"./connectionsService-BsJf8pFz.js";import{V as et,I as We}from"./video-VfwKgB6z.js";import{u as xt}from"./useMutation-a5tIBvQY.js";import{C as ks}from"./circle-x-BwMKIs8b.js";import{C as ma}from"./circle-check-big-DzPo5zZX.js";import{M as si,S as ai}from"./scroll-area-CavEOIyz.js";import{M as Cs}from"./map-pin-CPmcofD3.js";import{T as Ts}from"./textarea-BYtcLsMD.js";import{H as ir}from"./hash-BoTE56iw.js";import{F as ri}from"./folder-D0GKakGp.js";import{g as Hs,W as Jt,a as uo,f as mo}from"./storage.api-CFU3KJNp.js";import{S as xo,E as ho}from"./EmojiPicker-BToAe-MT.js";import{L as as}from"./list-BKc6EXnV.js";import{E as za}from"./eye-HfQCUjxJ.js";import{u as po}from"./useDebounce-Bfcb_jpD.js";import{A as ni}from"./arrow-left-BeDdBs_Q.js";import{M as ii}from"./maximize-2-WdbM7Kdx.js";import{T as ns}from"./trash-2-Du2vmQCH.js";import{I as Cr}from"./MediaProcessingService-glHGiE_o.js";import{C as go}from"./checkbox-pcbjC0d3.js";import{C as es,a as ts,b as ss}from"./collapsible-B22t1J-V.js";import{p as Zs}from"./product.service-CRLZOQsr.js";import{M as fo}from"./minus-CyVEzdqL.js";import{U as xa}from"./user-DwCALzIG.js";import{A as bo}from"./archive-LUe5bKi5.js";import{E as li}from"./ellipsis-vertical-DTqbEYYp.js";import{M as yo}from"./music-Cu8AQMFp.js";import{S as ms}from"./separator-CPT3uVRM.js";import{T as jo,M as vo}from"./TagSelector-ChoKzvjW.js";import{S as Tr}from"./shield-alert-04pSYngI.js";import{S as No}from"./save-Dua2yhWl.js";import{a as wo}from"./page-components-o2TF52HV.js";import{C as Wt,b as oi,c as ci,a as Qt}from"./card-DcKsxjXK.js";import{T as ko,a as Co,b as Us,c as zt,d as To,e as Nt}from"./table-CvSELOPi.js";import{A as Sr,a as Er,b as Ir,c as Ar,d as Mr,e as Dr,f as Or,g as Ur,h as Rr}from"./alert-dialog-D8P69s-m.js";import{C as So}from"./calendar-days-BwJfOz8M.js";import{S as _r}from"./square-pen-CJajoyrm.js";import"./code-BMAyHFJe.js";import"./eye-off-v1Z_lKS0.js";import"./index-KbFmSzBE.js";import"./agent.service-BcAkMU7j.js";import"./upload-C7TwpdyA.js";import"./index-BiSc3WD9.js";const Eo=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Js=$e("check-check",Eo);const Io=[["path",{d:"M18 20a6 6 0 0 0-12 0",key:"1qehca"}],["circle",{cx:"12",cy:"10",r:"4",key:"1h16sb"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],Ao=$e("circle-user-round",Io);const Mo=[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5.782 5.782A7 7 0 0 0 9 19h8.5a4.5 4.5 0 0 0 1.307-.193",key:"yfwify"}],["path",{d:"M21.532 16.5A4.5 4.5 0 0 0 17.5 10h-1.79A7.008 7.008 0 0 0 10 5.07",key:"jlfiyv"}]],Do=$e("cloud-off",Mo);const Oo=[["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M14 2v2",key:"6buw04"}],["path",{d:"M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1",key:"pwadti"}],["path",{d:"M6 2v2",key:"colzsn"}]],Uo=$e("coffee",Oo);const Ro=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]],di=$e("file-image",Ro);const _o=[["path",{d:"M2 7v10",key:"a2pl2d"}],["path",{d:"M6 5v14",key:"1kq3d7"}],["rect",{width:"12",height:"18",x:"10",y:"3",rx:"2",key:"13i7bc"}]],ui=$e("gallery-horizontal-end",_o);const Lo=[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]],mi=$e("keyboard",Lo);const Fo=[["rect",{width:"18",height:"7",x:"3",y:"3",rx:"1",key:"f1a2em"}],["rect",{width:"9",height:"7",x:"3",y:"14",rx:"1",key:"jqznyg"}],["rect",{width:"5",height:"7",x:"16",y:"14",rx:"1",key:"q5h2i8"}]],lr=$e("layout-template",Fo);const Po=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]],Vo=$e("lock-open",Po);const Bo=[["path",{d:"M15 18h-5",key:"95g1m2"}],["path",{d:"M18 14h-8",key:"sponae"}],["path",{d:"M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-4 0v-9a2 2 0 0 1 2-2h2",key:"39pd36"}],["rect",{width:"8",height:"4",x:"10",y:"6",rx:"1",key:"aywv1n"}]],xi=$e("newspaper",Bo);const $o=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]],zo=$e("panel-right-close",$o);const qo=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]],Ho=$e("panel-right-open",qo);const Go=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],Wo=$e("pause",Go);const Qo=[["path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272",key:"1wngk7"}],["path",{d:"M22 2 2 22",key:"y4kqgn"}],["path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473",key:"10hv5p"}]],Ko=$e("phone-off",Qo);const Yo=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]],Xo=$e("pin",Yo);const Zo=[["path",{d:"M18.36 6.64A9 9 0 0 1 20.77 15",key:"dxknvb"}],["path",{d:"M6.16 6.16a9 9 0 1 0 12.68 12.68",key:"1x7qb5"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],Jo=$e("power-off",Zo);const ec=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],tc=$e("rotate-cw",ec);const sc=[["path",{d:"M21 9a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 15 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2z",key:"1dfntj"}],["path",{d:"M15 3v5a1 1 0 0 0 1 1h5",key:"6s6qgf"}]],qa=$e("sticky-note",sc);const ac=[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]],Lr=$e("undo-2",ac);function rc(t,s,a){const r=Kl(t,a?.in);return isNaN(s)?Yl(t,NaN):(s&&r.setDate(r.getDate()+s),r)}function nc(){return Object.assign({},Xl())}function ic(t,s,a){return rc(t,-s,a)}function Fr(t,s=300){const[a,r]=i.useState(t);return i.useEffect(()=>{const n=setTimeout(()=>{r(t)},s);return()=>{clearTimeout(n)}},[t,s]),a}function ha(t){if(!t?.metadata)return null;const s=t.metadata;if(s.source?.type)return s.source;const a=s.campaign_attribution;return a?.ctwaClid?{type:"ctwa_ad",detail:a,capturedBy:"auto"}:null}function Pr(t){return ha(t)?.type==="ctwa_ad"}function Vr(t){const s=ha(t)?.detail;return s&&(s.campaignName||s.headline||s.adId)||null}const lc=new Set(["ad","post"]);function Ha(t){return!!t&&lc.has(t.sourceType)}function oc(t){const s=t.metadata?.referral;return Ha(s)?s:void 0}function hi(t){const s=ha(t)?.detail;if(Ha(s))return s;const a=t?.metadata?.campaign_attribution;return Ha(a)?a:void 0}function cc(t){const s=hi(t);return s?.sourceType==="post"?s:void 0}const pi={PRESENCE_TIMEOUT_MS:parseInt("300000",10)},wa="org-members";function cs(){const t=it(),a=Ye(n=>n.user)?.organizationId,r=rt({queryKey:[wa,a],queryFn:async()=>a?hl.getMembers(a):[],enabled:!!a,staleTime:300*1e3});return i.useEffect(()=>{if(!a)return;const n=l=>{t.setQueryData([wa,a],c=>c&&c.map(u=>u.user.id===l.userId?{...u,user:{...u.user,availabilityStatus:l.status}}:u))},o=l=>{t.setQueryData([wa,a],c=>c&&c.map(u=>u.user.id===l.userId?{...u,user:{...u.user,lastActivityAt:l.lastActivityAt}}:u))};Pe.onAdvisorStatus(n),Pe.onAdvisorActivity(o)},[a,t]),r}const Br={AVAILABLE:{color:"bg-green-500",label:"Disponible",ring:"ring-green-200"},AWAY:{color:"bg-yellow-500",label:"Ausente",ring:"ring-yellow-200"},UNAVAILABLE:{color:"bg-red-500",label:"No disponible",ring:"ring-red-200"}},dc={sm:"w-1.5 h-1.5",md:"w-2 h-2",lg:"w-2.5 h-2.5"},gi=i.memo(({userId:t,size:s="md",showTooltip:a=!0,className:r})=>{const{data:n=[]}=cs(),l=n.find(d=>d.user.id===t)?.user.availabilityStatus||"AVAILABLE",c=Br[l]||Br.AVAILABLE,u=e.jsx("span",{className:T("inline-block rounded-full ring-2 ring-white dark:ring-gray-900",dc[s],c.color,r),"aria-label":c.label});return a?e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:u}),e.jsx(Re,{side:"bottom",className:"text-xs",children:e.jsx("p",{children:c.label})})]}):u});gi.displayName="AdvisorStatusBadge";function qx(t){const{data:s=[]}=cs(),a=t?s.find(r=>r.user.id===t):void 0;return{status:a?.user.availabilityStatus||null,lastActivityAt:a?.user.lastActivityAt||null,name:a?.user.name||null,avatarUrl:a?.user.avatarUrl||null}}const fi=i.memo(({funnelId:t,stageId:s,compact:a=!1,className:r})=>{const{data:n}=la(),{funnel:o,stage:l}=i.useMemo(()=>{if(!t||!n)return{funnel:null,stage:null};const c=n.find(d=>d.id===t);if(!c)return{funnel:null,stage:null};const u=c.stages?.find(d=>d.id===s);return{funnel:c,stage:u}},[t,s,n]);return o?a?e.jsxs("span",{className:T("inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs","bg-indigo-50 text-indigo-700 border border-indigo-200 dark:bg-indigo-500/20 dark:text-indigo-300 dark:border-indigo-500/30","max-w-[120px] truncate",r),title:`${o.name}: ${l?.name||"Sin etapa"}`,children:[e.jsx(js,{className:"w-3 h-3 flex-shrink-0"}),l?.icon&&e.jsx("span",{className:"flex-shrink-0",children:l.icon}),e.jsx("span",{className:"truncate",children:l?.name||o.name})]}):e.jsxs("div",{className:T("flex items-center gap-2 px-2 py-1 rounded-lg","bg-indigo-50 border border-indigo-200 dark:bg-indigo-500/10 dark:border-indigo-500/20",r),children:[e.jsx(js,{className:"w-4 h-4 text-indigo-500 dark:text-indigo-400 flex-shrink-0"}),e.jsxs("div",{className:"text-sm min-w-0",children:[e.jsxs("span",{className:"text-indigo-600 dark:text-indigo-300 font-medium",children:[o.icon," ",o.name]}),l&&e.jsxs("span",{className:"text-gray-500 ml-1",children:[e.jsx("span",{className:"text-gray-400 mx-1",children:"→"}),l.icon," ",l.name]})]})]}):null});fi.displayName="FunnelBadge";const uc={ACTIVE:2,WAITING_INPUT:30},$r={ACTIVE:{label:"Ejecutando",tooltip:"El workflow esta procesando nodos. Esto suele tomar pocos segundos.",color:"text-emerald-700 dark:text-emerald-400",bgColor:"bg-emerald-50 dark:bg-emerald-900/20 border-emerald-200 dark:border-emerald-800",icon:Se,animate:!0},WAITING_INPUT:{label:"Esperando",tooltip:"El workflow espera una respuesta del cliente para continuar.",color:"text-amber-700 dark:text-amber-400",bgColor:"bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-800",icon:bt},WAITING_DELAY:{label:"En espera",tooltip:"El workflow esta en pausa temporal (nodo Espera). Continuara automaticamente.",color:"text-blue-700 dark:text-blue-400",bgColor:"bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800",icon:bt},PAUSED:{label:"Pausado",tooltip:"El workflow fue pausado. Se reanudara cuando las condiciones cambien.",color:"text-slate-600 dark:text-slate-400",bgColor:"bg-slate-100 dark:bg-slate-800/50 border-slate-300 dark:border-slate-700",icon:Wo},COMPLETED:{label:"Completado",tooltip:"El workflow finalizo correctamente.",color:"text-gray-500 dark:text-gray-500",bgColor:"bg-gray-50 dark:bg-gray-900/20 border-gray-200 dark:border-gray-800",icon:Za},STUCK:{label:"Sin respuesta",tooltip:"",color:"text-red-700 dark:text-red-400",bgColor:"bg-red-50 dark:bg-red-900/20 border-red-300 dark:border-red-800",icon:ft}};function mc(t){if(t<60)return`${Math.round(t)} min`;const s=Math.floor(t/60);return s<24?`${s}h ${Math.round(t%60)}min`:`${Math.floor(s/24)}d ${s%24}h`}const bi=({session:t,compact:s=!1,className:a})=>{const{isStuck:r,minutesSince:n}=i.useMemo(()=>{const d=uc[t.status];if(!d)return{isStuck:!1,minutesSince:0};const m=t.lastInteractionAt;if(!m)return{isStuck:!1,minutesSince:0};const x=(Date.now()-new Date(m).getTime())/6e4;return{isStuck:x>d,minutesSince:x}},[t.status,t.lastInteractionAt]),o=r?"STUCK":t.status,l=$r[o]||$r.ACTIVE,c=l.icon,u=r?`El cliente no ha respondido en ${mc(n)}. El workflow esta esperando una respuesta para continuar. Puedes asignar a un agente para liberar este ticket.`:l.tooltip;return e.jsxs(Oe,{delayDuration:200,children:[e.jsx(Ue,{asChild:!0,children:e.jsxs("div",{className:T("inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 cursor-default",l.bgColor,l.color,r&&"animate-pulse",a),children:[e.jsx(c,{className:T("w-3 h-3 shrink-0",!r&&l.animate&&"animate-spin")}),!s&&e.jsx("span",{className:"text-[10px] font-medium leading-none",children:l.label})]})}),e.jsx(Re,{side:"bottom",className:"max-w-[260px] text-xs",children:e.jsx("p",{children:u})})]})},xc=(t,s)=>{if((t==="email"||t==="EMAIL")&&s)return s.providerId?.endsWith("@gmail.com")||s.credentials?.email?.endsWith("@gmail.com")||s.name?.toLowerCase().includes("gmail")?e.jsx(zl,{className:"w-3 h-3 text-white"}):e.jsx(ql,{className:"w-3 h-3 text-white"});switch(t){case"whatsapp":case"whatsapp_business":case"wa":case"waba":return e.jsx($l,{className:"w-3 h-3 text-white"});case"instagram":return e.jsx(Yn,{className:"w-3 h-3 text-white"});case"facebook":return e.jsx(Kn,{className:"w-3 h-3 text-white",fill:"currentColor"});case"telegram":return e.jsx(Ds,{className:"w-3 h-3 text-white",fill:"currentColor"});case"web":return e.jsx(_n,{className:"w-3 h-3 text-white"});default:return e.jsx(Ms,{className:"w-3 h-3 text-white",fill:"currentColor"})}},hc=t=>{switch(t){case"whatsapp":case"whatsapp_business":case"wa":case"waba":return"bg-green-500";case"instagram":return"bg-gradient-to-tr from-yellow-500 via-pink-500 to-purple-600";case"facebook":return"bg-blue-600";case"telegram":return"bg-sky-500";case"web":return"bg-indigo-500";default:return"bg-gray-400"}},pc=t=>{switch(t){case"whatsapp":case"whatsapp_business":case"wa":case"waba":return"WAT";case"instagram":return"IG";case"facebook":return"FB";case"telegram":return"TG";case"web":return"WEB";default:return"CHAT"}},gc=t=>{switch(t){case"READ":return e.jsx(Js,{className:"w-3.5 h-3.5 text-blue-500"});case"DELIVERED":return e.jsx(Js,{className:"w-3.5 h-3.5 text-gray-400"});case"SENT":return e.jsx(Ie,{className:"w-3.5 h-3.5 text-gray-400"});case"PENDING":return e.jsx(bt,{className:"w-3.5 h-3.5 text-gray-400"});default:return null}},fc=t=>t.split(" ").map(s=>s[0]).slice(0,2).join("").toUpperCase(),bc=t=>Ol(t),yc=t=>{if(!t)return"Nueva conversación";const s=t.content;if(!s)return t.contentType==="IMAGE"?"📷 Imagen":t.contentType==="VIDEO"?"🎥 Video":t.contentType==="AUDIO"?"🎵 Audio":t.contentType==="DOCUMENT"?"📄 Documento":"Adjunto";if(typeof s=="string"&&(s.trim().startsWith("{")||s.includes('"type"'))){try{const n=s.indexOf("{"),o=s.lastIndexOf("}");if(n!==-1&&o!==-1&&o>n){const l=s.substring(n,o+1),c=JSON.parse(l);if(c.body&&typeof c.body=="string")return c.body;if(c.type==="list_reply"&&c.list_reply?.title)return`📋 ${c.list_reply.title}`;if(c.type==="button_reply"&&c.button_reply?.title)return`🔘 ${c.button_reply.title}`;if(c.message?.body)return c.message.body;if(c.text)return c.text}}catch{}const a=s.match(/"body"\s*:\s*"((?:[^"\\]|\\.)*)(?:"|$)/);if(a&&a[1])return a[1];const r=s.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)(?:"|$)/);if(r&&r[1])return r[1]}return typeof s=="string"?s:"Adjunto"},Ga=i.memo(({conversation:t,isActive:s,onClick:a})=>{const{contact:r,channel:n,lastMessage:o,ticket:l}=t,c=n?.type?.toLowerCase()||"web",u=o?.senderType==="BOT",d=l.unreadCount>0&&!s,m=Pr(l)?void 0:cc(l),x=i.useMemo(()=>t.contact?.lastSeenAt?new Date().getTime()-new Date(t.contact.lastSeenAt).getTime()<pi.PRESENCE_TIMEOUT_MS:!1,[t.contact?.lastSeenAt]),b=i.useMemo(()=>yc(o),[o]);return e.jsxs("div",{onClick:a,className:T("group flex items-start gap-3 px-3 py-3 cursor-pointer rounded-2xl mx-2 my-1 transition-all relative overflow-hidden border border-transparent",s?"bg-primary/10 text-primary dark:bg-primary/20 ring-1 ring-primary/20":"hover:bg-slate-50 dark:hover:bg-muted/30 hover:shadow-sm"),children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsxs(ht,{className:"h-11 w-11 border border-gray-100 dark:border-gray-700 shadow-sm",children:[e.jsx(pt,{src:r?.avatarUrl,alt:r?.name}),e.jsx(gt,{className:"bg-gray-100 text-gray-500 font-bold text-xs",children:fc(r?.name||"Sin Nombre")})]}),x&&e.jsx("span",{className:"absolute bottom-0 right-0 w-3 h-3 bg-white dark:bg-gray-900 rounded-full flex items-center justify-center",children:e.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full"})}),e.jsx("div",{className:T("absolute -top-1 -right-1 w-5 h-5 rounded-full flex items-center justify-center border-2 border-white dark:border-gray-900 shadow-sm z-10",hc(c)),children:e.jsx("div",{className:"scale-75",children:xc(c,n)})})]}),e.jsxs("div",{className:"flex-1 min-w-0 pt-0.5",children:[e.jsxs("div",{className:"flex justify-between items-baseline mb-1",children:[e.jsxs("div",{className:"min-w-0 flex-1 mr-2",children:[e.jsx("span",{className:T("font-semibold truncate text-sm leading-tight text-gray-900 dark:text-gray-100 block group-hover:text-primary transition-colors",d&&"font-bold"),children:r?.name||"Usuario"}),(r?.phone||c)&&e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[r?.phone?e.jsx("span",{className:"text-[11px] text-slate-400 dark:text-slate-500 font-medium block leading-tight",children:r.phone}):e.jsx("span",{className:"text-[11px] text-sky-600/70 dark:text-sky-400/70 font-medium block leading-tight italic",children:"Sin número"}),e.jsx("span",{className:T("text-[9px] px-1 rounded-[4px] font-bold tracking-wider",s?"bg-white/50 dark:bg-gray-800 text-primary":"bg-gray-100 dark:bg-gray-800 text-gray-400"),children:pc(c)}),n?.name&&e.jsx("span",{className:"text-[9px] text-slate-400 dark:text-slate-500 truncate max-w-[100px]",children:n.name})]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[o&&e.jsx("span",{className:T("text-[10px] whitespace-nowrap tabular-nums",d?"text-primary font-bold":"text-gray-400"),children:bc(o.createdAt)}),(l.status==="RESOLVED"||l.status==="ARCHIVED")&&e.jsx("span",{className:"text-[9px] px-1.5 py-px rounded-full font-semibold bg-slate-100 text-slate-500 dark:bg-slate-800 dark:text-slate-400",children:"Cerrada"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsxs("div",{className:"flex-1 flex items-center min-w-0 gap-1.5",children:[o&&o.senderType!=="CONTACT"&&e.jsx("span",{className:o.status==="READ"?"text-blue-500":"text-gray-300",children:gc(o.status||"SENT")}),e.jsxs("span",{className:T("truncate text-[13px] leading-snug",d?"text-gray-800 dark:text-gray-200 font-semibold":"text-gray-500 dark:text-gray-400"),children:[u&&e.jsx("span",{className:"text-primary text-[10px] mr-1 font-bold tracking-wide",children:"AI"}),b]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[l.assignedAgentId&&e.jsx(gi,{userId:l.assignedAgentId,size:"sm",showTooltip:!0}),l.assignedType==="AI"&&e.jsx(De,{variant:"secondary",className:"text-[9px] h-4 px-1 font-semibold text-gray-500 bg-gray-100 border-gray-200",children:"AI"}),l.assignedType==="META_AGENT"&&e.jsx(De,{variant:"secondary",className:"text-[9px] h-4 px-1 font-semibold text-sky-700 bg-sky-50 border-sky-200 dark:text-sky-300 dark:bg-sky-950/40 dark:border-sky-900",children:"Meta AI"}),l.metadata?.routingResolution?.resolvedAt&&e.jsx(De,{variant:"outline",className:T("text-[9px] h-4 px-1 font-semibold",l.metadata.routingResolution.resolvedAt==="CHANNEL_DIRECT"?"text-teal-600 bg-teal-50 border-teal-200":l.metadata.routingResolution.resolvedAt==="TRIGGER_MATCH"?"text-violet-600 bg-violet-50 border-violet-200":"text-slate-500 bg-slate-50 border-slate-200"),children:l.metadata.routingResolution.resolvedAt==="CHANNEL_DIRECT"?"Direct":l.metadata.routingResolution.resolvedAt==="TRIGGER_MATCH"?"Trigger":l.metadata.routingResolution.resolvedAt==="ORG_DEFAULT"?"Default":"Ruta"}),l.metadata?.workflowSession&&l.metadata.workflowSession.status!=="COMPLETED"&&e.jsx(bi,{session:l.metadata.workflowSession,compact:!0}),l.sourceCampaignId&&e.jsxs(De,{variant:"outline",className:"text-[9px] h-4 px-1.5 font-semibold text-violet-600 bg-violet-50 border-violet-200",children:[e.jsx(Es,{className:"w-2.5 h-2.5 mr-0.5"}),"Campaña"]}),Pr(l)&&e.jsxs(De,{variant:"outline",title:Vr(l)?`Llegó por el anuncio: ${Vr(l)}`:"Llegó haciendo clic en un anuncio",className:"text-[9px] h-4 px-1.5 font-semibold text-sky-700 bg-sky-50 border-sky-200",children:[e.jsx(oa,{className:"w-2.5 h-2.5 mr-0.5"}),"Anuncio"]}),m&&e.jsxs(De,{variant:"outline",title:m.headline?`Llegó desde la publicación: ${m.headline}`:"Llegó pulsando el botón de WhatsApp de una publicación",className:"text-[9px] h-4 px-1.5 font-semibold text-teal-700 bg-teal-50 border-teal-200",children:[e.jsx(xi,{className:"w-2.5 h-2.5 mr-0.5"}),"Publicación"]}),(l.metadata?.inactivity_cycle_count??0)>0&&e.jsxs(De,{variant:"outline",className:"text-[9px] h-4 px-1 font-semibold text-orange-600 bg-orange-50 border-orange-200",children:[e.jsx(Rn,{className:"w-2.5 h-2.5 mr-0.5"}),l.metadata.inactivity_cycle_count]}),l.funnelId&&e.jsx(fi,{funnelId:l.funnelId,stageId:l.funnelStageId,compact:!0}),d&&e.jsx("span",{className:"flex items-center justify-center min-w-[18px] h-[18px] px-1 bg-primary text-white text-[10px] font-bold rounded-full shadow-sm animate-in zoom-in duration-200",children:l.unreadCount})]})]})]})]})});Ga.displayName="ConversationItem";class ea extends i.Component{state={hasError:!1,error:null};static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("[InboxErrorBoundary] Error capturado:",s),console.error("[InboxErrorBoundary] Info:",a)}handleReset=()=>{this.setState({hasError:!1,error:null}),this.props.onReset?.()};render(){if(this.state.hasError){if(this.props.fallback)return this.props.fallback;const s=this.state.error?.message?.toLowerCase()||"",a=s.includes("network")||s.includes("fetch")||s.includes("connection")||s.includes("timeout");return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-8 text-center bg-gradient-to-b from-background to-muted/30",children:[e.jsxs("div",{className:"relative mb-6",children:[e.jsx("div",{className:T("w-24 h-24 rounded-full flex items-center justify-center","bg-gradient-to-br from-muted to-muted/50","shadow-lg shadow-muted/20"),children:a?e.jsx(pl,{className:"w-10 h-10 text-muted-foreground"}):e.jsx(Do,{className:"w-10 h-10 text-muted-foreground"})}),e.jsx("div",{className:"absolute -top-1 -right-1 w-4 h-4 bg-orange-400/80 rounded-full animate-pulse"}),e.jsx("div",{className:"absolute -bottom-2 -left-1 w-3 h-3 bg-primary/40 rounded-full animate-pulse delay-150"})]}),e.jsx("h3",{className:"text-xl font-semibold text-foreground mb-2",children:a?"¡Ups! Sin conexión":"¡Ups! Algo no salió bien"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-6 max-w-sm leading-relaxed",children:a?"Parece que perdimos la conexión con el servidor. Verifica tu internet e intenta de nuevo.":"No te preocupes, estas cosas pasan. Intenta recargar la página o vuelve en un momento."}),e.jsxs(K,{onClick:this.handleReset,className:"gap-2 rounded-full px-6 shadow-md hover:shadow-lg transition-all",children:[e.jsx(ys,{className:"w-4 h-4"}),"Reintentar"]}),e.jsxs("div",{className:"mt-8 flex items-center gap-2 text-xs text-muted-foreground/70",children:[e.jsx(Uo,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Mientras tanto, ¿un café?"})]})]})}return this.props.children}}function or(t){const s=t?.response,a=s?.data?.message;return a?Array.isArray(a)?a.join(". "):a:s?.status&&s.status>=500?"El servidor devolvió un error. Vuelve a intentarlo; si sigue, avisa al equipo.":"Revisa tu conexión y vuelve a intentarlo."}const jc={list:async t=>(await he.get("/campaigns",{params:t})).data,get:async t=>(await he.get(`/campaigns/${t}`)).data,getJobs:async(t,s)=>(await he.get(`/campaigns/${t}/jobs`,{params:s})).data,create:async t=>(await he.post("/campaigns",t)).data,getRetryAudience:async(t,s)=>(await he.get(`/campaigns/${t}/retry-audience`,{params:s})).data,update:async(t,s)=>(await he.patch(`/campaigns/${t}`,s)).data,delete:async t=>{await he.delete(`/campaigns/${t}`)},launch:async(t,s)=>(await he.post(`/campaigns/${t}/launch`,{channelId:s})).data,pause:async t=>(await he.post(`/campaigns/${t}/pause`)).data,resume:async t=>(await he.post(`/campaigns/${t}/resume`)).data,stop:async t=>(await he.post(`/campaigns/${t}/stop`)).data,verifyLaunch:async t=>(await he.get(`/campaigns/${t}/verify-launch`)).data,abort:async t=>(await he.post(`/campaigns/${t}/abort`)).data,forceProceed:async t=>(await he.post(`/campaigns/${t}/force-proceed`)).data,recalculate:async t=>(await he.post(`/campaigns/${t}/recalculate`)).data,previewAudience:async(t,s,a)=>(await he.post("/campaigns/audience/preview",t,{timeout:a?12e4:3e4,signal:s})).data,createSegment:async t=>(await he.post("/campaigns/segments",t)).data,listSegments:async()=>(await he.get("/campaigns/segments")).data,getTags:async()=>(await he.get("/tags")).data,getNonResponders:async t=>(await he.get(`/campaigns/${t}/non-responders`)).data,getTimestamps:async(t,s)=>{const a=new URLSearchParams;return s?.since&&a.set("since",s.since),(await he.get(`/campaigns/${t}/timestamps${a.toString()?"?"+a.toString():""}`)).data},getErrorSummary:async t=>(await he.get(`/campaigns/${t}/error-summary`)).data,getAnalytics:async t=>(await he.get("/campaigns/analytics",{params:t})).data,exportJobs:async(t,s)=>(await he.get(`/campaigns/${t}/jobs/export`,{params:s})).data,previewConversationExport:async t=>(await he.get(`/campaigns/${t}/conversations/preview`)).data,exportConversations:async t=>(await he.get(`/campaigns/${t}/conversations/export`)).data,getFailedContacts:async t=>(await he.get("/campaigns/failed-contacts",{params:t})).data,exportFailedContacts:async t=>(await he.get("/campaigns/failed-contacts/export",{params:t})).data,executeFailedContactsAction:async t=>(await he.post("/campaigns/failed-contacts/actions",t)).data},Wa={all:["campaigns"],list:t=>[...Wa.all,"list",t],detail:t=>[...Wa.all,"detail",t]},yi=t=>rt({queryKey:Wa.list(t),queryFn:()=>jc.list(t),staleTime:1e3*60*1}),vc=t=>{switch(t){case"SENDING":return"bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-500/20 dark:text-blue-300 dark:border-blue-500/30";case"COMPLETED":return"bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-500/20 dark:text-emerald-300 dark:border-emerald-500/30";case"FAILED":return"bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-500/20 dark:text-rose-300 dark:border-rose-500/30";case"STOPPED_BY_CIRCUIT":return"bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-500/20 dark:text-amber-300 dark:border-amber-500/30";case"PAUSED":return"bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-500/20 dark:text-amber-300 dark:border-amber-500/30";case"SCHEDULED":return"bg-indigo-50 text-indigo-700 border-indigo-200 dark:bg-indigo-500/20 dark:text-indigo-300 dark:border-indigo-500/30";case"DRAFT":return"bg-slate-100 text-slate-600 border-slate-200 dark:bg-slate-800 dark:text-slate-400 dark:border-slate-700";default:return"bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-400"}},Nc={DRAFT:"Borrador",SCHEDULED:"Programada",SENDING:"Enviando",COMPLETED:"Completada",FAILED:"Fallida",PAUSED:"Pausada",STOPPED_BY_CIRCUIT:"Detenida"};function wc({value:t,onChange:s}){const[a,r]=i.useState(!1),{data:n}=yi(),o=n?.data||[],l=o.find(c=>c.id===t);return e.jsxs(Xe,{open:a,onOpenChange:r,children:[e.jsx(Ze,{asChild:!0,children:e.jsxs(K,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal",children:[l?e.jsx("span",{className:"truncate",children:l.name}):e.jsx("span",{className:"text-muted-foreground",children:"Seleccionar campaña..."}),e.jsx(Vt,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Je,{className:"w-[350px] p-0",align:"start",children:e.jsxs(At,{children:[e.jsx(Mt,{placeholder:"Buscar campaña..."}),e.jsxs(Dt,{children:[e.jsx(Ot,{children:"No se encontraron campañas."}),e.jsxs(Be,{children:[e.jsxs(Le,{value:"all",onSelect:()=>{s(void 0),r(!1)},children:[e.jsx(Ie,{className:T("mr-2 h-4 w-4",t?"opacity-0":"opacity-100")}),"Todas las campañas"]}),o.map(c=>e.jsxs(Le,{value:c.name,onSelect:()=>{s(c.id===t?void 0:c.id),r(!1)},className:"flex items-start py-3",children:[e.jsx(Ie,{className:T("mr-2 h-4 w-4 mt-1 shrink-0",t===c.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex flex-col gap-1.5 w-full min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between w-full gap-2",children:[e.jsx("span",{className:"font-medium truncate",children:c.name}),e.jsx("span",{className:T("text-[9px] px-1.5 py-0.5 rounded-md border uppercase font-bold shrink-0",vc(c.status)),children:Nc[c.status]||c.status})]}),e.jsx("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground",children:e.jsx("span",{children:is(c.createdAt,{style:"short"})})})]})]},c.id))]})]})]})})]})}function kc({selectedTagIds:t=[],onChange:s}){const[a,r]=i.useState(!1),n=Gn(),o=Wn(u=>u.fetchFolders);i.useEffect(()=>{o()},[o]);const l=u=>{const d=t||[];if(d.includes(u)){const m=d.filter(x=>x!==u);s(m.length>0?m:void 0)}else s([...d,u])},c=t?.length||0;return e.jsxs(Xe,{open:a,onOpenChange:r,children:[e.jsx(Ze,{asChild:!0,children:e.jsxs(K,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between font-normal px-3",children:[e.jsxs("div",{className:"flex items-center gap-2 truncate",children:[e.jsx(Ln,{className:"h-4 w-4 text-muted-foreground"}),c>0?e.jsxs("span",{className:"font-medium",children:[c," etiqueta",c!==1?"s":""]}):e.jsx("span",{className:"text-muted-foreground",children:"Filtrar por etiquetas..."})]}),e.jsx(Vt,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Je,{className:"w-[300px] p-0",align:"start",children:e.jsxs(At,{children:[e.jsx(Mt,{placeholder:"Buscar etiquetas..."}),e.jsxs(Dt,{children:[e.jsx(Ot,{children:"No se encontraron etiquetas."}),e.jsx(Be,{children:n.map(u=>{const d=t?.includes(u.id);return e.jsxs(Le,{value:u.name,onSelect:()=>l(u.id),children:[e.jsx("div",{className:T("mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",d?"bg-primary text-primary-foreground":"opacity-50 [&_svg]:invisible"),children:e.jsx(Ie,{className:T("h-4 w-4")})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:u.color}}),e.jsx("span",{children:u.name})]})]},u.id)})})]})]})})]})}const Cc=(t,s,a=10)=>{if(t==="AVAILABLE")return"bg-green-500";if(t==="AWAY")return"bg-yellow-500";if(t==="UNAVAILABLE")return"bg-red-500";if(s){const r=new Date(s).getTime(),n=Date.now()-a*60*1e3;if(r>n)return"bg-green-500"}return"bg-gray-400"};function Tc({value:t,valueType:s,onChange:a,mode:r="ALL",className:n}){const[o,l]=i.useState(!1),c=Ft(h=>h.currentOrganization),u=c?.inactivityThresholdMinutes??10,d=r==="HUMAN"||r==="ALL",m=r==="AI"||r==="ALL",{data:x=[]}=cs(),{data:b=[]}=rr(c?.id),y=i.useMemo(()=>d?[...x].filter(h=>h.user.isActive!==!1).sort((h,I)=>{const U={AVAILABLE:0,AWAY:1,UNAVAILABLE:2},C=U[h.user.availabilityStatus||""]??3,E=U[I.user.availabilityStatus||""]??3;if(C!==E)return C-E;const M=h.user.lastActivityAt?new Date(h.user.lastActivityAt).getTime():0;return(I.user.lastActivityAt?new Date(I.user.lastActivityAt).getTime():0)-M}):[],[x,d]),p=i.useMemo(()=>m?b.filter(h=>h.agentType!=="analyzer"&&h.status==="active"):[],[b,m]),f=s==="HUMAN"?y.find(h=>h.user.id===t):void 0,g=s==="AI"?p.find(h=>h.id===t):void 0,v=(h,I)=>{a(h,I),l(!1)};return e.jsxs(Xe,{open:o,onOpenChange:l,children:[e.jsx(Ze,{asChild:!0,children:e.jsxs(K,{variant:"outline",role:"combobox","aria-expanded":o,className:T("w-full justify-between font-normal",n),children:[t&&(f||g)?e.jsxs("div",{className:"flex items-center gap-2 truncate",children:[g?e.jsx("div",{className:"h-5 w-5 bg-violet-100 dark:bg-violet-500/20 flex items-center justify-center rounded-full border border-violet-200 dark:border-violet-500/30",children:e.jsx(It,{className:"h-3 w-3 text-violet-600 dark:text-violet-300"})}):e.jsxs(ht,{className:"h-5 w-5 border border-border",children:[e.jsx(pt,{src:f?.user.avatarUrl}),e.jsx(gt,{className:"text-[9px] bg-blue-100 text-blue-700",children:(f?.user.name||"?").charAt(0).toUpperCase()})]}),e.jsx("span",{className:"truncate",children:g?.name||f?.user.name})]}):e.jsxs("div",{className:"flex items-center gap-2 truncate text-muted-foreground",children:[e.jsx(Ws,{className:"h-4 w-4"}),e.jsx("span",{children:"Todos los agentes"})]}),e.jsx(Vt,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Je,{className:"w-[300px] p-0",align:"start",children:e.jsxs(At,{children:[e.jsx(Mt,{placeholder:"Buscar agente..."}),e.jsxs(Dt,{children:[e.jsx(Ot,{children:"No se encontraron agentes."}),e.jsx(Be,{children:e.jsxs(Le,{value:"__all__",keywords:["todos","all","limpiar"],onSelect:()=>v(null,null),className:"gap-2 cursor-pointer",children:[e.jsx("div",{className:"h-6 w-6 rounded-full bg-muted flex items-center justify-center text-muted-foreground",children:e.jsx(Ws,{className:"h-3.5 w-3.5"})}),e.jsx("span",{children:"Todos los agentes"}),!t&&e.jsx(Ie,{className:"ml-auto h-4 w-4"})]})}),p.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Et,{}),e.jsx(Be,{heading:"Agentes IA",children:p.map(h=>e.jsxs(Le,{value:h.id,keywords:[h.name,"bot","ia","ai"],onSelect:()=>v(h.id,"AI"),className:"gap-2 cursor-pointer",children:[e.jsx("div",{className:"h-6 w-6 rounded-full bg-violet-100 dark:bg-violet-500/20 flex items-center justify-center border border-violet-200 dark:border-violet-500/30",children:e.jsx(It,{className:"h-3.5 w-3.5 text-violet-600 dark:text-violet-300"})}),e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:h.name}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Activo"})]}),t===h.id&&s==="AI"&&e.jsx(Ie,{className:"ml-auto h-4 w-4 opacity-100"})]},h.id))})]}),y.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Et,{}),e.jsx(Be,{heading:"Agentes (Humanos)",children:y.map(h=>e.jsxs(Le,{value:h.user.id,keywords:[h.user.name,h.user.email],onSelect:()=>v(h.user.id,"HUMAN"),className:"gap-2 cursor-pointer",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(ht,{className:"h-6 w-6",children:[e.jsx(pt,{src:h.user.avatarUrl}),e.jsx(gt,{children:h.user.name.charAt(0)})]}),e.jsx("div",{className:T("absolute -bottom-0.5 -right-0.5 h-2 w-2 rounded-full border border-white dark:border-gray-800",Cc(h.user.availabilityStatus,h.user.lastActivityAt,u))})]}),e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:h.user.name}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate",children:h.user.email})]}),t===h.user.id&&s==="HUMAN"&&e.jsx(Ie,{className:"ml-auto h-4 w-4 opacity-100"})]},h.id))})]}),p.length===0&&y.length===0&&e.jsx(Be,{children:e.jsxs("div",{className:"px-4 py-6 text-center text-xs text-muted-foreground flex flex-col items-center gap-2",children:[e.jsx(Pa,{className:"h-5 w-5 opacity-50"}),"Sin agentes disponibles"]})})]})]})})]})}function zr(t,s,a){const r=nc(),n=Ic(t,a.timeZone,a.locale??r.locale);return"formatToParts"in n?Sc(n,s):Ec(n,s)}function Sc(t,s){const a=t.formatToParts(s);for(let r=a.length-1;r>=0;--r)if(a[r].type==="timeZoneName")return a[r].value}function Ec(t,s){const a=t.format(s).replace(/\u200E/g,""),r=/ [\w-+ ]+$/.exec(a);return r?r[0].substr(1):""}function Ic(t,s,a){return new Intl.DateTimeFormat(a?[a.code,"en-US"]:void 0,{timeZone:s,timeZoneName:t})}function Ac(t,s){const a=Rc(s);return"formatToParts"in a?Dc(a,t):Oc(a,t)}const Mc={year:0,month:1,day:2,hour:3,minute:4,second:5};function Dc(t,s){try{const a=t.formatToParts(s),r=[];for(let n=0;n<a.length;n++){const o=Mc[a[n].type];o!==void 0&&(r[o]=parseInt(a[n].value,10))}return r}catch(a){if(a instanceof RangeError)return[NaN];throw a}}function Oc(t,s){const a=t.format(s),r=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(a);return[parseInt(r[3],10),parseInt(r[1],10),parseInt(r[2],10),parseInt(r[4],10),parseInt(r[5],10),parseInt(r[6],10)]}const ka={},qr=new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date("2014-06-25T04:00:00.123Z")),Uc=qr==="06/25/2014, 00:00:00"||qr==="06/25/2014 00:00:00";function Rc(t){return ka[t]||(ka[t]=Uc?new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:t,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}):new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})),ka[t]}function cr(t,s,a,r,n,o,l){const c=new Date(0);return c.setUTCFullYear(t,s,a),c.setUTCHours(r,n,o,l),c}const Hr=36e5,_c=6e4,Ca={timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function pa(t,s,a){if(!t)return 0;let r=Ca.timezoneZ.exec(t);if(r)return 0;let n,o;if(r=Ca.timezoneHH.exec(t),r)return n=parseInt(r[1],10),Gr(n)?-(n*Hr):NaN;if(r=Ca.timezoneHHMM.exec(t),r){n=parseInt(r[2],10);const l=parseInt(r[3],10);return Gr(n,l)?(o=Math.abs(n)*Hr+l*_c,r[1]==="+"?-o:o):NaN}if(Pc(t)){s=new Date(s||Date.now());const l=a?s:Lc(s),c=Qa(l,t);return-(a?c:Fc(s,c,t))}return NaN}function Lc(t){return cr(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds())}function Qa(t,s){const a=Ac(t,s),r=cr(a[0],a[1]-1,a[2],a[3]%24,a[4],a[5],0).getTime();let n=t.getTime();const o=n%1e3;return n-=o>=0?o:1e3+o,r-n}function Fc(t,s,a){let n=t.getTime()-s;const o=Qa(new Date(n),a);if(s===o)return s;n-=o-s;const l=Qa(new Date(n),a);return o===l?o:Math.max(o,l)}function Gr(t,s){return-23<=t&&t<=23&&(s==null||0<=s&&s<=59)}const Wr={};function Pc(t){if(Wr[t])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:t}),Wr[t]=!0,!0}catch{return!1}}const Vc=60*1e3,Bc={X:function(t,s,a){const r=Ta(a.timeZone,t);if(r===0)return"Z";switch(s){case"X":return Qr(r);case"XXXX":case"XX":return Kt(r);case"XXXXX":case"XXX":default:return Kt(r,":")}},x:function(t,s,a){const r=Ta(a.timeZone,t);switch(s){case"x":return Qr(r);case"xxxx":case"xx":return Kt(r);case"xxxxx":case"xxx":default:return Kt(r,":")}},O:function(t,s,a){const r=Ta(a.timeZone,t);switch(s){case"O":case"OO":case"OOO":return"GMT"+$c(r,":");case"OOOO":default:return"GMT"+Kt(r,":")}},z:function(t,s,a){switch(s){case"z":case"zz":case"zzz":return zr("short",t,a);case"zzzz":default:return zr("long",t,a)}}};function Ta(t,s){const a=t?pa(t,s,!0)/Vc:s?.getTimezoneOffset()??0;if(Number.isNaN(a))throw new RangeError("Invalid time zone specified: "+t);return a}function ta(t,s){const a=t<0?"-":"";let r=Math.abs(t).toString();for(;r.length<s;)r="0"+r;return a+r}function Kt(t,s=""){const a=t>0?"-":"+",r=Math.abs(t),n=ta(Math.floor(r/60),2),o=ta(Math.floor(r%60),2);return a+n+s+o}function Qr(t,s){return t%60===0?(t>0?"-":"+")+ta(Math.abs(t)/60,2):Kt(t,s)}function $c(t,s=""){const a=t>0?"-":"+",r=Math.abs(t),n=Math.floor(r/60),o=r%60;return o===0?a+String(n):a+String(n)+s+ta(o,2)}function Kr(t){const s=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return s.setUTCFullYear(t.getFullYear()),+t-+s}const ji=/(Z|[+-]\d{2}(?::?\d{2})?| UTC| [a-zA-Z]+\/[a-zA-Z_]+(?:\/[a-zA-Z_]+)?)$/,Sa=36e5,Yr=6e4,zc=2,He={dateTimePattern:/^([0-9W+-]+)(T| )(.*)/,datePattern:/^([0-9W+-]+)(.*)/,YY:/^(\d{2})$/,YYY:[/^([+-]\d{2})$/,/^([+-]\d{3})$/,/^([+-]\d{4})$/],YYYY:/^(\d{4})/,YYYYY:[/^([+-]\d{4})/,/^([+-]\d{5})/,/^([+-]\d{6})/],MM:/^-(\d{2})$/,DDD:/^-?(\d{3})$/,MMDD:/^-?(\d{2})-?(\d{2})$/,Www:/^-?W(\d{2})$/,WwwD:/^-?W(\d{2})-?(\d{1})$/,HH:/^(\d{2}([.,]\d*)?)$/,HHMM:/^(\d{2}):?(\d{2}([.,]\d*)?)$/,HHMMSS:/^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/,timeZone:ji};function sa(t,s={}){if(arguments.length<1)throw new TypeError("1 argument required, but only "+arguments.length+" present");if(t===null)return new Date(NaN);const a=s.additionalDigits==null?zc:Number(s.additionalDigits);if(a!==2&&a!==1&&a!==0)throw new RangeError("additionalDigits must be 0, 1 or 2");if(t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]")return new Date(t.getTime());if(typeof t=="number"||Object.prototype.toString.call(t)==="[object Number]")return new Date(t);if(Object.prototype.toString.call(t)!=="[object String]")return new Date(NaN);const r=qc(t),{year:n,restDateString:o}=Hc(r.date,a),l=Gc(o,n);if(l===null||isNaN(l.getTime()))return new Date(NaN);if(l){const c=l.getTime();let u=0,d;if(r.time&&(u=Wc(r.time),u===null||isNaN(u)))return new Date(NaN);if(r.timeZone||s.timeZone){if(d=pa(r.timeZone||s.timeZone,new Date(c+u)),isNaN(d))return new Date(NaN)}else d=Kr(new Date(c+u)),d=Kr(new Date(c+u+d));return new Date(c+u+d)}else return new Date(NaN)}function qc(t){const s={};let a=He.dateTimePattern.exec(t),r;if(a?(s.date=a[1],r=a[3]):(a=He.datePattern.exec(t),a?(s.date=a[1],r=a[2]):(s.date=null,r=t)),r){const n=He.timeZone.exec(r);n?(s.time=r.replace(n[1],""),s.timeZone=n[1].trim()):s.time=r}return s}function Hc(t,s){if(t){const a=He.YYY[s],r=He.YYYYY[s];let n=He.YYYY.exec(t)||r.exec(t);if(n){const o=n[1];return{year:parseInt(o,10),restDateString:t.slice(o.length)}}if(n=He.YY.exec(t)||a.exec(t),n){const o=n[1];return{year:parseInt(o,10)*100,restDateString:t.slice(o.length)}}}return{year:null}}function Gc(t,s){if(s===null)return null;let a,r,n;if(!t||!t.length)return a=new Date(0),a.setUTCFullYear(s),a;let o=He.MM.exec(t);if(o)return a=new Date(0),r=parseInt(o[1],10)-1,Zr(s,r)?(a.setUTCFullYear(s,r),a):new Date(NaN);if(o=He.DDD.exec(t),o){a=new Date(0);const l=parseInt(o[1],10);return Yc(s,l)?(a.setUTCFullYear(s,0,l),a):new Date(NaN)}if(o=He.MMDD.exec(t),o){a=new Date(0),r=parseInt(o[1],10)-1;const l=parseInt(o[2],10);return Zr(s,r,l)?(a.setUTCFullYear(s,r,l),a):new Date(NaN)}if(o=He.Www.exec(t),o)return n=parseInt(o[1],10)-1,Jr(n)?Xr(s,n):new Date(NaN);if(o=He.WwwD.exec(t),o){n=parseInt(o[1],10)-1;const l=parseInt(o[2],10)-1;return Jr(n,l)?Xr(s,n,l):new Date(NaN)}return null}function Wc(t){let s,a,r=He.HH.exec(t);if(r)return s=parseFloat(r[1].replace(",",".")),Ea(s)?s%24*Sa:NaN;if(r=He.HHMM.exec(t),r)return s=parseInt(r[1],10),a=parseFloat(r[2].replace(",",".")),Ea(s,a)?s%24*Sa+a*Yr:NaN;if(r=He.HHMMSS.exec(t),r){s=parseInt(r[1],10),a=parseInt(r[2],10);const n=parseFloat(r[3].replace(",","."));return Ea(s,a,n)?s%24*Sa+a*Yr+n*1e3:NaN}return null}function Xr(t,s,a){s=s||0,a=a||0;const r=new Date(0);r.setUTCFullYear(t,0,4);const n=r.getUTCDay()||7,o=s*7+a+1-n;return r.setUTCDate(r.getUTCDate()+o),r}const Qc=[31,28,31,30,31,30,31,31,30,31,30,31],Kc=[31,29,31,30,31,30,31,31,30,31,30,31];function vi(t){return t%400===0||t%4===0&&t%100!==0}function Zr(t,s,a){if(s<0||s>11)return!1;if(a!=null){if(a<1)return!1;const r=vi(t);if(r&&a>Kc[s]||!r&&a>Qc[s])return!1}return!0}function Yc(t,s){if(s<1)return!1;const a=vi(t);return!(a&&s>366||!a&&s>365)}function Jr(t,s){return!(t<0||t>52||s!=null&&(s<0||s>6))}function Ea(t,s,a){return!(t<0||t>=25||s!=null&&(s<0||s>=60)||a!=null&&(a<0||a>=60))}const Xc=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function Zc(t,s,a={}){s=String(s);const r=s.match(Xc);if(r){const n=sa(a.originalDate||t,a);s=r.reduce(function(o,l){if(l[0]==="'")return o;const c=o.indexOf(l),u=o[c-1]==="'",d=o.replace(l,"'"+Bc[l[0]](n,l,a)+"'");return u?d.substring(0,c-1)+d.substring(c+1):d},s)}return Zl(t,s,a)}function Jc(t,s,a){t=sa(t,a);const r=pa(s,t,!0),n=new Date(t.getTime()-r),o=new Date(0);return o.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),o.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),o}function dr(t,s,a,r){return r={...r,timeZone:s,originalDate:t},Zc(Jc(t,s,{timeZone:r.timeZone}),a,r)}function Ni(t,s,a){if(typeof t=="string"&&!t.match(ji))return sa(t,{...a,timeZone:s});t=sa(t,a);const r=cr(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()).getTime(),n=pa(s,new Date(r));return new Date(r+n)}const xs="30d",wi="America/Lima",ed={"7d":"Última semana","30d":"Último mes","90d":"Últimos 3 meses","180d":"Últimos 6 meses",custom:"Personalizado"},td={"7d":7,"30d":30,"90d":90,"180d":180},en=new Map;function tn(t){if(typeof t!="string"||t.length===0)return!1;const s=en.get(t);if(s!==void 0)return s;let a=!1;try{new Intl.DateTimeFormat(void 0,{timeZone:t}),a=!0}catch{console.warn(`[orgDate] Invalid IANA timezone "${t}" — falling back to ${wi}.`)}return en.set(t,a),a}function ki(){const t=Ft(a=>a.currentOrganization?.timezone),s=Ye(a=>a.user?.preferences?.timezone);return tn(t)?t:tn(s)?s:wi}function Rs(t,s){const a=td[t],r=dr(ic(new Date,a),s,"yyyy-MM-dd");return{dateFrom:Ni(`${r}T00:00:00`,s).toISOString()}}function sn(t,s,a){return Ni(`${t}T${a==="start"?"00:00:00.000":"23:59:59.999"}`,s).toISOString()}function sd(t,s){return dr(new Date(t),s,"d MMM yyyy",{locale:Jl})}function ad(t,s){return dr(new Date(t),s,"yyyy-MM-dd")}function Ci(t){let s=0;return t.status&&t.status!=="all"&&s++,t.assignedTo&&t.assignedTo!=="all"&&s++,t.hasUnread&&s++,t.hasUnansweredMessages&&s++,t.withoutPhone&&s++,t.tagIds?.length&&s++,t.assignedAgentId&&s++,t.sourceCampaignId&&s++,t.dateRange&&t.dateRange!=="all"&&s++,s}const Ti=i.memo(({filters:t,onChange:s,agentMode:a="ALL",canFilterByAgent:r=!1,className:n})=>{const[o,l]=i.useState(!1),[c,u]=i.useState(!1),[d,m]=i.useState(!1),x=ki(),{data:b}=la(),y=fe(w=>w.filters.funnelId),p=fe(w=>w.filters.funnelStageId),f=fe(w=>w.setFunnelFilter),g=fe(w=>w.setFunnelStageFilter),v=fe(w=>w.clearFunnelFilters),h=i.useMemo(()=>b?.find(w=>w.id===y),[b,y]),I=i.useMemo(()=>b?.filter(w=>w.active!==!1)??[],[b]),U=i.useMemo(()=>h?.stages?h.stages.filter(w=>w.active!==!1).sort((w,$)=>String(w.order).localeCompare(String($.order))):[],[h?.stages]),C=i.useMemo(()=>U.find(w=>w.id===p),[U,p]),E=Ci(t)+(y?1:0)+(p?1:0),M=w=>{s({...t,status:w})},F=w=>{s({...t,assignedTo:w})},_=w=>{s({...t,dateRange:w})},k=w=>{s({...t,dateRange:"custom",dateFrom:w.target.value?sn(w.target.value,x,"start"):void 0})},W=w=>{s({...t,dateRange:"custom",dateTo:w.target.value?sn(w.target.value,x,"end"):void 0})},q=w=>{s({...t,hasUnread:w})},ee=w=>{s({...t,hasUnansweredMessages:w})},le=w=>{s({...t,withoutPhone:w})},S=w=>{s({...t,sourceCampaignId:w})},P=w=>{s({...t,tagIds:w})},X=(w,$)=>{s({...t,assignedAgentId:w??void 0,assignedAgentType:$??void 0})},A=()=>{v(),s({status:"all",assignedTo:"all",hasUnread:!1,hasUnansweredMessages:!1,withoutPhone:!1,dateRange:"all",sourceCampaignId:void 0,tagIds:void 0,dateFrom:void 0,dateTo:void 0,assignedAgentId:void 0,assignedAgentType:void 0})},z=w=>{f(w==="_all"?void 0:w)},L=w=>{g(w==="_all"?void 0:w)},N=w=>{if(!w)return"";try{return ad(w,x)}catch{return""}};return e.jsxs(Xe,{open:o,onOpenChange:l,children:[e.jsx(Ze,{asChild:!0,children:e.jsxs(K,{variant:"outline",size:"sm",className:T("h-9 gap-2 rounded-full border-input bg-background hover:bg-accent hover:text-accent-foreground px-4 py-2 transition-all text-sm font-medium shadow-sm",E>0&&"border-primary/50 bg-primary/5 ring-1 ring-primary/20",n),children:[e.jsx(Na,{className:"w-4 h-4"}),e.jsx("span",{children:"Filtros"}),E>0&&e.jsx(De,{variant:"secondary",className:"h-5 min-w-5 p-0 px-1.5 ml-0.5 flex items-center justify-center text-[11px] bg-primary text-primary-foreground rounded-full",children:E})]})}),e.jsxs(Je,{align:"start",className:"w-[600px] p-0 overflow-hidden shadow-lg border-border",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b bg-muted/10",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Na,{className:"w-4 h-4 text-primary"}),e.jsx("h4",{className:"font-semibold text-foreground",children:"Filtros Avanzados"})]}),E>0&&e.jsxs(K,{variant:"ghost",size:"sm",onClick:A,className:"h-7 px-2 text-xs text-muted-foreground hover:text-destructive hover:bg-destructive/10",children:[e.jsx(Ge,{className:"w-3.5 h-3.5 mr-1.5"}),"Limpiar filtros"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-0 divide-x divide-border",children:[e.jsxs("div",{className:"p-4 space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(we,{className:"text-xs uppercase font-bold text-muted-foreground/80 tracking-wider flex items-center gap-1.5 px-0.5",children:[e.jsx(bt,{className:"w-3.5 h-3.5"}),"Estado & Asignación"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs(kt,{value:t.status||"all",onValueChange:M,children:[e.jsx(Ct,{className:"h-9 text-sm",children:e.jsx(Tt,{placeholder:"Estado"})}),e.jsxs(St,{children:[e.jsx(Me,{value:"all",children:"Todos"}),e.jsx(Me,{value:"OPEN",children:"Abierto"}),e.jsx(Me,{value:"WAITING",children:"En espera"}),e.jsx(Me,{value:"RESOLVED",children:"Resuelto"})]})]}),e.jsxs(kt,{value:t.assignedTo||"all",onValueChange:F,children:[e.jsx(Ct,{className:"h-9 text-sm",children:e.jsx(Tt,{placeholder:"Asignación"})}),e.jsxs(St,{children:[e.jsx(Me,{value:"all",children:"Todos"}),e.jsx(Me,{value:"me",children:"Mis tickets"}),e.jsx(Me,{value:"unassigned",children:"Sin asignar"})]})]})]})]}),r&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(we,{className:"text-xs uppercase font-bold text-muted-foreground/80 tracking-wider flex items-center gap-1.5 px-0.5",children:[e.jsx(Ao,{className:"w-3.5 h-3.5"}),"Agente"]}),e.jsx(Tc,{value:t.assignedAgentId??null,valueType:t.assignedAgentType??null,onChange:X,mode:a})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(we,{className:"text-xs uppercase font-bold text-muted-foreground/80 tracking-wider flex items-center gap-1.5 px-0.5",children:[e.jsx(Es,{className:"w-3.5 h-3.5"}),"Campaña Origen"]}),e.jsx(wc,{value:t.sourceCampaignId,onChange:S})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(we,{className:"text-xs uppercase font-bold text-muted-foreground/80 tracking-wider flex items-center gap-1.5 px-0.5",children:[e.jsx(Ln,{className:"w-3.5 h-3.5"}),"Etiquetas de Contacto"]}),e.jsx(kc,{selectedTagIds:t.tagIds,onChange:P})]}),I.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(we,{className:"text-xs uppercase font-bold text-muted-foreground/80 tracking-wider flex items-center gap-1.5 px-0.5",children:[e.jsx(js,{className:"w-3.5 h-3.5"}),"Funnel & Etapa"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs(Xe,{open:c,onOpenChange:u,children:[e.jsx(Ze,{asChild:!0,children:e.jsxs(K,{variant:"outline",role:"combobox","aria-expanded":c,className:"h-9 w-full justify-between font-normal text-sm px-3",children:[e.jsx("span",{className:T("truncate",!h&&"text-muted-foreground"),children:h?h.name:"Funnel"}),e.jsx(Vt,{className:"ml-2 h-3.5 w-3.5 shrink-0 opacity-50"})]})}),e.jsx(Je,{className:"w-[260px] p-0",align:"start",children:e.jsxs(At,{children:[e.jsx(Mt,{placeholder:"Buscar funnel...",className:"h-9"}),e.jsxs(Dt,{children:[e.jsx(Ot,{children:"No se encontraron funnels."}),e.jsxs(Be,{children:[e.jsxs(Le,{value:"__all-funnels",onSelect:()=>{z("_all"),u(!1)},children:[e.jsx(Ie,{className:T("mr-2 h-4 w-4",y?"opacity-0":"opacity-100")}),e.jsx("span",{className:"text-muted-foreground",children:"Todos los funnels"})]}),I.map(w=>e.jsxs(Le,{value:w.name,onSelect:()=>{z(w.id),u(!1)},children:[e.jsx(Ie,{className:T("mr-2 h-4 w-4",y===w.id?"opacity-100":"opacity-0")}),e.jsx("span",{className:"truncate",children:w.name})]},w.id))]})]})]})})]}),e.jsxs(Xe,{open:d,onOpenChange:w=>{w&&(!h||U.length===0)||m(w)},children:[e.jsx(Ze,{asChild:!0,children:e.jsxs(K,{variant:"outline",role:"combobox","aria-expanded":d,disabled:!h||U.length===0,className:"h-9 w-full justify-between font-normal text-sm px-3",children:[e.jsx("span",{className:T("truncate flex items-center gap-1.5",!p&&"text-muted-foreground"),children:C?e.jsxs(e.Fragment,{children:[C.icon&&e.jsx("span",{children:C.icon}),e.jsx("span",{className:"truncate",children:C.name})]}):"Etapa"}),e.jsx(Vt,{className:"ml-2 h-3.5 w-3.5 shrink-0 opacity-50"})]})}),e.jsx(Je,{className:"w-[260px] p-0",align:"start",children:e.jsxs(At,{children:[e.jsx(Mt,{placeholder:"Buscar etapa...",className:"h-9"}),e.jsxs(Dt,{children:[e.jsx(Ot,{children:"No se encontraron etapas."}),e.jsxs(Be,{children:[e.jsxs(Le,{value:"__all-stages",onSelect:()=>{L("_all"),m(!1)},children:[e.jsx(Ie,{className:T("mr-2 h-4 w-4",p?"opacity-0":"opacity-100")}),e.jsx("span",{className:"text-muted-foreground",children:"Todas las etapas"})]}),U.map(w=>e.jsxs(Le,{value:w.name,onSelect:()=>{L(w.id),m(!1)},children:[e.jsx(Ie,{className:T("mr-2 h-4 w-4",p===w.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex items-center gap-2 truncate",children:[w.icon&&e.jsx("span",{children:w.icon}),e.jsx("span",{className:"truncate",children:w.name})]})]},w.id))]})]})]})})]})]})]})]}),e.jsxs("div",{className:"p-4 space-y-6 bg-muted/5",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs(we,{className:"text-xs uppercase font-bold text-muted-foreground/80 tracking-wider flex items-center gap-1.5 px-0.5",children:[e.jsx(Pt,{className:"w-3.5 h-3.5"}),"Período de Tiempo"]}),e.jsxs(kt,{value:t.dateRange||"all",onValueChange:_,children:[e.jsx(Ct,{className:"h-9 text-sm bg-background",children:e.jsx(Tt,{placeholder:t.status==="RESOLVED"?"Último mes":"Todo el tiempo"})}),e.jsx(St,{children:t.status==="RESOLVED"?e.jsxs(e.Fragment,{children:[e.jsx(Me,{value:"7d",children:"Última semana"}),e.jsx(Me,{value:"30d",children:"Último mes"}),e.jsx(Me,{value:"90d",children:"Últimos 3 meses"}),e.jsx(Me,{value:"180d",children:"Últimos 6 meses"}),e.jsx(Me,{value:"custom",children:"Rango personalizado..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(Me,{value:"all",children:"Todo el tiempo"}),e.jsx(Me,{value:"6h",children:"Últimas 6 horas"}),e.jsx(Me,{value:"12h",children:"Últimas 12 horas"}),e.jsx(Me,{value:"24h",children:"Últimas 24 horas"}),e.jsx(Me,{value:"7d",children:"Últimos 7 días"}),e.jsx(Me,{value:"30d",children:"Últimos 30 días"}),e.jsx(Me,{value:"custom",children:"Rango personalizado..."})]})})]}),t.dateRange==="custom"&&e.jsxs("div",{className:"grid grid-cols-2 gap-2 p-3 bg-background rounded-md border shadow-sm animate-in zoom-in-95 duration-200",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(we,{className:"text-[10px] text-muted-foreground",children:"Desde"}),e.jsx(Te,{type:"date",className:"h-8 text-xs px-2",value:N(t.dateFrom),onChange:k})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(we,{className:"text-[10px] text-muted-foreground",children:"Hasta"}),e.jsx(Te,{type:"date",className:"h-8 text-xs px-2",value:N(t.dateTo),onChange:W})]})]})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs(we,{className:"text-xs uppercase font-bold text-muted-foreground/80 tracking-wider flex items-center gap-1.5 px-0.5",children:[e.jsx(Na,{className:"w-3.5 h-3.5"}),"Otros Filtros"]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-md border bg-background hover:bg-accent/5 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:T("w-8 h-8 rounded-full flex items-center justify-center transition-colors",t.hasUnread?"bg-primary/10 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(Ja,{className:"w-4 h-4"})}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(we,{className:"text-sm font-medium cursor-pointer",htmlFor:"unread-switch",children:"Solo no leídos"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Muestra solo conversaciones con mensajes nuevos"})]})]}),e.jsx(va,{id:"unread-switch",checked:t.hasUnread||!1,onCheckedChange:q})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-md border bg-background hover:bg-accent/5 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:T("w-8 h-8 rounded-full flex items-center justify-center transition-colors",t.hasUnansweredMessages?"bg-primary/10 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(ao,{className:"w-4 h-4"})}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(we,{className:"text-sm font-medium cursor-pointer",htmlFor:"unanswered-switch",children:"Sin respuesta del negocio"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Tickets cuyo último mensaje fue del cliente"})]})]}),e.jsx(va,{id:"unanswered-switch",checked:t.hasUnansweredMessages||!1,onCheckedChange:ee})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-md border bg-background hover:bg-accent/5 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:T("w-8 h-8 rounded-full flex items-center justify-center transition-colors",t.withoutPhone?"bg-sky-100 text-sky-700":"bg-muted text-muted-foreground"),children:e.jsx(Ko,{className:"w-4 h-4"})}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(we,{className:"text-sm font-medium cursor-pointer",htmlFor:"without-phone-switch",children:"Leads sin número"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"No pueden recibir plantillas ni campañas"})]})]}),e.jsx(va,{id:"without-phone-switch",checked:t.withoutPhone||!1,onCheckedChange:le})]})]})]})]}),E>0&&e.jsxs("div",{className:"bg-primary/5 p-2 px-4 border-t text-xs text-primary font-medium flex justify-center items-center",children:["Se están aplicando ",E," filtros a la vista actual"]})]})]})});Ti.displayName="FilterPopover";function rd({filters:t,onChange:s,funnelId:a,funnelStageId:r,onClearFunnel:n,onClearStage:o,agentName:l,canFilterByAgent:c}){const u=Gn(),{data:d}=yi(),{data:m}=la(),x=i.useMemo(()=>{const b=[];if(t.status&&t.status!=="all"&&t.status!=="RESOLVED"&&b.push({key:"status",label:`Estado: ${t.status==="OPEN"?"Abierto":"En espera"}`,onRemove:()=>s({...t,status:"all"})}),t.assignedTo&&t.assignedTo!=="all"&&b.push({key:"assignedTo",label:t.assignedTo==="me"?"Mis tickets":"Sin asignar",onRemove:()=>s({...t,assignedTo:"all"})}),t.hasUnread&&b.push({key:"hasUnread",label:"No leídos",onRemove:()=>s({...t,hasUnread:!1})}),t.hasUnansweredMessages&&b.push({key:"hasUnanswered",label:"Sin responder",onRemove:()=>s({...t,hasUnansweredMessages:!1})}),t.withoutPhone&&b.push({key:"withoutPhone",label:"Leads sin número",onRemove:()=>s({...t,withoutPhone:!1})}),t.tagIds?.length)for(const y of t.tagIds){const p=u.find(f=>f.id===y);b.push({key:`tag:${y}`,label:p?`Etiqueta: ${p.name}`:"Etiqueta",onRemove:()=>{const f=t.tagIds.filter(g=>g!==y);s({...t,tagIds:f.length?f:void 0})}})}if(t.sourceCampaignId){const y=d?.data?.find(p=>p.id===t.sourceCampaignId);b.push({key:"campaign",label:y?`Campaña: ${y.name}`:"Campaña",onRemove:()=>s({...t,sourceCampaignId:void 0})})}if(c&&t.assignedAgentId&&b.push({key:"agent",label:l?`Agente: ${l}`:"Agente",onRemove:()=>s({...t,assignedAgentId:void 0,assignedAgentType:void 0})}),a){const y=m?.find(p=>p.id===a);if(b.push({key:"funnel",label:y?`Funnel: ${y.name}`:"Funnel",onRemove:n}),r){const p=y?.stages?.find(f=>f.id===r);b.push({key:"stage",label:p?`Etapa: ${p.name}`:"Etapa",onRemove:o})}}return b},[t,s,u,d,m,a,r,n,o,l,c]);return x.length===0?null:e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:x.map(b=>e.jsxs(De,{variant:"secondary",className:"h-6 gap-1 text-xs max-w-[220px]",children:[e.jsx("span",{className:"truncate",children:b.label}),e.jsx("button",{onClick:b.onRemove,"aria-label":`Quitar filtro ${b.label}`,className:"shrink-0",children:e.jsx(Ge,{className:"w-3 h-3"})})]},b.key))})}const ds=()=>{const t=it(),s=fe(er(f=>({initialize:f.initialize,cleanup:f.cleanup,selectConversation:f.selectConversation,setTab:f.setTab,setChannelFilter:f.setChannelFilter,setScope:f.setScope,setSearch:f.setSearch,startTyping:f.startTyping,stopTyping:f.stopTyping}))),a=i.useCallback(async()=>{await Promise.all([t.invalidateQueries({queryKey:["inbox","conversations"]}),t.invalidateQueries({queryKey:["inbox","counts"]})])},[t]),r=i.useCallback(async f=>{await Promise.all([t.invalidateQueries({queryKey:["inbox","conversation",f]}),t.invalidateQueries({queryKey:["inbox","messages",f]})])},[t]),n=i.useCallback(async f=>await lt(()=>import("./index-DsyZ_FlA.js").then(g=>g.c3),__vite__mapDeps([0,1,2])).then(g=>g.inboxApi.sendMessage(f)),[]),o=i.useCallback(async f=>{if(f){const g=t.getQueryData(["inbox","conversations"]);if(g)for(const v of g.pages){const h=v.data.find(I=>I.ticket.id===f);if(h){t.setQueryData(["inbox","conversation",f],h);break}}}return s.selectConversation(f)},[t,s]),l=i.useCallback(async(f,g,v)=>{const{inboxApi:h}=await lt(async()=>{const{inboxApi:I}=await import("./index-DsyZ_FlA.js").then(U=>U.c3);return{inboxApi:I}},__vite__mapDeps([0,1,2]));await h.assignTicket(f,g,v),t.invalidateQueries({queryKey:["workflow","session",f]})},[t]),c=i.useCallback(async f=>{const{inboxApi:g}=await lt(async()=>{const{inboxApi:v}=await import("./index-DsyZ_FlA.js").then(h=>h.c3);return{inboxApi:v}},__vite__mapDeps([0,1,2]));await g.closeTicket(f)},[]),u=i.useCallback(async f=>{const{inboxApi:g}=await lt(async()=>{const{inboxApi:h}=await import("./index-DsyZ_FlA.js").then(I=>I.c3);return{inboxApi:h}},__vite__mapDeps([0,1,2])),v=await g.reopenTicket(f);return t.removeQueries({queryKey:["inbox","timeline"]}),await Promise.all([t.invalidateQueries({queryKey:["inbox","conversation",f]}),t.invalidateQueries({queryKey:["inbox","conversations"]}),t.invalidateQueries({queryKey:["inbox","counts"]}),t.invalidateQueries({queryKey:["workflow","session",f]})]),v},[t]),d=i.useCallback(async f=>{const{inboxApi:g}=await lt(async()=>{const{inboxApi:v}=await import("./index-DsyZ_FlA.js").then(h=>h.c3);return{inboxApi:v}},__vite__mapDeps([0,1,2]));return await g.assignToBestAgentInOrg(f)},[]),m=i.useCallback(async(f,g)=>{const{inboxApi:v}=await lt(async()=>{const{inboxApi:h}=await import("./index-DsyZ_FlA.js").then(I=>I.c3);return{inboxApi:h}},__vite__mapDeps([0,1,2]));await v.updateTicketStage(f,g)},[]),x=i.useCallback(async(f,g)=>{const{inboxApi:v}=await lt(async()=>{const{inboxApi:h}=await import("./index-DsyZ_FlA.js").then(I=>I.c3);return{inboxApi:h}},__vite__mapDeps([0,1,2]));await v.updateContact(f,g)},[]),b=i.useCallback(async(f,g)=>{const{inboxApi:v}=await lt(async()=>{const{inboxApi:I}=await import("./index-DsyZ_FlA.js").then(U=>U.c3);return{inboxApi:I}},__vite__mapDeps([0,1,2])),h=await v.registerSale(f,g);return await t.invalidateQueries({queryKey:["inbox","conversation",f]}),h},[t]),y=i.useCallback(async(f,g)=>{const{inboxApi:v}=await lt(async()=>{const{inboxApi:I}=await import("./index-DsyZ_FlA.js").then(U=>U.c3);return{inboxApi:I}},__vite__mapDeps([0,1,2])),h=await v.updateSale(f,g);return await t.invalidateQueries({queryKey:["inbox","conversation",f]}),h},[t]),p=i.useCallback(async f=>{const{inboxApi:g}=await lt(async()=>{const{inboxApi:v}=await import("./index-DsyZ_FlA.js").then(h=>h.c3);return{inboxApi:v}},__vite__mapDeps([0,1,2]));return g.getSale(f)},[]);return{initialize:s.initialize,cleanup:s.cleanup,fetchConversations:a,selectConversation:o,refreshConversation:r,sendMessage:n,setTab:s.setTab,setChannelFilter:s.setChannelFilter,setScope:s.setScope,setSearch:s.setSearch,assignTicket:l,assignBestAgentInOrg:d,closeTicket:c,reopenTicket:u,updateTicketStage:m,registerSale:b,updateSale:y,getSale:p,updateContact:x,startTyping:s.startTyping,stopTyping:s.stopTyping}};function nd(t){const s=fe(n=>n.filters),a={...s,excludeChannelTypes:"EMAIL",search:t?.search||s.search,status:t?.status,assignedTo:t?.assignedTo,assignedAgentId:t?.assignedAgentId,assignedAgentType:t?.assignedAgentType,hasUnread:t?.hasUnread,hasUnansweredMessages:t?.hasUnansweredMessages,withoutPhone:t?.withoutPhone,dateFrom:t?.dateFrom||s.dateFrom,dateTo:t?.dateTo||s.dateTo,sourceCampaignId:t?.sourceCampaignId??s.sourceCampaignId,tagIds:t?.tagIds},r=a.channelType&&["email","facebook","instagram","calendar"].includes(a.channelType);return da({queryKey:["inbox","conversations",a],queryFn:({pageParam:n=1})=>Ce.getConversations({...a,page:n}),enabled:!r,initialPageParam:1,getNextPageParam:n=>{if(n.hasMore)return n.page+1},staleTime:1e3*60*5,placeholderData:gl})}const Si=3;function id(t,s){if(t.status&&t.status!=="all"||t.hasUnread||t.assignedTo==="unassigned")return null;const a=(t.search??"").trim(),r={...a?{search:a}:{},...s.channelId?{channelId:s.channelId}:s.channelType?{channelType:s.channelType}:{excludeChannelTypes:"EMAIL"},...s.funnelId?{funnelId:s.funnelId}:{},...s.funnelStageId?{funnelStageId:s.funnelStageId}:{},...t.sourceCampaignId??s.sourceCampaignId?{sourceCampaignId:t.sourceCampaignId??s.sourceCampaignId}:{},...t.tagIds?.length?{tagIds:t.tagIds}:{},...t.assignedTo&&t.assignedTo!=="all"?{assignedTo:t.assignedTo}:{},...t.assignedAgentId?{assignedAgentId:t.assignedAgentId,assignedAgentType:t.assignedAgentType}:{},...t.hasUnansweredMessages?{hasUnansweredMessages:!0}:{},...t.withoutPhone?{withoutPhone:!0}:{},...t.dateFrom||s.dateFrom?{dateFrom:t.dateFrom||s.dateFrom}:{},...t.dateTo||s.dateTo?{dateTo:t.dateTo||s.dateTo}:{}},n=!!(r.channelId||r.channelType||r.funnelId||r.funnelStageId||r.sourceCampaignId||r.tagIds||r.assignedTo||r.assignedAgentId||r.hasUnansweredMessages||r.withoutPhone||r.dateFrom||r.dateTo);return a.length<Si&&!n?null:r}function ld(t){const s=fe(n=>n.filters),a=id(t,s);return{...da({queryKey:["inbox","closed-matches",a],queryFn:({pageParam:n=1})=>Ce.getClosedMatches({...a,page:n}),enabled:a!==null,initialPageParam:1,getNextPageParam:n=>n.hasMore?n.page+1:void 0,staleTime:3e4}),isActive:a!==null,isWindowed:a!==null&&(a.search??"").length<Si}}const od=88,Ei=i.memo(({activeConversationId:t,onSelectConversation:s})=>{const a=fe(O=>O.filters.tab),{can:r,isDenied:n}=fl(),o=n(fr.DENY_INBOX_WAITING),l=fe(O=>O.filters.scope),c=fe(O=>O.filters.search),u=fe(O=>O.filters.channelId),d=fe(O=>O.filters.channelType),m=fe(O=>O.filters.funnelId),x=fe(O=>O.filters.funnelStageId),b=fe(O=>O.clearFunnelFilters),y=fe(O=>O.setFunnelStageFilter),p=r(fr.VIEW_ALL_CONVERSATIONS),f=p&&a==="my_chats",g=a==="ai_agent"?"AI":a==="my_chats"?"HUMAN":"ALL",v=i.useMemo(()=>u?`id:${u}`:d?`type:${d}`:"all",[u,d]),[h,I]=i.useState({status:"all",assignedTo:"all",hasUnread:!1,hasUnansweredMessages:!1,withoutPhone:!1,dateRange:"all",dateFrom:void 0,dateTo:void 0,assignedAgentId:void 0,assignedAgentType:void 0}),U=p&&(h.status==="RESOLVED"||a==="my_chats"&&l==="all"||a==="ai_agent");i.useEffect(()=>{if(!h.assignedAgentId)return;const O=h.assignedAgentType==="HUMAN"&&a==="my_chats"||h.assignedAgentType==="AI"&&a==="ai_agent";(!U||!O)&&I(B=>({...B,assignedAgentId:void 0,assignedAgentType:void 0}))},[U,a,h.assignedAgentId,h.assignedAgentType]);const C=ki(),E=i.useCallback(O=>{let{dateRange:B,dateFrom:J,dateTo:me}=O;if(O.status==="RESOLVED"&&B&&B!=="custom")if(B==="7d"||B==="30d"||B==="90d"||B==="180d")J=Rs(B,C).dateFrom,me=void 0;else{const Y=Rs("30d",C);B="30d",J=Y.dateFrom,me=void 0}else if(B&&B!=="all"&&B!=="custom"){const Y=new Date;B==="6h"?J=new Date(Y.getTime()-360*60*1e3).toISOString():B==="12h"?J=new Date(Y.getTime()-720*60*1e3).toISOString():B==="24h"?J=new Date(Y.getTime()-1440*60*1e3).toISOString():B==="7d"?J=new Date(Y.getTime()-10080*60*1e3).toISOString():B==="30d"&&(J=new Date(Y.getTime()-720*60*60*1e3).toISOString()),me=Y.toISOString()}else B==="all"&&(J=void 0,me=void 0);I({...O,dateRange:B,dateFrom:J,dateTo:me})},[C]);i.useEffect(()=>{if(h.status==="RESOLVED"){const B=["7d","30d","90d","180d","custom"];if(!(h.dateRange&&B.includes(h.dateRange))){const{dateFrom:me}=Rs(xs,C);I(R=>({...R,dateRange:xs,dateFrom:me,dateTo:void 0}))}}else(h.dateRange==="90d"||h.dateRange==="180d")&&I(B=>({...B,dateRange:"all",dateFrom:void 0,dateTo:void 0}))},[h.status,h.dateRange,C]);const[M,F]=i.useState(""),_=Fr(M,400),k=Fr(h,250),[W,q]=i.useState(!1),[ee,le]=i.useState(null),{data:S,fetchNextPage:P,hasNextPage:X,isFetchingNextPage:A,isLoading:z,isFetching:L,isError:N,error:w,refetch:$}=nd({search:_,status:k.status==="all"?void 0:k.status,assignedTo:k.assignedTo==="all"?void 0:k.assignedTo,assignedAgentId:U?k.assignedAgentId:void 0,assignedAgentType:U?k.assignedAgentType:void 0,hasUnread:k.hasUnread,hasUnansweredMessages:k.hasUnansweredMessages,withoutPhone:k.withoutPhone,dateFrom:k.dateFrom,dateTo:k.dateTo,sourceCampaignId:k.sourceCampaignId,tagIds:k.tagIds}),ae=i.useMemo(()=>S?.pages.flatMap(O=>O.data)||[],[S]),ne=S?.pages[0]?.counts||{myChats:0,aiAgent:0,waiting:0,closed:0},{setTab:re,setChannelFilter:be,setScope:D,setSearch:Z}=ds(),te=Ft(O=>O.currentOrganization),{data:xe=[]}=cs(),{data:ge=[]}=rr(te?.id),ve=i.useMemo(()=>{const O=h.assignedAgentId,B=h.assignedAgentType;if(!O||!B)return null;if(B==="AI"){const me=ge.find(R=>R.id===O);return me?{name:me.name,type:"AI",avatarUrl:void 0}:null}const J=xe.find(me=>me.user.id===O);return J?{name:J.user.name,type:"HUMAN",avatarUrl:J.user.avatarUrl}:null},[h.assignedAgentId,h.assignedAgentType,ge,xe]);i.useEffect(()=>{_.length===0?c&&Z(""):_.length>=2&&_!==c&&Z(_)},[_,Z,c]);const V=ae,j=ld({search:_,status:k.status,hasUnread:k.hasUnread,assignedTo:k.assignedTo,assignedAgentId:U?k.assignedAgentId:void 0,assignedAgentType:U?k.assignedAgentType:void 0,hasUnansweredMessages:k.hasUnansweredMessages,withoutPhone:k.withoutPhone,dateFrom:k.dateFrom,dateTo:k.dateTo,sourceCampaignId:k.sourceCampaignId,tagIds:k.tagIds}),G=i.useMemo(()=>{if(!j.isActive)return[];const O=new Set;return(j.data?.pages.flatMap(B=>B.data)??[]).filter(B=>O.has(B.ticket.id)?!1:(O.add(B.ticket.id),!0))},[j.data,j.isActive]),se=G.length>0?e.jsxs("div",{className:"pb-4","data-testid":"closed-matches",children:[e.jsxs("div",{className:"px-4 pt-4 pb-1 flex items-center gap-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:[e.jsx(Xn,{className:"w-3.5 h-3.5"}),"Conversaciones cerradas",e.jsxs("span",{className:"ml-auto font-normal normal-case tracking-normal tabular-nums",children:[G.length,j.hasNextPage?"+":""]})]}),e.jsxs("p",{className:"px-4 pb-2 text-[11px] text-muted-foreground/80",children:["Ábrela y escríbele: la conversación sigue donde quedó.",j.isWindowed?" Se muestran las de los últimos 6 meses.":""]}),G.map(O=>e.jsx(ea,{fallback:e.jsx("div",{className:"h-16 flex items-center px-4 text-xs text-muted-foreground/60 truncate",children:"No se pudo mostrar esta conversación"}),children:e.jsx(Ga,{conversation:O,isActive:t===O.ticket.id,onClick:()=>s(O.ticket.id)})},O.ticket.id)),j.hasNextPage&&e.jsx("div",{className:"px-4 pt-2",children:e.jsxs(K,{variant:"ghost",size:"sm",className:"w-full h-8 text-xs text-muted-foreground",disabled:j.isFetchingNextPage,onClick:()=>void j.fetchNextPage(),children:[j.isFetchingNextPage?e.jsx(Se,{className:"w-3.5 h-3.5 animate-spin mr-1.5"}):null,"Ver más conversaciones cerradas"]})})]}):null,de=qn({count:V.length,getScrollElement:()=>ee,estimateSize:()=>od,overscan:5,enabled:!!ee}),Ae=i.useCallback(O=>{s(O)},[s]),ue=i.useCallback(O=>{re(O)},[re]);i.useEffect(()=>{o&&a==="waiting"&&re("my_chats")},[o,a,re]);const je=de.getVirtualItems(),ke=V.length;i.useEffect(()=>{const O=je[je.length-1];O&&O.index>=ke-1&&X&&!W&&!z&&queueMicrotask(()=>{q(!0),P().finally(()=>{q(!1)})})},[je,ke,X,W,z,P]);const Q=Ci(h)+(v!=="all"?1:0)+(m?1:0)+(x?1:0),ie=i.useCallback(()=>{be("all"),b(),I({status:"all",assignedTo:"all",hasUnread:!1,hasUnansweredMessages:!1,withoutPhone:!1,dateRange:"all",assignedAgentId:void 0,assignedAgentType:void 0}),F("")},[be,b]);return e.jsxs("div",{className:"flex flex-col h-full bg-white dark:bg-card border-r border-gray-100 dark:border-border",children:[e.jsxs("div",{className:"px-4 h-[60px] border-b border-gray-100 dark:border-border flex-shrink-0 bg-white dark:bg-card flex items-center justify-between gap-4",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(Hl,{value:v,onChange:be,excludeTypes:["email"],disableUnreachable:!0,className:"h-8 py-0 px-2 text-xs border-none bg-slate-50 dark:bg-slate-900 hover:bg-slate-100"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ti,{filters:h,onChange:E,agentMode:g,canFilterByAgent:U}),Q>0&&e.jsx(K,{variant:"ghost",size:"icon",onClick:ie,className:"h-8 w-8 text-muted-foreground hover:text-destructive rounded-full",title:"Limpiar todos los filtros",children:e.jsx(vr,{className:"w-3.5 h-3.5"})})]})]}),f&&h.status!=="RESOLVED"&&e.jsxs("div",{className:"px-3 py-2 flex items-center justify-between bg-gray-50/50 dark:bg-muted/20 border-b border-gray-100 dark:border-border",children:[e.jsx("span",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider",children:"Vista de Tickets"}),e.jsxs("div",{className:"flex bg-gray-200 dark:bg-muted p-0.5 rounded-lg",children:[e.jsx("button",{onClick:()=>D("me"),className:T("px-3 py-1 text-xs font-medium rounded-md transition-all",l==="me"?"bg-white dark:bg-card text-primary shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Mis Tickets"}),e.jsx("button",{onClick:()=>D("all"),className:T("px-3 py-1 text-xs font-medium rounded-md transition-all flex items-center gap-1.5",l==="all"?"bg-white dark:bg-card text-primary shadow-sm":"text-muted-foreground hover:text-foreground"),children:ve?e.jsxs(e.Fragment,{children:[ve.type==="AI"?e.jsx("div",{className:"h-4 w-4 bg-violet-100 dark:bg-violet-500/20 flex items-center justify-center rounded-full border border-violet-200 dark:border-violet-500/30",children:e.jsx(It,{className:"h-2.5 w-2.5 text-violet-600 dark:text-violet-300"})}):e.jsxs(ht,{className:"h-4 w-4 border border-border",children:[e.jsx(pt,{src:ve.avatarUrl}),e.jsx(gt,{className:"text-[8px] bg-blue-100 text-blue-700",children:ve.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"truncate max-w-[100px]",children:ve.name})]}):"Todos"})]})]}),e.jsxs("div",{className:"px-3 py-3 space-y-3 flex-shrink-0 bg-gray-50/30 dark:bg-muted/30",children:[e.jsxs("div",{className:"relative group",children:[e.jsx("div",{className:"absolute inset-y-0 left-3 flex items-center pointer-events-none",children:L?e.jsx(Se,{className:"h-4 w-4 text-primary animate-spin"}):e.jsx(Bt,{className:"h-4 w-4 text-gray-400 group-focus-within:text-primary transition-colors"})}),e.jsx(Te,{value:M,onChange:O=>F(O.target.value),placeholder:"Buscar por nombre, teléfono...",className:"pl-9 h-10 bg-white dark:bg-card border-gray-200 dark:border-border rounded-xl focus:ring-2 focus:ring-primary/10 focus:border-primary/20 transition-all text-[16px] md:text-sm shadow-sm"}),M&&e.jsx("button",{onClick:()=>{F(""),Z("")},className:"absolute inset-y-0 right-3 flex items-center text-gray-400 hover:text-gray-600",children:e.jsx(Ge,{className:"h-3 w-3"})})]}),e.jsx(rd,{filters:h,onChange:E,funnelId:m,funnelStageId:x,onClearFunnel:b,onClearStage:()=>y(void 0),agentName:ve?.name,canFilterByAgent:U}),h.status==="RESOLVED"?e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-primary/40 bg-primary/[0.03]","aria-current":"page",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-primary",children:[e.jsx("span",{children:"Tickets Cerrados"}),ne.closed>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded-full text-[10px] font-bold min-w-[18px] text-center bg-primary/10 text-primary",children:ne.closed})]}),h.dateRange&&e.jsxs(De,{variant:"secondary",className:"h-6 gap-1 text-[11px] font-medium bg-white dark:bg-card border border-border/60",children:[h.dateRange==="custom"&&h.dateFrom?`Desde ${sd(h.dateFrom,C)}`:ed[h.dateRange],h.dateRange!==xs&&e.jsx("button",{onClick:()=>{const{dateFrom:O}=Rs(xs,C);I(B=>({...B,dateRange:xs,dateFrom:O,dateTo:void 0}))},"aria-label":"Restablecer rango a último mes",children:e.jsx(Ge,{className:"w-3 h-3"})})]})]}):e.jsx("div",{className:T("grid w-full border-b border-gray-100 dark:border-border/60",o?"grid-cols-2":"grid-cols-3"),children:[{id:"my_chats",label:"Mis Chats",count:ne.myChats},{id:"ai_agent",label:"AI",count:ne.aiAgent},...o?[]:[{id:"waiting",label:"Espera",count:ne.waiting,color:"orange"}]].map(O=>e.jsxs("button",{onClick:()=>ue(O.id),className:T("relative py-3 text-xs font-semibold transition-all flex items-center justify-center gap-2 hover:bg-slate-50 dark:hover:bg-muted/30",a===O.id?"text-primary":"text-slate-500 dark:text-slate-400"),children:[O.label,O.count>0&&e.jsx("span",{className:T("px-1.5 py-0.5 rounded-full text-[10px] font-bold min-w-[18px] text-center",O.id==="waiting"?"bg-orange-100 text-orange-600 dark:bg-orange-950/40 dark:text-orange-400":a===O.id?"bg-primary/10 text-primary":"bg-slate-100 text-slate-500 dark:bg-slate-800 dark:text-slate-400"),children:O.count}),a===O.id&&e.jsx(jr.div,{layoutId:"activeTab",className:"absolute bottom-0 left-0 right-0 h-[2.5px] bg-primary rounded-t-full shadow-[0_-2px_8px_rgba(37,99,235,0.3)]",transition:{type:"spring",stiffness:380,damping:30}})]},O.id))})]}),e.jsx("div",{ref:le,className:"flex-1 overflow-y-auto",children:z&&ae.length===0?e.jsx("div",{className:"p-3 space-y-3",children:[...Array(5)].map((O,B)=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(gs,{className:"h-11 w-11 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(gs,{className:"h-4 w-3/4"}),e.jsx(gs,{className:"h-3 w-full"}),e.jsx(gs,{className:"h-3 w-1/4"})]})]},B))}):N?e.jsxs("div",{className:"flex flex-col items-center justify-center h-56 px-6 text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-destructive/10 flex items-center justify-center mb-3",children:e.jsx(ft,{className:"w-6 h-6 text-destructive"})}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:"No se pudieron cargar las conversaciones"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 max-w-[260px]",children:or(w)}),e.jsxs(K,{variant:"outline",size:"sm",className:"mt-4 h-8 gap-1.5 text-xs",onClick:()=>void $(),children:[e.jsx(vr,{className:"w-3.5 h-3.5"}),"Reintentar"]})]}):V.length===0?G.length>0?se:e.jsxs("div",{className:"flex flex-col items-center justify-center h-48 text-muted-foreground",children:[e.jsx(Ms,{className:"w-12 h-12 mb-3 text-muted-foreground/40"}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:"No hay conversaciones"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Q>0||v!=="all"?"Prueba ajustando los filtros":"Las nuevas conversaciones aparecerán aquí"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{height:`${de.getTotalSize()}px`,width:"100%",position:"relative"},children:[de.getVirtualItems().map(O=>{const B=V[O.index];return e.jsx("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:`${O.size}px`,transform:`translateY(${O.start}px)`},children:e.jsx(ea,{fallback:e.jsx("div",{className:"h-full flex items-center px-4 text-xs text-muted-foreground/60 truncate",children:"No se pudo mostrar esta conversación"}),children:e.jsx(Ga,{conversation:B,isActive:t===B.ticket.id,onClick:()=>Ae(B.ticket.id)})},B.ticket.id)},O.key)}),(A||W)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 flex justify-center py-4 bg-gradient-to-t from-white via-white/80 to-transparent dark:from-background dark:via-background/80 z-10 w-full",children:e.jsx(Se,{className:"w-5 h-5 animate-spin text-primary"})})]}),!X&&G.length>0&&se,!X&&ae.length>0&&G.length===0&&e.jsxs(jr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.5},className:"py-8 text-center flex flex-col items-center justify-center opacity-50",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center mb-2",children:e.jsx(Ie,{className:"w-5 h-5 text-slate-400"})}),e.jsx("p",{className:"text-xs text-muted-foreground font-medium",children:"Todo está al día"}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-0.5",children:"No hay más conversaciones para mostrar"})]})]})})]})});Ei.displayName="ConversationList";const Ii=i.memo(({url:t,showDownload:s=!0,transcription:a})=>{const r=typeof a?.text=="string"?a.text.trim():"";return e.jsxs("div",{className:"w-[330px]",children:[t&&e.jsx("div",{className:"-mx-3.5 -mt-2 mb-1.5 overflow-hidden",children:e.jsxs("div",{className:"flex items-center gap-2.5 p-2.5 bg-white/10 dark:bg-white/5",children:[e.jsx("div",{className:"w-10 h-10 rounded-full bg-white/20 dark:bg-white/10 flex items-center justify-center shrink-0",children:e.jsx("svg",{className:"w-5 h-5 opacity-70",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M12 3v18M6 8v8M18 8v8M3 11v2M21 11v2M9 5v14M15 5v14",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",fill:"none"})})}),e.jsx("audio",{src:t,controls:!0,className:"flex-1 h-8 [&::-webkit-media-controls-panel]:bg-transparent [&::-webkit-media-controls-current-time-display]:text-xs [&::-webkit-media-controls-time-remaining-display]:text-xs",preload:"none"}),s&&e.jsx("a",{href:t,download:!0,className:"w-8 h-8 rounded-full bg-white/20 dark:bg-white/10 flex items-center justify-center hover:bg-white/30 transition-colors shrink-0",title:"Descargar audio",children:e.jsx(ua,{className:"w-4 h-4"})})]})}),r&&e.jsxs("div",{className:"mt-1 flex items-start gap-1.5 px-0.5 text-[13px] leading-snug opacity-90","data-testid":"audio-transcription",title:a?.model?`Transcripción automática · ${a.model}`:"Transcripción automática",children:[e.jsx(vs,{className:"w-3.5 h-3.5 mt-0.5 shrink-0 opacity-60","aria-hidden":"true"}),e.jsxs("p",{className:"italic whitespace-pre-wrap break-words",children:[e.jsx("span",{className:"sr-only",children:"Transcripción: "}),r]})]})]})});Ii.displayName="AudioMessage";const ga=()=>/\{\{\s*([^}]+?)\s*\}\}/g;function us(t){return t?[...new Set([...t.matchAll(ga())].map(s=>s[1]))]:[]}const cd=t=>/^\d+$/.test(t);function Ai(t){const s=us(t);if(s.length===0)return"none";const a=s.filter(cd).length;return a===s.length?"numeric":a===0?"named":"mixed"}function dd(t){const s=us(t);return Ai(t)!=="numeric"?s:[...s].sort((a,r)=>Number(a)-Number(r))}function ud(t){const s=Object.create(null);if(!t)return s;for(const a of t.matchAll(ga()))s[a[1]]=(s[a[1]]||0)+1;return s}function Mi(t,s=[],a={}){const r=Object.create(null);return us(t).forEach((n,o)=>{const l=s[o];if(l==null){a.omitMissing||(r[n]="");return}r[n]=l}),r}const md=(t,s)=>Object.hasOwn(t,s)?t[s]:void 0;function Di(t,s,a={}){const r=Ai(t)==="named",n=a.missing??(()=>"");return dd(t).map(o=>{const l=md(s,o),c={type:"text",text:l==null?n(o):String(l)};return r&&(c.parameter_name=o),c})}function Oi(t,s,a){const r=Di(t,s,a);return r.length?{type:"body",parameters:r}:null}function xd(t,s,a){const r=Di(t,s,a);return r.length?{type:"header",parameters:r}:null}function hd(t,s,a={}){if(!t)return"";const r=a.unresolved==="placeholder";return t.replace(ga(),(n,o)=>{const l=Object.hasOwn(s,o)?s[o]:void 0;return l===void 0||l===""?r?n:"":l})}function pd(t,s=[],a={}){return hd(t,Mi(t,s),a)}const an="",rn="",nn="",ln="",on="",cn="",dn="",un="",gd="",fd="",bd=/\uE008(\d+)\uE009/g,yd=/\uE00A(\d+)\uE00B/g,jd=/([\uE000-\uE007])/,vd=/[\uE000-\uE00B]/g,Nd=/^[\w.]+$/,wd=/(^|[^\p{L}\p{N}*\uE008\uE009])\*([^\s*](?:[^*]*[^\s*])?)\*(?=[^\p{L}\p{N}*\uE008\uE009]|$)/gu,kd=/(^|[^\p{L}\p{N}_\uE008\uE009])_([^\s_](?:[^_]*[^\s_])?)_(?=[^\p{L}\p{N}_\uE008\uE009]|$)/gu,Cd=/(^|[^\p{L}\p{N}~\uE008\uE009])~([^\s~](?:[^~]*[^\s~])?)~(?=[^\p{L}\p{N}~\uE008\uE009]|$)/gu,Td=/```([^`]+)```/g;function Sd(t){const s=[];let a=t.replace(vd,"").replace(ga(),(l,c)=>Nd.test(c)?`${gd}${s.push(c)-1}${fd}`:l);const r=[];a=a.replace(Td,(l,c)=>`${r.push(c)-1}`),a=a.replace(wd,`$1${an}$2${rn}`).replace(kd,`$1${nn}$2${ln}`).replace(Cd,`$1${on}$2${cn}`).replace(yd,(l,c)=>`${dn}${r[Number(c)]}${un}`);const n={bold:!1,italic:!1,strike:!1,mono:!1},o=[];for(const l of a.split(jd)){switch(l){case an:n.bold=!0;continue;case rn:n.bold=!1;continue;case nn:n.italic=!0;continue;case ln:n.italic=!1;continue;case on:n.strike=!0;continue;case cn:n.strike=!1;continue;case dn:n.mono=!0;continue;case un:n.mono=!1;continue}if(!l)continue;let c=0;for(const u of l.matchAll(bd)){const d=u.index??0;d>c&&o.push({kind:"text",text:l.slice(c,d),...n}),o.push({kind:"variable",name:s[Number(u[1])],...n}),c=d+u[0].length}c<l.length&&o.push({kind:"text",text:l.slice(c),...n})}return o}function Ui(t){if(!t)return[];const s=[];return t.split(`
|
|
3
|
-
`).forEach((a,r)=>{r>0&&s.push({kind:"break"}),s.push(...Sd(a))}),s}function Ed(t,s){return Ui(t).map(a=>a.kind==="break"?`
|
|
4
|
-
`:a.kind==="text"?a.text:s(a.name)??`{{${a.name}}}`).join("")}const Id=(t,s)=>{let a=s||t||"";a.includes("?")&&(a=a.split("?")[0]);const r=a.split(".").pop()?.toLowerCase()||"";return{pdf:{type:"PDF",color:"bg-red-500",icon:"📄"},doc:{type:"DOC",color:"bg-blue-600",icon:"📝"},docx:{type:"DOCX",color:"bg-blue-600",icon:"📝"},xls:{type:"XLS",color:"bg-green-600",icon:"📊"},xlsx:{type:"XLSX",color:"bg-green-600",icon:"📊"},ppt:{type:"PPT",color:"bg-orange-500",icon:"📽️"},pptx:{type:"PPTX",color:"bg-orange-500",icon:"📽️"},txt:{type:"TXT",color:"bg-gray-500",icon:"📃"},zip:{type:"ZIP",color:"bg-yellow-600",icon:"📦"},rar:{type:"RAR",color:"bg-purple-600",icon:"📦"}}[r]||{type:r.toUpperCase()||"FILE",color:"bg-gray-500",icon:"📎"}},ur=i.memo(({url:t,caption:s,fileName:a,fileSize:r})=>{const n=a||"Documento",o=Id(t,a),c=(u=>u?u<1024?`${u} B`:u<1024*1024?`${(u/1024).toFixed(1)} KB`:`${(u/(1024*1024)).toFixed(1)} MB`:"")(r);return e.jsxs("div",{className:"w-[330px]",children:[e.jsx("div",{className:"-mx-3.5 -mt-2 mb-1.5 overflow-hidden",children:e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-white/10 dark:bg-white/5 border-b border-black/5 dark:border-white/10",children:[e.jsx("div",{className:T("w-10 h-10 rounded-lg flex items-center justify-center text-white text-[10px] font-bold shrink-0",o.color),children:o.type}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",title:n,children:n}),e.jsxs("p",{className:"text-[11px] opacity-60 mt-0.5",children:[o.type,c?` · ${c}`:""]})]}),t&&e.jsx("a",{href:t,download:n,target:"_blank",rel:"noopener noreferrer",className:"w-8 h-8 rounded-full bg-white/20 dark:bg-white/10 flex items-center justify-center hover:bg-white/30 transition-all shrink-0",title:"Descargar",children:e.jsx(ua,{className:"w-4 h-4"})})]})}),s&&e.jsx("div",{className:"text-sm leading-relaxed whitespace-pre-wrap",children:e.jsx(os,{content:s,variant:"standard"})})]})});ur.displayName="DocumentMessage";const Ad=/^[a-zA-Z0-9_.]+$/,_s=(t,s)=>{if(!Object.hasOwn(t,s))return;const a=t[s];return typeof a=="string"&&a!==""?a:void 0},Ri=(t,s)=>{if(s&&Ad.test(t))return _s(s,t)??_s(s,`contact.${t}`)??(t.startsWith("contact.")?_s(s,t.replace("contact.","")):void 0)??_s(s,`contact.metadata.${t}`)},mn={name:"Nombre","contact.name":"Nombre",phone:"Teléfono","contact.phone":"Teléfono",email:"Email","contact.email":"Email",tags:"Etiquetas","contact.tags":"Etiquetas",business:"Negocio"},Md=t=>Object.hasOwn(mn,t)?mn[t]:t,Dd=(t,s)=>{let a=t;return s.mono&&(a=e.jsx("code",{className:"bg-black/10 dark:bg-white/10 px-1 py-0.5 rounded text-[12px] font-mono",children:a})),s.strike&&(a=e.jsx("s",{children:a})),s.italic&&(a=e.jsx("em",{children:a})),s.bold&&(a=e.jsx("strong",{children:a})),a},Od=({name:t,resolvedVariables:s,style:a})=>{const r=Ri(t,s),n=Md(t),o=T(a.italic&&"italic",a.strike&&"line-through",a.mono&&"font-mono");return r?e.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 mx-0.5 rounded-md text-[12px] font-medium bg-white/30 text-inherit border border-white/30 align-middle cursor-help backdrop-blur-sm shadow-sm",title:`${n}: ${r}`,children:[e.jsxs("span",{className:"opacity-60 text-[10px]",children:[n,":"]}),e.jsx("span",{className:T(a.bold?"font-bold":"font-semibold",o),children:r})]}):e.jsx("span",{className:T("inline-flex items-center px-1.5 py-0.5 mx-0.5 rounded-md text-[11px] bg-black/20 text-inherit border border-black/10 align-middle",a.bold?"font-bold":"font-medium",o),title:`Variable: ${n}`,children:n})},Ia=({text:t,resolvedVariables:s})=>e.jsx("span",{children:Ui(t).map((a,r)=>{if(a.kind==="break")return e.jsx("br",{},r);const n=a.kind==="variable"?e.jsx(Od,{name:a.name,resolvedVariables:s,style:a}):a.text;return e.jsx(zn.Fragment,{children:Dd(n,a)},r)})}),Ud=(t,s)=>Ed(t,a=>Ri(a,s)),xn=({mediaType:t,mediaUrl:s,thumbnailUrl:a,fileName:r,headerText:n,bodyText:o,footerText:l,buttons:c=[],time:u,resolvedVariables:d,carousel:m})=>{const[x,b]=i.useState(!1),y=()=>{switch(t){case"IMAGE":return e.jsx(We,{className:"w-6 h-6 opacity-50"});case"VIDEO":return e.jsx(et,{className:"w-6 h-6 opacity-50"});case"DOCUMENT":return e.jsx(tt,{className:"w-6 h-6 opacity-50"});default:return null}},p=()=>{switch(t){case"IMAGE":return"Imagen";case"VIDEO":return"Video";case"DOCUMENT":return"Documento";default:return""}};return e.jsxs("div",{className:"flex flex-col gap-1 w-full",children:[t==="IMAGE"&&e.jsx("div",{className:"bg-black/10 dark:bg-black/20 aspect-video flex items-center justify-center mb-1 -mx-3.5 -mt-2 overflow-hidden cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>s&&b(!0),children:a||s?e.jsx(mt,{src:a||s||"",className:"w-full h-full object-cover",alt:"Media"}):e.jsxs("div",{className:"text-xs opacity-70 italic flex flex-col items-center gap-1",children:[y(),e.jsx("span",{children:p()})]})}),t==="VIDEO"&&e.jsx("div",{className:"bg-black/10 dark:bg-black/20 aspect-video flex items-center justify-center mb-1 -mx-3.5 -mt-2 overflow-hidden cursor-pointer group/video",onClick:()=>s&&b(!0),children:a?e.jsxs("div",{className:"relative w-full h-full",children:[e.jsx(mt,{src:a,className:"w-full h-full object-cover",alt:"Video Preview"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/20 group-hover/video:bg-black/40 transition-colors",children:e.jsx("div",{className:"w-10 h-10 rounded-full bg-white/20 backdrop-blur-md flex items-center justify-center text-white border border-white/30",children:e.jsx(et,{className:"w-5 h-5 fill-current"})})})]}):s?e.jsxs("div",{className:"relative w-full h-full",children:[e.jsx(bs,{src:s,className:"w-full h-full object-cover",controls:!1,muted:!0,preload:"metadata"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/20 group-hover/video:bg-black/40 transition-colors",children:e.jsx("div",{className:"w-10 h-10 rounded-full bg-white/20 backdrop-blur-md flex items-center justify-center text-white border border-white/30",children:e.jsx(et,{className:"w-5 h-5 fill-current"})})})]}):e.jsxs("div",{className:"text-xs opacity-70 italic flex flex-col items-center gap-1",children:[y(),e.jsx("span",{children:p()})]})}),t==="DOCUMENT"&&e.jsx(ur,{url:s,fileName:r}),m?.cards?.length&&e.jsx("div",{className:"mt-2 -mx-1 flex gap-3 overflow-x-auto pb-2 pt-1",children:m.cards.map((f,g)=>e.jsxs("div",{className:"min-w-[220px] max-w-[260px] bg-white dark:bg-[#111b21] rounded-xl border border-slate-200/60 dark:border-slate-700/60 overflow-hidden shrink-0 shadow-sm",children:[f.mediaUrl&&e.jsx("div",{className:"bg-black/10 dark:bg-black/30 aspect-4/3 overflow-hidden",children:e.jsx(mt,{src:f.mediaUrl,alt:`Card ${g+1}`,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"px-3 py-3 space-y-2",children:[f.bodyText&&e.jsx("div",{className:"text-[12px] text-slate-900 dark:text-slate-50 whitespace-pre-wrap leading-snug",children:e.jsx(Ia,{text:f.bodyText,resolvedVariables:d})}),f.buttons?.length?e.jsx("div",{className:"pt-2 space-y-1",children:f.buttons.map((v,h)=>e.jsxs("div",{className:"border border-emerald-500/70 text-emerald-600 dark:text-emerald-400 bg-transparent py-1.5 px-3 text-center font-semibold text-[11px] rounded-full truncate flex items-center justify-center gap-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500"}),e.jsx("span",{children:v})]},h))}):null]})]},g))}),n&&e.jsx("div",{className:"mb-1 font-bold text-sm text-inherit",children:e.jsx(Ia,{text:n||"",resolvedVariables:d})}),e.jsx("div",{className:"text-[13.5px] text-inherit whitespace-pre-wrap leading-snug",children:e.jsx(Ia,{text:o||"Sin contenido",resolvedVariables:d})}),l&&e.jsx("div",{className:"mt-1 text-[11px] opacity-80",children:e.jsx(Lt,{content:l||"",context:Zn})}),c.map((f,g)=>e.jsx("div",{className:"bg-white dark:bg-[#1F2C34] py-2 px-4 text-center text-[#00A884] font-medium text-[13px] rounded-lg shadow-sm w-full max-w-[85%] self-end truncate cursor-pointer hover:bg-slate-50 dark:hover:bg-[#2a3942] transition-colors",children:f},g)),e.jsx(ls,{isOpen:x,onClose:()=>b(!1),url:s||"",thumbnailUrl:a,type:t==="VIDEO"?"VIDEO":"IMAGE",caption:Ud(o||"",d)})]})};function Rd(){return xt({mutationFn:t=>Ce.retryMessage(t),onError:t=>{H.error(t?.response?.data?.message||"No se pudo reintentar el mensaje. Intenta de nuevo.")}})}const _d=new Set([131049,131050,130472]);function Ld(t){const s=t?.whatsappErrorCode;return s!=null&&_d.has(Number(s))}const hn=500,Yt=i.memo(({content:t,variant:s="whatsapp"})=>{const[a,r]=i.useState(!1),n=t.length>hn,o=n&&!a?t.slice(0,hn)+"...":t;return e.jsxs("div",{children:[e.jsx("div",{className:T("relative",n&&!a&&"max-h-[200px] overflow-hidden"),style:n&&!a?{WebkitMaskImage:"linear-gradient(to bottom, black 60%, transparent 100%)",maskImage:"linear-gradient(to bottom, black 60%, transparent 100%)"}:void 0,children:e.jsx(os,{content:o,className:"text-sm",variant:s})}),n&&e.jsx("button",{onClick:()=>r(!a),className:"text-[12px] font-medium mt-1 opacity-70 hover:opacity-100 transition-opacity cursor-pointer",children:a?"Leer menos":"Leer más"})]})});Yt.displayName="TextMessage";const _i=i.memo(({url:t,thumbnailUrl:s,caption:a})=>{const[r,n]=i.useState(!1),o=Nr(t),l=Nr(s),c=l.url||o.url,[u,d]=i.useState(!1),[m,x]=i.useState(!1),b=m||o.error||l.error,y=!u&&!b,p=!!s&&s!==t;return e.jsxs("div",{className:"w-[330px]",children:[c&&e.jsxs("div",{className:"relative overflow-hidden cursor-pointer group -mx-3.5 -mt-2 mb-1.5",onClick:()=>t&&n(!0),children:[y&&!b&&e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-gray-100 to-gray-200 dark:from-gray-800 dark:to-gray-700 animate-pulse",children:e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"w-10 h-10 rounded-full border-2 border-gray-300 dark:border-gray-600 border-t-primary animate-spin"})})}),b&&e.jsxs("div",{className:"w-full h-40 bg-gradient-to-br from-gray-100 to-gray-200 dark:from-gray-800 dark:to-gray-700 flex flex-col items-center justify-center gap-2 text-gray-400",children:[e.jsx(ct,{className:"w-8 h-8"}),e.jsx("span",{className:"text-xs font-medium",children:"No se pudo cargar"})]}),!b&&e.jsx("img",{src:c,alt:a||"Imagen",loading:"lazy",decoding:"async",className:T("w-full h-auto object-cover transition-all duration-300",y?"opacity-0 scale-95":"opacity-100 scale-100","group-hover:brightness-95"),onLoad:()=>d(!0),onError:()=>{d(!0),x(!0)}}),!y&&!b&&e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/50 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-200",children:e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 p-3 flex items-center justify-between",children:[e.jsxs("span",{className:"text-white/90 text-xs font-medium flex items-center gap-1.5",children:[e.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"})}),"Ver"]}),p&&e.jsx("span",{className:"text-white/70 text-[10px] bg-white/20 backdrop-blur-sm px-2 py-0.5 rounded-full",children:"HD"})]})}),o.url&&!y&&!b&&e.jsx("button",{onClick:f=>{f.stopPropagation(),window.open(o.url,"_blank")},className:"absolute top-2 right-2 h-8 w-8 rounded-full bg-black/40 backdrop-blur-sm flex items-center justify-center text-white opacity-0 group-hover:opacity-100 transition-all duration-200 hover:bg-black/60 hover:scale-110",title:"Descargar",children:e.jsx(ua,{className:"w-4 h-4"})})]}),a&&e.jsx(os,{content:a,className:"text-sm",variant:"whatsapp"}),e.jsx(ls,{isOpen:r,onClose:()=>n(!1),url:o.url||"",type:"IMAGE",caption:a,showDownload:!0})]})});_i.displayName="ImageMessage";const Li=i.memo(({url:t,thumbnailUrl:s,caption:a})=>{const[r,n]=i.useState(!1);return e.jsxs("div",{className:"w-[330px]",children:[t&&e.jsxs("div",{className:"relative overflow-hidden bg-[#e8e8e8] dark:bg-[#1a2a32] group cursor-pointer -mx-3.5 -mt-2 mb-1.5",onClick:()=>n(!0),children:[e.jsxs("div",{className:"aspect-video relative overflow-hidden flex items-center justify-center",children:[s?e.jsx("img",{src:s,alt:a||"Video",className:"w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"}):e.jsx(bs,{src:t,className:"w-full h-full object-cover",controls:!1,muted:!0,preload:"metadata"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none transition-all duration-300",children:e.jsx("div",{className:"bg-black/40 backdrop-blur-md rounded-full p-3.5 shadow-xl ring-1 ring-white/20 group-hover:scale-110 group-hover:bg-black/50 transition-all",children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"w-6 h-6 text-white ml-0.5",children:e.jsx("path",{d:"M8 5v14l11-7z"})})})}),e.jsx("div",{className:"absolute top-2.5 left-2.5 flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-all duration-300 translate-y-[-4px] group-hover:translate-y-0",children:e.jsx("span",{className:"px-2 py-0.5 rounded-md bg-black/60 backdrop-blur-md text-white text-[9px] font-bold uppercase tracking-widest border border-white/10 shadow-lg",children:"VIDEO"})})]}),e.jsx("button",{onClick:o=>{o.stopPropagation(),window.open(t,"_blank")},className:T("absolute top-2.5 right-2.5 h-8 w-8 rounded-full bg-black/50 backdrop-blur-md","flex items-center justify-center text-white border border-white/10","opacity-0 group-hover:opacity-100 transition-all duration-300 translate-y-[-4px] group-hover:translate-y-0","hover:bg-black/70 hover:scale-105"),title:"Descargar video",children:e.jsx(ua,{className:"w-4 h-4"})})]}),a&&e.jsx(os,{content:a,className:"text-sm mt-1",variant:"whatsapp"}),e.jsx(ls,{isOpen:r,onClose:()=>n(!1),url:t||"",thumbnailUrl:s,type:"VIDEO",caption:a,showDownload:!0})]})});Li.displayName="VideoMessage";const Fi=i.memo(({content:t,variant:s})=>{let a=s||"default";s||(t.includes("bloqueado")||t.includes("blocked")||t.includes("rechazado")||t.includes("Intento de envío")?a="error":t.includes("Advertencia")||t.includes("inactividad")||t.includes("Cierre")||t.includes("cerrado")||t.includes("Escalado")?a="warning":t.includes("enviado")||t.includes("notificado")||t.includes("completado")?a="success":(t.includes("📩")||t.includes("Respuesta automática"))&&(a="info"));const n={default:{icon:e.jsx(bt,{className:"w-3.5 h-3.5"}),borderClass:"border-gray-300 dark:border-gray-600",textClass:"text-gray-500 dark:text-gray-400",iconClass:"text-gray-500 dark:text-gray-400"},info:{icon:e.jsx(si,{className:"w-3.5 h-3.5"}),borderClass:"border-blue-300 dark:border-blue-600",textClass:"text-blue-600 dark:text-blue-400",iconClass:"text-blue-600 dark:text-blue-400"},success:{icon:e.jsx(ma,{className:"w-3.5 h-3.5"}),borderClass:"border-green-300 dark:border-green-600",textClass:"text-green-600 dark:text-green-400",iconClass:"text-green-600 dark:text-green-400"},warning:{icon:e.jsx(ft,{className:"w-3.5 h-3.5"}),borderClass:"border-amber-300 dark:border-amber-600",textClass:"text-amber-600 dark:text-amber-400",iconClass:"text-amber-600 dark:text-amber-400"},error:{icon:e.jsx(ks,{className:"w-3.5 h-3.5"}),borderClass:"border-red-300 dark:border-red-600",textClass:"text-red-600 dark:text-red-400",iconClass:"text-red-600 dark:text-red-400"}}[a],o=()=>t.split(/(\{\{.*?\}\})/g).map((c,u)=>{if(c.startsWith("{{")&&c.endsWith("}}")){const d=c.slice(2,-2);return e.jsx("span",{className:"text-blue-600 dark:text-blue-400 font-medium hover:underline cursor-pointer",title:d,children:d},u)}return c});return e.jsx("div",{className:"w-full flex justify-center py-3",children:e.jsxs("div",{className:T("inline-flex items-center gap-2.5 px-4 py-2.5 rounded-2xl max-w-[85%]",a==="error"?"bg-red-50 dark:bg-red-950/30":a==="warning"?"bg-amber-50 dark:bg-amber-950/30":a==="success"?"bg-green-50 dark:bg-green-950/30":a==="info"?"bg-blue-50 dark:bg-blue-950/30":"bg-gray-100 dark:bg-gray-800/60"),children:[e.jsx("span",{className:T("flex-shrink-0",n.iconClass),children:n.icon}),e.jsx("span",{className:T("text-[13px] font-medium leading-snug",n.textClass),children:o()})]})})});Fi.displayName="SystemMessage";const Pi=i.memo(({content:t,agentName:s})=>e.jsxs("div",{className:"w-full py-3",children:[e.jsx("div",{className:"flex justify-center mb-3",children:e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-amber-100/80 dark:bg-amber-900/40",children:[e.jsx(Is,{className:"w-3.5 h-3.5 text-amber-600 dark:text-amber-400"}),e.jsxs("span",{className:"text-xs text-amber-700 dark:text-amber-300 font-semibold",children:[s||"Agente"," agregó una nota:"]})]})}),e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[75%] px-4 py-3 bg-amber-50 dark:bg-amber-900/30 border border-amber-200 dark:border-amber-700/50 rounded-2xl rounded-tr-sm shadow-sm",children:e.jsx(os,{content:t,className:"text-sm text-amber-900 dark:text-amber-100 font-medium leading-relaxed"})})})]}));Pi.displayName="NoteMessage";const Vi=i.memo(({cardRef:t,accent:s=!1})=>{const a=t.label?.trim()||"Tarjeta",r=t.cardCount>0?`Carrusel · ${t.cardIndex+1} de ${t.cardCount}`:"Carrusel",[n,o]=i.useState(!1),l=t.fullUrl||t.imageUrl;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:T("mb-1.5 flex items-center gap-2 rounded-md overflow-hidden border-l-[3px] pl-2 pr-1.5 py-1",s?"bg-white/10 border-white/60":"bg-black/[0.035] dark:bg-white/[0.05] border-blue-500/70"),children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:T("text-[12px] font-medium truncate flex items-center gap-1",s?"text-white/90":"text-blue-600 dark:text-blue-300"),children:[e.jsx(Ns,{className:"w-3 h-3 shrink-0 opacity-80"}),e.jsx("span",{className:"truncate",children:a})]}),e.jsx("div",{className:T("text-[11px] truncate",s?"text-white/60":"text-slate-400 dark:text-slate-500"),children:r})]}),t.imageUrl?e.jsxs("button",{type:"button",onClick:()=>l&&o(!0),className:"shrink-0 rounded overflow-hidden relative group/qimg cursor-pointer","aria-label":"Ver imagen completa",children:[e.jsx(mt,{src:t.imageUrl,alt:"",className:"w-9 h-9 rounded object-cover"}),e.jsx("span",{className:"absolute inset-0 bg-black/0 group-hover/qimg:bg-black/25 transition-colors"})]}):e.jsx("div",{className:"w-9 h-9 rounded shrink-0 flex items-center justify-center bg-black/10 dark:bg-white/10 text-slate-400",children:t.mediaType==="video"?e.jsx(et,{className:"w-4 h-4"}):e.jsx(We,{className:"w-4 h-4"})})]}),e.jsx(ls,{isOpen:n,onClose:()=>o(!1),url:l||"",thumbnailUrl:t.imageUrl,type:t.mediaType==="video"?"VIDEO":"IMAGE",caption:t.label||void 0,showDownload:!0})]})});Vi.displayName="QuotedCardReply";function Fd({type:t}){switch(t){case"video":return e.jsx(et,{className:"w-4 h-4"});case"document":return e.jsx(tt,{className:"w-4 h-4"});case"audio":return e.jsx(vs,{className:"w-4 h-4"});case"location":return e.jsx(Cs,{className:"w-4 h-4"});default:return e.jsx(We,{className:"w-4 h-4"})}}const Ka=i.memo(({title:t="",subtitle:s="",thumbnailUrl:a,mediaType:r="text",accent:n=!1,onClick:o,unavailable:l=!1})=>{if(l)return e.jsxs("div",{className:T("mb-1.5 flex items-center gap-1.5 rounded-md border-l-[3px] pl-2 pr-2 py-1",n?"bg-white/5 border-white/40 text-white/75":"bg-black/[0.03] dark:bg-white/[0.04] border-slate-300 dark:border-slate-600 text-slate-400 dark:text-slate-500"),children:[e.jsx(Ns,{className:"w-3 h-3 shrink-0 opacity-70"}),e.jsx("span",{className:"text-[11.5px] italic truncate",children:"Mensaje citado no disponible"})]});const c=o?"button":"div";return e.jsxs(c,{type:o?"button":void 0,onClick:o,"aria-label":o?"Ir al mensaje citado":void 0,"data-quoted-jump":o?"true":void 0,className:T("mb-1.5 w-full flex items-center gap-2 rounded-md overflow-hidden border-l-[3px] pl-2 pr-1.5 py-1 text-left",n?"bg-white/10 border-white/60":"bg-black/[0.035] dark:bg-white/[0.05] border-blue-500/70",o&&"cursor-pointer transition hover:brightness-95 dark:hover:brightness-110"),children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:T("text-[12px] font-medium truncate flex items-center gap-1",n?"text-white/90":"text-blue-600 dark:text-blue-300"),children:[e.jsx(Ns,{className:"w-3 h-3 shrink-0 opacity-80"}),e.jsx("span",{className:"truncate",children:t})]}),e.jsx("div",{className:T("text-[11px] truncate",n?"text-white/70":"text-slate-500 dark:text-slate-400"),children:s})]}),a?e.jsx(mt,{src:a,alt:"",className:"w-9 h-9 rounded object-cover shrink-0"}):r!=="text"?e.jsx("div",{className:T("w-9 h-9 rounded shrink-0 flex items-center justify-center",n?"bg-white/15 text-white/80":"bg-black/10 dark:bg-white/10 text-slate-400"),children:e.jsx(Fd,{type:r})}):null]})});Ka.displayName="QuotedReply";const Bi=i.memo(({referral:t,accent:s=!1})=>{const[a,r]=i.useState(!1),[n,o]=i.useState(!1),l=t.thumbnailUrl||t.imageUrl,c=t.imageUrl||t.thumbnailUrl,u=!!l&&!n,d=t.sourceType==="post",m=d?xi:Es;return!l&&!t.headline&&!t.body&&!t.sourceUrl?null:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:T("-mx-3.5 -mt-2 mb-1.5 min-w-[240px] overflow-hidden border-b",s?"bg-white/10 border-white/20":"bg-black/[0.035] dark:bg-white/[0.05] border-black/5 dark:border-white/10"),children:[u&&e.jsxs("button",{type:"button",onClick:()=>c&&r(!0),className:"block w-full relative group/ad cursor-zoom-in","aria-label":d?"Ver la imagen de la publicación":"Ver la imagen del anuncio",children:[e.jsx("img",{src:l,alt:t.headline||(d?"Imagen de la publicación":"Creatividad del anuncio"),loading:"lazy",decoding:"async",className:"w-full aspect-[1.91/1] object-cover bg-black/10 dark:bg-white/[0.06]",onError:()=>o(!0)}),e.jsx("span",{className:"absolute inset-0 bg-black/0 group-hover/ad:bg-black/15 transition-colors"})]}),e.jsxs("div",{className:"px-3 py-2",children:[e.jsxs("div",{className:T("flex items-center gap-1.5 mb-1",s?"text-white/70":"text-slate-500 dark:text-slate-400"),children:[e.jsx(m,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide",children:d?"Publicación":"Anuncio"})]}),t.headline&&e.jsx("div",{className:T("text-[13px] font-semibold leading-snug line-clamp-2",s?"text-white":"text-slate-900 dark:text-slate-100"),children:t.headline}),t.body&&e.jsx("p",{className:T("mt-0.5 text-[11px] leading-snug line-clamp-3",s?"text-white/80":"text-slate-600 dark:text-slate-400"),children:t.body}),t.sourceUrl&&e.jsxs("a",{href:t.sourceUrl,target:"_blank",rel:"noopener noreferrer",className:T("mt-1.5 inline-flex items-center gap-1 text-[11px] font-medium hover:underline",s?"text-white/90":"text-blue-600 dark:text-blue-400"),children:[d?"Ver publicación":"Ver anuncio",e.jsx(ca,{className:"w-3 h-3"})]})]})]}),c&&e.jsx(ls,{isOpen:a,onClose:()=>r(!1),url:c,thumbnailUrl:t.thumbnailUrl,type:"IMAGE",caption:t.headline})]})});Bi.displayName="AdReferralCard";function Pd(t){const s=typeof t.content=="string"?t.content.trim():"",r=s.startsWith("http")||s.startsWith("gs://")?"":s;return t.contentType==="DOCUMENT"?t.fileName||r||"":t.contentType==="INTERACTIVE"?r||t.metadata?.interactive?.title||"":t.mediaCaption||r}function Vd(t){return{id:t.id,senderType:t.senderType,contentType:t.contentType,preview:Pd(t),thumbnailUrl:t.thumbnailUrl||t.mediaUrl||void 0}}function aa(t){const s={};for(const a of t||[]){const r=a?.channelMessageId;r&&(s[r]=Vd(a))}return s}function Bd(t,s){return t==="CONTACT"?s||"Cliente":"Tú"}function $d(t){if(t.preview)return t.preview;switch(t.contentType){case"IMAGE":return"Foto";case"VIDEO":return"Video";case"AUDIO":return"Audio";case"DOCUMENT":return"Documento";case"LOCATION":return"Ubicación";case"STICKER":return"Sticker";case"INTERACTIVE":return"Mensaje interactivo";default:return""}}function zd(t){switch(t){case"IMAGE":return"image";case"VIDEO":return"video";case"AUDIO":return"audio";case"DOCUMENT":return"document";case"LOCATION":return"location";default:return"text"}}const qd=new Set(["IMAGE","VIDEO","DOCUMENT"]),Hd=t=>{if(typeof t=="string")try{const{protocol:s}=new URL(t);return s==="https:"||s==="http:"?t:void 0}catch{return}};function Gd(t){const s=t.metadata??{};if(!qd.has(s.mediaType))return{};const a=s.mediaType,r=t.mediaUrl||(a==="DOCUMENT"?Hd(s.headerMediaUrl):void 0),n=typeof s.fileName=="string"&&s.fileName?s.fileName:void 0;return{mediaType:a,mediaUrl:r,fileName:n}}const Aa=t=>is(t,{style:"time-only"}),Wd=t=>is(t,{style:"short"}),Ls=t=>{if(t.mediaCaption)return t.mediaCaption;if(t.content&&!t.content.startsWith("http")&&!t.content.startsWith("gs://"))return t.content},Qd=t=>{switch(t){case"READ":return e.jsx(Js,{className:"w-4 h-4",style:{color:"#00a6ff"}});case"DELIVERED":return e.jsx(Js,{className:"w-4 h-4 text-gray-400"});case"SENT":return e.jsx(Ie,{className:"w-4 h-4 text-gray-400"});case"PENDING":return e.jsx(bt,{className:"w-4 h-4 text-gray-400"});case"FAILED":return e.jsx(ct,{className:"w-4 h-4 text-red-500"});default:return null}},mr=i.memo(({message:t,showTimestamp:s,contactName:a,onInteractiveOption:r,channelType:n,carouselCardRefs:o,quotedRefs:l,onQuoteClick:c,isHighlighted:u,adReferral:d,readOnly:m=!1})=>{const[x,b]=i.useState(!1);i.useEffect(()=>{const S=setTimeout(()=>b(!0),50);return()=>clearTimeout(S)},[]);const y=t.senderType==="AGENT"||t.senderType==="BOT"||t.senderType==="AI_AGENT",p=t.senderType==="BOT",f=p&&t.metadata?.isCampaignMessage,g=p&&t.metadata?.isWorkflowTemplate,v=p&&t.metadata?.source==="META_AGENT",h=t.senderType==="SYSTEM"||t.contentType==="SYSTEM",I=t.senderType==="NOTE",U=Ye(S=>S.user),{data:C=[]}=cs(),E=Rd(),M=i.useMemo(()=>{if(!I)return;const S=t.metadata;if(S?.authorName)return S.authorName;const P=S?.userId;if(P)return U?.id===P?U.name:C.find(X=>X.user.id===P)?.user.name},[I,t.metadata,C,U]),F=n==="whatsapp"||n==="whatsapp_business"?"whatsapp":"standard",_=t.metadata?.context?.id,k=t.metadata?.quotedMessage??(_?l?.[_]:void 0),W=!k&&!!_,q=t.metadata?.interactive?.id?o?.[t.metadata.interactive.id]:void 0,ee=oc(t)??d,le=()=>{if(I)return null;switch(t.contentType){case"TEXT":case"IMAGE":case"VIDEO":case"DOCUMENT":if(f||g)return e.jsx(xn,{headerText:t.metadata?.headerText,bodyText:t.metadata?.bodyText||t.content,footerText:t.metadata?.footerText,buttons:t.metadata?.buttons,mediaUrl:t.mediaUrl,thumbnailUrl:t.thumbnailUrl,mediaType:t.contentType==="IMAGE"||t.contentType==="VIDEO"||t.contentType==="DOCUMENT"?t.contentType:void 0,fileName:t.fileName||t.metadata?.fileName,time:Aa(t.createdAt),resolvedVariables:t.metadata?.resolvedVariables,carousel:t.metadata?.carousel});if(t.contentType==="IMAGE")return e.jsx(_i,{url:t.mediaUrl,thumbnailUrl:t.thumbnailUrl,caption:Ls(t)});if(t.contentType==="VIDEO")return e.jsx(Li,{url:t.mediaUrl,thumbnailUrl:t.thumbnailUrl,caption:Ls(t)});if(t.contentType==="DOCUMENT")return e.jsx(ur,{url:t.mediaUrl||t.attachments?.[0]?.sourceUrl,caption:Ls(t),fileName:t.fileName||t.metadata?.fileName,fileSize:t.fileSize||t.metadata?.fileSize});if(t.contentType==="TEXT")return e.jsx(Yt,{content:t.content,variant:F});break;case"AUDIO":{const S=Ls(t);return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ii,{url:t.mediaUrl,transcription:t.metadata?.transcription}),S&&e.jsx("div",{className:"px-1 text-sm text-gray-800 dark:text-gray-200",children:e.jsx(Yt,{content:S,variant:"standard"})})]})}case"INTERACTIVE":case"TEMPLATE":{if(g){const L=Gd(t);return e.jsx(xn,{headerText:t.metadata?.headerText,bodyText:t.metadata?.bodyText||t.content,footerText:t.metadata?.footerText,buttons:t.metadata?.buttons,mediaType:L.mediaType,mediaUrl:L.mediaUrl,thumbnailUrl:t.thumbnailUrl,fileName:L.fileName,time:Aa(t.createdAt),resolvedVariables:t.metadata?.resolvedVariables})}const S=t.metadata||{},P=S.interactive,A=(typeof t.content=="string"?t.content:"").trim().startsWith("{"),z=Array.isArray(S.options)&&S.options.length>0;if(S.carousel)return e.jsx(qs,{content:S.carousel,onOptionClick:m?void 0:r,disabled:y||m});if(!A&&!z){const L=t.content||P?.title||P?.id||"Respuesta interactiva",N=P?.id?o?.[P.id]:void 0;return N?e.jsxs("div",{children:[e.jsx(Vi,{cardRef:N,accent:y}),e.jsx(Yt,{content:L,variant:F})]}):e.jsx(Yt,{content:L,variant:F})}return e.jsx(qs,{content:t.content,options:S.options,interactiveType:S.interactiveType,menuButton:S.menuButton,sections:S.sections,onOptionClick:m?void 0:r,disabled:y||m})}default:if(typeof t.content=="string"&&t.content.trim().startsWith("{")&&t.content.includes('"type":"buttons"'))try{const S=JSON.parse(t.content),X=(S.buttons||S.action?.buttons||[]).map((z,L)=>({id:z.id||z.reply?.id||`btn-${L}`,label:z.title||z.reply?.title||z.label||(typeof z=="string"?z:"Button")}));let A=S.body||S.text||"";return X.length>0&&(A=A.replace(/\n\n(\d+\.\s+.+(\n|$))+$/,"").trim()),e.jsx(qs,{content:A,options:X,onOptionClick:m?void 0:r,disabled:y||m})}catch{}return e.jsx(Yt,{content:t.content,variant:F})}};return e.jsxs("div",{id:`msg-${t.id}`,className:T("group scroll-mt-4 rounded-xl transition-colors duration-500",u&&"bg-blue-500/10"),children:[s&&e.jsx("div",{className:"flex justify-center py-4 mb-2",children:e.jsx("div",{className:"inline-flex items-center px-4 py-2 bg-gray-100 dark:bg-gray-800/60 rounded-full shadow-sm",children:e.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400 font-medium",children:Wd(t.createdAt)})})}),I?e.jsx("div",{className:"flex justify-center my-3",children:e.jsx(Pi,{content:t.content,agentName:M})}):h?e.jsx(Fi,{content:t.content,variant:t.metadata?.systemType}):e.jsxs("div",{className:T("flex flex-col mb-1.5","transition-all duration-300 ease-out",x?"opacity-100 translate-y-0":"opacity-0 translate-y-2",y?"items-end":"items-start"),children:[p&&!h&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-1 mx-2 opacity-80",children:[e.jsx("span",{className:T("w-1 h-1 rounded-full",f||g?"bg-emerald-400":v?"bg-sky-500":"bg-primary animate-pulse")}),e.jsx("span",{className:"text-[9px] font-bold tracking-widest uppercase text-slate-500 dark:text-slate-400",children:f?"Campaña":g?"Workflow":v?"Meta AI":"AI Assistant"})]}),e.jsxs("div",{className:T("relative max-w-[75%] sm:max-w-[65%] shadow-sm transition-all text-[13.5px] leading-snug overflow-hidden",y?f?"bg-[#8023fe] text-white rounded-2xl rounded-tr-[4px] px-3.5 py-2":g?"bg-emerald-600 text-white rounded-2xl rounded-tr-[4px] px-3.5 py-2":"bg-blue-600 text-white rounded-2xl rounded-tr-[4px] px-3.5 py-2":"bg-white dark:bg-[#1E293B] text-slate-900 dark:text-slate-100 border border-slate-100 dark:border-slate-700/50 rounded-2xl rounded-tl-[4px] px-3.5 py-2",t.status==="FAILED"&&"ring-2 ring-red-500/50"),children:[!y&&ee&&e.jsx(Bi,{referral:ee}),!y&&t.uploadError&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-2 px-2 py-1.5 bg-amber-50 dark:bg-amber-950/40 text-amber-700 dark:text-amber-400 rounded-lg border border-amber-100 dark:border-amber-800/50",children:[e.jsx(ft,{className:"w-3.5 h-3.5 shrink-0"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[11px] font-bold",children:"Archivo no disponible"}),e.jsx("span",{className:"text-[9px] opacity-80",children:t.uploadError})]})]}),y&&t.status==="FAILED"&&e.jsxs("div",{className:"flex items-start gap-1.5 mb-2 px-2 py-1.5 bg-red-50 dark:bg-red-950/40 text-red-700 dark:text-red-400 rounded-lg border border-red-100 dark:border-red-800/50",children:[e.jsx(ks,{className:"w-3.5 h-3.5 shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"text-[11px] font-bold",children:"Error de envío"}),t.errorDetails?.message&&e.jsx("span",{className:"text-[10px] opacity-90",children:t.errorDetails.message}),t.errorDetails?.suggestion&&e.jsx("span",{className:"text-[9px] opacity-70 mt-0.5",children:t.errorDetails.suggestion})]}),!m&&!Ld(t.errorDetails)&&e.jsxs("button",{type:"button",onClick:()=>E.mutate(t.id),disabled:E.isPending,title:"Reintentar el envío de este mensaje",className:"ml-auto shrink-0 inline-flex items-center gap-1 px-2 py-1 rounded-md text-[10px] font-semibold bg-red-100 hover:bg-red-200 dark:bg-red-900/50 dark:hover:bg-red-900 text-red-700 dark:text-red-200 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(tc,{className:T("w-3 h-3",E.isPending&&"animate-spin")}),E.isPending?"Reintentando…":"Reintentar"]})]}),!q&&k?e.jsx(Ka,{title:Bd(k.senderType,a),subtitle:$d(k),thumbnailUrl:k.thumbnailUrl,mediaType:zd(k.contentType),accent:y,onClick:c?()=>c(k.id):void 0}):!q&&W?e.jsx(Ka,{unavailable:!0,accent:y}):null,e.jsx("div",{className:"wrap-break-word",children:le()}),e.jsxs("div",{className:T("flex items-center justify-end gap-1 mt-1 select-none",y?"text-white/60":"text-slate-400 dark:text-slate-500"),children:[e.jsx("span",{className:"text-[10px] leading-none",children:Aa(t.createdAt)}),y&&e.jsx("span",{className:"flex items-center",children:t.status==="FAILED"?t.errorDetails?e.jsx(rs,{delayDuration:200,children:e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsx(ct,{className:"w-3 h-3 text-red-300 cursor-help"})}),e.jsx(Re,{side:"top",className:"max-w-xs",children:e.jsxs("div",{className:"text-xs",children:[e.jsx("p",{className:"font-semibold text-red-600 dark:text-red-400",children:"Error de envío"}),e.jsx("p",{className:"mt-1",children:t.errorDetails.message}),t.errorDetails.suggestion&&e.jsx("p",{className:"mt-1 text-muted-foreground text-[10px]",children:t.errorDetails.suggestion})]})})]})}):e.jsx(ct,{className:"w-3 h-3 text-red-300"}):e.jsx("span",{className:t.status==="READ"?"text-sky-200":"",children:e.jsx("div",{className:"scale-75 origin-right",children:Qd(t.status)})})})]})]})]})]})});mr.displayName="ChatMessage";const Kd={RESOLVED_BY_AGENT:"Resuelto por el asesor",RESOLVED_BY_CLIENT:"Resuelto por el cliente",RESOLVED_BY_BOT:"Resuelto por el bot",INACTIVITY_CLIENT:"Cerrado por inactividad del cliente",INACTIVITY_AGENT:"Cerrado por inactividad del asesor",AUTO_CLOSED_INACTIVITY:"Cerrado automáticamente por inactividad",SESSION_TIMEOUT:"Cerrado al expirar la sesión",TRANSFERRED:"Transferido",SPAM:"Marcado como spam",DUPLICATE:"Duplicado",CHANNEL_MIGRATED:"Canal migrado",CONTACT_DELETED:"Contacto eliminado",CIRCUIT_BREAKER:"Cerrado por protección del canal",DEAD_WORKFLOW:"Cerrado por flujo interrumpido"};function Yd(t){if(t)return Kd[t]}function $i({ticket:t}){const s=!!t.closedAt,a=is(t.closedAt??t.lastMessageAt,{style:"short"}),r=s?`Conversación cerrada el ${a}`:`Conversación anterior · última actividad el ${a}`,n=Yd(t.closeReason);return e.jsxs("div",{role:"separator","aria-label":`Fin de la ${r.toLowerCase()}`,className:"flex items-center gap-3 py-4",children:[e.jsx("div",{className:"h-px flex-1 bg-gray-200 dark:bg-gray-700"}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Za,{className:"w-3.5 h-3.5 shrink-0","aria-hidden":"true"}),e.jsx("span",{className:"font-medium",children:r}),n&&e.jsxs("span",{className:"hidden sm:inline text-gray-400 dark:text-gray-500",children:["· ",n]})]}),e.jsx("div",{className:"h-px flex-1 bg-gray-200 dark:bg-gray-700"})]})}function Xd({history:t,contactId:s,onLoadPrevious:a}){if(t?.isError)return e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-6 text-muted-foreground text-xs",children:[e.jsx("span",{children:"No se pudo cargar la conversación anterior."}),e.jsx(K,{size:"sm",variant:"outline",onClick:t.onRetry,children:"Reintentar"})]});if(!!t&&(t.canLoadPrevious||t.isLoading)){const n=t.previousTicket,o=n?Hn(n.closedAt??n.lastMessageAt):null;return e.jsx("div",{className:"flex flex-col items-center justify-center gap-2 py-6 text-muted-foreground text-xs",children:e.jsxs(K,{size:"sm",variant:"outline",onClick:a,disabled:t.isLoading,className:"gap-1.5",children:[t.isLoading?e.jsx(Se,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Xn,{className:"w-3.5 h-3.5"}),t.isLoading?"Cargando conversación anterior…":o?`Cargar conversación anterior · ${o}`:"Cargar conversación anterior"]})})}return t?.reachedCap?e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-6 text-muted-foreground text-xs",children:[e.jsx("span",{children:"Se alcanzó el máximo de conversaciones en pantalla."}),s&&e.jsxs("a",{href:`/contactos?contactId=${s}&tab=conversations`,className:"inline-flex items-center gap-1 font-medium text-primary hover:underline",children:["Ver el historial completo en la ficha del contacto",e.jsx(ca,{className:"w-3 h-3"})]})]}):e.jsx("div",{className:"flex items-center justify-center py-6 text-muted-foreground text-xs",children:e.jsx("div",{className:"flex items-center gap-2 px-4 py-2 rounded-full bg-gray-100 dark:bg-gray-800/50",children:e.jsx("span",{className:"font-medium",children:t?.segments.length?"Inicio del historial con este contacto":"Inicio de la conversación"})})})}function Zd({messagesError:t,onRetryMessages:s,isLoading:a,messageCount:r}){return r>0?null:t?e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-12 text-muted-foreground",children:[e.jsx(ft,{className:"w-7 h-7 text-destructive"}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:"No se pudieron cargar los mensajes"}),e.jsx("p",{className:"text-xs text-center max-w-sm",children:or(t)}),s&&e.jsx(K,{size:"sm",variant:"outline",onClick:s,children:"Reintentar"})]}):a?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(Se,{className:"w-8 h-8 animate-spin text-primary mb-3"}),e.jsx("p",{className:"text-sm",children:"Cargando mensajes..."})]}):e.jsx("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:e.jsx("p",{className:"text-sm",children:"Esta conversación todavía no tiene mensajes."})})}const pn=300*1e3,zi=i.memo(({messages:t,conversation:s,typingIndicator:a,onInteractiveOption:r,fallbackReferral:n,fallbackReferralMessageId:o,onLoadMore:l,hasMore:c=!1,isLoadingMore:u=!1,history:d,onLoadPrevious:m,messagesError:x,onRetryMessages:b,isLoadingConversation:y=!1})=>{const p=i.useRef(null),[f,g]=i.useState(!1),[v,h]=i.useState(0),I=i.useMemo(()=>Xs(t),[t]),U=i.useMemo(()=>aa(t),[t]),[C,E]=i.useState(null),M=i.useRef(t.length),F=i.useRef(0),_=i.useRef(null),[k,W]=i.useState(0),q=i.useMemo(()=>{const L=[];for(const N of d?.segments??[]){const w=Xs(N.messages),$=aa(N.messages);N.messages.forEach((ae,ne)=>{const re=N.messages[ne-1];L.push({kind:"message",key:ae.id,message:ae,showTimestamp:!re||new Date(ae.createdAt).getTime()-new Date(re.createdAt).getTime()>pn,readOnly:!0,carouselCardRefs:w,quotedRefs:$})}),L.push({kind:"boundary",key:`boundary-${N.ticket.id}`,ticket:N.ticket})}return t.forEach((N,w)=>{const $=t[w-1];L.push({kind:"message",key:N.id,message:N,showTimestamp:$?new Date(N.createdAt).getTime()-new Date($.createdAt).getTime()>pn:c||!!d?.segments.length,readOnly:!1,carouselCardRefs:I,quotedRefs:U})}),L},[d?.segments,t,c,I,U]),ee=qn({count:q.length,scrollMargin:k,getScrollElement:()=>p.current,estimateSize:i.useCallback(()=>80,[]),overscan:5,getItemKey:i.useCallback(L=>q[L]?.key||L,[q])}),le=ee.getVirtualItems(),S=i.useCallback(L=>{const N=q.findIndex(w=>w.kind==="message"&&w.message.id===L);N<0||(ee.scrollToIndex(N,{align:"center"}),E(L),setTimeout(()=>E(w=>w===L?null:w),1600))},[q,ee]);i.useEffect(()=>{const L=t.length,N=M.current;if(L>N){const w=L-N;if(f)h($=>$+w);else{const $=setTimeout(()=>{ee.scrollToIndex(q.length-1,{align:"end"})},0);return M.current=L,()=>clearTimeout($)}}M.current=L},[t.length,f,ee,q.length]),i.useEffect(()=>{if(t.length>0){const L=setTimeout(()=>{ee.scrollToIndex(q.length-1,{align:"end"})},0);return()=>clearTimeout(L)}},[s?.ticket.id]),i.useEffect(()=>{if(u||F.current<=0)return;const L=p.current;if(!L)return;const N=L.scrollHeight-F.current;N>0&&(L.scrollTop=N),F.current=0},[u,q.length]),i.useLayoutEffect(()=>{const L=_.current?.offsetHeight??0;W(N=>N===L?N:L)},[c,t.length,d?.segments.length,d?.canLoadPrevious,d?.isLoading,d?.isError,d?.reachedCap]);const P=i.useCallback(()=>{p.current&&(F.current=p.current.scrollHeight),m?.()},[m]),X=i.useCallback(()=>{const L=p.current;if(!L)return;const{scrollTop:N,scrollHeight:w,clientHeight:$}=L,ae=w-N-$;g(ae>200);const ne=c||!!d?.canScrollLoad;N<100&&ne&&!u&&l&&(F.current=w,l())},[c,d?.canScrollLoad,u,l]),A=i.useCallback(()=>{setTimeout(()=>{ee.scrollToIndex(q.length-1,{align:"end"})},0),g(!1),h(0)},[q.length,ee]),z=ee.getTotalSize();return e.jsxs("div",{className:"flex-1 relative overflow-hidden",children:[e.jsxs("div",{ref:p,className:"h-full overflow-y-auto overscroll-contain bg-slate-50/50 dark:bg-[#0F172A]",onScroll:X,children:[!c&&t.length>0&&e.jsx("div",{ref:_,children:e.jsx(Xd,{history:d,contactId:s.contact?.id,onLoadPrevious:P})}),e.jsx(Zd,{messagesError:x,onRetryMessages:b,isLoading:y,messageCount:t.length}),e.jsxs("div",{className:"relative w-full",style:{height:`${z}px`},children:[u&&e.jsx("div",{className:"absolute top-0 left-0 right-0 flex items-center justify-center py-4 z-10",children:e.jsx(Se,{className:"w-5 h-5 animate-spin text-primary"})}),e.jsx("div",{className:"absolute top-0 left-0 w-full",style:{transform:`translateY(${(le[0]?.start??k)-k}px)`},children:le.map(L=>{const N=q[L.index];return N?e.jsx("div",{"data-index":L.index,ref:ee.measureElement,className:"p-2",children:N.kind==="boundary"?e.jsx($i,{ticket:N.ticket}):e.jsx(mr,{message:N.message,showTimestamp:N.showTimestamp,contactName:s.contact?.name,onInteractiveOption:r,channelType:s.channel?.type,carouselCardRefs:N.carouselCardRefs,quotedRefs:N.quotedRefs,onQuoteClick:S,isHighlighted:N.message.id===C,readOnly:N.readOnly,adReferral:N.message.id===o?n:void 0})},L.key):null})})]}),a?.isTyping&&e.jsxs("div",{className:"p-4 animate-in fade-in zoom-in duration-300",children:[e.jsxs("div",{className:"flex items-end gap-2 ml-1",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-xs font-bold text-primary shrink-0",children:s.contact?.name?.substring(0,2).toUpperCase()||"GU"}),e.jsxs("div",{className:"bg-gray-100 dark:bg-muted/80 px-4 py-3 rounded-2xl rounded-bl-sm flex items-center gap-1 shadow-sm",children:[e.jsx("span",{className:"w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce [animation-delay:-0.3s]"}),e.jsx("span",{className:"w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce [animation-delay:-0.15s]"}),e.jsx("span",{className:"w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce"})]})]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground ml-11 font-medium opacity-70",children:[a.userName||"Escribiendo","..."]})]})]}),f&&e.jsxs("button",{onClick:A,className:T("absolute bottom-4 right-4 z-20","min-w-10 h-10 px-3 rounded-full","bg-background/95 backdrop-blur-sm border border-border","shadow-lg shadow-black/5","flex items-center justify-center gap-2","text-muted-foreground hover:text-foreground","transition-all duration-200 hover:scale-105","animate-in fade-in zoom-in-50 duration-200",v>0&&"bg-primary text-primary-foreground border-primary"),title:v>0?`${v} mensaje${v>1?"s":""} nuevo${v>1?"s":""}`:"Ir al final","aria-label":v>0?`${v} mensajes nuevos`:"Ir al final de la conversación",children:[v>0&&e.jsx("span",{className:"text-xs font-semibold",children:v>99?"99+":v}),e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 14l-7 7m0 0l-7-7m7 7V3"})})]})]})});zi.displayName="VirtualizedMessageList";const Jd=t=>{switch(t){case"TEXT":return e.jsx(tt,{className:"w-4 h-4"});case"IMAGE":return e.jsx(We,{className:"w-4 h-4"});case"VIDEO":return e.jsx(et,{className:"w-4 h-4"});case"INTERACTIVE":return e.jsx(ws,{className:"w-4 h-4"});default:return e.jsx(tt,{className:"w-4 h-4"})}},gn=t=>{switch(t){case"TEXT":return"text-blue-500 bg-blue-50";case"IMAGE":return"text-green-500 bg-green-50";case"VIDEO":return"text-purple-500 bg-purple-50";case"INTERACTIVE":return"text-amber-500 bg-amber-50";default:return"text-gray-500 bg-gray-50"}},qi=i.memo(({searchQuery:t,onSelect:s,onClose:a,visible:r,searchMode:n="tabs",activeChannel:o})=>{const l=i.useRef(null),[c,u]=i.useState(0),[d,m]=i.useState(null),{data:x=[]}=Jn(),b=t,y=n==="tabs"?d:void 0,{data:p=[],isLoading:f}=ei({query:b,categoryId:y||void 0,enabled:r,limit:15,channelType:o?.type}),g=i.useMemo(()=>p.map(h=>({type:"TEMPLATE",data:h})),[p]);i.useEffect(()=>{u(0)},[g.length]);const v=i.useCallback(h=>{if(!(!r||g.length===0))switch(h.key){case"ArrowDown":h.preventDefault(),u(U=>U<g.length-1?U+1:0);break;case"ArrowUp":h.preventDefault(),u(U=>U>0?U-1:g.length-1);break;case"Enter":case"Tab":h.preventDefault();const I=g[c];I&&s(I.data);break;case"Escape":h.preventDefault(),a();break}},[r,g,c,s,a]);return i.useEffect(()=>{if(r)return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[r,v]),r?e.jsxs("div",{className:"absolute bottom-full left-0 right-0 mb-2 mx-4 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-xl shadow-xl z-50 overflow-hidden",role:"listbox",children:[e.jsxs("div",{className:"px-3 py-2 bg-gray-50 dark:bg-gray-800/50 border-b border-gray-100 dark:border-gray-700 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-gray-500 dark:text-gray-400",children:[e.jsx(ir,{className:"w-3.5 h-3.5"}),t?"Resultados":"Sugerencias"]}),e.jsx("div",{className:"text-[10px] text-gray-400",children:"↑↓ navegar • Enter seleccionar"})]}),n==="tabs"&&x.length>0&&e.jsxs("div",{className:"px-3 py-2 border-b border-gray-100 dark:border-gray-700 flex items-center gap-2 overflow-x-auto scrollbar-hide",children:[e.jsx("button",{type:"button",onClick:()=>m(null),className:T("px-3 py-1 rounded-full text-xs font-medium transition-all whitespace-nowrap",d===null?"bg-primary text-primary-foreground":"bg-gray-100 dark:bg-gray-800 text-gray-600 hover:bg-gray-200"),children:"Todas"}),x.map(h=>e.jsxs("button",{type:"button",onClick:()=>m(h.id),className:T("px-3 py-1 rounded-full text-xs font-medium transition-all whitespace-nowrap flex items-center gap-1.5",d===h.id?"bg-primary text-primary-foreground":"bg-gray-100 dark:bg-gray-800 text-gray-600 hover:bg-gray-200"),children:[h.color&&e.jsx("span",{className:"w-2 h-2 rounded-full",style:{backgroundColor:h.color}}),h.name]},h.id))]}),e.jsx("div",{ref:l,className:"max-h-[280px] overflow-y-auto",children:f?e.jsx("div",{className:"px-4 py-6 text-center text-sm text-gray-400",children:"Cargando..."}):g.length===0?e.jsx("div",{className:"px-4 py-6 text-center text-sm text-gray-400",children:t?"No se encontraron resultados":"No hay plantillas disponibles"}):g.map((h,I)=>{const U=I===c,C=h.data;return e.jsx(rs,{delayDuration:300,children:e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>s(C),className:T("w-full px-3 py-2.5 flex items-start gap-3 text-left transition-colors",U?"bg-primary/5":"hover:bg-gray-50 dark:hover:bg-gray-800"),children:[e.jsx("div",{className:T("w-8 h-8 rounded-lg flex items-center justify-center shrink-0 mt-0.5",gn(C.contentType)),children:Jd(C.contentType)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm truncate",children:C.name}),C.shortcut&&e.jsx("span",{className:"text-xs text-primary/70 font-mono bg-primary/5 px-1.5 py-0.5 rounded",children:C.shortcut})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[C.category&&e.jsxs("span",{className:"text-[10px] text-gray-400 flex items-center gap-1",children:[e.jsx(ri,{className:"w-3 h-3"}),C.category.name]}),C.tags&&C.tags.length>0&&e.jsx("div",{className:"flex gap-1",children:C.tags.slice(0,2).map(E=>e.jsxs("span",{className:"text-[10px] text-gray-400 bg-gray-100 dark:bg-gray-800 px-1.5 py-0.5 rounded",children:["#",E]},E))})]}),C.content&&e.jsx("div",{className:"text-xs text-gray-500 truncate mt-0.5",children:C.content})]})]})}),e.jsx(Re,{side:"right",className:"max-w-[300px] p-0 overflow-hidden border-border bg-popover text-popover-foreground shadow-xl !animate-none",sideOffset:10,children:e.jsxs("div",{className:"flex flex-col",children:[C.mediaUrl&&(C.contentType==="IMAGE"||C.contentType==="VIDEO")&&e.jsx("div",{className:"relative w-full aspect-video bg-gray-100 dark:bg-gray-900 border-b border-border",children:C.contentType==="VIDEO"?e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center",children:[C.thumbnailUrl?e.jsx("img",{src:C.thumbnailUrl,alt:"Preview",className:"w-full h-full object-cover opacity-80"}):e.jsxs("div",{className:"bg-gray-200 dark:bg-gray-800 w-full h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(et,{className:"w-8 h-8 mb-2 opacity-50"}),e.jsx("span",{className:"text-[10px]",children:"Vista previa de video"})]}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/20",children:e.jsx(bl,{className:"w-10 h-10 text-white fill-black/50"})})]}):e.jsx("img",{src:C.mediaUrl,alt:"Preview",className:"w-full h-full object-cover",loading:"lazy"})}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border pb-2 mb-2",children:[e.jsx("span",{className:T("text-[10px] px-1.5 py-0.5 rounded font-medium",gn(C.contentType)),children:C.contentType}),e.jsx("span",{className:"text-xs font-semibold truncate",children:C.name})]}),e.jsx("div",{className:"text-xs space-y-2 whitespace-pre-wrap max-h-[200px] overflow-y-auto",children:C.content||C.interactive?.body?.text||e.jsx("span",{className:"text-gray-400 italic",children:"Sin contenido de texto"})}),C.contentType==="INTERACTIVE"&&C.interactive?.buttons&&e.jsx("div",{className:"grid gap-1 pt-2",children:C.interactive.buttons.map((E,M)=>e.jsx("div",{className:"text-center bg-gray-50 dark:bg-gray-800 text-xs py-1.5 px-2 rounded border border-gray-100 dark:border-gray-700 text-primary",children:E.title},M))})]})]})})]})},C.id)})})]}):null});qi.displayName="TemplateSuggestions";const ot=(t,s)=>t.replace(/\{\{([^}]+)\}\}/g,(a,r)=>{const n=r.trim().split(".");let o=s;for(const l of n)if(o&&typeof o=="object"&&l in o)o=o[l];else return a;return o!=null?String(o):a}),eu=(t,s)=>{const a=[],r=/\{\{([^}]+)\}\}/g;let n;for(;(n=r.exec(t))!==null;){const o=n[1].trim(),l=o.split(".");let c=s,u=!0;for(const d of l)if(c&&typeof c=="object"&&d in c)c=c[d];else{u=!1;break}u&&c!==void 0&&c!==null&&a.push({variable:o,value:String(c),originalPattern:n[0]})}return a};async function tu(t){const s=await t.arrayBuffer(),a=await crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(a)).map(o=>o.toString(16).padStart(2,"0")).join("")}const su={},au=({onSendMessage:t,onSendNote:s,onStartTyping:a,onStopTyping:r,channel:n,ticketId:o,assignedType:l,typingEnabled:c=!0,mediaLimits:u,templateContext:d=su,disabled:m=!1})=>{const{ticketInactivityState:x}=fe(),b=it(),y=x[o]??!0,[p,f]=i.useState(""),[g,v]=i.useState("reply"),[h,I]=i.useState(!1),U=i.useRef(!1),C=i.useRef(null),E=3e4,[M,F]=i.useState(!1),[_,k]=i.useState(!1),[W,q]=i.useState([]),ee=i.useRef(null),le=i.useRef(null),[S,P]=i.useState(!1),[X,A]=i.useState(""),[z,L]=i.useState(null),[N,w]=i.useState([]),[$,ae]=i.useState(null),ne=i.useRef(0),re=3e3;i.useEffect(()=>()=>{C.current&&clearTimeout(C.current)},[]);const{status:be,recordingTime:D,audioBlob:Z,startRecording:te,stopRecording:xe,cancelRecording:ge,isSupported:ve}=io({maxDurationSeconds:120}),V=i.useMemo(()=>{const R=n?Hs(n.type):Jt;return{...u?.outbound||R.outbound,channelType:n?.type,allowedTypes:u?.allowedTypes,maxAttachments:u?.maxAttachments}},[u,n?.type]),{uploadFile:j,isUploading:G,error:se,feedback:de,progress:Ae}=nr({mediaLimits:V,channelId:n?.id,onError:R=>{const Y=R;Y.suggestion?H.error(Y.message,{description:Y.suggestion,duration:6e3}):H.error("Error al subir archivo",{description:Y.message})}});i.useEffect(()=>{se&&H.error("Error al subir archivo",{description:se.message})},[se]);const ue=be==="recording"||be==="paused";i.useEffect(()=>{g==="reply"&&p.startsWith("/")&&!p.includes(" ")?(P(!0),A(p.slice(1))):(P(!1),A(""))},[p,g]);const je=i.useCallback(R=>{if(m)return;const Y=R.target.value;if(f(Y),c&&g==="reply"&&Y.length>0){const ce=Date.now();ce-ne.current>re&&(a?.(),ne.current=ce)}else g==="reply"&&(r?.(),ne.current=0);const oe=ee.current;if(oe){oe.style.height="auto";const ce=Math.min(oe.scrollHeight,200);oe.style.height=`${ce}px`}Y.trim()===""&&ae(null)},[m,g,a,r,c]),ke=i.useCallback(async R=>{P(!1),ae(R.id);const Y=R.content||"",oe=eu(Y,d);if(w(oe),R.contentType==="TEXT"){const ce=ot(Y,d);f(ce),setTimeout(()=>ee.current?.focus(),0)}else if(["IMAGE","VIDEO","AUDIO","DOCUMENT"].includes(R.contentType.toUpperCase())){let ce=R.mediaUrl,pe=R;if(!ce)try{F(!0),pe=await b.fetchQuery({queryKey:$a.detail(R.id),queryFn:()=>Ba.getById(R.id),staleTime:1e3*60*5}),ce=pe.mediaUrl}catch(Ne){console.error("Failed to fetch template details:",Ne);return}finally{F(!1)}if(ce){const Ne=ot(pe.content||"",d);L({templateName:pe.name,contentType:pe.contentType,mediaUrl:ce,thumbnailUrl:pe.thumbnailUrl??void 0,gcsPath:pe.mediaGcsPath??void 0,mediaMimeType:pe.mediaMimeType??void 0,caption:Ne,fileSize:pe.fileSize?Number(pe.fileSize):void 0,fileHash:pe.fileHash}),f(Ne),setTimeout(()=>ee.current?.focus(),0)}else console.warn("Template selected but mediaUrl is missing:",pe),H.error("No se pudo cargar el archivo de la plantilla"),f(""),ae(null),w([])}else if(R.contentType==="INTERACTIVE")try{let ce=R;const pe=String(R.interactive?.header?.type||"").toLowerCase(),Ne=(pe==="image"||pe==="video"||pe==="document")&&!!R.interactive?.header?.mediaGcsPath,Ve=R.interactive?.header?.mediaUrl,_e=R.interactive?.type==="carousel"&&(R.interactive?.cards||[]).some(Ee=>Ee.imageGcsPath&&!Ee.thumbnailUrl);if(Ne&&!Ve||_e)try{ce=await b.fetchQuery({queryKey:$a.detail(R.id),queryFn:()=>Ba.getById(R.id),staleTime:1e3*60*5})}catch(Ee){console.warn("Failed to fetch full template for media URLs:",Ee)}const ye=ot(ce.interactive?.body?.text||ce.content||"",d),Qe=ce.interactive?.footer?.text?ot(ce.interactive?.footer?.text,d):void 0;let st;const ze=ce.interactive?.header;if(ze){const Ee=String(ze.type||"").toLowerCase();if(Ee==="text"||Ee==="string"){const Fe=ze.text?ot(ze.text,d):"";Fe.trim()&&(st={type:"text",text:Fe})}else(Ee==="image"||Ee==="video"||Ee==="document")&&ze.mediaGcsPath&&(st={type:Ee,mediaGcsPath:ze.mediaGcsPath,mediaMimeType:ze.mediaMimeType,mediaOriginalName:ze.mediaOriginalName,mediaUrl:ze.mediaUrl})}const _t=ce.interactive?.type==="carousel",Ke=ce.interactive?.type==="list";let $t;if(_t){const Ee=(ce.interactive?.cards||[]).filter(qe=>qe.imageGcsPath).map(qe=>({header:{type:"image",mediaGcsPath:qe.imageGcsPath,...qe.thumbnailUrl?{thumbnailUrl:qe.thumbnailUrl}:{}},...qe.cardBody?{body:ot(qe.cardBody,d)}:{},buttons:qe.urlButton?[{type:"cta_url",title:qe.urlButton.title,url:qe.urlButton.url}]:(qe.buttons||[]).map(at=>({type:"quick_reply",id:at.id,title:at.label}))}));if(Ee.length<2){H.error("La plantilla de carrusel necesita al menos 2 tarjetas con imagen.");return}const Fe=lo(Ee.map(qe=>(qe.buttons||[]).map(at=>at.title||"")));if(Fe!==-1){H.error(`La tarjeta ${Fe+1} tiene botones con títulos duplicados. WhatsApp requiere que sean únicos dentro de cada tarjeta.`);return}$t=JSON.stringify({kind:"carousel",body:ye,cards:Ee})}else if(Ke){const Ee=(ce.interactive?.sections||[]).flatMap(Fe=>Fe.rows||[]).map((Fe,qe)=>({id:Fe.id||`row-${qe}`,title:ot(Fe.title||"",d).trim(),...Fe.description?{description:ot(Fe.description,d).trim()}:{}})).filter(Fe=>Fe.title.length>0);if(Ee.length===0){H.error("La plantilla de menú no tiene opciones configuradas.");return}$t=JSON.stringify({type:"list",body:ye,menuButton:ce.interactive?.menuButton?ot(ce.interactive.menuButton,d):void 0,sections:[{rows:Ee}],header:st,footer:Qe})}else{const Ee=(ce.interactive?.buttons||[]).map((at,xl)=>({id:at.id||`btn-${xl}`,title:ot(at.title||at.text||"",d).trim()})).filter(at=>at.title.length>0);if(Ee.length===0){H.error("La plantilla no tiene botones configurados o tienen el texto vacío.");return}const Fe=Ee.map(at=>at.title.toLowerCase());if(new Set(Fe).size!==Fe.length){H.error("Los botones de la plantilla tienen títulos duplicados. WhatsApp requiere que sean únicos.");return}$t=JSON.stringify({type:ce.interactive?.type||"buttons",body:ye,buttons:Ee,header:st,footer:Qe})}L({templateName:ce.name,contentType:"INTERACTIVE",mediaUrl:"",caption:ye,interactiveContent:$t}),f(""),setTimeout(()=>ee.current?.focus(),0)}catch(ce){console.error("Error preparing interactive template:",ce)}},[b,d]),Q=i.useCallback(async()=>{if(m)return;const R=p.trim();if(!(!R&&W.length===0&&!z)&&!U.current){U.current=!0,I(!0),r?.(),C.current=setTimeout(()=>{U.current&&(console.warn("[useChatInput] Send timed out after 30s — unlocking input"),U.current=!1,I(!1),F(!1))},E);try{if(g==="note")s&&R&&(await s(R),f(""));else if(z){if(z.contentType==="INTERACTIVE"&&z.interactiveContent)await t(z.interactiveContent,"INTERACTIVE",{templateId:$||void 0});else{if(z.fileSize){const Y=z.contentType.toLowerCase(),oe=n?Hs(n.type):Jt,ce=n?.config?.mediaLimits||oe,Ne=(ce.outbound||ce)[Y]?.maxBytes||0;if(Ne>0&&(z.fileSize||0)>Ne){H.error("Plantilla no puede enviarse",{description:"Excede límite de tamaño"}),U.current=!1,I(!1),C.current&&(clearTimeout(C.current),C.current=null);return}}await t(R||"",z.contentType,{mediaUrl:z.mediaUrl,gcsPath:z.gcsPath,mediaMimeType:z.mediaMimeType,fileSize:z.fileSize,fileHash:z.fileHash,templateId:$||void 0,thumbnailUrl:z.thumbnailUrl})}L(null),w([]),ae(null),f("")}else if(W.length>0){for(const Y of W){const{file:oe,isDuplicate:ce,existingUrl:pe,gcsPath:Ne,hash:Ve}=Y;let _e="DOCUMENT";if(oe.type.startsWith("image/")?_e="IMAGE":oe.type.startsWith("video/")?_e="VIDEO":oe.type.startsWith("audio/")&&(_e="AUDIO"),ce&&pe&&Ne){await t(R||"",_e,{mediaUrl:pe,gcsPath:Ne,mediaMimeType:oe.type,fileSize:oe.size,fileHash:Ve,fileName:oe.name,width:Y.width,height:Y.height,duration:Y.duration,thumbnailUrl:Y.thumbnailUrl});continue}F(!0);try{const ye=await j(oe);await t(R||"",_e,{mediaUrl:ye.signedUrl,gcsPath:ye.gcsPath,mediaMimeType:ye.mimeType,fileSize:ye.size,fileHash:ye.hash,fileName:oe.name,width:Y.width,height:Y.height,duration:Y.duration,thumbnailUrl:ye.thumbnailUrl??void 0})}finally{F(!1)}}f(""),q([])}else await t(R,"TEXT",{templateId:$||void 0}),w([]),ae(null),f("");ee.current&&(ee.current.style.height="auto")}catch(Y){console.error("Error sending message:",Y)}finally{C.current&&(clearTimeout(C.current),C.current=null),U.current=!1,I(!1),setTimeout(()=>ee.current?.focus(),0)}}},[p,W,z,g,t,s,r,$,n,j]),ie=i.useCallback(R=>{if(!m){if(R.ctrlKey&&R.key==="n"){R.preventDefault(),v(Y=>Y==="note"?"reply":"note");return}if(R.key==="Escape"){R.preventDefault(),S?P(!1):z||$?(L(null),ae(null),w([]),(z||p.startsWith("/"))&&f("")):W.length>0&&q([]);return}if(!(S&&["ArrowUp","ArrowDown","Tab"].includes(R.key))&&R.key==="Enter"&&!R.shiftKey&&!S){if(R.preventDefault(),ue)return;Q()}}},[m,Q,S,z,W.length,$,ue,xe]),O=i.useCallback(async R=>{const Y=u?.maxAttachments??10;if(W.length+R.length>Y){H.error(`Solo puedes enviar hasta ${Y} archivos por mensaje.`);return}const oe=[],ce=[],pe=n?Hs(n.type):Jt,Ne=u?.outbound||pe.outbound,Ve=u?.allowedTypes;for(const _e of R){if(Ve){const st=uo(_e.type);if(!st||!Ve.includes(st)){ce.push(`Tipo no permitido: ${_e.name}`);continue}}const ye={...Jt.outbound};Ne&&(ye.image={maxBytes:Ne.image.maxBytes},ye.video={maxBytes:Ne.video.maxBytes},ye.audio={maxBytes:Ne.audio.maxBytes},ye.document={maxBytes:Ne.document.maxBytes});const Qe=ro(_e,ye);if(Qe.action==="REJECT"){ce.push(Qe.userMessage||`${_e.name} es demasiado grande`);continue}oe.push(_e)}if(ce.length>0&&H.error("Archivo(s) rechazado(s)",{description:ce.join(`
|
|
5
|
-
`)}),oe.length>0){const _e=oe.map(ye=>({file:ye}));q(ye=>[...ye,..._e]),_e.forEach(async ye=>{try{const Qe=tu(ye.file),st=ru(ye.file),[ze,_t]=await Promise.all([Qe,st]),Ke=await Ce.checkDuplicate(ze);q($t=>{const Ee=[...$t],Fe=Ee.findIndex(qe=>qe.file===ye.file);return Fe!==-1&&(Ee[Fe]={...Ee[Fe],hash:ze,isDuplicate:Ke.exists,existingUrl:Ke.signedUrl,gcsPath:Ke.gcsPath,thumbnailUrl:Ke.thumbnailUrl,..._t}),Ee}),Ke.exists&&console.log(`[useChatInput] Duplicate found for ${ye.file.name}, will skip upload.`)}catch(Qe){console.error("Error calculating hash or checking duplicate:",Qe)}})}},[W.length,u]),B=i.useCallback(async R=>{const Y=Array.from(R.target.files||[]);await O(Y),le.current&&(le.current.value=""),k(!1)},[O]),J=i.useCallback(R=>{const Y=R.clipboardData?.items;if(!Y)return;const oe=[];for(const ce of Y)if(ce.kind==="file"){const pe=ce.getAsFile();pe&&oe.push(pe)}oe.length>0&&(R.preventDefault(),O(oe))},[O]),me=i.useCallback(async()=>{if(Z&&!U.current){U.current=!0,I(!0),F(!0),C.current=setTimeout(()=>{U.current&&(console.warn("[useChatInput] Audio send timed out after 30s — unlocking input"),U.current=!1,I(!1),F(!1))},E);try{const R=Z.type.includes("webm"),Y=R?"webm":Z.type.includes("mp4")?"m4a":"ogg",oe=R?"audio/webm":Z.type,ce=new File([Z],`audio_${Date.now()}.${Y}`,{type:oe}),pe=await Ce.uploadMedia(ce);await t("","AUDIO",{mediaUrl:pe.signedUrl,gcsPath:pe.gcsPath,mediaMimeType:pe.mimeType,fileSize:pe.size,fileHash:pe.hash}),ge()}catch(R){console.error("Error sending audio:",R)}finally{C.current&&(clearTimeout(C.current),C.current=null),U.current=!1,I(!1),F(!1)}}},[Z,t,ge]);return i.useEffect(()=>{be==="stopped"&&Z&&me()},[be,Z,me]),{message:p,setMessage:f,mode:g,setMode:v,isSending:h,isUploading:M||G,attachments:W,setAttachments:q,attachPopoverOpen:_,setAttachPopoverOpen:k,showTemplateSuggestions:S,setShowTemplateSuggestions:P,templateSearchQuery:X,templateAttachment:z,setTemplateAttachment:L,replacedVariables:N,textareaRef:ee,fileInputRef:le,handleInput:je,handleSend:Q,handleKeyDown:ie,handleFileSelect:B,handlePaste:J,handleTemplateSelect:ke,startRecording:te,stopRecording:xe,cancelRecording:ge,isRecording:ue,recordingTime:D,isAudioSupported:ve,triggerFileInput:i.useCallback(R=>{le.current&&(le.current.setAttribute("accept",R),le.current.click())},[]),uploadFeedback:de,uploadProgress:Ae,inactivityActive:y}};async function ru(t){const s=t.type.startsWith("image/"),a=t.type.startsWith("video/"),r=t.type.startsWith("audio/");return s?new Promise(n=>{const o=new Image;o.onload=()=>{const l={width:o.width,height:o.height};n(l),URL.revokeObjectURL(o.src)},o.onerror=()=>n({}),o.src=URL.createObjectURL(t)}):a||r?new Promise(n=>{const o=document.createElement(a?"video":"audio");o.onloadedmetadata=()=>{const l={duration:o.duration};a&&(l.width=o.videoWidth,l.height=o.videoHeight),n(l),URL.revokeObjectURL(o.src)},o.onerror=()=>n({}),o.src=URL.createObjectURL(t)}):{}}const Hi=i.memo(()=>e.jsxs("div",{className:T("inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md","bg-emerald-100/80 dark:bg-emerald-500/20 text-emerald-700 dark:text-emerald-400","border border-emerald-200/50 dark:border-emerald-500/30","text-[9px] font-bold uppercase tracking-wider select-none shadow-sm backdrop-blur-[2px]"),children:[e.jsx(La,{className:"w-2.5 h-2.5 fill-current"}),e.jsx("span",{children:"Cloud Reused"})]}));Hi.displayName="CloudReusedBadge";const fn=t=>t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`,Gi=i.memo(({attachment:t,onRemove:s})=>{const{file:a,isDuplicate:r}=t,[n,o]=i.useState(null),l=x=>new Promise((b,y)=>{const p=document.createElement("video");p.preload="metadata",p.src=URL.createObjectURL(x),p.muted=!0,p.playsInline=!0,p.currentTime=1,p.onloadeddata=()=>{const f=document.createElement("canvas");f.width=p.videoWidth,f.height=p.videoHeight,f.getContext("2d")?.drawImage(p,0,0,f.width,f.height);const v=f.toDataURL("image/jpeg",.7);URL.revokeObjectURL(p.src),b(v)},p.onerror=f=>{URL.revokeObjectURL(p.src),y(f)}});i.useEffect(()=>{const x=a.type.startsWith("image/"),b=a.type.startsWith("video/"),y=a.type.startsWith("audio/");let p=null;return x||y?(p=URL.createObjectURL(a),o(p)):b&&l(a).then(o).catch(()=>o(null)),()=>{p&&(x||y)&&URL.revokeObjectURL(p)}},[a]);const c=a.type.startsWith("image/"),u=a.type.startsWith("video/"),d=a.type.startsWith("audio/"),m=[`Nombre: ${a.name}`,`Tamaño: ${fn(a.size)}`,`Tipo: ${a.type||"Desconocido"}`,r?"✨ Ya disponible en el servidor (no requiere subida)":"Pendiente de subida"].join(`
|
|
6
|
-
`);return e.jsx(rs,{children:e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsxs("div",{className:"relative group border border-gray-100 dark:border-gray-800 rounded-xl p-1.5 bg-white dark:bg-gray-900 flex items-center gap-2.5 pr-3 cursor-default transition-all hover:shadow-md hover:border-gray-200 dark:hover:border-gray-700 shadow-sm ring-1 ring-black/5 dark:ring-white/5",children:[c&&n?e.jsx("div",{className:"w-10 h-10 rounded-lg bg-gray-100 dark:bg-gray-700 overflow-hidden shrink-0 border border-black/5 dark:border-white/10 relative shadow-sm",children:e.jsx("img",{src:n,alt:"Preview",className:"w-full h-full object-cover"})}):u&&n?e.jsxs("div",{className:"w-10 h-10 rounded-lg bg-slate-100 dark:bg-slate-800 overflow-hidden shrink-0 border border-black/5 dark:border-white/10 relative group/thumb shadow-sm",children:[e.jsx("img",{src:n,alt:"Video Preview",className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 backdrop-blur-[0.5px] group-hover/thumb:bg-black/40 transition-colors",children:e.jsx("div",{className:"w-6 h-6 rounded-full bg-white/20 backdrop-blur-md flex items-center justify-center text-white border border-white/30 shadow-sm transition-transform group-hover/thumb:scale-110",children:e.jsx(et,{className:"w-3 h-3 fill-current ml-0.5"})})}),r&&e.jsx("div",{className:"absolute top-0.5 right-0.5 bg-[#195aec] text-white p-0.5 rounded-full shadow-sm ring-1 ring-white/20 z-10",children:e.jsx(eo,{className:"w-2.5 h-2.5"})})]}):d&&n?e.jsx("div",{className:"w-10 h-10 rounded-lg bg-emerald-50 dark:bg-emerald-900/20 flex items-center justify-center shrink-0 border border-emerald-100 dark:border-emerald-900/40 relative shadow-sm",children:e.jsx(vs,{className:"w-5 h-5 text-emerald-600 dark:text-emerald-400"})}):e.jsx("div",{className:"w-10 h-10 rounded-lg bg-gray-50 dark:bg-gray-800 flex items-center justify-center shrink-0 border border-gray-100 dark:border-gray-700 relative shadow-sm",children:e.jsx(tt,{className:"w-5 h-5 text-gray-400"})}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("div",{className:"text-[13px] text-gray-700 dark:text-gray-200 max-w-[140px] truncate font-semibold leading-tight",children:a.name}),e.jsxs("div",{className:"text-[10px] text-gray-400 font-medium",children:[fn(a.size)," • ",a.type.split("/")[1]?.toUpperCase()||"FILE"]})]}),r&&e.jsx("div",{className:"ml-2 animate-in fade-in zoom-in duration-300",children:e.jsx(Hi,{})}),e.jsx("button",{onClick:s,className:"absolute -top-1.5 -right-1.5 bg-gray-900 dark:bg-gray-100 text-white dark:text-gray-900 rounded-full p-1 hover:bg-red-500 dark:hover:bg-red-500 hover:text-white dark:hover:text-white transition-all shadow-md opacity-0 group-hover:opacity-100 scale-90 group-hover:scale-100 z-10 ring-2 ring-white dark:ring-gray-900",children:e.jsx(Ge,{className:"w-3 h-3"})})]})}),e.jsx(Re,{side:"top",className:"max-w-xs whitespace-pre-line text-[11px] p-2",children:m})]})})});Gi.displayName="AttachmentPreview";const Wi=i.memo(({content:t,replacedVariables:s})=>{if(s.length===0)return null;const a=[];return s.forEach(r=>{a.push({value:r.value,label:r.variable})}),e.jsxs("div",{className:"mx-3 mb-2 p-2 bg-primary/5 border border-primary/20 rounded-lg text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-primary/70 font-medium mb-1",children:[e.jsx(Is,{className:"w-3 h-3"}),e.jsx("span",{children:"Variables reemplazadas automáticamente"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:a.map((r,n)=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-primary/10 text-primary rounded-full",title:`{{${r.label}}}`,children:[e.jsx("span",{className:"font-medium",children:r.value}),e.jsxs("span",{className:"text-[10px] text-primary/60",children:["← ",r.label.split(".").pop()]})]},n))})]})});Wi.displayName="TemplatePreview";function nu({payload:t,carousel:s,templateName:a,onRemove:r}){const[n,o]=i.useState(!1),l=s.cards.length,c=s.cards.slice(0,3);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative group border border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-900/20 rounded-lg p-2 pr-8 flex items-center gap-3 min-w-[240px] max-w-[280px] shadow-sm animate-in fade-in slide-in-from-bottom-1 duration-300",children:[e.jsxs("button",{type:"button",onClick:()=>o(!0),className:"flex items-center gap-3 min-w-0 flex-1 text-left",children:[e.jsx("div",{className:"flex -space-x-2 shrink-0",children:c.map((u,d)=>u.imageUrl?e.jsx("img",{src:u.imageUrl,alt:"",className:"w-9 h-9 rounded-md object-cover ring-2 ring-white dark:ring-gray-900"},d):e.jsx("div",{className:"w-9 h-9 rounded-md bg-blue-100 dark:bg-blue-800 flex items-center justify-center ring-2 ring-white dark:ring-gray-900",children:e.jsx(We,{className:"w-4 h-4 text-blue-400"})},d))}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[a&&e.jsx("span",{className:"text-xs font-bold text-blue-700 dark:text-blue-300 truncate max-w-[150px]",children:a}),e.jsxs("span",{className:"text-[11px] text-blue-600 dark:text-blue-400 truncate",children:["Carrusel · ",l," ",l===1?"tarjeta":"tarjetas"]}),e.jsxs("span",{className:"text-[10px] text-blue-500/80 dark:text-blue-400/80 flex items-center gap-1",children:[e.jsx(za,{className:"w-3 h-3"})," Ver vista previa"]})]})]}),r&&e.jsx("button",{onClick:r,className:"absolute top-1 right-1 p-1 hover:bg-red-100 dark:hover:bg-red-900/30 rounded-full text-blue-400 hover:text-red-500 transition-colors",title:"Quitar plantilla",children:e.jsx(Ge,{className:"w-3.5 h-3.5"})})]}),e.jsx(yt,{open:n,onOpenChange:o,children:e.jsxs(jt,{className:"sm:max-w-[540px]",onInteractOutside:u=>{document.querySelector("[data-lightbox-overlay]")&&u.preventDefault()},onEscapeKeyDown:u=>{document.querySelector("[data-lightbox-overlay]")&&u.preventDefault()},children:[e.jsxs(Ut,{children:[e.jsx(vt,{children:"Vista previa del carrusel"}),e.jsx(Rt,{children:"Así se verá el mensaje en WhatsApp."})]}),e.jsx("div",{className:"rounded-xl bg-[#efeae2] dark:bg-[#0b141a] p-4 max-h-[70vh] overflow-y-auto",children:e.jsx(qs,{content:t,disabled:!0})})]})})]})}function iu(t){const s=String(t?.type||"").toLowerCase();if(s!=="image"&&s!=="video"&&s!=="document")return null;const a=t.mediaUrl,r=t.mediaOriginalName;return s==="image"?a?e.jsx("img",{src:a,alt:r||"Header media",className:"w-full h-32 object-cover bg-gray-100 dark:bg-gray-900"}):e.jsx("div",{className:"w-full h-32 bg-gray-100 dark:bg-gray-900 flex items-center justify-center text-gray-400",children:e.jsx(We,{className:"w-8 h-8"})}):s==="video"?e.jsx("div",{className:"w-full h-32 bg-gradient-to-br from-purple-100 to-blue-100 dark:from-purple-900/30 dark:to-blue-900/30 relative flex items-center justify-center",children:e.jsx("div",{className:"bg-black/40 rounded-full p-2",children:e.jsx(et,{className:"w-6 h-6 text-white"})})}):e.jsxs("div",{className:"bg-gray-50 dark:bg-gray-900 px-3 py-2 flex items-center gap-2 border-b border-gray-100 dark:border-gray-700",children:[e.jsx(tt,{className:"w-5 h-5 text-blue-500 shrink-0"}),e.jsx("span",{className:"text-[12px] truncate text-gray-700 dark:text-gray-300",children:r||"Documento"})]})}function lu(t){if(t==null)return null;if(typeof t=="string")return e.jsx("span",{children:t});if(typeof t!="object")return null;const s=String(t.type||"").toLowerCase();if(s==="text"||s==="string"){const a=(t.text||"").trim();return a?e.jsx("span",{children:a}):null}return null}const Qi=i.memo(({interactiveContent:t,templateName:s,onRemove:a})=>{try{const r=JSON.parse(t),n=ti(r);if(n)return e.jsx(nu,{payload:r,carousel:n,templateName:s,onRemove:a});const{type:o="buttons",body:l,buttons:c=[],sections:u,menuButton:d,header:m,footer:x}=r,b=iu(m),y=b?null:lu(m),p=Array.isArray(u)?u.flatMap(g=>Array.isArray(g?.rows)?g.rows:[]):[],f=String(o).toLowerCase()==="list"||p.length>0||!!d;return e.jsxs("div",{className:"flex flex-col gap-1.5 w-full max-w-[280px] animate-in fade-in slide-in-from-bottom-1 duration-300",children:[e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-xl border border-gray-100 dark:border-gray-700 shadow-sm overflow-hidden flex flex-col",children:[b,y&&e.jsx("div",{className:"px-3 pt-2.5 pb-1 font-bold text-[13px] text-blue-600 dark:text-blue-400 border-b border-gray-50/50 dark:border-gray-700/30",children:y}),e.jsx("div",{className:"px-3 py-2.5 text-[13px] text-gray-700 dark:text-gray-300 leading-relaxed font-medium",children:l||"Sin contenido"}),x&&e.jsx("div",{className:"px-3 pb-2.5 text-[10px] text-gray-400 dark:text-gray-500 font-normal",children:x}),f&&e.jsxs("div",{className:"border-t border-gray-100 dark:border-gray-700",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 px-3 py-2 text-[12px] font-semibold text-blue-600 dark:text-blue-400 border-b border-gray-50 dark:border-gray-700/40",children:[e.jsx(as,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:d?.trim()||"Ver opciones"})]}),p.length>0?e.jsx("div",{className:"max-h-[180px] overflow-y-auto",children:p.map((g,v)=>e.jsxs("div",{className:"px-3 py-2 border-b border-gray-50 dark:border-gray-700/40 last:border-b-0",children:[e.jsx("p",{className:"text-[12px] font-medium text-gray-800 dark:text-gray-100 truncate",children:g.title||g.label||`Opción ${v+1}`}),(g.description||"").trim()&&e.jsx("p",{className:"text-[10px] text-gray-400 dark:text-gray-500 truncate",children:g.description})]},g.id||v))}):e.jsx("p",{className:"px-3 py-2 text-[11px] text-gray-400 dark:text-gray-500 italic",children:"Sin opciones configuradas"})]})]}),!f&&e.jsx("div",{className:"flex flex-col gap-1 w-full",children:c.map((g,v)=>e.jsxs("div",{className:T("group relative overflow-hidden bg-white dark:bg-gray-800 py-2.5 px-3 text-center rounded-xl border border-gray-100 dark:border-gray-700 shadow-sm transition-all","text-[12px] font-semibold text-blue-600 dark:text-blue-400"),children:[e.jsx("span",{className:"relative z-10",children:g.title||g.text||"Botón"}),e.jsx("div",{className:"absolute inset-0 bg-blue-50/50 dark:bg-blue-400/5 opacity-0 group-hover:opacity-100 transition-opacity"})]},g.id||v))})]})}catch{return e.jsxs("div",{className:"p-3 bg-red-50 dark:bg-red-900/20 border border-red-100 dark:border-red-900/30 rounded-lg text-[11px] text-red-500 flex items-center gap-2",children:[e.jsx(ws,{className:"w-4 h-4"}),"Error al renderizar preview interactiva"]})}});Qi.displayName="InteractiveTemplatePreview";const ou=t=>{switch(t){case"TEXT":return e.jsx(tt,{className:"w-4 h-4"});case"IMAGE":return e.jsx(We,{className:"w-4 h-4"});case"VIDEO":return e.jsx(et,{className:"w-4 h-4"});case"INTERACTIVE":return e.jsx(ws,{className:"w-4 h-4"});default:return e.jsx(tt,{className:"w-4 h-4"})}},cu=t=>{switch(t){case"TEXT":return"text-blue-500 bg-blue-50 dark:bg-blue-950/30";case"IMAGE":return"text-green-500 bg-green-50 dark:bg-green-950/30";case"VIDEO":return"text-purple-500 bg-purple-50 dark:bg-purple-950/30";case"INTERACTIVE":return"text-amber-500 bg-amber-50 dark:bg-amber-950/30";default:return"text-gray-500 bg-gray-50 dark:bg-gray-950/30"}},Ki=i.memo(({onSelect:t,activeChannel:s,isOpen:a,autoFocusSearch:r=!0})=>{const[n,o]=i.useState(""),[l,c]=i.useState(null);i.useEffect(()=>{a&&(o(""),c(null))},[a]);const{data:u=[]}=Jn(),{data:d=[],isLoading:m}=ei({query:n,categoryId:l||void 0,enabled:a,limit:20,channelType:s?.type});return e.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[e.jsxs("div",{className:"shrink-0 px-6 py-3 space-y-3 border-b border-gray-100 dark:border-gray-800",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Bt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(Te,{placeholder:"Buscar plantilla...",value:n,onChange:x=>o(x.target.value),className:"pl-9 h-9 text-sm bg-gray-50 dark:bg-gray-900 border-gray-200 dark:border-gray-700",autoFocus:r})]}),u.length>0&&e.jsxs("div",{className:"flex gap-1.5 overflow-x-auto scrollbar-hide",children:[e.jsx("button",{onClick:()=>c(null),className:T("px-3 py-1 text-xs font-medium rounded-full transition-all whitespace-nowrap",l===null?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-gray-100 dark:hover:bg-gray-800"),children:"Todas"}),u.map(x=>e.jsxs("button",{onClick:()=>c(l===x.id?null:x.id),className:T("px-3 py-1 text-xs font-medium rounded-full transition-all whitespace-nowrap flex items-center gap-1.5",l===x.id?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-gray-100 dark:hover:bg-gray-800"),children:[x.color&&e.jsx("span",{className:"w-2 h-2 rounded-full",style:{backgroundColor:x.color}}),x.name]},x.id))]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"px-3 py-2",children:m?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Se,{className:"w-6 h-6 animate-spin text-primary"})}):d.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(Ys,{className:"w-10 h-10 mb-3 opacity-40"}),e.jsx("p",{className:"text-sm font-medium",children:"No se encontraron plantillas"}),e.jsx("p",{className:"text-xs mt-1 opacity-70",children:n?"Intenta con otra busqueda":"Crea plantillas desde el menu de Plantillas"})]}):e.jsx("div",{className:"space-y-1",children:d.map(x=>e.jsx(Yi,{template:x,onClick:()=>t(x)},x.id))})})})]})});Ki.displayName="NubotTemplateList";const Yi=i.memo(({template:t,onClick:s})=>e.jsx("button",{onClick:s,className:"w-full text-left px-3 py-3 rounded-lg transition-all group hover:bg-gray-50 dark:hover:bg-gray-800/50 border border-transparent hover:border-gray-200 dark:hover:border-gray-700 cursor-pointer",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:T("w-8 h-8 rounded-lg flex items-center justify-center shrink-0 mt-0.5",cu(t.contentType)),children:ou(t.contentType)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-0.5 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:t.name}),t.shortcut&&e.jsxs("span",{className:"text-[10px] text-primary/70 font-mono bg-primary/5 px-1.5 py-0.5 rounded",children:["/",t.shortcut]}),t.category&&e.jsxs(De,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border",children:[e.jsx(ri,{className:"w-2.5 h-2.5 mr-1"}),t.category.name]})]}),t.tags&&t.tags.length>0&&e.jsx("div",{className:"flex gap-1 mb-0.5",children:t.tags.slice(0,3).map(a=>e.jsxs("span",{className:"text-[10px] text-gray-400 bg-gray-100 dark:bg-gray-800 px-1.5 py-0.5 rounded",children:["#",a]},a))}),t.content&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:t.content})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity mt-1",children:t.contentType})]})}));Yi.displayName="NubotTemplateItem";const Gs={async getAll(t){const s=new URLSearchParams;return t?.channelId&&s.append("channelId",t.channelId),t?.status&&s.append("status",t.status),t?.category&&s.append("category",t.category),t?.qualityScore&&s.append("qualityScore",t.qualityScore),t?.search&&s.append("search",t.search),t?.sortBy&&s.append("sortBy",t.sortBy),t?.sortOrder&&s.append("sortOrder",t.sortOrder),t?.page&&s.append("page",String(t.page)),t?.limit&&s.append("limit",String(t.limit)),(await he.get(`/meta-templates${s.toString()?`?${s.toString()}`:""}`)).data},async getByChannel(t,s){const a=new URLSearchParams;s?.search&&a.set("search",s.search),s?.category&&a.set("category",s.category),s?.page&&a.set("page",String(s.page)),s?.limit&&a.set("limit",String(s.limit));const r=a.toString();return(await he.get(`/meta-templates/channels/${t}${r?`?${r}`:""}`)).data},async getById(t){return(await he.get(`/meta-templates/${t}`)).data},async create(t){return(await he.post("/meta-templates",t,{timeout:12e4})).data},async uploadMedia(t,s,a){const r=new FormData;return r.append("channelId",t),r.append("file",s),(await he.post("/meta-templates/upload-media",r,{headers:{"Content-Type":"multipart/form-data"},timeout:120*1e3,signal:a})).data},async update(t,s){return(await he.patch(`/meta-templates/${t}`,s)).data},async delete(t){await he.delete(`/meta-templates/${t}`)},async sync(t){return(await he.post("/meta-templates/sync",t,{timeout:9e4})).data},async getSampleMedia(t){return(await he.get(`/meta-templates/${t}/sample-media`,{timeout:3e4})).data},async checkStatus(t,s){return(await he.get(`/meta-templates/${t}/status`,{timeout:3e4,signal:s})).data},async syncAnalytics(t){return(await he.post(`/meta-templates/${t}/analytics`,{},{timeout:6e4})).data},async syncTemplateAnalytics(t,s){return(await he.post(`/meta-templates/${t}/analytics/${s}`,{},{timeout:3e4})).data},async syncSingle(t){return(await he.get(`/meta-templates/${t}/status`,{timeout:3e4})).data}},bn={channelId:"",status:"",category:"",search:"",qualityScore:""};yl(t=>({filters:bn,page:1,limit:20,sortBy:"createdAt",sortOrder:"DESC",selectedIds:[],density:"comfortable",selectedTemplateId:null,setFilters:s=>t(a=>({filters:{...a.filters,...s},page:1,selectedIds:[]})),setPage:s=>t({page:s,selectedIds:[]}),setLimit:s=>t({limit:s,page:1,selectedIds:[]}),resetFilters:()=>t(s=>({filters:{...bn,channelId:s.filters.channelId},page:1,selectedIds:[],sortBy:"createdAt",sortOrder:"DESC"})),setSorting:s=>t(a=>({sortBy:s,sortOrder:a.sortBy===s&&a.sortOrder==="DESC"?"ASC":"DESC",page:1})),toggleSelection:s=>t(a=>({selectedIds:a.selectedIds.includes(s)?a.selectedIds.filter(r=>r!==s):[...a.selectedIds,s]})),selectAll:s=>t({selectedIds:s}),clearSelection:()=>t({selectedIds:[]}),setDensity:s=>t({density:s}),setSelectedTemplate:s=>t({selectedTemplateId:s})}));const Xt={all:["meta-templates"],lists:()=>[...Xt.all,"list"],list:t=>[...Xt.lists(),t],details:()=>[...Xt.all,"detail"],detail:t=>[...Xt.details(),t],byChannel:t=>[...Xt.all,"channel",t]};function du(t){return rt({queryKey:t?Xt.byChannel(t):["meta-templates","channel","none"],queryFn:()=>t?Gs.getByChannel(t):null,enabled:!!t,staleTime:120*1e3})}function uu(t,s,a){return t?.cards?.length?t.cards.map((r,n)=>{const o=[],l=(r.components||[]).find(x=>String(x.type||"").toUpperCase()==="HEADER"),c=(r.components||[]).find(x=>String(x.type||"").toUpperCase()==="BODY"),u=(r.components||[]).find(x=>String(x.type||"").toUpperCase()==="BUTTONS"),d=s[n];if(l&&d){const x=String(l.format||"IMAGE").toLowerCase(),b={};d.gcsPath?b.link=d.gcsPath:d.signedUrl?b.link=d.signedUrl:d.previewUrl&&!a?.temporaryConnection?b.link=d.previewUrl:d.link&&(b.link=d.link),b.link&&(x==="image"||x==="video")&&o.push({type:"header",parameters:[{type:x,[x]:b}]})}const m=Oi(c?.text,Mi(c?.text,a?.perCardBodyValues?.[n]??[],{omitMissing:!0}),{missing:x=>`{{${x}}}`});return m&&o.push(m),u?.buttons?.length&&(u.buttons||[]).forEach((x,b)=>{const y=String(x.type||"").toUpperCase(),p=y==="QUICK_REPLY"?"quick_reply":y==="URL"?"url":y==="PHONE_NUMBER"?"phone_number":null;p&&o.push({type:"button",sub_type:p,index:b,parameters:[]})}),{card_index:n,components:o}}):[]}const mu={"contact.name":30,"contact.phone":15,"contact.email":40,"contact.tags":50},xu=60;function hu(t){return/\{\{.+?\}\}/.test(t)}function ra(t){if(!t)return 0;if(!hu(t))return t.length;let s=0,a=0;const r=/\{\{(.+?)\}\}/g;let n;for(;(n=r.exec(t))!==null;){s+=n.index-a;const o=n[1].trim();s+=mu[o]??xu,a=n.index+n[0].length}return s+=t.length-a,s}const xr={HEADER_TEXT:60,BODY_TEXT:1024,FOOTER_TEXT:60,BUTTON_TEXT:25,PARAM_VALUE:1024},yn={...xr},pu={HEADER_TEXT:256,BODY_TEXT:4096,FOOTER_TEXT:256,BUTTON_TEXT:40,PARAM_VALUE:4096},gu={WHATSAPP:xr,INSTAGRAM:yn,FACEBOOK:yn,WEB:pu};function fu(t){return gu[t.toUpperCase()]??xr}function bu(t,s){if(!t)return 0;const a=t.replace(/\{\{[^}]+\}\}/g,"").length,r=ud(t),n=Object.entries(r).reduce((o,[l,c])=>o+ra(s[l]||"")*c,0);return a+n}function Ss(t){if(!t||!t.type)return!1;const s=t.type.toUpperCase();return s==="WHATSAPP"||s==="WHATSAPP_BUSINESS"}const Fs=us;function fa(t){let s=[],a=[];const r=t.components;if(Array.isArray(r)){const n=r.find(l=>l.type==="HEADER"),o=r.find(l=>l.type==="BODY");n?.text&&n.format==="TEXT"&&(s=Fs(n.text)),o?.text&&(a=Fs(o.text))}else{const n=r;n.header?.text&&n.header?.type==="TEXT"&&(s=Fs(n.header.text)),n.body?.text&&(a=Fs(n.body.text))}return{headerVars:s,bodyVars:a,totalVars:s.length+a.length}}function ba(t){const s=t.components;if(Array.isArray(s)){const r=s.find(n=>n.type==="HEADER");return r?{type:r.format||"TEXT",text:r.text}:null}const a=s;return a?.header?{type:a.header.type||a.header.format||"TEXT",text:a.header.text}:null}function ya(t){const s=t.components;return Array.isArray(s)?s.find(a=>a.type==="BODY")?.text||"":s?.body?.text||""}function hr(t){const s=ba(t);return s?["IMAGE","VIDEO","DOCUMENT"].includes(s.type):!1}function yu(t,s,a,r,n,o){const l=[],{headerVars:c,bodyVars:u}=fa(t),d=ba(t);if(d&&["IMAGE","VIDEO","DOCUMENT"].includes(d.type)&&(r?.gcsPath||r?.id||r?.signedUrl)){const x={},b=d.type.toLowerCase();x.type=b,r?.gcsPath?x[b]={link:r.gcsPath}:r?.id?x[b]={id:r.id}:r?.signedUrl&&(x[b]={link:r.signedUrl}),l.push({type:"header",parameters:[x]})}else if(c.length>0){const x=xd(d?.text,s);x&&l.push(x)}if(u.length>0){const x=Oi(ya(t),a);x&&l.push(x)}const m=(t.components||[]).find(x=>String(x.type||"").toUpperCase()==="CAROUSEL");if(m){const x=uu(m,n||{},{perCardBodyValues:o});x.length>0&&l.push({type:"carousel",cards:x})}return l}function ju(t,s,a,r,n,o){const l=yu(t,s,a,r,n,o);return{metaTemplateId:t.id,components:l.length>0?l:void 0,variables:{header:{...s},body:{...a}},headerGcsPath:r?.gcsPath||void 0,headerMediaType:r?.detectedType||void 0,headerThumbnailUrl:r?.thumbnailUrl||void 0}}function vu({channelId:t,ticketId:s,previewContext:a,resolveTicketId:r}){const[n,o]=i.useState(!1),[l,c]=i.useState(""),[u,d]=i.useState(""),[m,x]=i.useState(null),[b,y]=i.useState({}),[p,f]=i.useState({}),[g,v]=i.useState(null),[h,I]=i.useState({}),[U,C]=i.useState({}),[E,M]=i.useState(!1),F=it(),_=i.useCallback(B=>["meta-template-sample-media",B],[]),k=i.useCallback(B=>B?.components?B.components.some(J=>J?.type==="HEADER"&&["IMAGE","VIDEO","DOCUMENT"].includes(J?.format)):!1,[]),{data:W,isFetching:q}=rt({queryKey:m?.id?_(m.id):["meta-template-sample-media","none"],queryFn:()=>Gs.getSampleMedia(m.id),enabled:!!m?.id&&k(m),staleTime:1380*60*1e3,gcTime:1440*60*1e3,retry:1});i.useEffect(()=>{if(!E){if(!W){g&&v(null);return}v({gcsPath:W.gcsPath,signedUrl:W.signedUrl,mimeType:W.mimeType,detectedType:W.detectedType,thumbnailUrl:W.thumbnailUrl??void 0})}},[W,E]);const{uploadState:ee,error:le,uploadFile:S,reset:P,isUploading:X,feedback:A}=nr({channelId:t||void 0}),{data:z,isLoading:L}=du(t),N=i.useMemo(()=>z?.data||[],[z]),w=z?.total??0,$=z!=null&&N.length>=w,ae=po(l,400),ne=!$&&ae.length>=2,{data:re,isLoading:be}=rt({queryKey:["meta-templates","channel-search",t,ae,u],queryFn:()=>Gs.getByChannel(t,{search:ae,category:u||void 0}),enabled:!!t&&ne,placeholderData:B=>B,staleTime:3e4}),D=L||ne&&be,{data:Z}=rt({queryKey:["metadata-schema",t],queryFn:()=>t?ar.getSchemaForChannel(t):null,enabled:!!t,staleTime:300*1e3}),te=i.useMemo(()=>fu("WHATSAPP"),[]),xe=w,ge=i.useMemo(()=>ne?re?.data||N:N.filter(B=>{const J=!l||B.name.toLowerCase().includes(l.toLowerCase()),me=!u||B.category===u;return J&&me}),[ne,re,N,l,u]),ve=i.useMemo(()=>{if(!m)return null;const B=ya(m);if(!B)return null;const me=B.replace(/\{\{[^}]+\}\}/g,"").length,R=te.BODY_TEXT,Y=R-me,oe=bu(B,p),ce=oe-me;return{staticLength:me,budgetForVars:Y,consumedByVars:ce,totalUsed:oe,totalBudget:R,exceeded:oe>R}},[m,p,te]),V=i.useCallback(async B=>{if(t)try{const me=await S(B,async(R,Y)=>{const oe=await Gl.uploadMedia(t,R,Y);return{id:oe.id,gcsPath:oe.gcsPath||"",signedUrl:"",mimeType:R.type,size:R.size,hash:oe.hash||Y,originalHash:Y,isOptimized:!1}});me&&(M(!0),v({id:me.id,detectedType:me.mimeType.startsWith("image/")?"IMAGE":me.mimeType.startsWith("video/")?"VIDEO":"DOCUMENT",previewUrl:URL.createObjectURL(B),signedUrl:me.signedUrl||"",mimeType:me.mimeType,originalName:B.name,gcsPath:me.gcsPath}))}catch(J){console.error("[MetaTemplatePicker] Media upload failed:",J);const me=J?.response?.status===403?"No tienes permisos para subir archivos en este canal":J?.message||"Error al subir archivo. Intenta de nuevo.";H.error("Error al subir archivo",{description:me})}},[t,S]),j=i.useCallback(()=>{v(null),I({}),C({}),M(!1),P()},[P]),G=i.useCallback(B=>{F.prefetchQuery({queryKey:_(B),queryFn:()=>Gs.getSampleMedia(B),staleTime:1380*60*1e3,gcTime:1440*60*1e3})},[F,_]),se=xt({mutationFn:async()=>{if(!m)throw new Error("No template selected");const B=(pe,Ne="")=>{if(!pe)return{};const Ve={};for(const[_e,ye]of Object.entries(pe))ye&&typeof ye=="object"&&!Array.isArray(ye)?Object.assign(Ve,B(ye,`${Ne}${_e}.`)):ye!=null&&(Ve[`${Ne}${_e}`]=String(ye));return Ve},J=B(s?a:void 0);let me=!1;const R=pe=>{let Ne=pe||"";return Ne=Ne.replace(/\{\{([a-zA-Z0-9_.]+)\}\}/g,(Ve,_e)=>{const ye=J[_e];return ye!==void 0&&ye!==""?ye:(me=!0,"-")}),!Ne||Ne.trim()===""?"-":Ne},Y=Object.fromEntries(Object.entries(b).map(([pe,Ne])=>[pe,R(Ne)])),oe=Object.fromEntries(Object.entries(p).map(([pe,Ne])=>[pe,R(Ne)])),ce=r?await r():s;return{hasMissingVars:me,response:await Ce.sendMetaTemplate(ce,ju(m,Y,oe,g,h,U))}},onSuccess:B=>{B.response.success?(H.success("Plantilla Meta enviada",{description:`"${m?.name}" enviada correctamente`}),B.hasMissingVars&&H.warning("Datos faltantes",{description:'Algunas variables no tenían información en el contacto y se rellenaron con "-"'}),Ae()):H.error("Error al enviar plantilla",{description:B.response.error||"Error desconocido"})},onError:B=>{if(B?.name==="ResumeRedirectedError"){Ae();return}B?.__resumeToasted||H.error("Error al enviar plantilla",{description:B?.response?.data?.message||B?.message||"Error inesperado"})}}),de=i.useCallback(()=>{o(!0),c(""),d(""),x(null),y({}),f({}),v(null),I({}),C({}),M(!1),P()},[P]),Ae=i.useCallback(()=>{o(!1),x(null),y({}),f({}),v(null),I({}),C({}),M(!1),P()},[P]),ue=i.useCallback(B=>{x(B),y({}),f({}),v(null),I({}),C({}),M(!1),P()},[P]),je=i.useCallback(()=>{x(null),y({}),f({}),v(null),I({}),C({}),M(!1),P()},[P]),ke=i.useCallback((B,J)=>{y(me=>({...me,[B]:J}))},[]),Q=i.useCallback((B,J)=>{f(me=>({...me,[B]:J}))},[]),ie=i.useCallback(()=>{se.mutate()},[se]),O=i.useMemo(()=>{if(!m)return!1;const{headerVars:B,bodyVars:J,totalVars:me}=fa(m);if(hr(m)&&!g?.gcsPath&&!g?.id&&!g?.signedUrl)return!1;const oe=(m.components||[]).find(Ve=>String(Ve.type||"").toUpperCase()==="CAROUSEL")?.cards||[];if(oe.length>0&&(!oe.every((ye,Qe)=>{if(!(ye.components||[]).some(_t=>String(_t.type||"").toUpperCase()==="HEADER"))return!0;const ze=h[Qe];return!!(ze?.gcsPath||ze?.id||ze?.signedUrl)})||!oe.every((ye,Qe)=>{const st=(ye.components||[]).find(Ke=>String(Ke.type||"").toUpperCase()==="BODY"),ze=us(st?.text).length,_t=U[Qe]||[];for(let Ke=0;Ke<ze;Ke++)if(!_t[Ke]?.trim())return!1;return!0})))return!1;if(me===0)return!0;const ce=B.every(Ve=>b[Ve]?.trim()),pe=J.every(Ve=>p[Ve]?.trim());return ve?.exceeded||J.some(Ve=>ra(p[Ve]||"")>te.PARAM_VALUE)?!1:ce&&pe},[m,b,p,g,h,U,ve,te]);return{isOpen:n,search:l,categoryFilter:u,selectedTemplate:m,headerValues:b,bodyValues:p,isReady:O,templates:ge,totalApproved:xe,isLoading:D,isSending:se.isPending,templateLimits:te,bodyBudget:ve,headerMediaData:g,mediaUploadState:ee,mediaUploadError:le,mediaUploadFeedback:A,isMediaUploading:X,isPrefillingMedia:q,handleMediaUpload:V,handleRemoveMedia:j,carouselMediaData:h,setCarouselMediaData:I,carouselBodyValues:U,setCarouselBodyValues:C,handleOpen:de,handleClose:Ae,handleSelectTemplate:ue,handleBack:je,handleSetHeaderValue:ke,handleSetBodyValue:Q,handleSend:ie,setSearch:c,setCategoryFilter:d,metadataSchema:Z,prefetchSampleMedia:G}}function Nu({onSelect:t,metadataSchema:s,contactMetadataRecord:a}){const[r,n]=i.useState(!1),o=[{value:"contact.name",label:"Nombre"},{value:"contact.phone",label:"Teléfono"},{value:"contact.email",label:"Email"}],l=i.useMemo(()=>s?.fields?s.fields.map(m=>({value:`contact.metadata.${m.key}`,label:m.label||m.key})):[],[s]),c=i.useMemo(()=>{if(!a)return[];const m=new Set(s?.fields?.map(x=>x.key)||[]);return Object.keys(a).filter(x=>!m.has(x)).map(x=>({value:`contact.metadata.${x}`,label:x}))},[a,s]),u=[{value:"contact.tags",label:"Etiquetas (Lista)"}],d=m=>{const x=`{{${m}}}`;t(x),n(!1)};return e.jsxs(Xe,{open:r,onOpenChange:n,children:[e.jsx(Ze,{asChild:!0,children:e.jsx(K,{variant:"outline",role:"combobox","aria-expanded":r,className:"h-9 w-9 p-0 shrink-0 text-muted-foreground hover:text-foreground",title:"Insertar Variable",children:e.jsx(Ul,{className:"h-4 w-4"})})}),e.jsx(Je,{className:"w-[300px] p-0",align:"start",children:e.jsxs(At,{children:[e.jsx(Mt,{placeholder:"Buscar variable..."}),e.jsxs(Dt,{children:[e.jsx(Ot,{children:"No se encontraron variables."}),e.jsx(Be,{heading:"Datos de Contacto",children:o.map(m=>e.jsxs(Le,{value:m.value,onSelect:()=>d(m.value),children:[e.jsx(Ie,{className:T("mr-2 h-4 w-4 opacity-0")}),e.jsx("span",{children:m.label}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground font-mono",children:`{{${m.value}}}`})]},m.value))}),e.jsx(Et,{}),l.length>0&&e.jsx(Be,{heading:"Metadatos en Esquema",children:l.map(m=>e.jsxs(Le,{value:m.value,onSelect:d,className:"flex justify-between",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-muted-foreground font-mono text-xs",children:`{{${m.value}}}`})]},m.value))}),c.length>0&&e.jsx(Be,{heading:"Campos Adicionales",children:c.map(m=>e.jsxs(Le,{value:m.value,onSelect:d,className:"flex justify-between",children:[e.jsx("span",{children:m.label}),e.jsx("span",{className:"text-muted-foreground font-mono text-xs",children:`{{${m.value}}}`})]},m.value))}),l.length===0&&c.length===0&&e.jsx(Be,{heading:"Metadatos Personalizados",children:e.jsx("div",{className:"px-2 py-3 text-xs text-muted-foreground italic",children:"No hay columnas personalizadas ni campos adicionales."})}),e.jsx(Et,{}),e.jsx(Be,{heading:"Otros",children:u.map(m=>e.jsxs(Le,{value:m.value,onSelect:()=>d(m.value),children:[e.jsx(Ie,{className:"mr-2 h-4 w-4 opacity-0"}),e.jsx("span",{children:m.label}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground font-mono",children:`{{${m.value}}}`})]},m.value))})]})]})})]})}function jn({className:t,value:s,onChange:a,metadataSchema:r,contactMetadataRecord:n,...o}){const l=c=>{const u=s+c;a({target:{value:u},currentTarget:{value:u}})};return e.jsxs("div",{className:T("flex w-full items-center gap-2",t),children:[e.jsx(Te,{value:s,onChange:a,className:"flex-1",...o}),e.jsx(Nu,{onSelect:l,metadataSchema:r,contactMetadataRecord:n})]})}function wu({used:t,limit:s,label:a,showBar:r=!1,className:n}){const o=s>0?t/s:0,l=t>s,c=l?"text-rose-600 dark:text-rose-400":o>.95?"text-rose-500 dark:text-rose-400":o>.8?"text-amber-600 dark:text-amber-400":"text-slate-400 dark:text-slate-500",u=l?"bg-rose-500":o>.95?"bg-rose-400":o>.8?"bg-amber-400":"bg-emerald-400";return e.jsxs("div",{className:T("flex flex-col gap-0.5",n),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[a&&e.jsx("span",{className:"text-[10px] text-slate-400 dark:text-slate-500",children:a}),e.jsxs("span",{className:T("text-[10px] font-mono tabular-nums",c),children:[t,"/",s]})]}),r&&e.jsx("div",{className:"h-1 w-full rounded-full bg-slate-100 dark:bg-slate-800 overflow-hidden",children:e.jsx("div",{className:T("h-full rounded-full transition-all duration-300",u),style:{width:`${Math.min(o*100,100)}%`}})}),l&&e.jsxs("span",{className:"text-[10px] text-rose-600 dark:text-rose-400",children:["Excede el límite por ",t-s," caracteres"]})]})}const ku=t=>{const s=t?.cards;return!Array.isArray(s)||s.length===0?[]:s.map(a=>{if(!Array.isArray(a.components))return{mediaUrl:a.mediaUrl,mediaType:a.mediaType,bodyText:a.bodyText,buttons:a.buttons};const r=a.components,n=r.find(c=>String(c.type||"").toUpperCase()==="HEADER"),o=r.find(c=>String(c.type||"").toUpperCase()==="BODY"),l=r.find(c=>String(c.type||"").toUpperCase()==="BUTTONS");return{mediaUrl:n?.example?.header_handle?.[0],mediaType:String(n?.format||"IMAGE").toUpperCase()==="VIDEO"?"VIDEO":"IMAGE",bodyText:o?.text,buttons:(l?.buttons||[]).map(c=>c.text||c.title).filter(Boolean)}})},Cu=({mode:t,selectedTemplate:s,variableValues:a=[],headerMediaData:r,contentType:n,content:o,mediaData:l,interactiveData:c,time:u,snapshot:d,compact:m=!1,previewContext:x,headerVariableValues:b=[],carousel:y})=>{const p=ku(y||d?.carousel),f=()=>p.length===0?null:e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-1 w-full max-w-[85%] self-end mt-1",children:p.map((U,C)=>e.jsxs("div",{className:"w-[150px] shrink-0 rounded-xl overflow-hidden bg-white dark:bg-[#005C4B] shadow-sm",children:[e.jsx("div",{className:"bg-slate-100 dark:bg-slate-800 h-24 flex items-center justify-center",children:U.mediaUrl?U.mediaType==="VIDEO"?e.jsx(bs,{src:U.mediaUrl,className:"w-full h-full object-cover"}):e.jsx(mt,{src:U.mediaUrl,className:"w-full h-full object-cover",alt:""}):e.jsx(We,{className:"w-6 h-6 text-slate-400"})}),e.jsxs("div",{className:"p-2 space-y-1.5",children:[U.bodyText&&e.jsx("p",{className:"text-[11px] text-[#111b21] dark:text-[#e9edef] line-clamp-3",children:U.bodyText}),(U.buttons||[]).map((E,M)=>e.jsx("div",{className:"text-center text-[11px] text-[#00a884] font-medium border-t border-slate-100 dark:border-white/10 pt-1",children:E},M))]})]},C))}),g=(U,C="")=>{if(!U)return{};const E={};for(const[M,F]of Object.entries(U))if(F&&typeof F=="object"&&!Array.isArray(F))Object.assign(E,g(F,`${C}${M}.`));else if(F!=null){const _=String(F).trim();E[`${C}${M}`]=_===""?"-":_}return E},v=g(x),h={...Zn};x&&(["contact","organization","agent","ticket","metadata"].forEach(U=>{x[U]&&Object.keys(h).forEach(C=>{C.startsWith(`${U}.`)&&(h[C]="-")})}),Object.assign(h,v));const I=()=>{if(d)return e.jsxs("div",{className:"flex flex-col items-end gap-1 w-full",children:[e.jsxs("div",{className:"bg-white dark:bg-[#005C4B] rounded-xl shadow-sm min-w-[60%] max-w-[85%] overflow-hidden self-end",children:[d.mediaType&&(()=>{const C=d.thumbnailUrl||d.mediaUrl;return e.jsx("div",{className:"bg-slate-100 dark:bg-slate-800 aspect-video flex items-center justify-center m-1 rounded-lg overflow-hidden",children:C?d.mediaType==="IMAGE"?e.jsx(mt,{src:C,className:"w-full h-full object-cover",alt:"Media"}):d.mediaType==="VIDEO"?e.jsx(bs,{src:C,className:"w-full h-full object-cover",controls:!0}):e.jsxs("div",{className:"text-xs text-slate-500 italic flex flex-col items-center gap-1",children:[e.jsx(ws,{className:"w-6 h-6 opacity-50"}),e.jsx("span",{children:"Documento"})]}):e.jsxs("div",{className:"text-xs text-slate-500 italic flex flex-col items-center gap-1",children:[e.jsx(La,{className:"w-6 h-6 opacity-50"}),e.jsx("span",{children:d.mediaType})]})})})(),d.headerText&&e.jsx("div",{className:"px-3 pt-2 font-bold text-[#111b21] dark:text-[#e9edef]",children:d.headerText}),e.jsx("div",{className:"px-3 py-2 text-[13px] text-[#111b21] dark:text-[#e9edef] whitespace-pre-wrap leading-relaxed",children:e.jsx(Lt,{content:d.resolvedContent||d.bodyText||"",context:h})}),d.footerText&&e.jsx("div",{className:"px-3 pb-1 text-[11px] text-[#667781] dark:text-[#8696a0]",children:d.footerText}),e.jsx("div",{className:"px-2 pb-1.5 flex justify-end",children:e.jsxs("span",{className:"text-[10px] text-[#667781] dark:text-[#8696a0] flex items-center gap-1",children:[u," ",e.jsx(Ie,{className:"h-2.5 w-2.5"})]})})]}),d.buttons?.map((C,E)=>e.jsx("div",{className:"bg-white dark:bg-[#005C4B] rounded-xl shadow-sm min-w-[60%] max-w-[85%] py-2.5 px-4 text-center text-[#00a884] font-medium cursor-pointer hover:bg-slate-50 dark:hover:bg-[#004b3e] transition-colors self-end mt-1",children:C},E)),f()]});if(t==="template"&&s){const C=s.components||[],E=C.find(q=>q.type==="HEADER"),M=C.find(q=>q.type==="BODY"),F=C.find(q=>q.type==="FOOTER"),_=(q,ee)=>pd(q,ee,{unresolved:"placeholder"}),k=M?.text||s.content||"",W=_(k,a);return e.jsxs("div",{className:"flex flex-col items-end gap-1 w-full",children:[e.jsxs("div",{className:"bg-white dark:bg-[#005C4B] rounded-xl shadow-sm min-w-[60%] max-w-[85%] overflow-hidden self-end",children:[E&&e.jsxs(e.Fragment,{children:[E.format==="IMAGE"&&e.jsx("div",{className:"bg-slate-100 dark:bg-slate-800 aspect-video flex items-center justify-center m-1 rounded-lg overflow-hidden",children:r?.previewUrl?e.jsx(mt,{src:r.previewUrl,className:"w-full h-full object-cover",alt:"Header"}):E.example?.header_handle?.[0]?e.jsx("img",{src:E.example.header_handle[0],className:"w-full h-full object-cover",alt:"Example"}):e.jsxs("div",{className:"text-xs text-slate-500 italic flex flex-col items-center gap-1",children:[e.jsx(We,{className:"w-6 h-6 opacity-50"}),e.jsx("span",{children:"Imagen"})]})}),E.format==="VIDEO"&&e.jsx("div",{className:"bg-slate-100 dark:bg-slate-800 aspect-video flex items-center justify-center m-1 rounded-lg overflow-hidden",children:r?.previewUrl?e.jsx(bs,{src:r.previewUrl,className:"w-full h-full object-cover",controls:!0}):e.jsxs("div",{className:"text-xs text-slate-500 italic flex flex-col items-center gap-1",children:[e.jsx(La,{className:"w-6 h-6 opacity-50"}),e.jsx("span",{children:"Video"})]})}),E.format==="DOCUMENT"&&e.jsx("div",{className:"bg-slate-100 dark:bg-slate-800 h-20 flex items-center justify-center m-1 rounded-lg",children:e.jsxs("div",{className:"text-xs text-slate-500 italic flex flex-col items-center gap-1",children:[e.jsx(ws,{className:"w-6 h-6 opacity-50"}),e.jsx("span",{children:"Documento"})]})}),E.format==="TEXT"&&e.jsx("div",{className:"px-3 pt-2 font-bold text-[#111b21] dark:text-[#e9edef]",children:e.jsx(Lt,{content:_(E.text,b),context:h})})]}),e.jsx("div",{className:"px-3 py-2 text-[13px] text-[#111b21] dark:text-[#e9edef] whitespace-pre-wrap leading-relaxed",children:e.jsx(Lt,{content:W,context:h})}),F&&F.text&&e.jsx("div",{className:"px-3 pb-1 text-[11px] text-[#667781] dark:text-[#8696a0]",children:F.text}),e.jsx("div",{className:"px-2 pb-1.5 flex justify-end",children:e.jsxs("span",{className:"text-[10px] text-[#667781] dark:text-[#8696a0] flex items-center gap-1",children:[u," ",e.jsx(Ie,{className:"h-2.5 w-2.5"})]})})]}),C.find(q=>q.type==="BUTTONS")?.buttons?.map((q,ee)=>e.jsx("div",{className:"bg-white dark:bg-[#005C4B] rounded-xl shadow-sm min-w-[60%] max-w-[85%] py-2.5 px-4 text-center text-[#00a884] font-medium cursor-pointer hover:bg-slate-50 dark:hover:bg-[#004b3e] transition-colors self-end mt-1",children:q.text||q.title},ee)),f()]})}const U=n==="INTERACTIVE"?c?.body:o;return e.jsxs("div",{className:"flex flex-col items-end gap-1 w-full",children:[e.jsxs("div",{className:"bg-white dark:bg-[#005C4B] rounded-xl shadow-sm min-w-[60%] max-w-[85%] overflow-hidden self-end",children:[n==="MEDIA"&&l&&e.jsx("div",{className:"bg-slate-100 dark:bg-slate-800 aspect-video flex items-center justify-center",children:l.detectedType==="IMAGE"?e.jsx(mt,{src:l.previewUrl||l.signedUrl,className:"w-full h-full object-cover",alt:"Preview"}):e.jsx("div",{className:"text-xs text-slate-500 italic",children:"Previsualización de Multimedia"})}),n==="INTERACTIVE"&&c?.header&&e.jsx("div",{className:"px-3 pt-3 pb-1 font-bold text-sm text-[#111b21] dark:text-[#e9edef]",children:e.jsx(Lt,{content:c.header,context:h})}),e.jsx("div",{className:"px-3 py-2 text-[13px] text-[#111b21] dark:text-[#e9edef] whitespace-pre-wrap leading-relaxed",children:e.jsx(Lt,{content:U||"",context:h})}),n==="INTERACTIVE"&&c?.footer&&e.jsx("div",{className:"px-3 pb-1 text-[11px] text-[#667781] dark:text-[#8696a0]",children:e.jsx(Lt,{content:c.footer,context:h})}),e.jsx("div",{className:"px-2 pb-1.5 flex justify-end",children:e.jsxs("span",{className:"text-[10px] text-[#667781] dark:text-[#8696a0] flex items-center gap-1",children:[u," ",e.jsx(Ie,{className:"h-2.5 w-2.5"})]})})]}),n==="INTERACTIVE"&&c?.buttons.map((C,E)=>e.jsx("div",{className:"bg-white dark:bg-[#1F2C34] py-2 px-4 text-center text-[#00A884] font-medium text-[13px] rounded-lg shadow-sm w-full max-w-[85%] self-end truncate",children:oo(C.text||"Botón",h)},E))]})};return m?e.jsx(wr,{time:u,children:I()}):e.jsxs("div",{className:"lg:col-span-5 sticky top-8 h-full flex flex-col items-center justify-start pt-10",children:[e.jsx("div",{className:"mb-6 text-center",children:e.jsx("span",{className:"bg-white/80 backdrop-blur px-3 py-1 rounded-full text-[10px] font-bold tracking-wider text-slate-400 border border-slate-200 uppercase shadow-sm",children:"Vista Previa en Vivo"})}),e.jsx(wr,{time:u,children:I()}),e.jsx("p",{className:"text-[10px] text-slate-400 text-center mt-6 max-w-xs leading-relaxed",children:"Esta vista es una aproximación. El resultado final en el dispositivo del cliente puede variar ligeramente."})]})},pr={MARKETING:{label:"Marketing",icon:Is,color:"text-emerald-600 dark:text-emerald-400",bg:"bg-emerald-50 dark:bg-emerald-950/30 border-emerald-200 dark:border-emerald-800"},UTILITY:{label:"Utilidad",icon:Qs,color:"text-blue-600 dark:text-blue-400",bg:"bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-800"},AUTHENTICATION:{label:"Auth",icon:Qs,color:"text-amber-600 dark:text-amber-400",bg:"bg-amber-50 dark:bg-amber-950/30 border-amber-200 dark:border-amber-800"}},gr=i.memo(t=>{const{selectedTemplate:s,templates:a,totalApproved:r,isLoading:n,search:o,onSearchChange:l,categoryFilter:c,onCategoryFilterChange:u,onSelectTemplate:d,onHoverTemplate:m,onBack:x,headerValues:b,bodyValues:y,onSetHeaderValue:p,onSetBodyValue:f,templateLimits:g,bodyBudget:v,headerMediaData:h,mediaUploadState:I,mediaUploadError:U,mediaUploadFeedback:C,isMediaUploading:E,onMediaUpload:M,onRemoveMedia:F,carouselMediaData:_,onCarouselMediaChange:k,carouselBodyValues:W,onCarouselBodyChange:q,isReady:ee,isSending:le,onSend:S,metadataSchema:P,contactMetadataRecord:X,previewContext:A,embedded:z=!1}=t;return s?e.jsx(Zi,{template:s,headerValues:b,bodyValues:y,onSetHeaderValue:p,onSetBodyValue:f,templateLimits:g,bodyBudget:v,headerMediaData:h,mediaUploadState:I,mediaUploadError:U,mediaUploadFeedback:C,isMediaUploading:E,onMediaUpload:M,onRemoveMedia:F,carouselMediaData:_,onCarouselMediaChange:k,carouselBodyValues:W,onCarouselBodyChange:q,onBack:x,isReady:ee,isSending:le,onSend:S,metadataSchema:P,contactMetadataRecord:X,previewContext:A}):e.jsx(Xi,{templates:a,totalApproved:r,isLoading:n,search:o,onSearchChange:l,categoryFilter:c,onCategoryFilterChange:u,onSelectTemplate:d,onHoverTemplate:m,embedded:z})});gr.displayName="MetaTemplatePickerContent";const Tu=i.memo(({isOpen:t,onClose:s,...a})=>e.jsx(yt,{open:t,onOpenChange:r=>!r&&s(),children:e.jsx(jt,{className:"sm:max-w-3xl max-h-[88vh] p-0 gap-0 overflow-hidden border-none shadow-2xl bg-white/98 dark:bg-zinc-950/98 backdrop-blur-xl",children:e.jsx(gr,{...a})})}));Tu.displayName="MetaTemplatePicker";const Xi=i.memo(({templates:t,totalApproved:s,isLoading:a,search:r,onSearchChange:n,categoryFilter:o,onCategoryFilterChange:l,onSelectTemplate:c,onHoverTemplate:u,embedded:d=!1})=>{const m=d?"div":zn.Fragment,x=d?{className:"flex flex-col h-full overflow-hidden"}:{};return e.jsxs(m,{...x,children:[!d&&e.jsxs(Ut,{className:"px-6 pt-6 pb-4 border-b border-gray-100 dark:border-gray-800",children:[e.jsxs(vt,{className:"flex items-center gap-2.5 text-lg font-semibold",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-emerald-100 dark:bg-emerald-900/40 flex items-center justify-center",children:e.jsx(lr,{className:"w-4 h-4 text-emerald-600 dark:text-emerald-400"})}),"Plantillas de WhatsApp"]}),e.jsxs(Rt,{className:"text-sm text-muted-foreground",children:[s," plantilla",s!==1?"s":""," aprobada",s!==1?"s":""," disponible",s!==1?"s":""]})]}),e.jsxs("div",{className:"shrink-0 px-6 py-3 space-y-3 border-b border-gray-100 dark:border-gray-800",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Bt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(Te,{placeholder:"Buscar plantilla...",value:r,onChange:b=>n(b.target.value),className:"pl-9 h-9 text-sm bg-gray-50 dark:bg-gray-900 border-gray-200 dark:border-gray-700",autoFocus:!0})]}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("button",{onClick:()=>l(""),className:T("px-3 py-1 text-xs font-medium rounded-full transition-all",o?"text-muted-foreground hover:bg-gray-100 dark:hover:bg-gray-800":"bg-primary text-primary-foreground shadow-sm"),children:"Todas"}),Object.entries(pr).map(([b,y])=>{const p=y.icon;return e.jsxs("button",{onClick:()=>l(o===b?"":b),className:T("px-3 py-1 text-xs font-medium rounded-full transition-all flex items-center gap-1",o===b?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:bg-gray-100 dark:hover:bg-gray-800"),children:[e.jsx(p,{className:"w-3 h-3"}),y.label]},b)})]})]}),d?e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"px-3 py-2",children:a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Se,{className:"w-6 h-6 animate-spin text-primary"})}):t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(Ys,{className:"w-10 h-10 mb-3 opacity-40"}),e.jsx("p",{className:"text-sm font-medium",children:"No se encontraron plantillas"}),e.jsx("p",{className:"text-xs mt-1 opacity-70",children:r?"Intenta con otra busqueda":"Sincroniza tus plantillas desde Meta"})]}):e.jsx("div",{className:"space-y-1",children:t.map(b=>e.jsx(Ya,{template:b,onClick:()=>c(b),onHover:u},b.id))})})}):e.jsx(ai,{className:"flex-1 max-h-[50vh]",children:e.jsx("div",{className:"px-3 py-2",children:a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Se,{className:"w-6 h-6 animate-spin text-primary"})}):t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-muted-foreground",children:[e.jsx(Ys,{className:"w-10 h-10 mb-3 opacity-40"}),e.jsx("p",{className:"text-sm font-medium",children:"No se encontraron plantillas"}),e.jsx("p",{className:"text-xs mt-1 opacity-70",children:r?"Intenta con otra busqueda":"Sincroniza tus plantillas desde Meta"})]}):e.jsx("div",{className:"space-y-1",children:t.map(b=>e.jsx(Ya,{template:b,onClick:()=>c(b),onHover:u},b.id))})})})]})});Xi.displayName="TemplateListView";const Ya=i.memo(({template:t,onClick:s,onHover:a})=>{const r=ya(t),n=ba(t),{totalVars:o}=fa(t),l=hr(t),c=pr[t.category],u=t.status==="APPROVED",d=l&&u&&a?()=>a(t.id):void 0;return e.jsx("button",{onClick:u?s:void 0,onMouseEnter:d,disabled:!u,className:T("w-full text-left px-3 py-3 rounded-lg transition-all group relative",u?"hover:bg-gray-50 dark:hover:bg-gray-800/50 border border-transparent hover:border-gray-200 dark:hover:border-gray-700 cursor-pointer":"opacity-60 cursor-not-allowed bg-gray-50 dark:bg-gray-900/40 border border-transparent grayscale-[30%]"),children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:t.name}),c&&e.jsx(De,{variant:"outline",className:T("text-[10px] px-1.5 py-0 h-4 border",c.bg,c.color),children:c.label}),!u&&e.jsx(De,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border border-rose-200 bg-rose-50 text-rose-600 dark:border-rose-900/50 dark:bg-rose-900/20 dark:text-rose-400",children:t.status==="PENDING"?"En Revisión (Meta)":t.status==="REJECTED"?"Rechazada":"Inactiva"}),o>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground bg-gray-100 dark:bg-gray-800 px-1.5 py-0.5 rounded",children:[o," var",o!==1?"s":""]}),l&&e.jsx("span",{className:"text-[10px] text-purple-600 dark:text-purple-400 bg-purple-50 dark:bg-purple-900/20 px-1.5 py-0.5 rounded border border-purple-200 dark:border-purple-800",children:"📎 Media"})]}),n&&n.type!=="TEXT"&&e.jsxs("div",{className:"flex items-center gap-1 mb-1 text-[11px] text-muted-foreground",children:[n.type==="IMAGE"&&e.jsx(We,{className:"w-3 h-3"}),n.type==="VIDEO"&&e.jsx(et,{className:"w-3 h-3"}),n.type==="DOCUMENT"&&e.jsx(tt,{className:"w-3 h-3"}),e.jsxs("span",{children:["Encabezado: ",n.type.toLowerCase()]})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 leading-relaxed",children:r||"Sin contenido de cuerpo"}),e.jsx("span",{className:"text-[10px] text-muted-foreground/60 mt-1 inline-block",children:t.language.toUpperCase()})]}),u&&e.jsx(Fn,{className:"w-4 h-4 text-muted-foreground/40 group-hover:text-muted-foreground mt-1 transition-colors"})]})})});Ya.displayName="TemplateListItem";const Zi=i.memo(({template:t,headerValues:s,bodyValues:a,onSetHeaderValue:r,onSetBodyValue:n,templateLimits:o,bodyBudget:l,headerMediaData:c,mediaUploadState:u,mediaUploadError:d,mediaUploadFeedback:m,isMediaUploading:x,onMediaUpload:b,onRemoveMedia:y,carouselMediaData:p,onCarouselMediaChange:f,carouselBodyValues:g,onCarouselBodyChange:v,onBack:h,isReady:I,isSending:U,onSend:C,metadataSchema:E,contactMetadataRecord:M,previewContext:F})=>{const{headerVars:_,bodyVars:k,totalVars:W}=fa(t);ya(t);const q=ba(t),ee=pr[t.category],le=hr(t),S=i.useMemo(()=>k.map(N=>a[N]||""),[k,a]),P=i.useMemo(()=>_.map(N=>s[N]||""),[_,s]),X=i.useMemo(()=>{const N=t.components;if(Array.isArray(N))return{...t,components:N};const w=[],$=N;return $.header&&w.push({type:"HEADER",format:$.header.type||$.header.format||"TEXT",text:$.header.text,example:$.header.example}),$.body&&w.push({type:"BODY",text:$.body.text,example:$.body.example}),$.footer&&w.push({type:"FOOTER",text:$.footer.text}),$.buttons&&w.push({type:"BUTTONS",buttons:$.buttons}),{...t,components:w}},[t]),A=i.useMemo(()=>new Date().toLocaleTimeString("es",{hour:"2-digit",minute:"2-digit"}),[]),z=i.useMemo(()=>{if(q)switch(q.type){case"IMAGE":return{"image/*":[]};case"VIDEO":return{"video/*":[]};case"DOCUMENT":return{"application/pdf":[]};default:return}},[q]),L=le||W>0;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"shrink-0 px-6 pt-5 pb-4 border-b border-gray-100 dark:border-gray-800",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(K,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:h,children:e.jsx(ni,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-base font-semibold truncate",children:t.name}),ee&&e.jsx(De,{variant:"outline",className:T("text-[10px] px-1.5 py-0 h-4 border",ee.bg,ee.color),children:ee.label})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[t.language.toUpperCase(),W>0&&` · ${W} variable${W!==1?"s":""}`,le&&` · Media ${q?.type?.toLowerCase()}`]})]})]})}),e.jsxs("div",{className:"flex flex-col md:flex-row flex-1 overflow-hidden max-h-[63vh]",children:[L&&e.jsxs("div",{className:"md:w-1/2 px-5 py-4 border-b md:border-b-0 md:border-r border-gray-100 dark:border-gray-800 overflow-y-auto space-y-5",children:[le&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[q?.type==="IMAGE"&&e.jsx(We,{className:"w-4 h-4 text-slate-500"}),q?.type==="VIDEO"&&e.jsx(et,{className:"w-4 h-4 text-slate-500"}),q?.type==="DOCUMENT"&&e.jsx(tt,{className:"w-4 h-4 text-slate-500"}),e.jsxs(we,{className:"text-xs font-bold text-slate-500 uppercase tracking-widest",children:["Multimedia del Encabezado (",q?.type,")"]})]}),u==="ERROR"&&d&&e.jsxs("div",{className:"bg-rose-100 dark:bg-rose-900/40 p-3 rounded-lg flex items-start gap-2 border border-rose-200 dark:border-rose-800",children:[e.jsx(ct,{className:"w-4 h-4 text-rose-600 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-rose-700 dark:text-rose-400",children:[e.jsx("p",{className:"font-bold",children:"Error al subir archivo"}),e.jsx("p",{className:"text-[11px] opacity-80",children:d.message})]})]}),e.jsx(kr,{onUpload:N=>{(N.file||N.originalFile)&&b(N.originalFile||N.file)},currentMedia:c,onRemove:y,maxSizeMB:16,acceptedTypes:z}),x&&e.jsxs("div",{className:"flex items-center justify-center gap-2 text-primary py-1",children:[e.jsx(Se,{className:"h-3.5 w-3.5 animate-spin"}),e.jsx("span",{className:"text-xs font-medium",children:m||"Procesando..."})]})]}),(()=>{const N=(t.components||[]).find(w=>String(w.type||"").toUpperCase()==="CAROUSEL");return!N?.cards?.length||!f?null:e.jsxs("div",{className:"space-y-3",children:[e.jsxs(we,{className:"text-xs font-bold text-slate-500 uppercase tracking-widest",children:["Multimedia por tarjeta (",N.cards.length,")"]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:N.cards.map((w,$)=>{const ae=(w.components||[]).find(re=>String(re.type||"").toUpperCase()==="HEADER"),ne=String(ae?.format||"IMAGE").toUpperCase();return e.jsxs("div",{className:"space-y-1.5 rounded-lg border border-slate-200 dark:border-slate-700 p-2",children:[e.jsxs("span",{className:"flex items-center gap-1 text-[10px] font-medium text-slate-500",children:[e.jsx("span",{className:"inline-flex items-center justify-center w-3.5 h-3.5 rounded-full bg-primary/10 text-primary text-[8px] font-bold shrink-0",children:$+1}),"Tarjeta ",$+1]}),e.jsx(kr,{onUpload:re=>f($,re),currentMedia:p?.[$]||null,onRemove:()=>f($,null),maxSizeMB:16,acceptedTypes:ne==="VIDEO"?{"video/mp4":[],"video/3gpp":[]}:{"image/jpeg":[],"image/png":[]}})]},$)})})]})})(),(()=>{const N=(t.components||[]).find($=>String($.type||"").toUpperCase()==="CAROUSEL");if(!N?.cards?.length||!v)return null;const w=N.cards.map(($,ae)=>{const ne=($.components||[]).find(be=>String(be.type||"").toUpperCase()==="BODY"),re=ne?.text?us(ne.text):[];return{idx:ae,placeholders:re,bodyText:ne?.text||""}}).filter($=>$.placeholders.length>0);return w.length===0?null:e.jsxs("div",{className:"space-y-3",children:[e.jsx(we,{className:"text-xs font-bold text-slate-500 uppercase tracking-widest",children:"Variables por tarjeta"}),e.jsx("div",{className:"space-y-2",children:w.map(({idx:$,placeholders:ae,bodyText:ne})=>e.jsxs("div",{className:"space-y-1.5 rounded-lg border border-slate-200 dark:border-slate-700 p-2",children:[e.jsxs("span",{className:"text-[11px] font-medium text-slate-500",children:["Tarjeta ",$+1,e.jsxs("span",{className:"ml-1 text-slate-400",children:["· ",ne]})]}),ae.map((re,be)=>e.jsx(Te,{value:g?.[$]?.[be]||"",onChange:D=>{const Z=[...g?.[$]||[]];Z[be]=D.target.value,v($,Z)},placeholder:`Valor para {{${re}}}`,className:"h-8 text-xs"},be))]},$))})]})})(),W>0&&e.jsxs("div",{className:"space-y-4",children:[_.length>0&&e.jsxs("div",{children:[e.jsxs(we,{className:"text-xs font-bold text-slate-500 uppercase tracking-widest ml-1 mb-2 block",children:["Variables del Encabezado (",_.length,")"]}),e.jsx("div",{className:"grid gap-3 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-xl border border-slate-100 dark:border-slate-800",children:_.map(N=>{const w=ra(s[N]||"");return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(we,{className:"text-xs font-bold text-slate-600 dark:text-slate-400",children:`Variable {{${N}}}`}),e.jsxs("span",{className:T("text-[10px] font-mono tabular-nums",w>o.PARAM_VALUE?"text-rose-500":"text-slate-400"),children:["~",w," car."]})]}),e.jsx(jn,{placeholder:`Valor para {{${N}}}`,className:"bg-white dark:bg-slate-900 border-slate-200",value:s[N]||"",onChange:$=>r(N,$.target.value),metadataSchema:E,contactMetadataRecord:M})]},`header-${N}`)})})]}),k.length>0&&e.jsxs("div",{children:[e.jsxs(we,{className:"text-xs font-bold text-slate-500 uppercase tracking-widest ml-1 mb-2 block",children:["Variables del Mensaje (",k.length,")"]}),e.jsxs("div",{className:"grid gap-3 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-xl border border-slate-100 dark:border-slate-800",children:[k.map(N=>{const w=ra(a[N]||"");return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(we,{className:"text-xs font-bold text-slate-600 dark:text-slate-400",children:`Variable {{${N}}}`}),e.jsxs("span",{className:T("text-[10px] font-mono tabular-nums",w>o.PARAM_VALUE?"text-rose-500":"text-slate-400"),children:["~",w," car."]})]}),e.jsx(jn,{placeholder:`Valor para {{${N}}}`,className:"bg-white dark:bg-slate-900 border-slate-200",value:a[N]||"",onChange:$=>n(N,$.target.value),metadataSchema:E,contactMetadataRecord:M})]},`body-${N}`)}),l&&e.jsx("div",{className:"pt-2 border-t border-slate-200 dark:border-slate-700",children:e.jsx(wu,{used:l.totalUsed,limit:l.totalBudget,label:"Presupuesto del cuerpo (incluye texto fijo + variables)",showBar:!0})})]})]})]})]}),e.jsxs("div",{className:T("flex-1 flex flex-col items-center justify-start py-4 px-3 overflow-y-auto bg-slate-50/50 dark:bg-slate-900/30",L?"md:w-1/2":"w-full"),children:[e.jsx("div",{className:"mb-3 text-center",children:e.jsx("span",{className:"bg-white/80 dark:bg-slate-800/80 backdrop-blur px-3 py-1 rounded-full text-[10px] font-bold tracking-wider text-slate-400 border border-slate-200 dark:border-slate-700 uppercase shadow-sm",children:"Vista Previa en Vivo"})}),e.jsx(Cu,{mode:"template",selectedTemplate:X,variableValues:S,headerVariableValues:P,headerMediaData:c,time:A,previewContext:F,compact:!0}),e.jsx("p",{className:"text-[9px] text-slate-400 text-center mt-3 max-w-xs leading-relaxed",children:"Vista aproximada. El dispositivo del cliente puede variar."})]})]}),e.jsxs("div",{className:"shrink-0 px-6 py-4 border-t border-gray-100 dark:border-gray-800 flex items-center justify-between",children:[e.jsx("div",{className:"flex flex-col gap-0.5",children:l?.exceeded?e.jsxs("p",{className:"text-xs text-rose-600 dark:text-rose-400 font-medium flex items-center gap-1",children:[e.jsx(ct,{className:"w-3 h-3"}),"Excede el límite de ",l.totalBudget," caracteres"]}):le&&!c?.id&&!c?.signedUrl?e.jsxs("p",{className:"text-xs text-amber-600 dark:text-amber-400 font-medium flex items-center gap-1",children:[e.jsx(ct,{className:"w-3 h-3"}),"Sube la multimedia del encabezado para enviar"]}):W>0&&!I?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Completa todas las variables para enviar"}):e.jsx("p",{className:"text-xs text-emerald-600 dark:text-emerald-400 font-medium",children:"✓ Listo para enviar"})}),e.jsxs(K,{onClick:C,disabled:!I||U,className:"gap-2 bg-emerald-600 hover:bg-emerald-700 text-white",children:[U?e.jsx(Se,{className:"w-4 h-4 animate-spin"}):e.jsx(Ds,{className:"w-4 h-4"}),"Enviar Plantilla"]})]})]})});Zi.displayName="TemplateDetailView";const Ji=i.memo(({isOpen:t,onClose:s,onSelectNubotTemplate:a,activeChannel:r,isWhatsApp:n,metaPickerProps:o})=>{const l=n?"whatsapp":"nubot",[c,u]=i.useState(l);i.useEffect(()=>{t&&u(n?"whatsapp":"nubot")},[t,n]);const d=i.useCallback(x=>{x!=="whatsapp"&&o.selectedTemplate&&o.onBack(),u(x)},[o.selectedTemplate,o.onBack]),m=n;return e.jsx(yt,{open:t,onOpenChange:x=>!x&&s(),children:e.jsxs(jt,{className:"sm:max-w-3xl h-[80vh] p-0 gap-0 overflow-hidden border shadow-2xl bg-white dark:bg-zinc-950 rounded-xl flex flex-col",children:[e.jsxs("div",{className:"shrink-0 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-900/50",children:[e.jsx("div",{className:"flex items-center justify-between px-5 pt-4 pb-2",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-emerald-100 dark:bg-emerald-900/40 flex items-center justify-center",children:e.jsx(lr,{className:"w-4 h-4 text-emerald-600 dark:text-emerald-400"})}),e.jsxs("div",{children:[e.jsx(vt,{className:"text-base font-semibold leading-tight",children:"Plantillas"}),e.jsx(Rt,{className:"text-xs text-muted-foreground mt-0.5",children:c==="whatsapp"?`${o.totalApproved} plantillas aprobadas por Meta`:"Respuestas rapidas del equipo"})]})]})}),m&&e.jsxs("div",{className:"flex px-5 gap-1",children:[e.jsxs("button",{onClick:()=>d("whatsapp"),className:T("flex items-center gap-1.5 px-3.5 py-2 text-sm font-medium rounded-t-lg border border-b-0 transition-all -mb-px",c==="whatsapp"?"bg-white dark:bg-zinc-950 text-emerald-700 dark:text-emerald-400 border-gray-200 dark:border-gray-700":"bg-transparent text-gray-500 dark:text-gray-400 border-transparent hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100/50 dark:hover:bg-gray-800/50"),children:[e.jsx(si,{className:"w-3.5 h-3.5"}),"WhatsApp"]}),e.jsxs("button",{onClick:()=>d("nubot"),className:T("flex items-center gap-1.5 px-3.5 py-2 text-sm font-medium rounded-t-lg border border-b-0 transition-all -mb-px",c==="nubot"?"bg-white dark:bg-zinc-950 text-blue-700 dark:text-blue-400 border-gray-200 dark:border-gray-700":"bg-transparent text-gray-500 dark:text-gray-400 border-transparent hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100/50 dark:hover:bg-gray-800/50"),children:[e.jsx(Ys,{className:"w-3.5 h-3.5"}),"NuBot"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-hidden min-h-0 flex flex-col",children:[c==="whatsapp"&&n&&e.jsx(gr,{...o,embedded:!0}),c==="nubot"&&e.jsx(Ki,{onSelect:a,activeChannel:r,isOpen:t&&c==="nubot",autoFocusSearch:c==="nubot"})]})]})})});Ji.displayName="TemplatePicker";const Su=t=>t?t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`:"N/A",el=i.memo(t=>{const{disabled:s=!1,channelName:a="Canal",onOpenButtonDialog:r,onOpenCarouselDialog:n}=t,{message:o,setMessage:l,mode:c,setMode:u,isSending:d,isUploading:m,attachments:x,setAttachments:b,attachPopoverOpen:y,setAttachPopoverOpen:p,showTemplateSuggestions:f,setShowTemplateSuggestions:g,templateSearchQuery:v,templateAttachment:h,setTemplateAttachment:I,replacedVariables:U,textareaRef:C,fileInputRef:E,handleInput:M,handleKeyDown:F,handleFileSelect:_,handlePaste:k,handleTemplateSelect:W,startRecording:q,stopRecording:ee,cancelRecording:le,isRecording:S,recordingTime:P,isAudioSupported:X,triggerFileInput:A,handleSend:z,uploadFeedback:L,uploadProgress:N,inactivityActive:w}=au({...t,disabled:s}),{setTicketInactivityState:$}=fe(),ae=it(),ne=i.useCallback(()=>{const se=t.channel?.type;ae.prefetchQuery({queryKey:$a.search("",void 0,se),queryFn:()=>Ba.searchForChat({q:"",limit:20,channelType:se}),staleTime:3e4})},[ae,t.channel?.type]),re=i.useCallback(async()=>{if(!t.canToggleInactivity)return;const se=!w;$(t.ticketId,se);try{await Ce.toggleInactivity(t.ticketId,se)}catch(de){console.error("[ChatInput] Failed to toggle inactivity:",de),$(t.ticketId,!se)}},[t.canToggleInactivity,t.ticketId,w,$]),be=Ss(t.channel),D=vu({channelId:be&&t.channel?.id||null,ticketId:t.ticketId,previewContext:t.templateContext,resolveTicketId:t.resolveTicketId}),[Z,te]=i.useState(!1),xe=i.useMemo(()=>h?.contentType==="INTERACTIVE"&&!!h.interactiveContent&&!!ti(h.interactiveContent),[h]),ge=i.useCallback(se=>{W(se),D.handleClose()},[W,D.handleClose]),ve=i.useMemo(()=>({templates:D.templates,totalApproved:D.totalApproved,isLoading:D.isLoading,search:D.search,onSearchChange:D.setSearch,categoryFilter:D.categoryFilter,onCategoryFilterChange:D.setCategoryFilter,selectedTemplate:D.selectedTemplate,onSelectTemplate:D.handleSelectTemplate,onHoverTemplate:D.prefetchSampleMedia,onBack:D.handleBack,headerValues:D.headerValues,bodyValues:D.bodyValues,onSetHeaderValue:D.handleSetHeaderValue,onSetBodyValue:D.handleSetBodyValue,templateLimits:D.templateLimits,bodyBudget:D.bodyBudget,headerMediaData:D.headerMediaData,mediaUploadState:D.mediaUploadState,mediaUploadError:D.mediaUploadError,mediaUploadFeedback:D.mediaUploadFeedback,isMediaUploading:D.isMediaUploading,onMediaUpload:D.handleMediaUpload,onRemoveMedia:D.handleRemoveMedia,carouselMediaData:D.carouselMediaData,onCarouselMediaChange:(se,de)=>D.setCarouselMediaData(Ae=>({...Ae,[se]:de})),carouselBodyValues:D.carouselBodyValues,onCarouselBodyChange:(se,de)=>D.setCarouselBodyValues(Ae=>({...Ae,[se]:de})),isReady:D.isReady,isSending:D.isSending,onSend:D.handleSend,metadataSchema:D.metadataSchema,contactMetadataRecord:t.templateContext?.contact?.metadata,previewContext:t.templateContext}),[D,t.templateContext]),V=se=>{s||(l(de=>de+se),setTimeout(()=>C.current?.focus(),0))},j=se=>{b(de=>de.filter((Ae,ue)=>ue!==se))},G=i.useCallback(()=>{I(null),l("")},[I,l]);return e.jsxs("div",{className:"flex flex-col border-t border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 shadow-sm shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-gray-100 dark:border-gray-800 bg-gray-50/80 dark:bg-gray-900/80 backdrop-blur-sm",children:[e.jsxs("div",{className:"flex items-center gap-1 bg-gray-200/50 dark:bg-gray-800/80 p-0.5 rounded-lg border border-gray-200/50 dark:border-gray-700/50",children:[e.jsxs("button",{onClick:()=>u("reply"),className:T("flex items-center gap-1.5 px-3 py-1 rounded-md text-xs font-medium transition-all duration-200",c==="reply"?"bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 shadow-sm ring-1 ring-black/5 dark:ring-white/5":"text-gray-500 hover:text-gray-700 dark:text-gray-400 hover:bg-gray-200/50 dark:hover:bg-gray-700/50"),children:[e.jsx(as,{className:"w-3.5 h-3.5"}),"Responder"]}),e.jsxs("button",{onClick:()=>u("note"),className:T("flex items-center gap-1.5 px-3 py-1 rounded-md text-xs font-medium transition-all duration-200",c==="note"?"bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 shadow-sm ring-1 ring-amber-500/10":"text-gray-500 hover:text-gray-700 dark:text-gray-400 hover:bg-gray-200/50 dark:hover:bg-gray-700/50"),title:"Nota interna (Ctrl+N)",children:[e.jsx(qa,{className:"w-3.5 h-3.5"}),"Nota Interna"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[m&&e.jsxs("div",{className:"flex items-center gap-1.5 text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20 px-2 py-0.5 rounded-full animate-pulse border border-blue-100 dark:border-blue-900",children:[e.jsx(Se,{className:"w-3 h-3 animate-spin"}),e.jsx("span",{className:"font-medium",children:L||"Procesando multimedia..."}),N>0&&e.jsxs("span",{className:"text-[10px] opacity-80",children:[Math.round(N),"%"]})]}),t.assignedType==="META_AGENT"&&c==="reply"&&e.jsxs("div",{className:"flex items-center gap-1.5 text-sky-700 dark:text-sky-300 bg-sky-50 dark:bg-sky-950/40 px-2 py-0.5 rounded-full border border-sky-100 dark:border-sky-900",children:[e.jsx(Fa,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{className:"font-medium",children:"Meta está atendiendo. Si escribes, tomas la conversación y el agente de Meta deja de responderle."})]}),t.inactivityEnabled&&t.assignedType==="AI"&&c==="reply"&&e.jsx(rs,{children:e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsxs("button",{onClick:re,className:T("group flex items-center gap-1.5 px-2.5 py-1 rounded-lg border transition-all duration-200",t.canToggleInactivity?"cursor-pointer":"cursor-default opacity-70",w?"bg-emerald-50 dark:bg-emerald-900/20 border-emerald-200 dark:border-emerald-800 text-emerald-700 dark:text-emerald-400 hover:bg-emerald-100 dark:hover:bg-emerald-900/30":"bg-gray-50 dark:bg-gray-800/60 border-gray-200 dark:border-gray-700 text-gray-400 dark:text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-800"),children:[e.jsx("div",{className:T("relative w-6 h-3.5 rounded-full transition-colors duration-200 shrink-0",w?"bg-emerald-500 dark:bg-emerald-500":"bg-gray-300 dark:bg-gray-600"),children:e.jsx("div",{className:T("absolute top-0.5 w-2.5 h-2.5 rounded-full bg-white shadow-sm transition-all duration-200",w?"left-[13px]":"left-[1px]")})}),e.jsx("span",{className:"font-medium text-[11px] leading-tight",children:w?"Recordatorios activos":"Recordatorios pausados"})]})}),e.jsx(Re,{side:"top",className:"max-w-[260px] p-2.5",children:t.canToggleInactivity?w?e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-semibold text-emerald-700 dark:text-emerald-400",children:"Recordatorios automáticos activos"}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:"Si el cliente no responde, el bot enviará recordatorios automáticos según la configuración del canal."}),e.jsx("p",{className:"text-[10px] text-muted-foreground/70 italic",children:"Clic para desactivar en este ticket"})]}):e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-semibold text-gray-500 dark:text-gray-400",children:"Recordatorios pausados"}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:"No se enviarán recordatorios automáticos al cliente en este ticket."}),e.jsx("p",{className:"text-[10px] text-muted-foreground/70 italic",children:"Clic para activar recordatorios"})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Solo el agente asignado puede modificar esta configuración."})})]})}),c==="reply"&&e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-0.5 bg-white dark:bg-gray-800 rounded-full border border-gray-100 dark:border-gray-700 text-gray-500 shadow-sm",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"}),e.jsx("span",{className:"max-w-[120px] truncate font-medium text-gray-700 dark:text-gray-300",children:a})]})]})]}),e.jsxs("div",{className:T("flex flex-col relative transition-colors duration-300",c==="note"?"bg-amber-50/30 dark:bg-amber-950/10":"bg-white dark:bg-gray-900"),children:[(x.length>0||h)&&e.jsxs("div",{className:"px-3 pt-3 flex gap-3 overflow-x-auto pb-2",children:[h&&e.jsxs("div",{className:"flex flex-col gap-2 shrink-0",children:[!xe&&e.jsx(rs,{children:e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsxs("div",{className:T("relative group border border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-900/20 rounded-lg p-2 pr-8 flex items-center gap-3 min-w-[220px] shadow-sm transition-all",h.contentType==="INTERACTIVE"&&"mb-1"),children:[e.jsxs("div",{className:"w-10 h-10 rounded bg-blue-100 dark:bg-blue-800 flex items-center justify-center text-blue-600 dark:text-blue-300 shrink-0 overflow-hidden relative cursor-zoom-in group/thumb",onClick:()=>{["IMAGE","VIDEO"].includes(h.contentType)&&te(!0)},children:[h.thumbnailUrl?e.jsx("img",{src:h.thumbnailUrl,alt:"Preview",className:"w-full h-full object-cover"}):h.contentType==="IMAGE"?e.jsx(We,{className:"w-5 h-5"}):h.contentType==="VIDEO"?e.jsx("div",{className:"relative w-full h-full flex items-center justify-center bg-blue-200/50 dark:bg-blue-700/50",children:e.jsx(et,{className:"w-5 h-5"})}):h.contentType==="AUDIO"?e.jsx(vs,{className:"w-5 h-5"}):h.contentType==="INTERACTIVE"?e.jsx(as,{className:"w-5 h-5"}):e.jsx(tt,{className:"w-5 h-5"}),["IMAGE","VIDEO"].includes(h.contentType)&&e.jsx("div",{className:"absolute inset-0 bg-black/10 opacity-0 group-hover/thumb:opacity-100 flex items-center justify-center transition-opacity",children:e.jsx(ii,{className:"w-3.5 h-3.5 text-white drop-shadow-md"})})]}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("span",{className:"text-xs font-bold text-blue-700 dark:text-blue-300 truncate max-w-[150px]",children:h.templateName}),e.jsxs("div",{className:"flex items-center gap-1 text-[10px] text-blue-600 dark:text-blue-400",children:[e.jsx(Fa,{className:"w-2.5 h-2.5"}),"Plantilla • ",h.contentType]})]}),e.jsx("button",{onClick:()=>{I(null),l("")},className:"absolute top-1 right-1 p-1 hover:bg-red-100 dark:hover:bg-red-900/30 rounded-full text-blue-400 hover:text-red-500 transition-colors",title:"Quitar plantilla",children:e.jsx(Ge,{className:"w-3.5 h-3.5"})})]})}),e.jsx(Re,{side:"top",className:"max-w-xs p-3 text-[11px] bg-[#0f172a] text-white border-none shadow-2xl rounded-xl ring-1 ring-white/10",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-white/10 pb-1.5 mb-1.5",children:[e.jsx("div",{className:"w-1.5 h-3 bg-blue-500 rounded-full"}),e.jsx("p",{className:"font-bold text-gray-100",children:h.templateName})]}),e.jsxs("p",{className:"flex justify-between gap-4",children:[e.jsx("span",{className:"text-gray-400",children:"Tipo:"}),e.jsx("span",{className:"text-blue-400 font-medium",children:h.contentType})]}),h.mediaMimeType&&e.jsxs("p",{className:"flex justify-between gap-4",children:[e.jsx("span",{className:"text-gray-400",children:"MIME:"}),e.jsx("span",{className:"text-purple-400",children:h.mediaMimeType})]}),h.fileSize&&e.jsxs("p",{className:"flex justify-between gap-4",children:[e.jsx("span",{className:"text-gray-400",children:"Tamaño:"}),e.jsx("span",{className:"text-emerald-400 font-mono",children:Su(h.fileSize)})]}),h.fileHash&&e.jsxs("div",{className:"mt-2 pt-1 border-t border-white/5",children:[e.jsx("span",{className:"text-[10px] text-gray-500 block mb-0.5 font-mono",children:"SHA256:"}),e.jsx("p",{className:"font-mono text-[9px] text-amber-500/80 break-all leading-tight",children:h.fileHash})]}),h.mediaUrl&&e.jsxs("div",{className:"flex flex-col gap-0.5 opacity-60 mt-1",children:[e.jsx("span",{className:"text-[10px] text-gray-500",children:"URL de Media:"}),e.jsx("p",{className:"truncate text-[9px] font-mono",children:h.mediaUrl})]})]})})]})}),h.contentType==="AUDIO"&&h.mediaUrl&&e.jsx("div",{className:"bg-blue-50/30 dark:bg-blue-900/10 rounded-lg p-2 border border-blue-100/50 dark:border-blue-800/30 animate-in zoom-in-95 duration-200",children:e.jsx("audio",{src:h.mediaUrl,controls:!0,className:"h-8 max-w-[220px]"})}),h.contentType==="INTERACTIVE"&&h.interactiveContent&&e.jsx(Qi,{interactiveContent:h.interactiveContent,templateName:h.templateName,onRemove:G})]}),x.map((se,de)=>e.jsx(Gi,{attachment:se,onRemove:()=>j(de)},de))]}),e.jsx("div",{className:"px-1 pt-1 is-empty:hidden",children:e.jsx(Wi,{content:o,replacedVariables:U})}),e.jsxs("div",{className:"relative w-full",children:[f&&e.jsx("div",{className:"absolute bottom-full left-0 w-full mb-2 z-50 px-2",children:e.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-xl shadow-2xl border border-gray-100 dark:border-gray-800 overflow-hidden max-h-[320px] flex flex-col animate-in slide-in-from-bottom-2 duration-200",children:[e.jsxs("div",{className:"px-3 py-2 bg-gray-50 dark:bg-gray-800 border-b border-gray-100 dark:border-gray-700 flex items-center justify-between shadow-sm z-10",children:[e.jsxs("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider flex items-center gap-2",children:[e.jsx(as,{className:"w-3 h-3"})," Plantillas"]}),e.jsx("span",{className:"text-[10px] text-gray-400 bg-gray-100 dark:bg-gray-700 px-1.5 py-0.5 rounded",children:"ESC para cerrar"})]}),e.jsx("div",{className:"overflow-y-auto",children:e.jsx(qi,{searchQuery:v,onSelect:W,visible:!0,onClose:()=>g(!1),activeChannel:t.channel?{type:t.channel.type,id:t.channel.id}:void 0})})]})}),e.jsxs("div",{className:"relative w-full",children:[e.jsx(Ts,{ref:C,value:o,onChange:M,onKeyDown:F,onPaste:k,readOnly:!!h?.interactiveContent,disabled:s||d,placeholder:h?.interactiveContent?"Plantilla interactiva lista para enviar... (Presiona Enter para enviar o ESC para borrar)":c==="note"?"Escribe una nota interna para el equipo...":"Escribe un mensaje...",className:"min-h-[90px] max-h-[400px] py-4 px-4 w-full bg-transparent border-none focus-visible:ring-0 resize-none text-[15px] leading-relaxed placeholder:text-gray-400",style:{minHeight:"90px"},rows:2}),c==="reply"&&o.length>3600&&e.jsxs("div",{className:T("absolute bottom-2 right-3 px-1.5 py-0.5 rounded text-[11px] font-medium tabular-nums select-none pointer-events-none",o.length>4096?"bg-red-50 text-red-600 dark:bg-red-950/60 dark:text-red-400":"bg-amber-50 text-amber-600 dark:bg-amber-950/60 dark:text-amber-400"),children:[o.length,"/4096"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-3 pb-3 pt-1",children:[e.jsxs("div",{className:"flex items-center gap-1 w-full relative",children:[e.jsxs(Xe,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx("div",{children:e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-9 w-9 text-gray-400 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",disabled:s,children:e.jsx(xo,{className:"w-5 h-5"})})}),e.jsx(Re,{side:"top",children:"Emojis"})]})})}),e.jsx(Je,{side:"top",align:"start",className:"w-[420px] p-0 shadow-xl rounded-xl overflow-hidden bg-card",children:e.jsx(ho,{onSelect:V})})]}),e.jsxs(Xe,{open:y,onOpenChange:p,children:[e.jsx(Ze,{asChild:!0,children:e.jsx("div",{children:e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-9 w-9 text-gray-400 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",disabled:s||c==="note",children:e.jsx(no,{className:"w-5 h-5"})})}),e.jsx(Re,{side:"top",children:"Adjuntar archivo"})]})})}),e.jsx(Je,{side:"top",align:"start",className:"w-56 p-1.5 rounded-xl border-gray-100 shadow-lg",children:e.jsxs("div",{className:"grid gap-1",children:[e.jsxs("button",{className:"flex items-center gap-3 px-3 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-800 rounded-lg transition-colors w-full text-left font-medium",onClick:()=>A("image/*,video/*"),children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-purple-50 dark:bg-purple-900/20 flex items-center justify-center text-purple-600 dark:text-purple-400",children:e.jsx(We,{className:"w-4 h-4"})}),"Foto o Video"]}),e.jsxs("button",{className:"flex items-center gap-3 px-3 py-2.5 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-800 rounded-lg transition-colors w-full text-left font-medium",onClick:()=>A("*/*"),children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-orange-50 dark:bg-orange-900/20 flex items-center justify-center text-orange-600 dark:text-orange-400",children:e.jsx(tt,{className:"w-4 h-4"})}),"Documento"]})]})})]}),e.jsx("input",{type:"file",ref:E,className:"hidden",multiple:!0,onChange:_}),S?e.jsxs("div",{className:"flex items-center gap-3 px-3 py-1.5 bg-red-50 dark:bg-red-900/20 rounded-full border border-red-100 dark:border-red-900/30 animate-in fade-in slide-in-from-left-2 duration-200 ml-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"relative flex h-2.5 w-2.5",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2.5 w-2.5 bg-red-500"})]}),e.jsxs("span",{className:"text-xs font-mono font-medium text-red-600 dark:text-red-400 tabular-nums",children:[P," ",e.jsx("span",{className:"opacity-50 mx-1",children:"/"})," 02:00"]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 h-3 opacity-60",children:[e.jsx("div",{className:"w-0.5 h-full bg-red-400 rounded-full animate-[pulse_1s_ease-in-out_infinite]"}),e.jsx("div",{className:"w-0.5 h-2/3 bg-red-400 rounded-full animate-[pulse_1.2s_ease-in-out_infinite]"}),e.jsx("div",{className:"w-0.5 h-full bg-red-400 rounded-full animate-[pulse_0.8s_ease-in-out_infinite]"}),e.jsx("div",{className:"w-0.5 h-1/2 bg-red-400 rounded-full animate-[pulse_1.5s_ease-in-out_infinite]"})]}),e.jsx("div",{className:"w-px h-4 bg-red-200 dark:bg-red-800 mx-1"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsx("button",{onClick:le,className:"p-1 text-gray-400 hover:text-gray-600 hover:bg-black/5 rounded-full transition-colors",children:e.jsx(Ge,{className:"w-4 h-4"})})}),e.jsx(Re,{side:"top",children:"Cancelar"})]}),e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsx("button",{onClick:ee,className:"flex items-center justify-center w-7 h-7 bg-red-500 hover:bg-red-600 text-white rounded-full shadow-sm transition-transform hover:scale-105 active:scale-95",children:e.jsx(Ie,{className:"w-3.5 h-3.5"})})}),e.jsx(Re,{side:"top",children:"Enviar Audio"})]})]})]}):e.jsxs(e.Fragment,{children:[c==="reply"&&e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-9 w-9 text-gray-400 hover:text-gray-600 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",onClick:X?q:void 0,disabled:!X||s,children:e.jsx(vs,{className:"w-5 h-5"})})}),e.jsx(Re,{side:"top",children:"Grabar audio"})]}),c==="reply"&&r&&!h&&e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-9 w-9 text-gray-400 hover:text-purple-600 hover:bg-purple-50 dark:hover:bg-purple-900/20 rounded-lg transition-colors",onClick:r,disabled:s,children:e.jsx(oa,{className:"w-5 h-5"})})}),e.jsx(Re,{side:"top",children:"Opciones Interactivas"})]}),c==="reply"&&n&&!h&&e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-9 w-9 text-gray-400 hover:text-purple-600 hover:bg-purple-50 dark:hover:bg-purple-900/20 rounded-lg transition-colors",onClick:n,disabled:s,children:e.jsx(ui,{className:"w-5 h-5"})})}),e.jsx(Re,{side:"top",children:"Enviar carrusel"})]}),c==="reply"&&!h&&e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-9 w-9 text-gray-400 hover:text-primary hover:bg-primary/5 dark:hover:bg-primary/10 rounded-lg transition-colors",onClick:D.handleOpen,onMouseEnter:ne,disabled:s,children:e.jsx(lr,{className:"w-5 h-5"})})}),e.jsx(Re,{side:"top",children:"Plantillas"})]})]})]}),e.jsx("div",{children:!S&&e.jsxs("div",{className:"flex items-center gap-3",children:[o.length>0&&e.jsx("span",{className:"text-[10px] text-gray-300 dark:text-gray-600 font-medium select-none animate-in fade-in tabular-nums",children:o.length}),e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsx(K,{size:"icon",className:T("h-9 w-9 rounded-xl shadow-sm transition-all duration-200",c==="note"?"bg-amber-500 hover:bg-amber-600 text-white shadow-amber-500/20":"bg-primary hover:bg-primary/90 text-white shadow-primary/20",o.trim()||x.length>0||h?"scale-100 opacity-100 translate-x-0":"scale-90 opacity-0 translate-x-2 pointer-events-none w-0 p-0 overflow-hidden ml-0"),onClick:z,disabled:d||s,children:d?e.jsx(Se,{className:"w-4 h-4 animate-spin"}):e.jsx(Ds,{className:"w-4 h-4 ml-0.5"})})}),e.jsx(Re,{side:"top",children:"Enviar (Enter)"})]})]})})]})]}),h&&e.jsx(ls,{isOpen:Z,onClose:()=>te(!1),url:h.mediaUrl,type:h.contentType==="VIDEO"?"VIDEO":"IMAGE",caption:h.caption}),e.jsx(Ji,{isOpen:D.isOpen,onClose:D.handleClose,onSelectNubotTemplate:ge,activeChannel:t.channel?{type:t.channel.type,id:t.channel.id}:void 0,isWhatsApp:be,metaPickerProps:ve})]})});el.displayName="ChatInput";const nt=3,vn=20,Ps=10,Nn=24,Ma=72,wn=20,kn=1024,tl="Ver opciones",Vs=({n:t,max:s})=>e.jsxs("span",{className:T("text-[10px] tabular-nums shrink-0",t>=s?"text-amber-500 font-medium":"text-muted-foreground"),children:[t,"/",s]}),Eu=({body:t,isList:s,menuButton:a,options:r})=>{const n=r.filter(o=>o.label.trim());return e.jsx("div",{className:"rounded-xl bg-muted/60 p-3 flex justify-end",children:e.jsxs("div",{className:"max-w-[240px] w-full bg-[#2563eb] rounded-[14px] rounded-br-[4px] px-3 pt-2 pb-1.5",children:[e.jsx("p",{className:"text-[13px] text-white break-words leading-snug",children:t.trim()||e.jsx("span",{className:"text-white/60 italic",children:"Tu mensaje…"})}),n.length>0&&(s?e.jsxs("div",{className:"mt-2 rounded-[9px] bg-white overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1.5 border-b border-slate-200 text-[12px] font-medium text-blue-600",children:[e.jsx(as,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:a.trim()||tl})]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:n.map(o=>e.jsxs("div",{className:"px-2.5 py-1.5 border-b border-slate-100 last:border-b-0",children:[e.jsx("p",{className:"text-[12px] font-medium text-slate-800 truncate",children:o.label}),o.description?.trim()&&e.jsx("p",{className:"text-[10px] text-slate-500 truncate",children:o.description})]},o.id))})]}):e.jsx("div",{className:"mt-2 flex flex-col gap-1",children:n.slice(0,nt).map(o=>e.jsx("div",{className:"rounded-lg bg-white text-blue-600 text-[12px] font-medium text-center py-1.5 px-2 truncate",children:o.label},o.id))})),e.jsx("div",{className:"text-right mt-1",children:e.jsx("span",{className:"text-[9px] text-white/70",children:"10:36"})})]})})},Iu=({isOpen:t,onClose:s,onSend:a})=>{const[r,n]=i.useState(""),[o,l]=i.useState("buttons"),[c,u]=i.useState(""),[d,m]=i.useState([{id:"btn-1",label:""},{id:"btn-2",label:""}]),x=o==="list"||d.length>nt,b=x?Nn:vn,y=d.filter(M=>M.label.trim()).length,p=r.trim().length>0&&y>0,f=M=>{M==="buttons"&&d.length>nt&&m(d.slice(0,nt)),l(M)},g=()=>{d.length<Ps&&m([...d,{id:`btn-${Date.now()}`,label:""}])},v=M=>{d.length>1&&m(d.filter((F,_)=>_!==M))},h=(M,F)=>{if(F.length<=b){const _=[...d];_[M]={..._[M],label:F},m(_)}},I=(M,F)=>{if(F.length<=Ma){const _=[...d];_[M]={..._[M],description:F||void 0},m(_)}},U=()=>{n(""),l("buttons"),u(""),m([{id:"btn-1",label:""},{id:"btn-2",label:""}])},C=()=>{if(!p)return;const M=d.filter(F=>F.label.trim()!=="").map(F=>({id:F.id,label:F.label.trim(),...F.description?.trim()?{description:F.description.trim()}:{}}));a({body:r,options:M,displayMode:M.length>nt?"list":o,menuButton:c.trim()||void 0}),U(),s()},E=({active:M,onClick:F,disabled:_,icon:k,label:W})=>e.jsxs("button",{type:"button",onClick:F,disabled:_,title:_?`Con más de ${nt} opciones solo cabe el menú`:void 0,className:T("flex-1 flex items-center justify-center gap-1.5 h-8 rounded-md text-[13px] transition-colors disabled:opacity-40 disabled:cursor-not-allowed",M?"bg-background shadow-sm text-foreground font-medium":"text-muted-foreground hover:text-foreground"),children:[e.jsx(k,{className:"w-3.5 h-3.5"})," ",W]});return e.jsx(yt,{open:t,onOpenChange:M=>!M&&s(),children:e.jsxs(jt,{className:"sm:max-w-[640px]",children:[e.jsx(Ut,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-primary/10 text-primary flex items-center justify-center shrink-0",children:e.jsx(oa,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0 text-left",children:[e.jsx(vt,{className:"text-base",children:"Enviar opciones interactivas"}),e.jsx(Rt,{className:"text-xs",children:"El cliente elige una opción tocándola."})]})]})}),e.jsxs("div",{className:"flex gap-1 p-0.5 rounded-lg bg-muted",children:[e.jsx(E,{active:!x,onClick:()=>f("buttons"),disabled:d.length>nt,icon:Ms,label:"Botones"}),e.jsx(E,{active:x,onClick:()=>f("list"),icon:as,label:"Menú (lista)"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1.05fr_0.95fr] gap-4 sm:gap-5",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Mensaje principal"}),e.jsx(Vs,{n:r.length,max:kn})]}),e.jsx(Ts,{value:r,onChange:M=>n(M.target.value.slice(0,kn)),placeholder:"Escribe el texto de tu mensaje…",rows:3,className:"resize-none text-[13px]"})]}),x&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Texto del botón del menú"}),e.jsx(Vs,{n:c.length,max:wn})]}),e.jsx(Te,{value:c,onChange:M=>u(M.target.value.slice(0,wn)),placeholder:tl,className:"h-9 text-[13px]"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("span",{className:"text-xs font-medium text-muted-foreground",children:["Opciones (",d.length,"/",x?Ps:nt,")"]}),e.jsxs(K,{variant:"ghost",size:"sm",onClick:g,disabled:d.length>=Ps,className:"h-6 text-xs text-primary hover:text-primary gap-1",children:[e.jsx(dt,{className:"w-3 h-3"})," Agregar"]})]}),o!=="list"&&d.length>nt&&e.jsxs("div",{className:"mb-2 rounded-md border border-sky-200 bg-sky-50 dark:border-sky-800 dark:bg-sky-950/30 px-2.5 py-1.5 text-[11px] text-sky-700 dark:text-sky-300",children:[d.length," opciones — WhatsApp solo admite ",nt," botones; se enviará como ",e.jsx("strong",{children:"menú"}),"."]}),e.jsx("div",{className:"space-y-2 max-h-[38vh] overflow-y-auto pr-0.5",children:d.map((M,F)=>e.jsxs("div",{className:"rounded-lg border border-border bg-muted/40 p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-[18px] h-[18px] rounded-full bg-primary/10 text-primary text-[10px] font-medium flex items-center justify-center shrink-0",children:F+1}),e.jsx(Te,{value:M.label,onChange:_=>h(F,_.target.value),placeholder:x?`Opción ${F+1}`:`Botón ${F+1}`,className:"h-8 text-[13px] flex-1"}),e.jsx(Vs,{n:M.label.length,max:b}),d.length>1&&e.jsx(K,{variant:"ghost",size:"icon",onClick:()=>v(F),className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-red-500",children:e.jsx(ns,{className:"w-4 h-4"})})]}),x&&e.jsxs("div",{className:"mt-1.5 flex items-center gap-2 pl-[26px]",children:[e.jsx(Te,{value:M.description||"",onChange:_=>I(F,_.target.value),placeholder:"Descripción (opcional)",className:"h-7 text-xs flex-1"}),e.jsx(Vs,{n:(M.description||"").length,max:Ma})]})]},M.id))}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-2",children:x?`Máx ${Ps} opciones · ${Nn} car. por título · ${Ma} por descripción`:`Máx ${nt} botones · ${vn} car. por botón`})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground uppercase tracking-wide mb-2",children:"Vista previa"}),e.jsx(Eu,{body:r,isList:x,menuButton:c,options:d})]})]}),e.jsxs(tr,{children:[e.jsx(K,{variant:"outline",onClick:s,children:"Cancelar"}),e.jsxs(K,{onClick:C,disabled:!p,className:"gap-1.5",children:[e.jsx(Ds,{className:"w-4 h-4"})," ",x?"Enviar menú":"Enviar"]})]})]})})},{CAROUSEL_MIN_CARDS:Bs,CAROUSEL_MAX_CARDS:hs,CAROUSEL_CARD_BODY:Da,CAROUSEL_MAX_CARD_BUTTONS:Oa,CAROUSEL_BUTTON_TITLE:Cn,BODY_TEXT:Tn}=co,Sn=({n:t,max:s})=>e.jsxs("span",{className:T("text-[10px] tabular-nums shrink-0",t>=s?"text-amber-500 font-medium":"text-muted-foreground"),children:[t,"/",s]}),ps=()=>({id:`card-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,uploading:!1,body:"",url:""}),Au=t=>t.toLowerCase().replace(/\s+/g,"-").slice(0,24),Mu=({isOpen:t,onClose:s,onSend:a,channelId:r})=>{const[n,o]=i.useState(""),[l,c]=i.useState("quick_reply"),[u,d]=i.useState(["Me interesa"]),[m,x]=i.useState([ps(),ps()]),{uploadFile:b}=nr({mediaLimits:Jt.outbound,channelId:r,onError:S=>H.error("Error al subir imagen",{description:S.message})}),y=(S,P)=>{x(X=>X.map((A,z)=>z===S?{...A,...P}:A))},p=()=>{m.length<hs&&x(S=>[...S,ps()])},f=S=>{m.length>Bs&&x(P=>P.filter((X,A)=>A!==S))},g=(S,P)=>d(X=>X.map((A,z)=>z===S?P.slice(0,Cn):A)),v=()=>d(S=>S.length<Oa?[...S,"Opción"]:S),h=S=>d(P=>P.length>1?P.filter((X,A)=>A!==S):P),I=S=>{c(S),S==="cta_url"&&d(P=>P.slice(0,1))},U=async(S,P)=>{if(!r){H.error("Selecciona un canal antes de subir imágenes");return}y(S,{uploading:!0});try{const X=await b(P);X?(y(S,{gcsPath:X.gcsPath,previewUrl:X.thumbnailUrl||X.signedUrl,sizeKB:Math.max(1,Math.round(X.size/1024)),optimized:X.isOptimized,fileName:P.name,uploading:!1}),X.isDuplicate&&H.info(`Imagen reutilizada para tarjeta ${S+1}`)):y(S,{uploading:!1})}catch{y(S,{uploading:!1})}},C=S=>P=>{const X=P.target.files?.[0];X&&U(S,X),P.target.value=""},E=()=>{o(""),c("quick_reply"),d(["Me interesa"]),x([ps(),ps()])},M=u.map(S=>S.trim()),F=M.every(S=>S.length>0),_=m.every(S=>!!S.gcsPath),k=l!=="cta_url"||m.every(S=>S.url.trim().length>0),W=m.some(S=>S.uploading),q=n.trim().length>0&&F&&m.length>=Bs&&_&&k&&!W,ee=()=>{if(!q)return;const S={kind:"carousel",body:n.trim(),cards:m.map((P,X)=>({header:{type:"image",mediaGcsPath:P.gcsPath},...P.body.trim()?{body:P.body.trim()}:{},buttons:l==="cta_url"?[{type:"cta_url",title:M[0],url:P.url.trim()}]:M.map((A,z)=>({type:"quick_reply",title:A,id:`card-${X}-b${z}-${Au(A)}`}))}))};a(S),E(),s()},le=({active:S,onClick:P,icon:X,label:A})=>e.jsxs("button",{type:"button",onClick:P,className:T("flex-1 flex items-center justify-center gap-1.5 h-8 rounded-md text-[13px] transition-all",S?"bg-white dark:bg-slate-900 shadow-sm text-primary font-semibold ring-1 ring-black/5 dark:ring-white/10":"text-muted-foreground hover:text-foreground"),children:[e.jsx(X,{className:"w-3.5 h-3.5"})," ",A]});return e.jsx(yt,{open:t,onOpenChange:S=>!S&&s(),children:e.jsxs(jt,{className:"sm:max-w-[680px]",children:[e.jsx(Ut,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 text-primary flex items-center justify-center shrink-0 ring-1 ring-primary/15",children:e.jsx(ui,{className:"w-[18px] h-[18px]"})}),e.jsxs("div",{className:"min-w-0 text-left",children:[e.jsx(vt,{className:"text-base",children:"Enviar carrusel"}),e.jsx(Rt,{className:"text-xs",children:"Tarjetas deslizables con imagen y botón. Solo dentro de la ventana de 24h."})]})]})}),e.jsxs("div",{className:"space-y-3.5 min-w-0",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-700 dark:text-slate-200",children:"Mensaje principal"}),e.jsx(Sn,{n:n.length,max:Tn})]}),e.jsx(Ts,{value:n,onChange:S=>o(S.target.value.slice(0,Tn)),placeholder:"Texto que precede al carrusel…",rows:2,className:"resize-none text-[13px]"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs font-semibold text-slate-700 dark:text-slate-200",children:"Tarjetas"}),e.jsxs("span",{className:T("text-[10px] tabular-nums px-1.5 py-0.5 rounded-full font-medium",m.length>=hs?"bg-amber-100 text-amber-700 dark:bg-amber-500/15 dark:text-amber-400":"bg-slate-100 text-slate-500 dark:bg-slate-800 dark:text-slate-400"),children:[m.length,"/",hs]})]}),e.jsxs(K,{variant:"ghost",size:"sm",onClick:p,disabled:m.length>=hs,className:"h-7 text-xs text-primary hover:text-primary gap-1",children:[e.jsx(dt,{className:"w-3.5 h-3.5"})," Tarjeta"]})]}),e.jsx("div",{className:"flex gap-3 overflow-x-auto pb-2",children:m.map((S,P)=>e.jsxs("div",{className:"w-[210px] shrink-0 rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800/60 shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-2.5 py-1.5 border-b border-slate-100 dark:border-slate-700/50 bg-slate-50/70 dark:bg-slate-800/40",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] font-medium text-slate-600 dark:text-slate-300",children:[e.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 rounded-full bg-primary/10 text-primary text-[9px] font-bold tabular-nums",children:P+1}),"Tarjeta ",P+1]}),m.length>Bs&&e.jsx("button",{type:"button",onClick:()=>f(P),className:"text-slate-400 hover:text-red-500 p-0.5 rounded transition-colors",title:"Eliminar tarjeta",children:e.jsx(ns,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"p-2.5 space-y-2",children:[S.previewUrl?e.jsxs("div",{className:"relative group/img rounded-lg overflow-hidden bg-slate-100 dark:bg-slate-900",children:[e.jsx("img",{src:S.previewUrl,alt:"",className:"w-full aspect-[1.91/1] object-cover"}),e.jsxs("label",{className:"absolute inset-0 flex items-center justify-center gap-1.5 text-white text-[11px] font-medium bg-black/45 opacity-0 group-hover/img:opacity-100 cursor-pointer transition-opacity",children:[e.jsx(Cr,{className:"w-4 h-4"})," Cambiar",e.jsx("input",{type:"file",accept:"image/jpeg,image/png",className:"hidden",onChange:C(P)})]}),e.jsx("button",{type:"button",onClick:()=>y(P,{gcsPath:void 0,previewUrl:void 0,sizeKB:void 0,optimized:void 0,fileName:void 0}),className:"absolute top-1.5 right-1.5 z-10 bg-black/55 hover:bg-red-500 rounded-full p-1 text-white transition-colors",title:"Quitar imagen",children:e.jsx(Ge,{className:"w-3 h-3"})}),S.uploading&&e.jsx("div",{className:"absolute inset-0 bg-black/55 flex items-center justify-center",children:e.jsx(Se,{className:"w-5 h-5 text-white animate-spin"})})]}):e.jsxs("label",{className:T("w-full aspect-[1.91/1] rounded-lg border border-dashed border-slate-300 dark:border-slate-600 flex flex-col items-center justify-center gap-1 cursor-pointer text-slate-400 hover:border-primary/50 hover:bg-primary/5 hover:text-primary transition-colors",S.uploading&&"pointer-events-none opacity-70"),children:[S.uploading?e.jsx(Se,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Cr,{className:"w-5 h-5"}),e.jsx("span",{className:"text-[11px] font-medium",children:"Subir imagen"}),e.jsx("span",{className:"text-[9px] opacity-80",children:"JPG o PNG · obligatoria"})]}),e.jsx("input",{type:"file",accept:"image/jpeg,image/png",className:"hidden",onChange:C(P)})]}),S.gcsPath&&S.sizeKB!=null&&e.jsxs("p",{className:"flex items-center gap-1 text-[9px] text-slate-400 truncate",title:S.fileName,children:[e.jsx(Za,{className:"w-2.5 h-2.5 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-medium text-emerald-600 dark:text-emerald-400",children:S.optimized?"Optimizada":"Lista"}),e.jsxs("span",{children:["· ",S.sizeKB," KB"]}),S.fileName&&e.jsxs("span",{className:"truncate",children:["· ",S.fileName]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Ts,{value:S.body,onChange:X=>y(P,{body:X.target.value.slice(0,Da)}),placeholder:"Texto (opcional)",rows:2,className:"resize-none text-[12px] pb-4"}),e.jsxs("span",{className:"absolute bottom-1.5 right-2 text-[9px] tabular-nums text-slate-400 pointer-events-none",children:[S.body.length,"/",Da]})]}),l==="cta_url"&&e.jsxs("div",{className:"relative",children:[e.jsx(fs,{className:"w-3.5 h-3.5 text-slate-400 absolute left-2 top-1/2 -translate-y-1/2 pointer-events-none"}),e.jsx(Te,{value:S.url,onChange:X=>y(P,{url:X.target.value}),placeholder:"https://…",className:"h-8 text-[11px] pl-7"})]})]})]},S.id))}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:[Bs,"–",hs," tarjetas · imagen obligatoria por tarjeta · cuerpo máx ",Da]})]}),e.jsxs("div",{className:"rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800/50 shadow-sm p-3 space-y-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-semibold text-slate-700 dark:text-slate-200",children:[e.jsx(oa,{className:"w-3.5 h-3.5 text-primary"}),u.length>1?"Botones":"Botón"," ",e.jsx("span",{className:"font-normal text-muted-foreground",children:"(igual en todas las tarjetas)"})]}),l==="quick_reply"&&u.length<Oa&&e.jsxs(K,{variant:"ghost",size:"sm",onClick:v,className:"h-6 px-1.5 text-[11px] gap-1 text-slate-500 hover:text-primary",children:[e.jsx(dt,{className:"w-3 h-3"})," 2.º botón"]})]}),e.jsxs("div",{className:"flex gap-1 p-1 rounded-lg bg-slate-100 dark:bg-slate-800",children:[e.jsx(le,{active:l==="quick_reply",onClick:()=>I("quick_reply"),icon:Ns,label:"Respuesta rápida"}),e.jsx(le,{active:l==="cta_url",onClick:()=>I("cta_url"),icon:fs,label:"Enlace (URL)"})]}),u.map((S,P)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[l==="cta_url"?e.jsx(fs,{className:"w-3.5 h-3.5 text-slate-400 absolute left-2.5 top-1/2 -translate-y-1/2 pointer-events-none"}):e.jsx(Ns,{className:"w-3.5 h-3.5 text-slate-400 absolute left-2.5 top-1/2 -translate-y-1/2 pointer-events-none"}),e.jsx(Te,{value:S,onChange:X=>g(P,X.target.value),placeholder:`Texto del botón ${u.length>1?P+1:""}`.trim(),className:"h-9 text-[13px] pl-8 font-medium"})]}),e.jsx(Sn,{n:S.length,max:Cn}),u.length>1&&e.jsx("button",{type:"button",onClick:()=>h(P),className:"text-slate-400 hover:text-red-500 p-1 rounded transition-colors shrink-0",title:"Quitar botón",children:e.jsx(ns,{className:"w-3.5 h-3.5"})})]},P)),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:l==="cta_url"?"Cada tarjeta abre su propia URL (definida arriba). Meta permite 1 botón de enlace por tarjeta.":`Al tocar, la respuesta identifica qué tarjeta eligió el cliente. Meta permite hasta ${Oa} botones por tarjeta.`})]})]}),e.jsxs(tr,{children:[e.jsx(K,{variant:"outline",onClick:s,children:"Cancelar"}),e.jsxs(K,{onClick:ee,disabled:!q,className:"gap-1.5",children:[e.jsx(Ds,{className:"w-4 h-4"})," Enviar carrusel"]})]})]})})},sl=t=>t==="RESOLVED"||t==="ARCHIVED";class Du extends Error{constructor(s){super("El contacto ya tiene una conversación abierta"),this.ticketId=s,this.name="ResumeRedirectedError"}}function al(){const t=it();return i.useCallback(async(s,a)=>{if(!sl(a))return s;let r;try{r=await Ce.resumeTicket(s)}catch(n){const o=n?.response?.data?.message||n?.message||"No se pudo retomar la conversación";throw H.error(typeof o=="string"?o:"No se pudo retomar la conversación"),n&&typeof n=="object"&&(n.__resumeToasted=!0),n}if(t.invalidateQueries({queryKey:["inbox","closed-matches"]}),t.invalidateQueries({queryKey:["inbox","conversations"]}),r.ticketId!==s&&await fe.getState().selectConversation(r.ticketId),r.outcome==="existing"&&!r.assignedToMe)throw H.info("Este contacto ya tiene una conversación abierta. Te llevamos a ella."),new Du(r.ticketId);return r.ticketId},[t])}const rl=i.memo(({isLoadingMore:t,isLoadingConversation:s,loadError:a,onRetryLoad:r})=>a?e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center bg-background px-6",children:[e.jsx("div",{className:"w-16 h-16 mb-5 rounded-full bg-destructive/10 flex items-center justify-center",children:e.jsx(ft,{className:"w-7 h-7 text-destructive"})}),e.jsx("h3",{className:"text-base font-semibold text-foreground mb-1.5",children:"No se pudo abrir la conversación"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-sm mb-4",children:or(a)}),r&&e.jsx(K,{size:"sm",variant:"outline",onClick:r,children:"Reintentar"})]}):t||s?e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center bg-background/50 backdrop-blur-sm",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"w-16 h-16 rounded-full border-4 border-primary/20 border-t-primary animate-spin"}),e.jsx(Se,{className:"w-6 h-6 text-primary absolute inset-0 m-auto animate-pulse"})]}),e.jsx("p",{className:"mt-4 text-sm font-medium text-muted-foreground animate-pulse",children:"Cargando conversación..."})]}):e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center bg-background",children:[e.jsx("div",{className:"w-24 h-24 mb-6 rounded-full bg-muted/50 dark:bg-muted flex items-center justify-center border border-border",children:e.jsx(Bt,{className:"w-10 h-10 text-muted-foreground/70"})}),e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-2",children:"Selecciona una conversación"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-sm px-4",children:"Elige una conversación de la lista para ver los mensajes y responder a tus clientes."})]}));rl.displayName="ChatEmptyState";const Ou=/^[A-Z]{2}\.(?:ENT\.)?[A-Za-z0-9]{1,128}$/;function na(t){return!!t&&Ou.test(t)}function Uu(t,s,a){return t||s||(na(a)?"Lead sin número":"Sin contacto")}const Ua=(t,s,a=10)=>{if(t)switch(t){case"AVAILABLE":return"text-green-500";case"AWAY":return"text-yellow-500";case"UNAVAILABLE":return"text-red-500"}if(s){const r=new Date(s),n=a*60*1e3,o=new Date(Date.now()-n);if(r>o)return"text-green-500"}return"text-gray-400"},Ru=(t,s=10)=>{if(!t)return!1;const a=new Date(t),r=s*60*1e3,n=new Date(Date.now()-r);return a>n},_u=(t,s=10,a)=>{if(a==="UNAVAILABLE")return"No disponible";if(!t)return"Sin actividad";const r=new Date(t),o=new Date().getTime()-r.getTime(),l=Math.floor(o/(60*1e3));if(l<1)return"Activo ahora";if(l<s)return`Activo hace ${l} min`;{const c=Math.floor(l/60);return c<1?`Inactivo (${l} min)`:c<24?`Inactivo (${c}h)`:"Inactivo (+1 día)"}};function Lu({currentAgentId:t,currentAssignedType:s,onAssign:a,onAssignToTeam:r,onAssignBestAgent:n,disabled:o=!1,humansOnly:l=!1}){const[c,u]=i.useState(!1),[d,m]=i.useState(!1),{user:x}=Ye(),{data:b=[]}=cs(),y=Ft(k=>k.currentOrganization),p=Ft(k=>k.teams),f=Ft(k=>k.fetchTeams),g=y?.inactivityThresholdMinutes??10,{data:v=[]}=rr(y?.id);i.useEffect(()=>{(c||t&&s==="AI")&&y?.id&&(console.log("[AgentSelector] Fetching Teams for org:",y.id),f(y.id))},[c,t,s,y?.id,f]);const h=i.useMemo(()=>[...b].filter(k=>k.user.isActive!==!1).sort((k,W)=>{const q={AVAILABLE:0,AWAY:1,UNAVAILABLE:2},ee=q[k.user.availabilityStatus||""]??3,le=q[W.user.availabilityStatus||""]??3;if(ee!==le)return ee-le;const S=k.user.lastActivityAt?new Date(k.user.lastActivityAt).getTime():0;return(W.user.lastActivityAt?new Date(W.user.lastActivityAt).getTime():0)-S}),[b]),I=i.useMemo(()=>p.filter(k=>!k.members||k.members.length===0?!1:k.members.some(W=>W.user?.isActive!==!1)),[p]),U=async(k,W="HUMAN")=>{if(!d){if(k===t&&W===s){console.log("[AgentSelector] Ignoring reassignment to same agent"),u(!1);return}m(!0);try{await a(k,W),u(!1)}finally{m(!1)}}},C=async k=>{if(!(!r||d)){m(!0);try{await r(k),u(!1)}finally{m(!1)}}},E=b.find(k=>k.user.id===t),M=v.find(k=>k.id===t),F=s==="AI"?M?.name||"Agente IA":E?.user.name||"Agente desconocido",_=s==="AI"?null:E?.user.avatarUrl;return e.jsxs(Xe,{open:c,onOpenChange:u,children:[e.jsx(Ze,{asChild:!0,children:e.jsxs(K,{variant:"outline",role:"combobox","aria-expanded":c,disabled:o,className:T("w-full min-w-[120px] max-w-[200px] justify-between h-9 px-3 bg-white hover:bg-gray-50/50 border-gray-200",o&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"flex items-center gap-2 truncate",children:t?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[s==="AI"?e.jsx("div",{className:"h-5 w-5 bg-violet-100 flex items-center justify-center rounded-full border border-violet-200",children:e.jsx(It,{className:"h-3 w-3 text-violet-600"})}):e.jsxs(ht,{className:"h-5 w-5 border border-gray-200",children:[e.jsx(pt,{src:_||void 0}),e.jsx(gt,{className:"text-[9px] bg-blue-100 text-blue-700",children:F.charAt(0).toUpperCase()})]}),s!=="AI"&&E?.user&&e.jsx("div",{className:T("absolute -bottom-0.5 -right-0.5 h-1.5 w-1.5 rounded-full border border-white dark:border-gray-800",Ua(E.user.availabilityStatus,E.user.lastActivityAt,g).replace("text-","bg-"))})]}),e.jsx("span",{className:"text-sm font-medium text-gray-700 group-hover:text-blue-700 truncate",children:F})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-5 w-5 rounded-full bg-gray-100 flex items-center justify-center text-gray-400 group-hover:bg-blue-100 group-hover:text-blue-600 transition-colors",children:e.jsx(Pa,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-sm text-muted-foreground group-hover:text-blue-600",children:"Asignar agente..."})]})}),e.jsx(Vt,{className:"ml-2 h-3 w-3 shrink-0 opacity-50"})]})}),e.jsx(Je,{className:"w-[260px] p-0",align:"end",children:e.jsxs(At,{children:[e.jsx(Mt,{placeholder:"Buscar agente..."}),e.jsxs(Dt,{children:[e.jsx(Ot,{children:"No se encontraron agentes."}),e.jsxs(Be,{heading:"Sugerencias",children:[x&&e.jsxs(Le,{value:x.id,onSelect:()=>U(x.id,"HUMAN"),className:"gap-2 cursor-pointer",disabled:d,children:[e.jsxs("div",{className:"relative",children:[e.jsxs(ht,{className:"h-6 w-6",children:[e.jsx(pt,{src:x.avatar}),e.jsx(gt,{children:x.name?.charAt(0)})]}),e.jsx("div",{className:T("absolute -bottom-0.5 -right-0.5 h-1.5 w-1.5 rounded-full border border-white dark:border-gray-800",Ua(x.availabilityStatus,void 0,g).replace("text-","bg-"))})]}),e.jsx("span",{children:"Asignar a mí"}),t===x.id&&s!=="AI"&&e.jsx(Ie,{className:"ml-auto h-4 w-4"})]}),t&&e.jsxs(Le,{value:"unassign",onSelect:()=>U(null),className:"gap-2 cursor-pointer text-orange-600 hover:text-orange-700",disabled:d,children:[e.jsx("div",{className:"h-6 w-6 rounded-full bg-orange-100 flex items-center justify-center",children:e.jsx(Pa,{className:"h-3.5 w-3.5 text-orange-600"})}),e.jsx("span",{children:"Regresar a En Espera"})]})]}),b.length>1&&n&&s!=="HUMAN"&&e.jsxs(e.Fragment,{children:[e.jsx(Et,{}),e.jsx(Be,{heading:"Asignación Inteligente",children:e.jsxs(Le,{value:"auto-assign-org",onSelect:async()=>{if(!d){m(!0);try{await n(),u(!1)}finally{m(!1)}}},className:"gap-2 cursor-pointer",disabled:d,children:[e.jsx("div",{className:"h-6 w-6 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center text-white shadow-sm",children:e.jsx(Ws,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-indigo-700 dark:text-indigo-400",children:"Asignar al mejor agente"}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Busca disponible en toda la organización"})]})]})})]}),!l&&v.filter(k=>k.agentType!=="analyzer"&&k.status==="active").length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Et,{}),e.jsx(Be,{heading:"Agentes IA",children:v.filter(k=>k.agentType!=="analyzer"&&k.status==="active").map(k=>e.jsxs(Le,{value:k.id,keywords:[k.name,"bot","ia","ai"],onSelect:()=>U(k.id,"AI"),className:"gap-2 cursor-pointer",disabled:d,children:[e.jsx("div",{className:"h-6 w-6 rounded-full bg-violet-100 flex items-center justify-center border border-violet-200",children:e.jsx(It,{className:"h-3.5 w-3.5 text-violet-600"})}),e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:k.name}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:k.status==="active"?"Activo":"Inactivo"})]}),t===k.id&&s==="AI"&&e.jsx(Ie,{className:"ml-auto h-4 w-4 opacity-100"})]},k.id))})]}),I.length>0&&r&&e.jsxs(e.Fragment,{children:[e.jsx(Et,{}),e.jsx(Be,{heading:"Equipos (Asignación inteligente)",children:I.map(k=>e.jsxs(Le,{value:`team-${k.id}`,onSelect:()=>C(k.id),className:"gap-2 cursor-pointer",disabled:d,children:[e.jsx("div",{className:"h-6 w-6 rounded-full bg-purple-100 flex items-center justify-center",children:e.jsx(Ws,{className:"h-3.5 w-3.5 text-purple-600"})}),e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:k.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[k.members?.length||0," miembros"]})]})]},k.id))})]}),e.jsx(Be,{heading:"Agentes (Humanos)",children:h.filter(k=>k.user.id!==x?.id).map(k=>e.jsxs(Le,{value:k.user.id,keywords:[k.user.name,k.user.email],onSelect:()=>U(k.user.id,"HUMAN"),className:"gap-2 cursor-pointer",disabled:d,children:[e.jsxs("div",{className:"relative",children:[e.jsxs(ht,{className:"h-6 w-6",children:[e.jsx(pt,{src:k.user.avatarUrl}),e.jsx(gt,{children:k.user.name.charAt(0)})]}),e.jsx("div",{className:T("absolute -bottom-0.5 -right-0.5 h-2 w-2 rounded-full border border-white dark:border-gray-800",Ua(k.user.availabilityStatus,k.user.lastActivityAt,g).replace("text-","bg-"))})]}),e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:k.user.name}),e.jsx("span",{className:T("text-[10px]",Ru(k.user.lastActivityAt,g)&&k.user.availabilityStatus!=="UNAVAILABLE"?"text-green-600":"text-muted-foreground"),children:_u(k.user.lastActivityAt,g,k.user.availabilityStatus)})]}),t===k.user.id&&s!=="AI"&&e.jsx(Ie,{className:"ml-auto h-4 w-4 opacity-100"})]},k.id))})]})]})})]})}function Fu(){const t=it(),s=()=>{t.invalidateQueries({queryKey:["conversations"]}),t.invalidateQueries({queryKey:["activeConversation"]}),t.invalidateQueries({queryKey:["inbox"]}),t.invalidateQueries({queryKey:["pipeline-board"]}),t.removeQueries({queryKey:["stage-tickets"]})},a=xt({mutationFn:l=>Ce.assignTicketToFunnel(l.ticketId,{funnelId:l.funnelId,stageId:l.stageId,reason:l.reason}),onSuccess:()=>{H.success("Ticket asignado al funnel"),s()},onError:l=>{H.error(l.message||"Error al asignar al funnel")}}),r=xt({mutationFn:l=>Ce.moveTicketToStage(l.ticketId,{stageId:l.stageId,reason:l.reason}),onSuccess:()=>{H.success("Ticket movido a nueva etapa"),s()},onError:l=>{H.error(l.message||"Error al mover etapa")}}),n=xt({mutationFn:l=>Ce.removeTicketFromFunnel(l.ticketId,l.reason),onSuccess:()=>{H.success("Ticket removido del funnel"),s()},onError:l=>{H.error(l.message||"Error al remover del funnel")}}),o=xt({mutationFn:l=>Ce.transferTicketToFunnel(l.ticketId,{funnelId:l.funnelId,stageId:l.stageId,reason:l.reason}),onSuccess:()=>{H.success("Ticket transferido a nuevo funnel"),s()},onError:l=>{H.error(l.message||"Error al transferir al funnel")}});return{assignToFunnel:a,moveToStage:r,removeFromFunnel:n,transferToFunnel:o}}const nl=i.memo(({ticketId:t,currentFunnelId:s,currentStageId:a,compact:r=!1,className:n,disabled:o=!1})=>{const[l,c]=i.useState(!1),{data:u,isLoading:d}=la(),{assignToFunnel:m,removeFromFunnel:x}=Fu(),b=m.isPending||x.isPending,y=i.useMemo(()=>u?.find(E=>E.id===s),[u,s]),p=i.useMemo(()=>y?.stages?.find(E=>E.id===a),[y,a]),f=i.useMemo(()=>u?.filter(E=>E.active!==!1)||[],[u]),g=async(E,M)=>{if(!b){if(M.id===a&&E===s){c(!1);return}try{await m.mutateAsync({ticketId:t,funnelId:E,stageId:M.id,reason:"Asignación manual desde inbox"}),c(!1)}catch(F){console.error("[FunnelStageSelector] Error:",F)}}},v=async()=>{if(!b)try{await x.mutateAsync({ticketId:t,reason:"Removido manualmente desde inbox"}),c(!1)}catch(E){console.error("[FunnelStageSelector] Error removing:",E)}};if(!u||u.length===0)return null;const h=y&&y.active===!1,I=p&&p.active===!1,U=h||I,C=y&&p?`${p.name}`:"Asignar funnel...";return p?.icon||y?.icon,e.jsxs(Xe,{open:l,onOpenChange:c,children:[e.jsx(Ze,{asChild:!0,children:e.jsxs(K,{variant:"outline",role:"combobox","aria-expanded":l,disabled:b||d||o,className:T("justify-between bg-white hover:bg-gray-50/50",r?"h-9 px-3 w-[180px]":"h-9 px-3 w-full",U?"border-amber-300 bg-amber-50 hover:bg-amber-100/50":"border-gray-200",o&&"opacity-50 cursor-not-allowed",n),children:[e.jsx("div",{className:"flex items-center gap-2 truncate",children:s?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:T("h-5 w-5 flex items-center justify-center rounded-full border",U?"bg-amber-100 border-amber-300":"bg-indigo-100 border-indigo-200"),children:U?e.jsx(ft,{className:"h-3 w-3 text-amber-600"}):e.jsx(js,{className:"h-3 w-3 text-indigo-600"})}),e.jsx("span",{className:T("text-sm font-medium truncate",U?"text-amber-700":"text-gray-700"),children:r?p?.name||"Sin etapa":C}),U&&e.jsx("span",{className:"text-[10px] font-medium text-amber-600 bg-amber-100 px-1.5 py-0.5 rounded-full",children:"Inactivo"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-5 w-5 rounded-full bg-gray-100 flex items-center justify-center text-gray-400 group-hover:bg-indigo-100 group-hover:text-indigo-600 transition-colors",children:e.jsx(js,{className:"h-3 w-3"})}),e.jsx("span",{className:"text-sm text-muted-foreground group-hover:text-indigo-600",children:r?"Funnel":"Asignar funnel..."})]})}),e.jsx(Vt,{className:"ml-2 h-3 w-3 shrink-0 opacity-50"})]})}),e.jsx(Je,{className:"w-[280px] p-0",align:"end",children:e.jsxs(At,{children:[e.jsx(Mt,{placeholder:"Buscar funnel o etapa..."}),e.jsxs(Dt,{children:[e.jsx(Ot,{children:"No se encontraron funnels."}),s&&e.jsxs(e.Fragment,{children:[e.jsx(Be,{heading:"Acciones",children:e.jsxs(Le,{value:"remove-from-funnel",onSelect:v,className:"gap-2 cursor-pointer text-red-600 hover:text-red-700",disabled:b,children:[e.jsx("div",{className:"h-6 w-6 rounded-full bg-red-100 flex items-center justify-center",children:e.jsx(Ge,{className:"h-3.5 w-3.5 text-red-600"})}),e.jsx("span",{children:"Remover del funnel"})]})}),e.jsx(Et,{})]}),f.map(E=>e.jsx(il,{funnel:E,currentFunnelId:s,currentStageId:a,onSelect:g,disabled:b},E.id))]})]})})]})}),il=i.memo(({funnel:t,currentFunnelId:s,currentStageId:a,onSelect:r,disabled:n=!1})=>{const o=i.useMemo(()=>(t.stages?.filter(l=>l.active!==!1)||[]).sort((l,c)=>String(l.order)<String(c.order)?-1:String(l.order)>String(c.order)?1:0),[t.stages]);return o.length===0?null:e.jsx(Be,{heading:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{children:t.name}),t.default&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"(Default)"})]}),children:o.map(l=>e.jsxs(Le,{value:`${t.name}-${l.name}`,keywords:[t.name,l.name,l.description||""],onSelect:()=>r(t.id,l),className:"gap-2 cursor-pointer pl-4",disabled:n,children:[e.jsx(Fn,{className:"h-3 w-3 text-muted-foreground"}),e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[l.icon&&e.jsx("span",{className:"text-sm",children:l.icon}),e.jsx("span",{className:"text-sm truncate",children:l.name}),l.default&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"(Default)"})]}),a===l.id&&s===t.id&&e.jsx(Ie,{className:"ml-auto h-4 w-4 text-indigo-600"})]},l.id))})});nl.displayName="FunnelStageSelector";il.displayName="FunnelGroup";function Pu({onSelect:t,onManualEntry:s,disabled:a}){const[r,n]=i.useState(!1),[o,l]=i.useState(""),[c,u]=i.useState([]),[d,m]=i.useState(!1),x=i.useRef(null),b=i.useRef(null),y=i.useCallback(async g=>{m(!0);try{const v=await Zs.getProducts({search:g||void 0,limit:100});u(v.data)}catch{u([])}finally{m(!1)}},[]);i.useEffect(()=>{r&&(y(""),setTimeout(()=>b.current?.focus(),100))},[r,y]),i.useEffect(()=>{if(r)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{y(o)},300),()=>{x.current&&clearTimeout(x.current)}},[o,r,y]);const p=g=>{t(g),n(!1),l("")},f=(g,v)=>{const h=typeof g=="number"?g:Number(g);return new Intl.NumberFormat("es-PE",{style:"currency",currency:v||"USD",minimumFractionDigits:2}).format(isFinite(h)?h:0)};return e.jsxs(Xe,{open:r,onOpenChange:n,children:[e.jsx(Ze,{asChild:!0,children:e.jsxs(K,{variant:"outline",size:"sm",className:"gap-2 text-sm",disabled:a,children:[e.jsx(dt,{className:"w-4 h-4"}),"Agregar Producto"]})}),e.jsxs(Je,{className:"w-80 p-0",align:"start",children:[e.jsx("div",{className:"p-3 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(Bt,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Te,{ref:b,placeholder:"Buscar producto...",value:o,onChange:g=>l(g.target.value),className:"pl-9 h-9"})]})}),e.jsx("div",{className:"max-h-60 overflow-y-auto",children:d?e.jsxs("div",{className:"flex items-center justify-center py-6 text-muted-foreground",children:[e.jsx(Se,{className:"w-4 h-4 animate-spin mr-2"}),e.jsx("span",{className:"text-sm",children:"Buscando..."})]}):c.length===0?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No se encontraron productos"}):c.map(g=>e.jsxs("button",{className:T("w-full flex items-center gap-3 px-3 py-2.5 text-left","hover:bg-accent/50 transition-colors cursor-pointer","border-b border-border/30 last:border-0"),onClick:()=>p(g),children:[e.jsx("div",{className:"w-9 h-9 rounded-md bg-muted/50 flex items-center justify-center shrink-0 overflow-hidden",children:g.thumbnailUrl||g.imageUrl?e.jsx("img",{src:g.thumbnailUrl||g.imageUrl,alt:g.name,className:"w-full h-full object-cover rounded-md"}):e.jsx(Ks,{className:"w-4 h-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:g.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:f(g.price,g.currency)})]})]},g.id))}),e.jsx("div",{className:"border-t p-2",children:e.jsxs("button",{className:"w-full flex items-center gap-2 px-3 py-2 rounded-md text-sm text-primary hover:bg-primary/5 transition-colors cursor-pointer",onClick:()=>{s(),n(!1),l("")},children:[e.jsx(dt,{className:"w-4 h-4"}),"Agregar manualmente"]})})]})]})}let Vu=0;const Ra=()=>`item-${++Vu}`;function Bu({open:t,onOpenChange:s,ticketId:a,onSubmit:r,onUpdate:n,onLoadSale:o,existingSale:l}){const c=!!l,[u,d]=i.useState([]),[m,x]=i.useState("USD"),[b,y]=i.useState(""),[p,f]=i.useState(""),[g,v]=i.useState(!1),[h,I]=i.useState(!1),[U,C]=i.useState(!1),[E,M]=i.useState(!1);i.useEffect(()=>{if(!t||!c||!o)return;let V=!1;return M(!0),o(a).then(j=>{if(V||!j)return;x(j.currency||"USD"),y(j.notes||""),f(j.metadata?.externalEventId||"");const G=(j.items||[]).map(se=>({_key:Ra(),productId:se.productId||void 0,productName:se.productName,unitPrice:Number(se.unitPrice),quantity:Number(se.quantity),productSku:se.productSku,productImageUrl:se.productImageUrl}));d(G)}).catch(()=>{V||H.error("No se pudo cargar la venta existente")}).finally(()=>{V||M(!1)}),()=>{V=!0}},[t,c,o,a]),i.useEffect(()=>{if(t)return;const V=setTimeout(()=>{c||(d([]),y(""),f("")),v(!1),I(!1)},300);return()=>clearTimeout(V)},[t,c]);const[F,_]=i.useState(""),[k,W]=i.useState(""),[q,ee]=i.useState("1"),[le,S]=i.useState(!1),[P,X]=i.useState(""),[A,z]=i.useState(""),[L,N]=i.useState(""),[w,$]=i.useState([]),[ae,ne]=i.useState(null),re=Pn();i.useEffect(()=>{if(!t)return;let V=!1;return Zs.getCatalogs().then(j=>{if(V)return;const G=(j||[]).filter(de=>de.isActive!==!1);$(G);const se=G.find(de=>de.isDefault)||G[0];se&&N(se.id)}).catch(()=>{}),he.get("/analytics/meta-pixel/config").then(j=>{V||ne(!!j.data?.configured)}).catch(()=>{V||ne(!1)}),()=>{V=!0}},[t]);const be=i.useMemo(()=>u.reduce((V,j)=>V+j.unitPrice*j.quantity,0),[u]),D=i.useCallback(V=>new Intl.NumberFormat("es-PE",{style:"currency",currency:m,minimumFractionDigits:2}).format(V),[m]),Z=i.useCallback(V=>{d(j=>{if(j.find(de=>de.productId===V.id))return j.map(de=>de.productId===V.id?{...de,quantity:de.quantity+1}:de);const se=Number(V.price);return[...j,{_key:Ra(),productId:V.id,productName:V.name,unitPrice:isFinite(se)?se:0,quantity:1,productSku:V.externalId,productImageUrl:V.thumbnailUrl||V.imageUrl}]})},[]),te=i.useCallback(()=>{const V=parseFloat(k),j=parseInt(q,10);if(!F.trim()||isNaN(V)||V<=0){H.error("Ingresa nombre y precio válidos");return}if(le&&!L){H.error("Selecciona un catálogo para guardar el producto");return}d(G=>[...G,{_key:Ra(),productName:F.trim(),unitPrice:V,quantity:j>0?j:1,productSku:A.trim()||void 0,saveToCatalog:le,productCatalogId:le?L:void 0,productDescription:le&&P.trim()?P.trim():void 0}]),_(""),W(""),ee("1"),S(!1),X(""),z(""),I(!1)},[F,k,q,le,A,P,L]),xe=i.useCallback(V=>{d(j=>j.filter(G=>G._key!==V))},[]),ge=i.useCallback((V,j)=>{d(G=>G.map(se=>se._key===V?{...se,quantity:Math.max(1,se.quantity+j)}:se))},[]),ve=async()=>{if(u.length===0){H.error("Agrega al menos un producto");return}C(!0);try{const V={items:u.map(({_key:se,...de})=>de),currency:m,notes:b.trim()||void 0,externalEventId:p.trim()||void 0},G=await(c&&n?n:r)(a,V);H.success(c?`Venta actualizada: ${G.orderNumber} — ${D(G.total)}`:`Venta registrada: ${G.orderNumber} — ${D(G.total)}`),s(!1),ae===!1&&H.warning("Mejora la atribución de tus campañas",{description:"Esta venta no se reportó a Meta. Conecta tu Pixel de Meta para que los anuncios CTWA atribuyan esta y futuras conversiones.",duration:1e4,action:{label:"Conectar Pixel",onClick:()=>re("/conexiones/meta-pixel")}})}catch(V){H.error(V?.response?.data?.message||(c?"Error al actualizar la venta":"Error al registrar la venta"))}finally{C(!1)}};return e.jsx(jl,{open:t,onOpenChange:s,children:e.jsxs(vl,{side:"right",className:"w-full sm:max-w-lg flex flex-col p-0",children:[e.jsxs(Nl,{className:"border-b",children:[e.jsxs(wl,{className:"flex items-center gap-2",children:[e.jsx(Va,{className:`w-5 h-5 ${c?"text-emerald-600":"text-primary"}`}),c?"Editar Venta":"Registrar Venta",c&&l&&e.jsx(De,{variant:"outline",className:"ml-1 font-mono text-[10px] bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-950/20 dark:text-emerald-400",children:l.orderNumber})]}),e.jsx(kl,{children:c?"Modifica los productos, cantidades o agrega más items a esta venta.":"Selecciona productos del catálogo o agrega manualmente."})]}),E&&e.jsxs("div",{className:"flex-1 flex items-center justify-center text-muted-foreground",children:[e.jsx(Se,{className:"w-5 h-5 animate-spin mr-2"}),e.jsx("span",{className:"text-sm",children:"Cargando venta..."})]}),!E&&e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-4 px-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pu,{onSelect:Z,onManualEntry:()=>I(!0)}),e.jsxs(kt,{value:m,onValueChange:x,children:[e.jsx(Ct,{className:"w-28 h-9",children:e.jsx(Tt,{})}),e.jsx(St,{children:to.map(V=>e.jsx(Me,{value:V.value,children:V.value},V.value))})]})]}),h&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Agregar manualmente"}),e.jsx(K,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground",onClick:()=>I(!1),children:"×"})]}),e.jsxs("div",{className:"grid grid-cols-[1fr_80px_60px] gap-2",children:[e.jsx("div",{children:e.jsx(Te,{placeholder:"Nombre del producto",value:F,onChange:V=>_(V.target.value),className:"h-8 text-sm"})}),e.jsx("div",{children:e.jsx(Te,{placeholder:"Precio",type:"number",step:"0.01",min:"0",value:k,onChange:V=>W(V.target.value),className:"h-8 text-sm"})}),e.jsx("div",{children:e.jsx(Te,{placeholder:"Cant.",type:"number",min:"1",value:q,onChange:V=>ee(V.target.value),className:"h-8 text-sm"})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(go,{id:"save-catalog",checked:le,onCheckedChange:V=>S(V===!0)}),e.jsx(we,{htmlFor:"save-catalog",className:"text-xs text-muted-foreground cursor-pointer",children:"Guardar en catálogo"})]}),!le&&e.jsxs(K,{size:"sm",className:"h-7 text-xs",onClick:te,children:[e.jsx(dt,{className:"w-3 h-3 mr-1"}),"Agregar"]})]}),le&&e.jsxs("div",{className:"space-y-2 pt-2 border-t border-border/50",children:[e.jsxs("div",{children:[e.jsx(we,{className:"text-[11px] text-muted-foreground",children:"Catálogo"}),e.jsxs(kt,{value:L,onValueChange:N,children:[e.jsx(Ct,{className:"h-8 text-sm mt-1",children:e.jsx(Tt,{placeholder:"Selecciona catálogo..."})}),e.jsx(St,{children:w.length===0?e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No hay catálogos"}):w.map(V=>e.jsxs(Me,{value:V.id,children:[V.name,V.isDefault&&e.jsx("span",{className:"text-[10px] text-muted-foreground ml-1",children:"(default)"})]},V.id))})]})]}),e.jsxs("div",{children:[e.jsxs(we,{className:"text-[11px] text-muted-foreground",children:["SKU ",e.jsx("span",{className:"text-muted-foreground/60",children:"(opcional)"})]}),e.jsx(Te,{placeholder:"Ej: WIDGET-001",value:A,onChange:V=>z(V.target.value),className:"h-8 text-sm mt-1 font-mono"})]}),e.jsxs("div",{children:[e.jsxs(we,{className:"text-[11px] text-muted-foreground",children:["Descripción ",e.jsx("span",{className:"text-muted-foreground/60",children:"(opcional)"})]}),e.jsx("textarea",{placeholder:"Descripción del producto...",value:P,onChange:V=>X(V.target.value),rows:2,className:"mt-1 w-full rounded-md border border-input bg-transparent px-3 py-1.5 text-sm shadow-xs placeholder:text-muted-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring resize-y"})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground/80 pt-1",children:["Para agregar imagen u otros detalles, edita el producto en"," ",e.jsx(Cl,{to:"/configuracion/productos",className:"text-primary hover:underline",target:"_blank",children:"Productos"}),"."]}),e.jsxs(K,{size:"sm",className:"h-7 text-xs w-full",onClick:te,children:[e.jsx(dt,{className:"w-3 h-3 mr-1"}),"Agregar y guardar en catálogo"]})]})]}),u.length>0&&e.jsxs("div",{className:"rounded-lg border divide-y",children:[u.map(V=>e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2.5",children:[e.jsx("div",{className:"w-8 h-8 rounded-md bg-muted/50 flex items-center justify-center shrink-0 overflow-hidden",children:V.productImageUrl?e.jsx("img",{src:V.productImageUrl,alt:V.productName,className:"w-full h-full object-cover rounded-md"}):e.jsx(Ks,{className:"w-3.5 h-3.5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:V.productName}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[D(V.unitPrice)," x ",V.quantity]}),V.saveToCatalog&&e.jsx(De,{variant:"secondary",className:"h-4 px-1 text-[10px]",children:"Catálogo"})]})]}),e.jsx("span",{className:"text-sm font-medium tabular-nums shrink-0",children:D(V.unitPrice*V.quantity)}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[e.jsx(K,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>ge(V._key,-1),children:e.jsx(fo,{className:"w-3 h-3"})}),e.jsx("span",{className:"text-xs w-5 text-center tabular-nums",children:V.quantity}),e.jsx(K,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>ge(V._key,1),children:e.jsx(dt,{className:"w-3 h-3"})})]}),e.jsx(K,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive/60 hover:text-destructive",onClick:()=>xe(V._key),children:e.jsx(ns,{className:"w-3.5 h-3.5"})})]},V._key)),e.jsxs("div",{className:"flex items-center justify-between px-3 py-2.5 bg-muted/30",children:[e.jsx("span",{className:"text-sm font-medium",children:"Total"}),e.jsx("span",{className:"text-base font-bold tabular-nums",children:D(be)})]})]}),e.jsxs("div",{children:[e.jsx(we,{htmlFor:"sale-notes",className:"text-xs text-muted-foreground",children:"Notas (opcional)"}),e.jsx(Te,{id:"sale-notes",placeholder:"Notas sobre esta venta...",value:b,onChange:V=>y(V.target.value),className:"mt-1 h-8 text-sm"})]}),e.jsxs(es,{open:g,onOpenChange:v,children:[e.jsx(ts,{asChild:!0,children:e.jsxs(K,{variant:"ghost",size:"sm",className:"gap-1.5 text-xs text-muted-foreground h-7 px-2",children:[e.jsx(Zt,{className:`w-3 h-3 transition-transform ${g?"rotate-180":""}`}),"Avanzado"]})}),e.jsx(ss,{className:"mt-2",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(we,{htmlFor:"event-id",className:"text-xs text-muted-foreground",children:"Event ID (Meta CAPI)"}),e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsx(Tl,{className:"w-3 h-3 text-muted-foreground/50 cursor-help"})}),e.jsx(Re,{side:"top",className:"max-w-[260px]",children:e.jsx("p",{className:"text-xs",children:"Si tu web usa un ID diferente al Order ID de Nubot para deduplicar conversiones en el Pixel de Meta, ingrésalo aquí."})})]})]}),e.jsx(Te,{id:"event-id",placeholder:"Se usará el Order ID por defecto",value:p,onChange:V=>f(V.target.value),className:"mt-1 h-8 text-sm font-mono"})]})})]})]}),e.jsxs(Sl,{className:"border-t mt-auto sm:flex-row sm:justify-end",children:[e.jsx(K,{variant:"outline",onClick:()=>s(!1),disabled:U,children:"Cancelar"}),e.jsx(K,{onClick:ve,disabled:u.length===0||U||E,className:"gap-2",children:U?e.jsxs(e.Fragment,{children:[e.jsx(Se,{className:"w-4 h-4 animate-spin"}),c?"Guardando...":"Registrando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Va,{className:"w-4 h-4"}),c?"Guardar Cambios":"Registrar Venta",u.length>0&&e.jsx(De,{variant:"secondary",className:"ml-1 bg-primary-foreground/20 text-primary-foreground",children:D(be)})]})})]})]})})}const $u=new Set(["IN_PROGRESS_HUMAN","IN_PROGRESS_AI","WAITING","WAITING_ASSIGNMENT","OPEN"]),Xa=i.memo(({status:t,className:s,hideIfActive:a=!1})=>{if(!t||a&&$u.has(t))return null;const r=zu(t);if(!r)return null;const n=r.icon;return e.jsxs("span",{className:T("inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium leading-none border",r.classes,s),children:[e.jsx(n,{className:"w-3 h-3"}),e.jsx("span",{children:r.label})]})});Xa.displayName="TicketStatusBadge";function zu(t){switch(t){case"RESOLVED":return{label:"Resuelto",icon:ma,classes:"bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-500/15 dark:text-emerald-300 dark:border-emerald-500/30"};case"ARCHIVED":return{label:"Archivado",icon:bo,classes:"bg-slate-100 text-slate-600 border-slate-200 dark:bg-slate-800 dark:text-slate-400 dark:border-slate-700"};case"WAITING_ASSIGNMENT":case"WAITING":return{label:"En espera",icon:bt,classes:"bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-500/15 dark:text-amber-300 dark:border-amber-500/30"};case"IN_PROGRESS_AI":return{label:"Bot",icon:It,classes:"bg-sky-50 text-sky-700 border-sky-200 dark:bg-sky-500/15 dark:text-sky-300 dark:border-sky-500/30"};case"IN_PROGRESS_HUMAN":case"OPEN":return{label:"Activo",icon:xa,classes:"bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-500/15 dark:text-emerald-300 dark:border-emerald-500/30"};case"CAMPAIGN_OUTBOUND":return{label:"Campaña",icon:Es,classes:"bg-indigo-50 text-indigo-700 border-indigo-200 dark:bg-indigo-500/15 dark:text-indigo-300 dark:border-indigo-500/30"};default:return null}}function qu(t){const s=it(),a=rt({queryKey:["workflow","session",t],queryFn:async()=>{const{data:u}=await he.get(`/workflows/sessions/by-ticket/${t}`);return u??null},enabled:!!t,staleTime:3e4}),r=()=>{s.invalidateQueries({queryKey:["workflow","session",t]})},n=xt({mutationFn:async()=>{const{data:u}=await he.post(`/workflows/sessions/by-ticket/${t}/reset`);return u},onSuccess:()=>{H.success("Flujo reiniciado correctamente"),r()},onError:u=>{H.error(u?.response?.data?.message||"Error al reiniciar flujo")}}),o=xt({mutationFn:async()=>{const{data:u}=await he.patch(`/workflows/sessions/by-ticket/${t}/pause`);return u},onSuccess:()=>{H.success("Flujo pausado"),r()},onError:u=>{H.error(u?.response?.data?.message||"Error al pausar flujo")}}),l=xt({mutationFn:async()=>{const{data:u}=await he.patch(`/workflows/sessions/by-ticket/${t}/resume`);return u},onSuccess:()=>{H.success("Flujo reanudado"),r()},onError:u=>{H.error(u?.response?.data?.message||"Error al reanudar flujo")}}),c=a.data??null;return{session:c,isLoading:a.isLoading,hasSession:!!c&&c.status!=="COMPLETED",reset:n.mutate,pause:o.mutate,resume:l.mutate,resumeAsync:l.mutateAsync,isResetting:n.isPending,isPausing:o.isPending,isResuming:l.isPending,invalidate:r}}const ll=i.memo(({conversation:t,ticketStatus:s,isContactOnline:a,keepSessionAlive:r,onBack:n,onOpenProfile:o,onResolve:l,onAssignAgent:c,onAssignToTeam:u,onToggleKeepSession:d,onOpenShortcuts:m,onOpenMediaLimits:x,onToggleMediaOverride:b,onAssignBestAgent:y,onRequestContactInfo:p,disabled:f=!1})=>{const{contact:g,ticket:v,channel:h}=t,{session:I,hasSession:U,resumeAsync:C}=qu(v.id),{registerSale:E,updateSale:M,getSale:F}=ds(),_=v.assignedType==="META_AGENT",k=!!v.metadata?.meta_agent,W=Ye(j=>j.user?.isSuperAdmin),q=k||W&&Ss(h),ee=v.status!=="RESOLVED"&&v.status!=="ARCHIVED",[le,S]=i.useState(!1),P=i.useCallback(async()=>{const j=h?.id||v.channelId;if(j){S(!0);try{const{data:G}=await he.post(`/channels/${j}/meta-agent/release`,{ticketId:v.id});G?.released?H.success("Conversación devuelta al agente de Meta"):H.info(G?.omitido?`No se devolvió: ${G.omitido}`:"No se devolvió la conversación")}catch(G){H.error(G?.response?.data?.message||"No se pudo devolver la conversación a Meta")}finally{S(!1)}}},[h?.id,v.channelId,v.id]),[X,A]=i.useState(!1),z=i.useCallback(async()=>{const j=h?.id||v.channelId;if(j){A(!0);try{const{data:G}=await he.post(`/channels/${j}/meta-agent/recall`,{ticketId:v.id,forzar:!_});G?.released?H.success("Conversación recuperada: pasa a Nubot"):H.info(G?.omitido?`No se recuperó: ${G.omitido}`:"No se recuperó la conversación")}catch(G){H.error(G?.response?.data?.message||"No se pudo recuperar la conversación")}finally{A(!1)}}},[h?.id,v.channelId,v.id,_]),[L,N]=i.useState(!1),w=v.metadata?.saleOrderId,$=v.metadata?.saleTotal,ae=v.metadata?.saleCurrency||"USD",ne=v.metadata?.saleOrderNumber,re=!!w,be=v.status!=="RESOLVED"&&v.status!=="CLOSED",[D,Z]=i.useState(!1),te=!!p&&be&&!D&&!g?.phone&&String(h?.type||"").toLowerCase().startsWith("whatsapp")&&na(v.metadata?.customer_identifier),xe=i.useCallback(()=>{p?.(),Z(!0),H.success("Solicitud enviada",{description:"El lead verá el botón de WhatsApp para compartir su número."})},[p]),[ge,ve]=i.useState(!1),V=i.useCallback(async()=>{ve(!0);try{I?.status==="PAUSED"&&await C(),await c(null)}catch(j){H.error(j?.response?.data?.message||"Error al devolver al bot")}finally{ve(!1)}},[I?.status,C,c]);return e.jsxs("div",{className:"@container flex items-center gap-2 @md:gap-3 px-2 @md:px-4 h-14 border-b border-slate-100 bg-white/70 dark:bg-background/80 backdrop-blur-md sticky top-0 z-10 w-full",children:[e.jsxs("div",{className:"flex items-center gap-2 @md:gap-3 min-w-0",children:[n&&e.jsx(K,{variant:"ghost",size:"icon",onClick:n,className:"md:hidden h-9 w-9 shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Volver a la lista",children:e.jsx(ni,{className:"w-5 h-5"})}),e.jsxs("div",{className:"relative group cursor-pointer shrink-0",onClick:o,children:[e.jsxs(ht,{className:"h-9 w-9 @md:h-10 @md:w-10 border border-border transition-transform group-hover:scale-105",children:[e.jsx(pt,{src:g?.avatarUrl}),e.jsx(gt,{className:"bg-primary/10 text-primary font-medium text-sm",children:(g?.name||g?.phone||"U").charAt(0).toUpperCase()})]}),a&&e.jsx("span",{className:"absolute bottom-0 right-0 w-2.5 h-2.5 bg-emerald-500 border-2 border-background rounded-full"})]}),e.jsxs("div",{className:"hidden @xl:block min-w-0 shrink",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{className:"font-semibold text-foreground text-sm truncate max-w-[140px] @2xl:max-w-[180px] @3xl:max-w-[220px]",children:g?.name||g?.phone||"Usuario"}),e.jsx(Xa,{status:v.status,hideIfActive:!0}),g?.tags&&g.tags.length>0&&e.jsxs(De,{variant:"secondary",className:"hidden @2xl:inline-flex h-5 px-1.5 text-[10px] font-normal text-muted-foreground bg-muted/50 border border-border",children:[g.tags[0],g.tags.length>1&&` + ${g.tags.length-1} `]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Uu(g?.phone,g?.email,v.metadata?.customer_identifier)}),te&&e.jsx(K,{variant:"ghost",size:"sm",disabled:f,onClick:xe,className:"h-5 px-1.5 text-[11px] font-normal text-primary hover:text-primary shrink-0",title:"Enviar el botón de WhatsApp para que el lead comparta su número",children:"Solicitar número"})]})]}),e.jsx("div",{className:"@xl:hidden",children:e.jsx(Xa,{status:v.status,hideIfActive:!0})}),e.jsxs("div",{className:"hidden @md:flex items-center shrink min-w-0 gap-1.5",children:[_?e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsxs(De,{variant:"outline",className:"h-7 gap-1.5 px-2.5 font-medium whitespace-nowrap text-sky-700 bg-sky-50 border-sky-200 dark:text-sky-300 dark:bg-sky-950/40 dark:border-sky-900",children:[e.jsx(It,{className:"w-3.5 h-3.5"}),"Meta está atendiendo"]})}),e.jsx(Re,{side:"bottom",className:"max-w-[260px] text-xs",children:"El agente de IA de Meta le responde a este cliente. Si escribes, tomas la conversación y Meta deja de responderle."})]}):e.jsx(Lu,{currentAgentId:v.assignedType==="AI"&&v.aiAgentId||v.assignedAgentId,currentAssignedType:v.assignedType,onAssign:c,onAssignToTeam:u,onAssignBestAgent:y,disabled:f}),q&&!_&&ee&&e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsxs(K,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs whitespace-nowrap text-sky-700 dark:text-sky-300",onClick:P,disabled:f||le,children:[e.jsx(Lr,{className:"w-3.5 h-3.5 mr-1"}),"Devolver a Meta"]})}),e.jsx(Re,{side:"bottom",className:"max-w-[260px] text-xs",children:"El agente de Meta vuelve a responderle a este cliente desde ahora."})]}),W&&Ss(h)&&ee&&e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsxs(K,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs whitespace-nowrap text-amber-700 dark:text-amber-400",onClick:z,disabled:f||X,children:[e.jsx(Lr,{className:"w-3.5 h-3.5 mr-1 rotate-180"}),_?"Recuperar de Meta":"Recuperar de Meta (forzado)"]})}),e.jsx(Re,{side:"bottom",className:"max-w-[260px] text-xs",children:_?"Le quita el hilo a Meta sin escribirle al cliente (thread_control take). Pasa a Espera, sin asignar. Solo tú ves este botón.":"Diagnóstico: Nubot no muestra a Meta como dueño de este ticket, pero igual llama a thread_control take contra la API real, para ver qué responde Meta. Solo tú ves este botón."})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 @md:gap-2 shrink-0 ml-auto",children:[U&&I&&e.jsx("div",{className:"hidden @lg:flex",children:e.jsx(bi,{session:I})}),(v.metadata?.inactivity_cycle_count??0)>0&&e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsx("div",{className:"hidden @md:flex",children:e.jsxs(De,{variant:"outline",className:"text-[10px] h-6 px-1.5 font-semibold text-orange-600 bg-orange-50 border-orange-200 gap-1 cursor-default",children:[e.jsx(Rn,{className:"w-3 h-3"}),v.metadata.inactivity_cycle_count," ",v.metadata.inactivity_cycle_count===1?"ciclo":"ciclos"]})})}),e.jsxs(Re,{side:"bottom",className:"max-w-[250px]",children:[e.jsx("p",{className:"font-medium",children:"Ciclos de inactividad del cliente"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["El cliente ha pasado por ",v.metadata.inactivity_cycle_count," ",v.metadata.inactivity_cycle_count===1?"ciclo":"ciclos"," de inactividad sin responder"]})]})]}),v.assignedType==="HUMAN"&&U&&I&&e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsxs(K,{variant:"outline",size:"sm",className:"hidden @md:inline-flex h-7 gap-1.5 text-xs bg-emerald-50 border-emerald-200 text-emerald-700 hover:bg-emerald-100 hover:text-emerald-800 dark:bg-emerald-950/20 dark:border-emerald-800 dark:text-emerald-400 dark:hover:bg-emerald-950/40",onClick:V,disabled:ge||f,children:[e.jsx(It,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"hidden @2xl:inline",children:ge?"Devolviendo...":"Regresar al Bot"})]})}),e.jsx(Re,{side:"bottom",children:I.status==="PAUSED"?"Reanudar flujo y devolver al bot":"Devolver ticket al bot"})]}),e.jsx("div",{className:"hidden @md:flex",children:e.jsx(nl,{ticketId:v.id,currentFunnelId:v.funnelId,currentStageId:v.funnelStageId,compact:!0,disabled:f})}),be&&e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:re?e.jsxs(K,{variant:"outline",size:"sm",className:"hidden @md:inline-flex h-7 gap-1.5 text-xs bg-emerald-50 border-emerald-200 text-emerald-700 hover:bg-emerald-100 dark:bg-emerald-950/20 dark:border-emerald-800 dark:text-emerald-400 cursor-pointer",onClick:()=>N(!0),children:[e.jsx(Ie,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"hidden @xl:inline tabular-nums",children:new Intl.NumberFormat("es-PE",{style:"currency",currency:ae}).format($)})]}):e.jsxs(K,{variant:"default",size:"sm",className:"hidden @md:inline-flex h-7 gap-1.5 text-xs cursor-pointer",onClick:()=>N(!0),disabled:f,children:[e.jsx(Va,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"hidden @xl:inline",children:"Registrar Venta"})]})}),e.jsx(Re,{side:"bottom",children:re?`Venta: ${ne||w}`:"Registrar una venta para este ticket"})]}),e.jsxs(Vn,{children:[e.jsx(Bn,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-8 w-8 rounded-full text-muted-foreground hover:text-foreground",children:e.jsx(li,{className:"w-4 h-4"})})}),e.jsxs($n,{align:"end",className:"w-56",children:[e.jsx(El,{children:"Opciones"}),e.jsx(zs,{}),l&&s!=="RESOLVED"&&s!=="ARCHIVED"&&e.jsxs(e.Fragment,{children:[e.jsxs(wt,{onClick:l,disabled:f,className:"gap-2 cursor-pointer text-emerald-600 dark:text-emerald-400 focus:text-emerald-700 focus:bg-emerald-50 dark:focus:bg-emerald-950/30",children:[e.jsx(ma,{className:"w-4 h-4"}),e.jsx("span",{className:"font-medium",children:"Finalizar Chat"})]}),e.jsx(zs,{})]}),(()=>{const j=h?.config?.session_timeout_sec,G=j!==void 0&&j!==-1&&j!==0,se=!!h?.config?.auto_close?.enabled,de=v.assignedType==="HUMAN"||v.assignedType==="AI";return(G||se)&&de})()&&e.jsxs(wt,{onClick:d,disabled:f,className:"gap-2 cursor-pointer",children:[e.jsx(Xo,{className:T("w-4 h-4 transition-transform",r?"text-amber-500 rotate-0":"text-muted-foreground rotate-45")}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:T(r?"text-amber-600 dark:text-amber-400 font-medium":""),children:r?"Sesión fijada":"Fijar sesión"}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:r?"No se cerrará por inactividad":"Evita el cierre automático"})]})]}),e.jsxs(wt,{onClick:m,className:"gap-2 cursor-pointer",children:[e.jsx(mi,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{children:"Atajos de Teclado"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground font-mono",children:"Ctrl+H"})]}),e.jsxs(wt,{onClick:x,className:"gap-2 cursor-pointer",children:[e.jsx(di,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{children:"Límites de Multimedia"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground font-mono",children:"Ctrl+M"})]}),h?.config?.mediaLimits?.allowAgentOverride&&e.jsxs(e.Fragment,{children:[e.jsx(zs,{}),e.jsx(wt,{onClick:b,className:"gap-2 cursor-pointer",children:v.metadata?.media_override?e.jsxs(e.Fragment,{children:[e.jsx(Vo,{className:"w-4 h-4 text-green-500"}),e.jsx("span",{className:"text-green-600 font-medium",children:"Media Desbloqueada"})]}):e.jsxs(e.Fragment,{children:[e.jsx(As,{className:"w-4 h-4 text-orange-500"}),e.jsx("span",{children:"Desbloquear Media (Ticket)"})]})})]})]})]})]}),e.jsx(Bu,{open:L,onOpenChange:N,ticketId:v.id,onSubmit:E,onUpdate:M,onLoadSale:F,existingSale:re?{orderId:w,orderNumber:ne||w,total:$,currency:ae}:null})]})});ll.displayName="ChatHeader";const ol=i.memo(({ticketId:t,contactId:s,channelId:a,canReopen:r,onTicketReopened:n,onNavigateToTicket:o})=>{const{reopenTicket:l}=ds(),[c,u]=i.useState(!1),d=rt({queryKey:["inbox","contact-open-ticket",s,a],queryFn:()=>Ce.getContactOpenTicket(s,a),enabled:!!s&&r,staleTime:5e3,refetchOnWindowFocus:!0}),m=d.data??null,x=!!m,b=async()=>{if(!(c||!r)){u(!0);try{await l(t),H.success("Ticket reabierto"),n?.()}catch(p){const f=p?.response?.data;p?.response?.status===409&&f?.existingTicketId?(await d.refetch(),H.error(`Este contacto ya tiene un ticket abierto${f.channelName?` en ${f.channelName}`:""}. Abre ese ticket en lugar de reabrir este.`)):p?.response?.status===403?H.error("Solo administradores pueden reabrir tickets"):H.error(f?.message||"No se pudo reabrir el ticket. Intenta de nuevo.")}finally{u(!1)}}},y=i.useMemo(()=>m?.ticketId?m.ticketId.slice(0,8):null,[m]);return e.jsxs("div",{className:T("flex items-center justify-between gap-3 px-4 py-2.5 border-t border-b","bg-emerald-50/70 dark:bg-emerald-950/30","border-emerald-200 dark:border-emerald-900/50"),role:"status",children:[e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[e.jsx("div",{className:"flex items-center justify-center w-8 h-8 rounded-full bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300 shrink-0",children:e.jsx(As,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-emerald-900 dark:text-emerald-100 leading-tight",children:"Conversación cerrada"}),e.jsx("p",{className:"text-xs text-emerald-700/80 dark:text-emerald-300/70 leading-tight",children:"Si le escribes o le envías una plantilla, la conversación sigue y queda asignada a ti."})]})]}),r&&e.jsx(rs,{delayDuration:150,children:e.jsxs(Oe,{children:[e.jsx(Ue,{asChild:!0,children:e.jsx("span",{tabIndex:x?0:-1,children:e.jsxs(K,{size:"sm",variant:"outline",disabled:x||c||d.isLoading,onClick:b,className:T("h-8 gap-1.5 border-emerald-300 text-emerald-700 hover:bg-emerald-100 hover:text-emerald-900","dark:border-emerald-700 dark:text-emerald-200 dark:hover:bg-emerald-900/40"),children:[c?e.jsx(Se,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(ys,{className:"w-3.5 h-3.5"}),"Reabrir ticket"]})})}),x&&m&&e.jsx(Re,{side:"left",className:"max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs leading-relaxed",children:["Este contacto ya tiene un ticket abierto",m.channelName?` en ${m.channelName}`:"",y?` (#${y})`:"",". No se puede reabrir este hasta que el otro se cierre."]}),o&&m.ticketId&&e.jsxs(K,{size:"sm",variant:"secondary",className:"h-7 w-full text-xs gap-1.5",onClick:()=>o(m.ticketId),children:[e.jsx(ca,{className:"w-3 h-3"}),"Ver ticket vigente"]})]})})]})})]})});ol.displayName="ResolvedBanner";const Hu=300*1e3;i.memo(function({segment:s,contactName:a,channelType:r,onQuoteClick:n,highlightedId:o}){const l=i.useMemo(()=>Xs(s.messages),[s.messages]),c=i.useMemo(()=>aa(s.messages),[s.messages]);return e.jsxs("section",{className:"space-y-4","aria-label":`Conversación anterior del ${new Date(s.ticket.createdAt).toLocaleDateString("es-ES")}`,children:[s.messages.map((u,d)=>{const m=s.messages[d-1],x=!m||new Date(u.createdAt).getTime()-new Date(m.createdAt).getTime()>Hu;return e.jsx(mr,{message:u,showTimestamp:x,contactName:a,channelType:r,carouselCardRefs:l,quotedRefs:c,onQuoteClick:n,isHighlighted:u.id===o,readOnly:!0},u.id)}),e.jsx($i,{ticket:s.ticket})]})});const Gu=({isOpen:t,onClose:s,channel:a})=>{const r=a?Hs(a.type):Jt,n=a?.config?.mediaLimits?.outbound||r.outbound,o=a?.config?.mediaLimits?.allowAgentOverride,l=[{label:"Imágenes",limit:n.image,icon:We},{label:"Videos",limit:n.video,icon:so},{label:"Audios",limit:n.audio,icon:yo},{label:"Documentos",limit:n.document,icon:tt}];return e.jsx(yt,{open:t,onOpenChange:s,children:e.jsx(jt,{className:"sm:max-w-md border-none shadow-2xl bg-white/95 dark:bg-zinc-950/95 backdrop-blur-md p-0 overflow-hidden",children:e.jsxs("div",{className:"p-8",children:[e.jsxs(Ut,{className:"pb-4 mb-6 border-b border-gray-100 dark:border-gray-800",children:[e.jsxs(vt,{className:"flex items-center gap-2.5 text-xl font-light tracking-tight text-foreground",children:[e.jsx(di,{className:"w-5 h-5 text-primary/70"}),"Límites de Multimedia"]}),e.jsx(Rt,{className:"text-sm font-normal text-muted-foreground mt-1",children:"Peso máximo permitido para archivos salientes en este canal."})]}),e.jsx("div",{className:"space-y-5",children:l.map(c=>e.jsxs("div",{className:"flex items-center justify-between group",children:[e.jsxs("span",{className:"text-sm font-medium text-gray-600 dark:text-gray-300 group-hover:text-primary transition-colors flex items-center gap-3",children:[e.jsx(c.icon,{className:"w-4 h-4 text-muted-foreground/40 group-hover:text-primary/50 transition-colors"}),c.label]}),e.jsx("div",{className:"flex gap-1",children:e.jsx("kbd",{className:"px-3 py-1 text-xs font-semibold text-gray-500 bg-gray-100/60 border border-gray-200 rounded-lg dark:bg-gray-800/60 dark:text-gray-400 dark:border-gray-700 shadow-sm min-w-[65px] text-center",children:mo(c.limit.maxBytes)})})]},c.label))}),e.jsxs("div",{className:"mt-10 pt-8 border-t border-gray-100 dark:border-gray-800 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3.5 p-4 bg-muted/40 dark:bg-zinc-900/40 rounded-2xl border border-border/50",children:[e.jsx(Fa,{className:"w-4 h-4 text-muted-foreground/60 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-[11px] text-muted-foreground leading-relaxed",children:[e.jsx("p",{className:"font-semibold mb-1 text-foreground/80 lowercase italic opacity-80",children:"Nota de optimización"}),e.jsxs("p",{children:["Actualmente, solo las ",e.jsx("span",{className:"font-bold text-foreground/90",children:"imágenes"})," son optimizadas automáticamente para reducir su impacto en el canal."]})]})]}),o&&e.jsxs("div",{className:"flex items-start gap-3.5 p-4 bg-amber-50/30 dark:bg-amber-900/10 rounded-2xl border border-amber-200/20",children:[e.jsx(ct,{className:"w-4 h-4 text-amber-500/60 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-[11px] text-muted-foreground leading-relaxed",children:[e.jsx("p",{className:"font-semibold mb-1 text-amber-800/80 dark:text-amber-200/80",children:"Bypass"}),e.jsx("p",{children:"Los límites para este ticket han sido desactivados manualmente por el agente."})]})]})]})]})})})},Wu=new Set(["AGENT","BOT","AI_AGENT","NOTE"]);function Qu(t){return!!t&&Wu.has(t.senderType)}function Ku({esCargaInicial:t,hayMensajeNuevo:s,estaLeyendoArriba:a,estaCargandoMasArriba:r,ultimo:n}){return r?"no-tocar":t?"ir-al-final":s?Qu(n)?"ir-al-final":a?"contar-nuevos":"ir-al-final":"no-tocar"}const Yu=({conversation:t,messages:s,isLoadingMore:a,hasMore:r,onLoadMore:n,history:o,onSendMessage:l})=>{const[c,u]=i.useState(t?.ticket.status||"OPEN"),d=Ye(D=>D.user),m=fe(D=>D.activeConversationId),{assignTicket:x}=ds(),b=i.useRef(null),y=i.useRef(null),p=i.useRef(0),[f,g]=i.useState(!1),[v,h]=i.useState(!1),[I,U]=i.useState(!1),[C,E]=i.useState(!1),[M,F]=i.useState(!1),[_,k]=i.useState(()=>t?.ticket?.metadata?.keepSessionAlive??t?.ticket?.assignedType==="HUMAN");i.useEffect(()=>{const D=Z=>{(Z.ctrlKey||Z.metaKey)&&Z.key.toLowerCase()==="h"&&(Z.preventDefault(),E(te=>!te)),(Z.ctrlKey||Z.metaKey)&&Z.key.toLowerCase()==="m"&&(Z.preventDefault(),F(te=>!te))};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[]),i.useEffect(()=>{t?.ticket&&(k(t.ticket.metadata?.keepSessionAlive??t.ticket.assignedType==="HUMAN"),t.ticket.status&&u(t.ticket.status))},[t?.ticket]);const W=i.useMemo(()=>{if(!s||s.length===0)return[];const D=new Set;return s.filter(Z=>D.has(Z.id)?!1:(D.add(Z.id),!0))},[s]),q=i.useRef(!0),ee=i.useRef(0),le=i.useRef(!1),[S,P]=i.useState(0);i.useEffect(()=>{if(!b.current||W.length===0)return;const D=W.length>ee.current,Z=W.length-ee.current,te=q.current;ee.current=W.length;const xe=Ku({esCargaInicial:te,hayMensajeNuevo:D,estaLeyendoArriba:le.current,estaCargandoMasArriba:!!a,ultimo:W[W.length-1]});if(xe!=="no-tocar"){if(xe==="contar-nuevos"){P(ge=>ge+Math.max(Z,1));return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{b.current?.scrollIntoView({behavior:te?"instant":"smooth"}),q.current=!1,P(0)})})}},[W,a]),i.useEffect(()=>{if(!a&&p.current>0&&y.current){const D=y.current,te=D.scrollHeight-p.current;te>0&&(D.scrollTop=te),p.current=0}},[a,W]);const X=i.useCallback(D=>{const Z=D.currentTarget,te=Z.scrollHeight-Z.scrollTop-Z.clientHeight,ge=te>500;le.current=ge,U(G=>G!==ge?ge:G),ge||P(0);const ve=t?.ticket?.id,V=t?.ticket?.unreadCount??0;if(te<100&&ve&&V>0&&W.length>0){const G=W[W.length-1];if(G){const se=G.channelMessageId||void 0,de=G.id&&!G.id.startsWith("temp-")?G.id:void 0;Ce.markAsRead(ve,de,se).catch(console.error)}}const j=r||!!o?.canScrollLoad;Z.scrollTop<50&&j&&!a&&n&&(p.current=Z.scrollHeight,n())},[r,o?.canScrollLoad,a,n,t?.ticket?.id,t?.ticket?.unreadCount,W]),A=i.useCallback(()=>{o?.canLoadPrevious&&(y.current&&(p.current=y.current.scrollHeight),o.onLoadPrevious())},[o]),z=i.useCallback(()=>{b.current?.scrollIntoView({behavior:"smooth"}),P(0)},[]),L=async(D,Z="HUMAN")=>{if(t)try{await x(t.ticket.id,D,Z)}catch(te){console.error("Failed to assign ticket",te)}},N=async()=>{if(t)try{const D=Ce.assignToBestAgentInOrg(t.ticket.id);H.promise(D,{loading:"Buscando al mejor agente...",success:Z=>`Asignado a ${Z.agentName} (Score: ${Z.score})`,error:Z=>`Error: ${Z.response?.data?.message||"No se pudo asignar automáticamente"}`}),await D}catch(D){console.error("Failed to auto-assign ticket",D)}},w=async D=>{if(!t)return{assignedAgentId:"",agentName:""};try{return await Ce.assignToTeam(t.ticket.id,D)}catch(Z){return console.error("Failed to assign ticket to team",Z),{assignedAgentId:"",agentName:""}}},$=async()=>{if(!t?.ticket)return;const D=!_;k(D);try{await Ce.toggleKeepSession(t.ticket.id,D)}catch(Z){console.error("Error toggling keep session:",Z),k(!D)}},ae=async()=>{if(!t?.ticket)return;const D=t.ticket.metadata?.media_override===!0;try{await Ce.updateTicketMetadata(t.ticket.id,{...t.ticket.metadata,media_override:!D})}catch(Z){console.error("Failed to toggle media override",Z)}},ne=D=>{const te=D.displayMode==="list"||D.options.length>3?{type:"list",body:D.body,menuButton:D.menuButton||void 0,options:D.options.map(xe=>({id:xe.id,label:xe.label,...xe.description?{description:xe.description}:{}}))}:{type:"buttons",body:D.body,buttons:D.options.map(xe=>({id:xe.id,title:xe.label}))};Promise.resolve(l?.(JSON.stringify(te),"INTERACTIVE")).catch(()=>{}),g(!1)},re=D=>{Promise.resolve(l?.(JSON.stringify(D),"INTERACTIVE")).catch(()=>{}),h(!1)},be=i.useMemo(()=>t?.contact?.lastSeenAt?Date.now()-new Date(t.contact.lastSeenAt).getTime()<(pi?.PRESENCE_TIMEOUT_MS||6e4):!1,[t?.contact?.lastSeenAt]);return{ticketStatus:c,setTicketStatus:u,user:d,messagesEndRef:b,messagesContainerRef:y,isButtonDialogOpen:f,setIsButtonDialogOpen:g,isCarouselDialogOpen:v,setIsCarouselDialogOpen:h,isScrolledUp:I,newMessageCount:S,keepSessionAlive:_,showShortcutsDialog:C,setShowShortcutsDialog:E,showMediaLimitsDialog:M,setShowMediaLimitsDialog:F,localMessages:W,isContactOnline:be,activeConversationId:m,handleMessagesScroll:X,handleLoadPrevious:A,scrollToBottom:z,handleAssignAgent:L,handleAssignBestAgent:N,handleAssignToTeam:w,handleToggleKeepSession:$,handleToggleMediaOverride:ae,handleSendButtonMessage:ne,handleSendCarousel:re}},cl=i.memo(({conversation:t,messages:s,typingIndicator:a,onOpenProfile:r,onBack:n,onSendMessage:o,onSendNote:l,onInteractiveOption:c,onStartTyping:u,onStopTyping:d,onResolve:m,onLoadMore:x,hasMore:b=!1,isLoadingMore:y=!1,isLoadingConversation:p=!1,history:f,loadError:g,messagesError:v,onRetryLoad:h,onRetryMessages:I})=>{const U=sr(R=>R.channels),{ticketStatus:C,user:E,isButtonDialogOpen:M,setIsButtonDialogOpen:F,isCarouselDialogOpen:_,setIsCarouselDialogOpen:k,keepSessionAlive:W,showShortcutsDialog:q,setShowShortcutsDialog:ee,showMediaLimitsDialog:le,setShowMediaLimitsDialog:S,localMessages:P,isContactOnline:X,handleAssignAgent:A,handleAssignBestAgent:z,handleAssignToTeam:L,handleToggleKeepSession:N,handleToggleMediaOverride:w,handleSendButtonMessage:$,handleSendCarousel:ae}=Yu({conversation:t,messages:s,isLoadingMore:y,hasMore:b,onLoadMore:x,history:f,onSendMessage:o}),ne=fe(R=>R.setTicketInactivityState);i.useMemo(()=>Xs(P),[P]),i.useMemo(()=>aa(P),[P]);const re=i.useMemo(()=>hi(t?.ticket),[t?.ticket]),be=i.useMemo(()=>{if(!(!re||b))return P.find(R=>R.senderType==="CONTACT")?.id},[re,b,P]),[D,Z]=i.useState(null);i.useCallback(R=>{const Y=document.getElementById(`msg-${R}`);Y&&(Y.scrollIntoView({behavior:"smooth",block:"center"}),Z(R),setTimeout(()=>Z(oe=>oe===R?null:oe),1600))},[]);const te=i.useCallback((R,Y="TEXT",oe)=>{if(!(!R.trim()&&Y==="TEXT"))return o?.(R,Y,oe)},[o]),xe=i.useCallback((R,Y)=>{c?.(R,Y)},[c]),ge=i.useCallback(()=>{const R=t?.contact?.name?.trim();Promise.resolve(o?.(JSON.stringify({kind:"request_contact_info",body:`${R?`${R}, para`:"Para"} poder darte seguimiento y enviarte la información, ¿nos compartes tu número de teléfono?`}),"INTERACTIVE")).catch(()=>{})},[o,t?.contact?.name]);i.useEffect(()=>{const R=t?.ticket;if(!R?.id)return;const Y=R.metadata?.inactivity_disabled!==void 0,oe=R.assignedType==="HUMAN",pe=!(Y?R.metadata?.inactivity_disabled===!0:oe),Ne=fe.getState().ticketInactivityState[R.id];(Ne===void 0||Ne!==pe)&&ne(R.id,pe)},[t?.ticket?.id,t?.ticket?.metadata?.inactivity_disabled,t?.ticket?.assignedType,ne]);const ve=al(),V=t?.ticket?.id,j=t?.ticket?.status,G=i.useCallback(()=>ve(V??"",j),[ve,V,j]),se=i.useMemo(()=>{const R=t?.ticket?.metadata,Y=R?.last_client_message_at??R?.resumed_client_last_message_at;let oe=Y?new Date(Y).getTime():0;for(const ce of P){if(ce.senderType!=="CONTACT")continue;const pe=new Date(ce.createdAt).getTime();pe>oe&&(oe=pe)}return oe||null},[t?.ticket?.metadata,P]),de=Ss(t?.channel)&&se!==null&&Date.now()-se>1440*60*1e3;if(!t)return e.jsx(rl,{isLoadingMore:y,isLoadingConversation:p,loadError:g,onRetryLoad:h});const{contact:Ae,ticket:ue,channel:je}=t,ke=U.find(R=>R.id===je?.id),Q=ke?ke.isActive:je?.isActive??!0,ie=je?.name||"Canal Desconocido",O=ue?.status==="WAITING"||ue?.status==="WAITING_ASSIGNMENT",B=ue?.status==="RESOLVED"||ue?.status==="ARCHIVED",J=!!(E?.isSuperAdmin||E?.role==="OWNER"||E?.role==="ADMIN"),me=Ae?.hasLimitTag===!0;return e.jsxs("div",{className:"flex-1 flex flex-col bg-background h-full",children:[e.jsx(ll,{conversation:t,disabled:!Q||B,ticketStatus:C,isContactOnline:X,keepSessionAlive:W,onBack:n,onOpenProfile:r,onResolve:m,onAssignAgent:A,onAssignToTeam:L,onAssignBestAgent:z,onToggleKeepSession:N,onOpenShortcuts:()=>ee(!0),onOpenMediaLimits:()=>S(!0),onToggleMediaOverride:w,onRequestContactInfo:ge}),!Q&&e.jsxs("div",{className:"bg-amber-50 dark:bg-amber-950/30 px-6 py-3 border-b border-amber-100 dark:border-amber-900/50 flex items-center justify-center gap-2 text-amber-700 dark:text-amber-500 text-sm",children:[e.jsx(ft,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:"Canal Desactivado"}),e.jsx("span",{className:"hidden sm:inline text-amber-600/80 dark:text-amber-500/80",children:"• Este canal no recibirá nuevos mensajes hasta que sea reactivado."})]}),ue.sourceCampaignId&&(()=>{const R=E?.role==="OWNER"||E?.role==="ADMIN";return e.jsxs("div",{className:"bg-violet-50 dark:bg-violet-950/30 px-4 py-2 border-b border-violet-100 dark:border-violet-900/50 flex items-center justify-between text-violet-700 dark:text-violet-400 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Es,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:"Respuesta a Campaña"}),e.jsx("span",{className:"hidden sm:inline text-violet-600/80 dark:text-violet-400/80",children:"• Este cliente respondió a un mensaje de campaña masiva."})]}),e.jsxs(K,{variant:"ghost",size:"sm",className:T("h-6 text-violet-600 dark:text-violet-400",R?"hover:text-violet-700 hover:bg-violet-100 dark:hover:bg-violet-900/50 cursor-pointer":"opacity-50 cursor-not-allowed"),onClick:R?()=>window.open(`/campanas/${ue.sourceCampaignId}`,"_blank"):void 0,disabled:!R,title:R?"Ver detalles de la campaña":"Solo administradores pueden ver los detalles de la campaña",children:["Ver Campaña",e.jsx(ca,{className:"w-3 h-3 ml-1"})]})]})})(),e.jsx(zi,{messages:P,conversation:t,typingIndicator:a,onInteractiveOption:xe,fallbackReferral:re,fallbackReferralMessageId:be,onLoadMore:x,hasMore:b,isLoadingMore:y,history:f,onLoadPrevious:f?.onLoadPrevious,messagesError:v,onRetryMessages:I,isLoadingConversation:p}),me&&e.jsxs("div",{className:"bg-red-50 dark:bg-red-950/30 px-6 py-3 border-t border-red-100 dark:border-red-900/50 flex items-center justify-center gap-2 text-red-700 dark:text-red-400 text-sm",children:[e.jsx(As,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:"Límite de Contactos Excedido"}),e.jsx("span",{className:"hidden sm:inline text-red-600/80 dark:text-red-400/80",children:"• Has alcanzado el máximo de contactos permitidos en tu plan. Actualiza tu plan para continuar enviando mensajes."})]}),B&&e.jsx(ol,{ticketId:ue.id,contactId:Ae?.id,channelId:ue.channelId,canReopen:J,onNavigateToTicket:R=>{fe.getState().selectConversation(R)}}),Q&&de&&!O&&e.jsxs("div",{className:"bg-amber-50 dark:bg-amber-950/30 px-4 py-2 border-t border-amber-100 dark:border-amber-900/50 flex items-start gap-2 text-amber-800 dark:text-amber-400 text-xs",children:[e.jsx(ft,{className:"w-3.5 h-3.5 flex-shrink-0 mt-0.5"}),e.jsx("span",{children:"Pasaron más de 24 horas desde el último mensaje del cliente. WhatsApp solo entrega plantillas: usa el botón de plantillas para escribirle."})]}),Q?e.jsxs("div",{className:"relative",children:[e.jsx(el,{onSendMessage:te,onSendNote:l,onStartTyping:u,onStopTyping:d,onOpenButtonDialog:()=>F(!0),onOpenCarouselDialog:Ss(t?.channel)?()=>k(!0):void 0,channelName:ie,ticketId:t?.ticket.id||"",disabled:O||me,resolveTicketId:G,inactivityEnabled:(()=>{const R=je?.config?.client_inactivity;if(!R?.enabled||ue.assignedType==="HUMAN"&&!R.apply_to_human_tickets)return!1;const Y=R.max_cycles??3;return!(Y>0&&(ue.metadata?.inactivity_cycle_count??0)>=Y)})(),canToggleInactivity:E?.role==="OWNER"||E?.role==="ADMIN"||!!E?.id&&E.id===ue.assignedAgentId,typingEnabled:je?.config?.typingIndicators?.outbound!==!1,assignedType:ue.assignedType,mediaLimits:je?.config?.mediaLimits,channel:je,templateContext:{contact:{name:Ae?.name,firstName:Ae?.name?.split(" ")[0],lastName:Ae?.name?.split(" ").slice(1).join(" "),phone:Ae?.phone,email:Ae?.email,metadata:Ae?.metadata},ticket:{id:ue.id,number:ue.id?.slice(-6)},agent:{name:E?.name}}}),O&&e.jsx("div",{className:"absolute inset-0 bg-white/10 dark:bg-gray-900/10 z-50 pointer-events-none"})]}):e.jsxs("div",{className:"p-4 bg-gray-50 dark:bg-muted/20 border-t flex flex-col items-center justify-center text-gray-400 dark:text-muted-foreground text-sm gap-2 min-h-[80px]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jo,{className:"w-4 h-4"}),e.jsx("span",{className:"font-medium",children:"Interacción desactivada"})]}),e.jsx("span",{className:"text-xs opacity-70",children:"Reactiva el canal para responder"})]}),e.jsx(Iu,{isOpen:M,onClose:()=>F(!1),onSend:$}),e.jsx(Mu,{isOpen:_,onClose:()=>k(!1),onSend:ae,channelId:ue.channelId}),e.jsx(yt,{open:q,onOpenChange:ee,children:e.jsxs(jt,{className:"sm:max-w-md border-none shadow-2xl bg-white/95 dark:bg-zinc-950/95 backdrop-blur-md",children:[e.jsxs(Ut,{className:"pb-4 border-b border-gray-100 dark:border-gray-800",children:[e.jsxs(vt,{className:"flex items-center gap-2 text-xl font-light tracking-tight",children:[e.jsx(mi,{className:"w-5 h-5 text-primary/80"}),"Atajos de Teclado"]}),e.jsx(Rt,{children:"Domina tu flujo de trabajo con estos accesos rápidos."})]}),e.jsx("div",{className:"grid gap-5 py-4",children:[{label:"Enviar mensaje",keys:["Enter"]},{label:"Nueva línea",keys:["Shift","Enter"]},{label:"Nota interna (Toggle)",keys:["Ctrl","N"]},{label:"Info del contacto (Toggle)",keys:["Ctrl","I"]},{label:"Buscar plantillas",keys:["/"]},{label:"Cerrar Plantillas/Adjuntos",keys:["Esc"]}].map((R,Y)=>e.jsxs("div",{className:"flex items-center justify-between group",children:[e.jsx("span",{className:"text-sm font-medium text-gray-600 dark:text-gray-300 group-hover:text-primary transition-colors",children:R.label}),e.jsx("div",{className:"flex gap-1",children:R.keys.map((oe,ce)=>e.jsx("kbd",{className:"px-2.5 py-1 text-xs font-semibold text-gray-500 bg-gray-100 border border-gray-200 rounded-md dark:bg-gray-800 dark:text-gray-400 dark:border-gray-700 shadow-sm",children:oe},ce))})]},Y))})]})}),e.jsx(Gu,{isOpen:le,onClose:S,channel:je})]})});cl.displayName="ChatView";const Xu=t=>["inbox","channel-schema","with-system",t];function Zu(t){return rt({queryKey:Xu(t),queryFn:()=>t?ar.getSchemaForChannel(t,{entityType:"contact",includeSystem:!0}):null,enabled:!!t,staleTime:600*1e3,gcTime:1800*1e3})}function dl(){const t=it(),s=fe(a=>a.activeConversationId);return rt({queryKey:["inbox","conversation",s],queryFn:()=>s?Ce.getConversation(s):Promise.resolve(null),enabled:!!s,staleTime:1e3*60,initialData:()=>{if(!s)return;const a=t.getQueryData(["inbox","conversations"]);if(a)for(const r of a.pages){const n=r.data.find(o=>o.ticket.id===s);if(n)return n}},initialDataUpdatedAt:()=>(t.getQueryData(["inbox","conversations"]),t.getQueryState(["inbox","conversations"])?.dataUpdatedAt)})}function Ju(t){const s=new Date(t),r=new Date().getTime()-s.getTime(),n=Math.floor(r/6e4),o=Math.floor(r/36e5),l=Math.floor(r/864e5);return n<1?"Ahora":n<60?`Hace ${n} min`:o<24?`Hace ${o}h`:l<7?`Hace ${l} días`:Hn(s)}const ul=i.memo(({notes:t,isLoading:s=!1,className:a})=>{const r=t.filter(n=>n.senderType==="NOTE").filter((n,o,l)=>o===l.findIndex(c=>c.id===n.id));return e.jsx("div",{className:T("space-y-3",a),children:s?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Se,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):r.length===0?e.jsxs("div",{className:"text-center py-8 px-4 border border-dashed rounded-lg bg-gray-50/50",children:[e.jsx("div",{className:"w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-2 text-gray-400",children:e.jsx(qa,{className:"h-5 w-5"})}),e.jsx("p",{className:"text-sm font-medium text-gray-900",children:"Sin notas"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:'Usa la pestaña "Nota Interna" en el chat para crear una.'})]}):e.jsx("div",{className:"max-h-80 overflow-y-auto pr-2 space-y-2.5",children:r.map(n=>e.jsxs("div",{className:"p-3 bg-white border border-gray-100 rounded-xl shadow-sm hover:border-gray-200 transition-colors group",children:[e.jsxs("div",{className:"flex items-start gap-2 mb-1.5",children:[e.jsx("span",{className:"flex items-center justify-center w-5 h-5 rounded bg-amber-100 text-amber-600",children:e.jsx(qa,{className:"w-3 h-3"})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"text-[10px] uppercase font-bold text-gray-500 tracking-wide",children:"Nota Interna"})}),e.jsx("span",{className:"text-[10px] text-gray-400 group-hover:text-gray-600 transition-colors",children:Ju(n.createdAt)})]}),e.jsx("div",{className:"pl-7",children:e.jsx(os,{content:n.content,className:"text-sm text-gray-700 leading-relaxed"})})]},n.id))})})});ul.displayName="ContactNotes";const em=({ticketId:t,currentSource:s,onSourceUpdated:a,compact:r=!1})=>{const{data:n=[]}=rt({queryKey:["inbox","source-types"],queryFn:()=>Ce.getSourceTypes(),staleTime:1/0,gcTime:1/0}),[o,l]=i.useState(!1),[c,u]=i.useState(s?.type||""),[d,m]=i.useState(""),[x,b]=i.useState(!1);i.useEffect(()=>{l(!1),u(s?.type||""),m("")},[t,s?.type]);const y=i.useMemo(()=>n.find(I=>I.value===s?.type),[n,s?.type]),p=i.useMemo(()=>n.find(I=>I.value===c),[n,c]),f=async()=>{if(!c){H.error("Selecciona una fuente");return}b(!0);try{const I={};if(p?.requiresDetail&&d.trim()){const E={referral:"referrerName",meta_lead_form:"formName",web_form:"formName",other:"description"}[c]||"note";I[E]=d.trim()}const U=await Ce.setTicketSource(t,{type:c,detail:Object.keys(I).length>0?I:void 0});H.success("Fuente del lead actualizada"),a?.(U.source),l(!1)}catch(I){H.error(I?.response?.data?.message||"Error al guardar la fuente")}finally{b(!1)}};if(o)return e.jsxs("div",{className:T("space-y-2",r?"py-2":"py-3"),children:[e.jsx(we,{className:"text-[11px] text-muted-foreground",children:"Fuente del lead"}),e.jsxs(kt,{value:c,onValueChange:I=>u(I),children:[e.jsx(Ct,{className:"h-8 text-sm",children:e.jsx(Tt,{placeholder:"Selecciona una fuente..."})}),e.jsx(St,{children:n.map(I=>e.jsx(Me,{value:I.value,children:I.label},I.value))})]}),p?.requiresDetail&&e.jsx(Te,{placeholder:tm(c),value:d,onChange:I=>m(I.target.value),className:"h-8 text-sm"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(K,{size:"sm",className:"h-7 text-xs flex-1",onClick:f,disabled:x||!c,children:[x?e.jsx(Se,{className:"w-3 h-3 mr-1.5 animate-spin"}):e.jsx(Ie,{className:"w-3 h-3 mr-1.5"}),"Guardar"]}),e.jsx(K,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>l(!1),disabled:x,children:e.jsx(Ge,{className:"w-3 h-3"})})]})]});if(!s)return e.jsxs("div",{className:T("flex items-center gap-2 rounded-md bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-900/40 px-3",r?"py-1.5":"py-2"),children:[e.jsx(ct,{className:"w-3.5 h-3.5 text-amber-600 shrink-0"}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"text-xs font-medium text-amber-800 dark:text-amber-300",children:"Fuente no identificada"})}),e.jsx(K,{size:"sm",variant:"ghost",className:"h-6 text-[11px] px-2 text-amber-700 hover:text-amber-900 hover:bg-amber-100 dark:text-amber-300",onClick:()=>l(!0),children:"Marcar"})]});const g=s.capturedBy==="auto",v=y?.label||s.type,h=sm(s);return e.jsx("div",{className:T("rounded-md border px-3 group",g?"bg-emerald-50/50 dark:bg-emerald-950/20 border-emerald-200 dark:border-emerald-900/40":"bg-muted/30 border-border",r?"py-1.5":"py-2"),children:e.jsxs("div",{className:"flex items-start gap-2",children:[g?e.jsx(Is,{className:"w-3.5 h-3.5 text-emerald-600 mt-0.5 shrink-0"}):e.jsx("div",{className:"w-3.5 h-3.5 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:T("text-[10px] uppercase tracking-wide font-bold",g?"text-emerald-700 dark:text-emerald-400":"text-muted-foreground"),children:g?"Auto":"Manual"}),e.jsx("span",{className:"text-xs font-medium truncate",children:v})]}),h&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5 truncate",children:h})]}),e.jsx(K,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>l(!0),title:"Cambiar fuente",children:e.jsx(Qn,{className:"w-3 h-3"})})]})})};function tm(t){switch(t){case"referral":return"Nombre del referidor";case"meta_lead_form":return"Nombre del formulario";case"web_form":return"Nombre del formulario web";case"other":return"Descripción breve";default:return""}}function sm(t){if(!t.detail)return null;const s=t.detail;return t.type==="ctwa_ad"?s.campaignName||s.headline||s.adId||null:t.type==="referral"?s.referrerName?`Referido por: ${s.referrerName}`:null:t.type==="meta_lead_form"||t.type==="web_form"?s.formName||s.formId||null:t.type==="other"&&s.description||null}const am={ad:"Del anuncio",ai:"IA",agent:null};function rm({ticketId:t,current:s,onUpdated:a,disabled:r}){const[n,o]=i.useState(s),[l,c]=i.useState(!1),[u,d]=i.useState(""),[m,x]=i.useState([]),[b,y]=i.useState(!1),[p,f]=i.useState(!1),g=i.useRef(null),v=i.useRef(null),{data:h}=rt({queryKey:["products","has-any"],queryFn:async()=>(await Zs.getProducts({limit:1})).data.length>0,staleTime:300*1e3});i.useEffect(()=>{o(s)},[t,s?.productId,s?.general,s?.setAt]);const I=i.useCallback(async E=>{y(!0);try{const M=await Zs.getProducts({search:E||void 0,limit:100});x(M.data)}catch{x([])}finally{y(!1)}},[]);i.useEffect(()=>{if(l)return g.current&&clearTimeout(g.current),g.current=setTimeout(()=>I(u),u?300:0),()=>{g.current&&clearTimeout(g.current)}},[l,u,I]),i.useEffect(()=>{l?setTimeout(()=>v.current?.focus(),50):d("")},[l]);const U=async E=>{f(!0);try{const{productInterest:M}=await Ce.setProductInterest(t,E);o(M),c(!1),a?.(M),H.success(M?"Producto de interés guardado":"Producto de interés quitado")}catch(M){const F=M?.response?.data?.message;H.error(F||"No se pudo guardar el producto de interés")}finally{f(!1)}},C=n?am[n.source]:null;return!n&&!h?null:e.jsxs(Xe,{open:l,onOpenChange:E=>!r&&c(E),children:[e.jsx(Ze,{asChild:!0,children:e.jsx("button",{type:"button",disabled:r,"aria-label":"Producto de interés",className:T("group w-full rounded-md border px-3 py-1.5 text-left transition-colors",n?"bg-muted/30 border-border hover:bg-muted/50":"bg-amber-50 dark:bg-amber-950/20 border-amber-200 dark:border-amber-900/40 hover:bg-amber-100/70"),children:n?e.jsxs("div",{className:"flex items-start gap-2",children:[n.general?e.jsx(br,{className:"w-3.5 h-3.5 text-muted-foreground mt-0.5 shrink-0"}):e.jsx(Ks,{className:"w-3.5 h-3.5 text-muted-foreground mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-1.5",children:[e.jsx("span",{className:"whitespace-nowrap text-[10px] uppercase tracking-wide font-bold text-muted-foreground",children:"Producto de interés"}),C&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 whitespace-nowrap text-[10px] font-semibold text-emerald-700 dark:text-emerald-400",children:[e.jsx(Is,{className:"w-2.5 h-2.5"}),C]})]}),e.jsx("p",{className:"text-xs font-medium truncate",children:n.general?"General":n.name||n.externalId||"Producto"}),!n.general&&n.category&&e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:n.category})]}),e.jsx(Qn,{className:"w-3 h-3 mt-1 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ct,{className:"w-3.5 h-3.5 text-amber-600 shrink-0"}),e.jsx("span",{className:"flex-1 text-xs font-medium text-amber-800 dark:text-amber-300",children:"Falta elegir el producto de interés"}),e.jsx("span",{className:"text-[11px] font-medium text-amber-700 dark:text-amber-300",children:"Elegir"})]})})}),e.jsxs(Je,{className:"w-80 p-0",align:"start",children:[e.jsx("div",{className:"p-3 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(Bt,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(Te,{ref:v,placeholder:"Buscar producto...",value:u,onChange:E=>d(E.target.value),className:"pl-9 h-9"})]})}),e.jsxs("div",{className:"max-h-64 overflow-y-auto",children:[e.jsxs("button",{type:"button",disabled:p,onClick:()=>U({general:!0}),className:"w-full flex items-center gap-3 px-3 py-2.5 text-left hover:bg-accent/50 border-b border-border/30",children:[e.jsx(br,{className:"w-4 h-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:"General"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No pregunta por un producto en concreto"})]}),n?.general&&e.jsx(Ie,{className:"w-4 h-4 text-primary"})]}),b?e.jsxs("div",{className:"flex items-center justify-center py-6 text-muted-foreground",children:[e.jsx(Se,{className:"w-4 h-4 animate-spin mr-2"}),e.jsx("span",{className:"text-sm",children:"Buscando..."})]}):m.length===0?e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No se encontraron productos"}):m.map(E=>e.jsxs("button",{type:"button",disabled:p,onClick:()=>U({productId:E.id}),className:"w-full flex items-center gap-3 px-3 py-2.5 text-left hover:bg-accent/50 border-b border-border/30 last:border-0",children:[e.jsx(Ks,{className:"w-4 h-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:E.name}),(E.externalCategory||E.externalId)&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:[E.externalCategory,E.externalId].filter(Boolean).join(" · ")})]}),n?.productId===E.id&&e.jsx(Ie,{className:"w-4 h-4 text-primary"})]},E.id))]}),n&&e.jsx("div",{className:"border-t p-2",children:e.jsxs(K,{variant:"ghost",size:"sm",disabled:p,onClick:()=>U({}),className:"w-full justify-start gap-2 text-muted-foreground",children:[p?e.jsx(Se,{className:"w-4 h-4 animate-spin"}):e.jsx(Ge,{className:"w-4 h-4"}),"Quitar producto de interés"]})})]})]})}const qt=t=>typeof t=="string"&&t.trim()?t:null;function nm(t){const s=t?.metadata?.product_interest;if(!s||typeof s!="object")return null;const a=s,r=a.general===!0,n=qt(a.productId);return!r&&!n?null:{productId:r?null:n,externalId:r?null:qt(a.externalId),name:r?null:qt(a.name),category:r?null:qt(a.category),general:r,source:a.source==="ad"||a.source==="ai"?a.source:"agent",setBy:qt(a.setBy),setAt:qt(a.setAt)??""}}const ml=i.memo(({onClose:t,className:s,contact:a,ticketId:r,messages:n=[]})=>{const o=Rl(a?.id),l=_l(),c=Ll(),u=Fl(),d=o.data??null,m=o.isLoading,x=Pl(),b=Wn(Q=>Q.fetchFolders);i.useEffect(()=>{b()},[b]);const y=dl(),p=y.data?.ticket?.id===r?y.data??null:null,g=Zu(p?.channel?.id).data??null,v=d?.tags||[],h=!!d?.isBlacklisted,I=d?.metadata_history??[],[U,C]=i.useState(null);i.useEffect(()=>{if(!r){C(null);return}let Q=!1;return ar.listSchemas({entityType:"ticket",includeSystem:!0}).then(ie=>{Q||C(ie.length>0?ie[0]:null)}).catch(()=>{Q||C(null)}),()=>{Q=!0}},[r]);const[E,M]=i.useState({});i.useEffect(()=>{M(p?.ticket?.metadata||{})},[p?.ticket?.metadata]);const F=i.useRef(null),_=i.useRef(null),[k,W]=i.useState(!1),[q,ee]=i.useState(!1),[le,S]=i.useState(!1),P=k||q,X=i.useCallback(async()=>{S(!0);try{const Q=[];k&&F.current&&Q.push(F.current.save()),q&&_.current&&Q.push(_.current.save()),await Promise.all(Q)}finally{S(!1)}},[k,q]),A=i.useMemo(()=>n.filter(Q=>Q.senderType==="NOTE"),[n]),z=i.useMemo(()=>{if(!p||!d)return null;const Q=p.channel?.type?.toUpperCase()||"",ie=Q.includes("WHATSAPP");let O=p.ticket?.metadata?.customer_identifier;O?.startsWith("wamid.")&&(O=void 0);const B=d.identities?.filter(me=>{const R=me.type.toUpperCase();return R===Q||ie&&R.includes("WHATSAPP")}),J=B?.find(me=>!na(me.identifierValue))||B?.[0];return ie&&!na(J?.identifierValue)&&(!J||J.identifierValue.startsWith("wamid."))&&d.phone?{identifierValue:d.phone,isBlacklisted:d.isBlacklisted||!1,type:"WHATSAPP"}:O&&!J?{identifierValue:O,isBlacklisted:!1,type:Q}:J||null},[p,d]),L=Ye(Q=>Q.user),N=L?.organizationId,w=p?.channel?.id,$=sr(Q=>w?Q.channels.find(ie=>ie.id===w):void 0),ae=$?$.isActive:p?.channel?.isActive??!0,ne=p?.ticket?.status==="RESOLVED"||p?.ticket?.status==="ARCHIVED",re=!ae||ne,be=L?.role==="OWNER"||L?.role==="ADMIN",[D,Z]=i.useState({personalInfo:!0,notes:!0,tags:!0,metadata:!0,ticketMetadata:!1}),te=i.useCallback(()=>{a?.id&&u(a.id)},[a?.id,u]),xe=i.useCallback(async Q=>{const ie=a?.id;if(!ie)return;const B=(c(ie)?.tags||[]).some(J=>J.id===Q.id);try{B?(await Ce.removeTag(ie,Q.id),l(ie,J=>J&&{...J,tags:(J.tags||[]).filter(me=>me.id!==Q.id)})):(await Ce.assignTag(ie,Q.id),l(ie,J=>J&&{...J,tags:[...J.tags||[],Q]}))}catch(J){console.error("Error toggling tag:",J),H.error("Error al actualizar etiqueta")}},[a?.id,c,l]),ge=i.useCallback(async(Q,ie)=>{const O=a?.id;try{const B=await Ce.createTag({name:Q,folderId:ie});O&&(await Ce.assignTag(O,B.id),l(O,J=>J&&{...J,tags:[...J.tags||[],B]})),await b(!0),H.success("Etiqueta creada")}catch(B){throw console.error("Error creating tag:",B),H.error("Error al crear etiqueta"),B}},[a?.id,l,b]),ve=i.useCallback(async(Q,ie)=>{try{await Ce.createFolder({name:Q,color:ie}),await b(!0),H.success("Carpeta creada")}catch(O){throw console.error("Error creating folder:",O),H.error("Error al crear carpeta"),O}},[b]),{updateContact:V,refreshConversation:j}=ds(),G=i.useCallback(async Q=>{if(a?.id)try{await V(a.id,Q),a?.id&&l(a.id,ie=>ie&&{...ie,...Q})}catch(ie){throw console.error("Error saving contact info:",ie),H.error("Error al guardar información"),ie}},[a?.id,V]),se=i.useCallback(async Q=>{if(a?.id)try{await V(a.id,{metadata:Q}),a?.id&&l(a.id,ie=>ie&&{...ie,metadata:Q})}catch(ie){throw console.error("Error saving metadata:",ie),H.error("Error al guardar información"),ie}},[a?.id,V,l]),de=i.useCallback(async Q=>{if(r)try{await Ce.updateTicketCustomMetadata(r,Q),M(ie=>{const O={...ie};for(const[B,J]of Object.entries(Q))J===null?delete O[B]:O[B]=J;return O})}catch(ie){throw console.error("Error saving ticket metadata:",ie),H.error("Error al guardar campos del ticket"),ie}},[r]),Ae=i.useCallback(async()=>{const Q=d?.id;if(!Q)return;const ie=!!c(Q)?.isBlacklisted;try{ie?(await Os.unblockContact(Q),l(Q,O=>O&&{...O,isBlacklisted:!1}),H.success("Contacto desbloqueado globalmente")):(await Os.blockContact(Q,"MANUAL"),l(Q,O=>O&&{...O,isBlacklisted:!0}),H.success("Contacto bloqueado globalmente")),te()}catch(O){console.error("Error toggling blacklist:",O),H.error("Error al actualizar bloqueo")}},[d?.id,c,l,te]),ue=i.useCallback(async()=>{const Q=d?.orgId||N,ie=z,O=ie?.identifierValue;if(!Q||!O){H.error("No se pudo identificar el canal del ticket");return}const B=ie?.isBlacklisted||!1;try{B?(await Os.unblockIdentifier(Q,O),H.success("Canal desbloqueado")):(await Os.blockIdentifier(Q,O,"MANUAL"),H.success("Canal bloqueado")),te()}catch(J){console.error("Error toggling channel blacklist:",J),H.error("Error al actualizar bloqueo del canal")}},[d,N,z,te]),je=Q=>{Z(ie=>({...ie,[Q]:!ie[Q]}))};if(!a||!d)return e.jsx("div",{className:T("w-full bg-background border-l flex items-center justify-center",s),children:m?e.jsx(Se,{className:"h-8 w-8 animate-spin text-muted-foreground"}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Selecciona una conversación"})});const ke=d?.name||d?.phone||"Sin nombre";return e.jsxs("div",{className:T("w-full bg-white dark:bg-card border-l border-gray-100 dark:border-border flex flex-col h-full min-h-0 overflow-hidden",s),children:[e.jsxs("div",{className:"flex items-center justify-between px-4 h-[52px] border-b",children:[e.jsx("h3",{className:"font-semibold text-foreground truncate",children:ke}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(Vn,{children:[e.jsx(Bn,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(li,{className:"h-4 w-4"})})}),e.jsxs($n,{align:"end",className:"w-56",children:[p&&e.jsxs(wt,{onClick:ue,children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),z?.isBlacklisted?"Desbloquear este canal":"Bloquear solo este canal"]}),e.jsx(wt,{onClick:Ae,className:"text-destructive focus:text-destructive",children:h?e.jsxs(e.Fragment,{children:[e.jsx(Qs,{className:"h-4 w-4 mr-2"}),"Desbloquear todo (Global)"]}):e.jsxs(e.Fragment,{children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Bloquear todo (Global)"]})}),e.jsx(zs,{}),e.jsx(wt,{onClick:te,children:"Recargar información"})]})]}),t&&e.jsx(K,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:t,children:e.jsx(Ge,{className:"h-4 w-4"})})]})]}),e.jsx(ai,{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsxs("div",{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-col items-center text-center",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(ht,{className:"h-20 w-20 border-4 border-background shadow-lg",children:[e.jsx(pt,{src:d.avatarUrl}),e.jsx(gt,{className:"bg-gradient-to-br from-primary to-primary/60 text-primary-foreground text-2xl font-semibold",children:ke.charAt(0).toUpperCase()})]}),h&&e.jsx("div",{className:"absolute -bottom-1 -right-1 bg-destructive text-destructive-foreground rounded-full p-1",children:e.jsx(ja,{className:"h-3 w-3"})})]}),e.jsx("h2",{className:"mt-3 text-lg font-semibold text-foreground",children:ke}),e.jsx("div",{className:"flex items-center gap-1.5 mt-1",children:h?e.jsxs(e.Fragment,{children:[e.jsx(ks,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"text-sm text-destructive",children:"Bloqueado"})]}):d.lastSeenAt?e.jsxs(e.Fragment,{children:[e.jsx(bt,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Último acceso: ",is(d.lastSeenAt,{style:"short"})]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Sin actividad reciente"})})]}),p?.ticket?.id&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:T(re&&"pointer-events-none opacity-60"),"aria-disabled":re,children:[e.jsx(em,{ticketId:p.ticket.id,currentSource:ha(p.ticket),onSourceUpdated:()=>{j?.(p.ticket.id)},compact:!0}),e.jsx("div",{className:"mt-2",children:e.jsx(rm,{ticketId:p.ticket.id,current:nm(p.ticket),onUpdated:()=>j?.(p.ticket.id),disabled:re})})]}),e.jsx(ms,{})]}),e.jsxs(es,{open:D.personalInfo,onOpenChange:()=>je("personalInfo"),children:[e.jsxs(ts,{className:"flex items-center justify-between w-full py-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"Información de contacto"})]}),e.jsx(Zt,{className:T("h-4 w-4 transition-transform",D.personalInfo&&"rotate-180")})]}),e.jsx(ss,{children:e.jsx("div",{className:T("pt-2",re&&"pointer-events-none opacity-60"),"aria-disabled":re,children:e.jsx(Vl,{name:d.name,email:d.email,phone:d.phone,onSave:G})})})]}),e.jsx(ms,{}),e.jsxs(es,{open:D.notes,onOpenChange:()=>je("notes"),children:[e.jsxs(ts,{className:"flex items-center justify-between w-full py-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ms,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:"Notas"}),A.length>0&&e.jsx(De,{variant:"secondary",className:"h-5 text-xs",children:A.length})]}),e.jsx(Zt,{className:T("h-4 w-4 transition-transform",D.notes&&"rotate-180")})]}),e.jsx(ss,{children:e.jsx("div",{className:"pt-2",children:e.jsx(ul,{notes:A,isLoading:m})})})]}),e.jsx(ms,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Etiquetas de contacto"}),m?e.jsx(Se,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(jo,{selectedTags:v,folders:x,onToggleTag:xe,onCreateTag:be?ge:void 0,onCreateFolder:be?ve:void 0,disabled:re})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:v.length>0?v.map(Q=>{const O=x.find(J=>J.tags?.some(me=>me.id===Q.id))?.color||Q.color,B=Q.readOnly||Q.isSystem;return e.jsxs(De,{variant:"secondary",className:T("text-xs transition-all pl-2 font-medium shadow-sm",B?"cursor-default opacity-90":"cursor-pointer hover:opacity-90 hover:scale-105"),style:{backgroundColor:O,color:"#ffffff",textShadow:"0 1px 2px rgba(0,0,0,0.2)"},title:B?"Etiqueta del sistema — no se puede remover":void 0,onClick:B?void 0:()=>xe(Q),children:[Q.name,B?e.jsx(As,{className:"h-3 w-3 ml-1 opacity-70"}):e.jsx(Ge,{className:"h-3 w-3 ml-1 opacity-80"})]},Q.id)}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Sin etiquetas"})})]}),e.jsx(ms,{}),e.jsxs(es,{open:D.metadata,onOpenChange:()=>je("metadata"),children:[e.jsxs(ts,{className:"flex items-center justify-between w-full py-1",children:[e.jsx("span",{className:"text-sm font-medium",children:"Información adicional"}),e.jsx(Zt,{className:T("h-4 w-4 transition-transform",D.metadata&&"rotate-180")})]}),e.jsx(ss,{children:e.jsx("div",{className:T("pt-2",re&&"pointer-events-none opacity-60"),"aria-disabled":re,children:e.jsx(yr,{ref:F,metadata:d.metadata,schema:g,metadataHistory:I,onSave:se,isLoading:m,hideSaveButton:!0,onChangesChange:W})})})]}),r&&e.jsxs(e.Fragment,{children:[e.jsx(ms,{}),e.jsxs(es,{open:D.ticketMetadata,onOpenChange:()=>je("ticketMetadata"),children:[e.jsxs(ts,{className:"flex items-center justify-between w-full py-1",children:[e.jsx("span",{className:"text-sm font-medium",children:"Campos del Ticket"}),e.jsx(Zt,{className:T("h-4 w-4 transition-transform",D.ticketMetadata&&"rotate-180")})]}),e.jsx(ss,{children:e.jsx("div",{className:"pt-2",children:e.jsx(yr,{ref:_,metadata:E,schema:U,metadataHistory:[],onSave:de,isLoading:m,hideSaveButton:!0,onChangesChange:ee})})})]})]})]})}),e.jsx("div",{className:"p-3 border-t bg-muted/20",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[P&&e.jsxs(K,{variant:"default",className:"w-full text-xs h-9 shadow-sm",onClick:X,disabled:le,children:[le?e.jsx(Se,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(No,{className:"h-4 w-4 mr-2"}),"Guardar cambios"]}),p&&e.jsxs(K,{variant:z?.isBlacklisted?"default":"outline",className:T("w-full shadow-sm text-xs h-9",z?.isBlacklisted&&"bg-orange-600 hover:bg-orange-700"),onClick:ue,children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),z?.isBlacklisted?"Desbloquear este canal":"Bloquear solo este canal"]}),e.jsx(K,{variant:h?"default":"ghost",className:T("w-full text-xs h-8 text-muted-foreground hover:text-destructive",h&&"bg-destructive hover:bg-destructive/90 text-white"),onClick:Ae,children:h?e.jsxs(e.Fragment,{children:[e.jsx(Qs,{className:"h-3.5 w-3.5 mr-2"}),"Desbloquear de forma Global"]}):e.jsxs(e.Fragment,{children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-2"}),"Bloquear Contacto Globalmente"]})})]})})]})});ml.displayName="ContactPanel";const im={name:xa,email:Ja,phone:Wl,location:Cs,city:Cs,country:_n,website:fs,url:fs,date:Pt,birthday:Pt,created:Pt,id:ir};function En(t,s){if(s==null)return"—";if(t.toLowerCase().includes("date")||t.toLowerCase().includes("at")){const a=new Date(s);if(!isNaN(a.getTime()))return is(a,{style:"short"})}return typeof s=="boolean"?s?"Sí":"No":Array.isArray(s)?s.join(", ")||"—":typeof s=="object"?JSON.stringify(s):String(s)}function lm(t){const s=t.toLowerCase();for(const[a,r]of Object.entries(im))if(s.includes(a))return r;return ir}function _a(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^\w/,s=>s.toUpperCase())}const om=i.memo(({metadata:t,className:s})=>{if(!t||Object.keys(t).length===0)return e.jsx("div",{className:T("text-sm text-muted-foreground italic",s),children:"Sin información adicional"});const a=[],r=[];for(const[n,o]of Object.entries(t))n!=="tags"&&(typeof o=="object"&&o!==null&&!Array.isArray(o)?r.push([n,o]):a.push([n,o]));return e.jsxs("div",{className:T("space-y-2",s),children:[a.map(([n,o])=>{const l=lm(n);return e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(l,{className:"h-4 w-4 mt-0.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("span",{className:"text-muted-foreground",children:[_a(n),":"]})," ",e.jsx("span",{className:"font-medium text-foreground break-words",children:En(n,o)})]})]},n)}),r.map(([n,o])=>e.jsxs(es,{className:"border rounded-lg",children:[e.jsxs(ts,{className:"flex items-center justify-between w-full px-3 py-2 text-sm hover:bg-accent rounded-lg",children:[e.jsx("span",{className:"font-medium",children:_a(n)}),e.jsx(Zt,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(ss,{children:e.jsx("div",{className:"px-3 pb-2 space-y-1",children:Object.entries(o).map(([l,c])=>e.jsxs("div",{className:"flex items-start gap-2 text-sm pl-2",children:[e.jsxs("span",{className:"text-muted-foreground",children:[_a(l),":"]}),e.jsx("span",{className:"font-medium break-words",children:En(l,c)})]},l))})})]},n))]})});om.displayName="MetadataDisplay";const cm=[{label:"Chats",value:"all",icon:Ms},{label:"Comentarios Facebook",value:"type:facebook",icon:Kn},{label:"Comentarios Instagram",value:"type:instagram",icon:Yn},{label:"Reserva de Citas",value:"type:calendar",icon:Pt}],dm=()=>{const t=fe(r=>r.filters.channelType),s=fe(r=>r.setChannelFilter),a=t?`type:${t}`:"all";return e.jsx("div",{className:"w-full bg-white dark:bg-card border-b border-gray-100 dark:border-border/60",children:e.jsx("div",{className:"flex px-4 overflow-x-auto scrollbar-hide snap-x",children:cm.map(r=>{const n=a===r.value,o=r.icon,l=r.value!=="all";return e.jsxs("button",{onClick:()=>!l&&s(r.value),disabled:l,title:l?"Disponible en Nubot":void 0,className:T("relative flex items-center gap-2 px-4 py-3.5 text-sm font-medium transition-colors whitespace-nowrap snap-start",n?"text-primary":"text-slate-500 hover:text-slate-800 dark:text-slate-400 dark:hover:text-slate-200",l&&"cursor-not-allowed opacity-50 hover:text-slate-500 dark:hover:text-slate-400"),children:[e.jsx(o,{className:T("w-4 h-4",n?"text-primary":"text-slate-400")}),r.label,l&&e.jsx(As,{className:"w-3 h-3 text-slate-400"}),n&&e.jsx("div",{className:"absolute left-0 right-0 bottom-0 h-0.5 bg-primary rounded-t-md"})]},r.value)})})})},um=()=>fe(er(t=>t.activeConversationId)),mm=()=>fe(er(t=>t.isConnected)),xm=()=>{const t=fe(s=>s.error);return i.useMemo(()=>({isLoading:!1,isLoadingMessages:!1,error:t}),[t])},hm=t=>{const s=i.useCallback(a=>t?a.typingIndicators[t]:void 0,[t]);return fe(s)};function In(t){return Object.fromEntries(Object.entries(t).filter(([s,a])=>a!==void 0))}function pm(){const t=it(),s=i.useCallback((u,d={})=>{if(u.metadata?.hideFromAgent)return;const m=["inbox","messages",u.ticketId];t.setQueryData(m,x=>{if(!x||x.pages.length===0){console.log(`[useChatSocket] ❄️ Cold cache for ticket ${u.ticketId}. Invalidating...`),t.invalidateQueries({queryKey:m});return}return x.pages[0]?.data.some(y=>y.id===u.id||!!u.channelMessageId&&y.channelMessageId===u.channelMessageId||!!u.waId&&(y.channelMessageId===u.waId||y.waId===u.waId))||!1?(d.silent||console.warn(`[useChatSocket] ⚠️ Duplicate message ignored: ${u.id}`),x):(console.log(`[useChatSocket] 💉 Injecting message ${u.id} into ticket ${u.ticketId}. Cache now has ${x.pages[0]?.data.length+1} messages in page 0.`),{...x,pages:x.pages.map((y,p)=>{if(p===0){const f=[u,...y.data];return f.sort((g,v)=>new Date(v.channelTimestamp||v.createdAt).getTime()-new Date(g.channelTimestamp||g.createdAt).getTime()),{...y,data:f,total:(y.total??0)+1}}return y})})})},[t]),a={current:0},r=i.useCallback(()=>{const u=Date.now();u-a.current>500&&(a.current=u,t.invalidateQueries({queryKey:["inbox","conversations"]}))},[t]),n=i.useRef(null),o=i.useCallback(u=>{if(!u.id||!u.status&&!u.metadata)return;const d=u.ticketId;if(!d){console.log(`[useChatSocket] ⚠️ Message update without ticketId: ${u.id}`);return}const m=["inbox","messages",d];t.setQueryData(m,x=>x?.pages?{...x,pages:x.pages.map(b=>({...b,data:b.data.map(y=>y.id===u.id?{...y,...u.status&&{status:u.status,errorDetails:u.errorDetails},...u.metadata&&{metadata:{...y.metadata||{},...u.metadata}}}:y)}))}:x),console.log(`[useChatSocket] ✓✓ Message ${u.id} updated${u.status?` → ${u.status}`:""}${u.errorDetails?" (with errorDetails)":""}${u.metadata?` (metadata: ${Object.keys(u.metadata).join(",")})`:""}`)},[t]),l=i.useCallback(u=>{const d=u?.id;d&&t.setQueryData(Bl(d),m=>m&&{...m,...u})},[t]),c=i.useCallback((u,d)=>{t.setQueryData(["inbox","conversation",u],m=>{if(!m)return m;if(typeof d=="function")return d(m);const x={...m,...d};return d.ticket&&m.ticket&&(x.ticket={...m.ticket,...In(d.ticket)}),x}),t.setQueriesData({queryKey:["inbox","conversations"]},m=>m?.pages?{...m,pages:m.pages.map(x=>({...x,data:x.data.map(b=>{if(b.ticket.id===u){if(typeof d=="function")return d(b);const y={...b,...d};return d.ticket&&b.ticket&&(y.ticket={...b.ticket,...In(d.ticket)}),"unreadCount"in d&&!d.ticket&&(y.ticket={...b.ticket,unreadCount:d.unreadCount}),y}return b})}))}:m)},[t]);i.useEffect(()=>{const u=A=>{if(s(A),c(A.ticketId,L=>({...L,lastMessage:A,ticket:{...L.ticket,unreadCount:A.senderType==="CONTACT"?(L.ticket.unreadCount||0)+1:L.ticket.unreadCount}})),fe.getState().activeConversationId===A.ticketId&&A.senderType==="CONTACT"){const L=A.id&&!A.id.startsWith("temp-");Ce.markAsRead(A.ticketId,L?A.id:void 0).catch(N=>console.warn(`[useChatSocket] Failed to mark new message as read: ${N.message}`))}},d=A=>{o(A)},m=()=>{n.current&&clearTimeout(n.current),n.current=setTimeout(()=>{n.current=null,t.invalidateQueries({queryKey:["inbox","conversations"]}),t.invalidateQueries({queryKey:["inbox","counts"]})},500)},x=A=>{c(A.id,{ticket:A})},b=A=>{const z=Ye.getState().user?.id,L={};if(A.unreadCount!==void 0&&(L.unreadCount=A.unreadCount),A.lastMessage&&(L.lastMessage=A.lastMessage),A.ticket&&(L.ticket=A.ticket),A.contact&&(L.contact=A.contact,l(A.contact)),A.channel&&(L.channel=A.channel),A.sourceCampaignId!==void 0&&(L.ticket={...L.ticket||{},sourceCampaignId:A.sourceCampaignId},A.ticket&&(A.ticket.sourceCampaignId=A.sourceCampaignId)),(A.funnelId!==void 0||A.funnelStageId!==void 0)&&(L.ticket={...L.ticket||{},...A.funnelId!==void 0?{funnelId:A.funnelId}:{},...A.funnelStageId!==void 0?{funnelStageId:A.funnelStageId}:{}}),Object.keys(L).length>0&&c(A.ticketId,L),A.ticket){const N=A.ticket,w=String(A.channel?.type??N.channel?.type??N.channelType??"").toUpperCase()==="EMAIL";t.getQueriesData({queryKey:["inbox","conversations"]}).forEach(([ae,ne])=>{const re=ae[2]||{},be=re.status==="RESOLVED";if(!ne?.pages){let te=!0;be||(re.tab==="my_chats"?te=re.scope==="all"?N.assignedType==="HUMAN"&&!!N.assignedAgentId:N.assignedAgentId===z:re.tab==="ai_agent"?te=N.assignedType==="AI"||N.assignedType==="META_AGENT":re.tab==="waiting"&&(te=N.status==="WAITING_ASSIGNMENT"||N.status==="IN_PROGRESS_HUMAN"&&!N.assignedAgentId)),N.status==="RESOLVED"?te=be&&te:be&&(te=!1),w&&(te=!1),te&&(console.log(`[useChatSocket] 🔄 Invalidating empty cache for ticket ${N.id} in ${JSON.stringify(re)}`),t.invalidateQueries({queryKey:ae}));return}let D=!0;be||(re.tab==="my_chats"?re.scope==="all"?D=N.assignedType==="HUMAN"&&!!N.assignedAgentId:D=N.assignedAgentId===z:re.tab==="ai_agent"?D=N.assignedType==="AI"||N.assignedType==="META_AGENT":re.tab==="waiting"&&(D=N.status==="WAITING_ASSIGNMENT"||N.status==="IN_PROGRESS_HUMAN"&&!N.assignedAgentId)),N.status==="RESOLVED"?D=be&&D:be&&(D=!1),w&&(D=!1);const Z=ne.pages.some(te=>te.data.some(xe=>xe.ticket.id===N.id));D&&!Z?(console.log(`[useChatSocket] ➕ Adding ticket ${N.id} to query ${JSON.stringify(re)}`),t.setQueryData(ae,te=>{if(!te?.pages)return te;const xe={ticket:N,contact:A.contact||N.contact||{name:"Usuario"},channel:A.channel||N.channel||null,lastMessage:A.lastMessage||{content:N.lastMessagePreview||"...",createdAt:N.lastMessageAt||new Date().toISOString()},messages:[]};return{...te,pages:te.pages.map((ge,ve)=>ve===0?{...ge,data:[xe,...ge.data],total:(ge.total||0)+1}:ge)}})):!D&&Z&&(console.log(`[useChatSocket] ➖ Removing ticket ${N.id} from query ${JSON.stringify(re)}`),t.setQueryData(ae,xe=>xe?.pages?{...xe,pages:xe.pages.map(ge=>({...ge,data:ge.data.filter(ve=>ve.ticket.id!==N.id),total:Math.max(0,(ge.total||0)-1)}))}:xe),fe.getState().activeConversationId===N.id&&(console.log(`[useChatSocket] 🧹 Ticket ${N.id} removed from view — will re-verify before deselecting`),setTimeout(()=>{if(fe.getState().activeConversationId!==N.id)return;t.getQueriesData({queryKey:["inbox","conversations"]}).some(([,V])=>V?.pages?.some(j=>j.data.some(G=>G.ticket.id===N.id)))?console.log(`[useChatSocket] ✅ Ticket ${N.id} is back in list — keeping selection`):(console.log(`[useChatSocket] 🧹 Confirmed: deselecting ${N.id}`),fe.getState().selectConversation(null))},300)))})}A.lastMessage&&(s(A.lastMessage,{silent:!0}),r())},p=async()=>{console.log("[useChatSocket] 🔌 Socket reconnected. Executing Soft Sync (Delta)..."),t.invalidateQueries({queryKey:["inbox","conversations"]}),t.invalidateQueries({queryKey:["inbox","counts"]});const A=t.getQueriesData({queryKey:["inbox","messages"]}),z=A.filter(([,L])=>L?.pages?.[0]?.data?.length&&L.pages[0].data.length>0).map(([L,N])=>{const w=N.pages[0].data[0];return{queryKey:L,data:N,lastTimestamp:new Date(w.channelTimestamp||w.createdAt).getTime()}}).sort((L,N)=>N.lastTimestamp-L.lastTimestamp).slice(0,10);console.log(`[useChatSocket] 📊 Syncing ${z.length} of ${A.length} cached tickets`),await Promise.allSettled(z.map(async({queryKey:L,data:N})=>{const w=L[2],$=N.pages[0].data[0],ae=$.channelTimestamp||$.createdAt;try{const ne=await Ce.getMessages(w,{after:ae,limit:50});ne.data.length>0&&(console.log(`[useChatSocket] 📥 Found ${ne.data.length} missed messages for ${w}`),ne.data.forEach(re=>s(re)))}catch(ne){console.error(`[useChatSocket] ❌ Error syncing ticket ${w}:`,ne),t.invalidateQueries({queryKey:L})}}))},f=A=>{t.invalidateQueries({queryKey:["workflow","session"]})},g=A=>{t.getQueriesData({queryKey:["inbox","conversations"]}).forEach(([L,N])=>{!N?.pages||!N.pages.some($=>$.data.some(ae=>ae.ticket.id===A))||t.setQueryData(L,$=>$?.pages?{...$,pages:$.pages.map(ae=>({...ae,data:ae.data.filter(ne=>ne.ticket.id!==A),total:Math.max(0,(ae.total||0)-1)}))}:$)})},v=A=>{const{ticketId:z,reason:L}=A;console.log(`[useChatSocket] ⏰ ticket:expired ${z} reason=${L}`),g(z),t.invalidateQueries({queryKey:["inbox","counts"]}),fe.getState().activeConversationId===z&&setTimeout(()=>{if(fe.getState().activeConversationId!==z)return;t.getQueriesData({queryKey:["inbox","conversations"]}).some(([,ae])=>ae?.pages?.some(ne=>ne.data.some(re=>re.ticket.id===z)))||fe.getState().selectConversation(null)},300)},h=A=>{const{ticketId:z,assignedAgentId:L}=A,N=Ye.getState().user;if(L===null||L===N?.id||Il(N)){fe.getState().activeConversationId===z&&Pe.joinTicketRoom(z);return}g(z),t.invalidateQueries({queryKey:["inbox","counts"]}),fe.getState().activeConversationId===z&&fe.getState().selectConversation(null)},I=A=>{A.userId===Ye.getState().user?.id&&(Ye.getState().setPermissions(A.permissions??[]),t.invalidateQueries({queryKey:["inbox","conversations"]}),t.invalidateQueries({queryKey:["inbox","counts"]}))},U=Pe.onMessage(u),C=Pe.onMessageUpdate(d),E=Pe.onCountsUpdate(m),M=Pe.onTicketUpdate(x),F=Pe.onConversationUpdate(b),_=Pe.onWorkflowSessionUpdate(f),k=Pe.onTicketExpired(v),W=Pe.onConversationScope(h),q=Pe.onPermissionsUpdated(I),ee=A=>{l(A)},le=Pe.onContactUpdate(ee),S=A=>{A.ticketIds.forEach(z=>{c(z,{ticket:{funnelId:A.funnelId,funnelStageId:A.funnelStageId}})}),t.invalidateQueries({queryKey:["inbox","counts"]})},P=Pe.onBulkConversationUpdate(S),X=Pe.socket;return X&&X.on("connect",p),()=>{n.current&&(clearTimeout(n.current),n.current=null),U(),C(),E(),M(),F(),le(),P(),_(),k(),W(),q(),X&&X.off("connect",p)}},[t,s,o,r])}const gm=3,fm=500;function bm(t){const s=it();return da({queryKey:["inbox","messages",t],queryFn:async({pageParam:a,queryKey:r})=>{if(!t)throw new Error("No ticket ID");let n=[];a||(n=s.getQueryData(r)?.pages[0]?.data||[],n.length>0&&console.log(`[useMessagesQuery] 📦 Pre-fetch cache (Page 0) has ${n.length} messages (from WebSocket)`));const o=await Ce.getMessages(t,{cursor:a,limit:50,includePreviousTicket:!0});if(console.log(`[useMessagesQuery] 📥 Backend returned ${o.data.length} messages for ${t}`),!a&&n.length>0){const l=new Set(o.data.map(d=>d.id)),c=new Set(o.data.filter(d=>!!d.channelMessageId).map(d=>d.channelMessageId)),u=n.filter(d=>{const m=l.has(d.id),x=!!d.channelMessageId&&c.has(d.channelMessageId);return!m&&!x});if(u.length>0){console.log(`[useMessagesQuery] 🔥 MERGING ${u.length} WebSocket messages not in DB yet:`,u.map(m=>({id:m.id.slice(-8),content:m.content?.slice(0,20)})));const d=[...u,...o.data].sort((m,x)=>new Date(x.channelTimestamp||x.createdAt).getTime()-new Date(m.channelTimestamp||m.createdAt).getTime());o.data=d,o.total=Math.max(o.total??0,d.length)}else console.log(`[useMessagesQuery] ✅ All ${n.length} cached messages found in backend response (deduplicated by ID or ChannelID)`)}return o.data=o.data.filter(l=>!l.metadata?.hideFromAgent),o},initialPageParam:void 0,getNextPageParam:a=>{if(a.hasMore!==!1){if(a.nextCursor)return a.nextCursor;if(!(!a.data||a.data.length<50))return a.data[a.data.length-1]?.channelTimestamp||a.data[a.data.length-1]?.createdAt}},enabled:!!t,staleTime:1e3*60*5,refetchOnMount:!0,refetchOnWindowFocus:!1,refetchOnReconnect:!0,gcTime:1e3*60*30,refetchInterval:a=>{const r=a.state.data?.pages;return r?.length===1&&r[0].data?.length===0&&(a.state.dataUpdateCount||0)<gm?fm:!1}})}const ym=10,jm=50;function vm(t,s,a){const r=ym,[n,o]=i.useState(null),l=!!t&&n===t,c=da({queryKey:["inbox","timeline",t,s?.id],enabled:l&&!!s,initialPageParam:{ticket:s},queryFn:async({pageParam:C})=>{const{ticket:E,cursor:M}=C,F=await Ce.getMessages(E.id,{cursor:M,limit:jm,includePreviousTicket:!0});return{ticket:E,data:(F.data??[]).filter(_=>!_.metadata?.hideFromAgent),hasMore:F.hasMore,nextCursor:F.nextCursor??null,previousTicket:F.previousTicket??null}},getNextPageParam:(C,E)=>C.hasMore&&C.nextCursor?{ticket:C.ticket,cursor:C.nextCursor}:C.previousTicket?new Set(E.map(F=>F.ticket.id)).size>=r?void 0:{ticket:C.previousTicket}:void 0,staleTime:1/0,refetchOnMount:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,gcTime:1e3*60*10}),u=c.data?.pages,d=u?.[u.length-1],m=i.useMemo(()=>{if(!u?.length)return[];const C=new Map;for(const E of u){let M=C.get(E.ticket.id);M||(M={ticket:E.ticket,messages:[]},C.set(E.ticket.id,M)),M.messages.push(...E.data)}return Array.from(C.values()).map(E=>{const M=new Set,F=E.messages.filter(_=>M.has(_.id)?!1:(M.add(_.id),!0)).sort((_,k)=>{const W=new Date(_.channelTimestamp||_.createdAt).getTime(),q=new Date(k.channelTimestamp||k.createdAt).getTime();return W!==q?W-q:_.id.localeCompare(k.id)});return{ticket:E.ticket,messages:F}}).reverse()},[u]),x=i.useMemo(()=>new Set((u??[]).map(C=>C.ticket.id)).size,[u]),b=l?x>=r:r<=0,y=l?d?.previousTicket??null:s??null,p=l&&!!d?.hasMore&&!c.isFetching,f=!!y&&!b&&!c.isFetching&&(!l||!d?.hasMore),{fetchNextPage:g,refetch:v}=c,h=i.useCallback(()=>{u?.length?g():v()},[u?.length,g,v]),I=i.useCallback(()=>{if(t){if(!l){o(t);return}g()}},[t,l,g]),U=i.useCallback(()=>{g()},[g]);return{segments:m,isStarted:l,isFetching:c.isFetching,isError:c.isError,canScrollLoad:p,canLoadPrevious:f,previousTicket:y,reachedCap:b,loadPrevious:I,loadMoreInTicket:U,retry:h}}const $s=({title:t,value:s,subtitle:a,icon:r,iconColor:n="text-primary",iconBgColor:o="bg-primary/10",loading:l=!1,trend:c})=>e.jsxs(Wt,{className:"bg-card border-border hover:shadow-md transition-shadow",children:[e.jsxs(oi,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ci,{className:"text-sm font-medium text-foreground",children:t}),e.jsx("div",{className:`p-2 rounded-lg ${o}`,children:e.jsx(r,{className:`h-4 w-4 ${n}`})})]}),e.jsxs(Qt,{children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[l?e.jsx(ys,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx("span",{className:"text-2xl font-bold text-foreground",children:typeof s=="number"?s.toLocaleString():s}),c&&!l&&e.jsxs("span",{className:`text-xs font-medium ${c.isPositive?"text-emerald-600":"text-red-600"}`,children:[c.isPositive?"↑":"↓"," ",Math.abs(c.value),"%"]})]}),a&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:a})]})]}),Nm={summary:"",description:"",startDate:"",startTime:"",endDate:"",endTime:"",location:"",attendees:""},ia=t=>t.toISOString().slice(0,10),An=t=>t.toTimeString().slice(0,5),wm=t=>{const s=t.start.dateTime?new Date(t.start.dateTime):null,a=t.end.dateTime?new Date(t.end.dateTime):null;return{summary:t.summary||"",description:t.description||"",startDate:s?ia(s):t.start.date||"",startTime:s?An(s):"09:00",endDate:a?ia(a):t.end.date||"",endTime:a?An(a):"10:00",location:t.location||"",attendees:t.attendees?.map(r=>r.email).join(", ")||""}},Mn=(t,s)=>{const a={summary:t.summary};return t.description&&(a.description=t.description),t.location&&(a.location=t.location),a.start={dateTime:new Date(`${t.startDate}T${t.startTime}`).toISOString(),timeZone:s},a.end={dateTime:new Date(`${t.endDate}T${t.endTime}`).toISOString(),timeZone:s},t.attendees.trim()&&(a.attendees=t.attendees.split(",").map(r=>r.trim()).filter(Boolean).map(r=>({email:r}))),a},Dn=t=>t?new Date(t).toLocaleDateString("es-ES",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):"N/A",On=t=>{if(t.start.dateTime){const s=new Date(t.start.dateTime),a=new Date(t.end.dateTime);return`${s.toLocaleDateString("es-ES",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"})} - ${a.toLocaleTimeString("es-ES",{hour:"2-digit",minute:"2-digit"})}`}return t.start.date?`${t.start.date} (todo el día)`:"N/A"},Ht=t=>{if(t.start.dateTime)return new Date(t.start.dateTime)>new Date;if(t.start.date){const s=t.start.date,a=new Date().toISOString().split("T")[0];return s>=a}return!1},Gt=t=>{const s=new Date().toISOString().split("T")[0];return t.start.dateTime?t.start.dateTime.startsWith(s):t.start.date?t.start.date===s:!1},Un=({open:t,onOpenChange:s,title:a,description:r,initialData:n,isSubmitting:o,onSubmit:l})=>{const[c,u]=i.useState(n);i.useEffect(()=>{t&&u(n)},[t,n]);const d=(x,b)=>u(y=>({...y,[x]:b})),m=c.summary.trim()&&c.startDate&&c.startTime&&c.endDate&&c.endTime;return e.jsx(yt,{open:t,onOpenChange:s,children:e.jsxs(jt,{className:"sm:max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(Ut,{children:[e.jsx(vt,{children:a}),e.jsx(Rt,{children:r})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(we,{htmlFor:"evt-summary",children:"Título *"}),e.jsx(Te,{id:"evt-summary",value:c.summary,onChange:x=>d("summary",x.target.value),placeholder:"Reunión de equipo"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(we,{htmlFor:"evt-desc",children:"Descripción"}),e.jsx(Ts,{id:"evt-desc",value:c.description,onChange:x=>d("description",x.target.value),placeholder:"Detalles del evento...",rows:3})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(we,{htmlFor:"evt-start-date",children:"Fecha inicio *"}),e.jsx(Te,{id:"evt-start-date",type:"date",value:c.startDate,onChange:x=>d("startDate",x.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(we,{htmlFor:"evt-start-time",children:"Hora inicio *"}),e.jsx(Te,{id:"evt-start-time",type:"time",value:c.startTime,onChange:x=>d("startTime",x.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(we,{htmlFor:"evt-end-date",children:"Fecha fin *"}),e.jsx(Te,{id:"evt-end-date",type:"date",value:c.endDate,onChange:x=>d("endDate",x.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(we,{htmlFor:"evt-end-time",children:"Hora fin *"}),e.jsx(Te,{id:"evt-end-time",type:"time",value:c.endTime,onChange:x=>d("endTime",x.target.value)})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(we,{htmlFor:"evt-location",children:"Ubicación"}),e.jsx(Te,{id:"evt-location",value:c.location,onChange:x=>d("location",x.target.value),placeholder:"Oficina, Google Meet, etc."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(we,{htmlFor:"evt-attendees",children:"Invitados (emails separados por coma)"}),e.jsx(Te,{id:"evt-attendees",value:c.attendees,onChange:x=>d("attendees",x.target.value),placeholder:"user@ejemplo.com, otro@ejemplo.com"})]})]}),e.jsxs(tr,{children:[e.jsx(K,{variant:"outline",onClick:()=>s(!1),disabled:o,children:"Cancelar"}),e.jsx(K,{onClick:()=>l(c),disabled:!m||o,children:o?"Guardando...":"Guardar"})]})]})})},km=()=>{const t=Pn(),{channels:s,fetchChannels:a}=sr(),[r,n]=i.useState(null),[o,l]=i.useState(null),[c,u]=i.useState([]),[d,m]=i.useState([]),[x,b]=i.useState("primary"),[y,p]=i.useState(!0),[f,g]=i.useState(!1),[v,h]=i.useState(!1),[I,U]=i.useState(!1),[C,E]=i.useState(!1),[M,F]=i.useState({search:"",calendarId:"_all"}),[_,k]=i.useState(null),[W,q]=i.useState(!1),[ee,le]=i.useState(!1),[S,P]=i.useState(null),[X,A]=i.useState(!1),[z,L]=i.useState(null),N=Intl.DateTimeFormat().resolvedOptions().timeZone,w=s.filter(j=>j.type==="CALENDAR"&&!j.deletedAt);i.useEffect(()=>{a()},[a]),i.useEffect(()=>{w.length>0&&!r&&n(w[0])},[w,r]);const $=i.useCallback(async()=>{if(r){p(!0);try{const j=await ut.getGoogleCalendarStatus(r.id);if(l(j),j.config?.selectedCalendarId&&b(j.config.selectedCalendarId),j.status==="connected"){const G=await ut.listGoogleCalendars(r.id);u(G)}}catch{H.error("Error al cargar estado")}finally{p(!1)}}},[r]),ae=i.useCallback(async()=>{if(!(!r||o?.status!=="connected")){g(!0);try{const j=await ut.listGoogleCalendarEvents({channelId:r.id,calendarId:M.calendarId!=="_all"?M.calendarId:x,maxResults:100});m(j)}catch{H.error("Error al cargar eventos")}finally{g(!1)}}},[r,o?.status,x,M.calendarId]);i.useEffect(()=>{$()},[$]),i.useEffect(()=>{if(o?.status==="connected"){ae();const j=M.calendarId!=="_all"?M.calendarId:x;r&&j&&ut.subscribeGoogleCalendarWatch(r.id,j).catch(()=>{})}},[o?.status,x,ae,r,M.calendarId]),i.useEffect(()=>{const j=Ye.getState().user,G=j?.organizationId;if(!G||!j?.id)return;Pe.getConnectionStatus()||Pe.connect(j.id,G);const se=Pe.onCalendarEventsUpdate(de=>{de.channelId===r?.id&&(de.calendarId===x||M.calendarId==="_all"||de.calendarId===M.calendarId)&&m(de.events)});return()=>{se()}},[r?.id,x,M.calendarId]);const ne=async()=>{h(!0);try{const{url:j}=await ut.getGoogleCalendarAuthUrl();if(!j){H.error("No se pudo obtener URL de autorización");return}window.location.href=j}catch(j){H.error(j.message||"Error al iniciar OAuth")}finally{h(!1)}},re=async j=>{if(!r)return;b(j),(await ut.updateGoogleCalendarConfig({selectedCalendarId:j},r.id)).success&&(H.success("Calendario actualizado"),ae())},be=async j=>{if(r){A(!0);try{const G=Mn(j,N);await ut.createGoogleCalendarEvent(G,x,r.id)?(H.success("Evento creado"),q(!1),ae()):H.error("Error al crear evento")}catch{H.error("Error al crear evento")}finally{A(!1)}}},D=async j=>{if(!(!S||!r)){A(!0);try{const G=Mn(j,N);await ut.updateGoogleCalendarEvent(S.id,G,x,r.id)?(H.success("Evento actualizado"),le(!1),P(null),ae()):H.error("Error al actualizar evento")}catch{H.error("Error al actualizar evento")}finally{A(!1)}}},Z=async j=>{if(r){L(j);try{(await ut.deleteGoogleCalendarEvent(j,x,r.id)).success?(H.success("Evento eliminado"),m(se=>se.filter(de=>de.id!==j)),_?.id===j&&k(null)):H.error("Error al eliminar evento")}catch{H.error("Error al eliminar evento")}finally{L(null)}}},te=j=>{P(j),le(!0)},xe=d.filter(j=>{if(M.search){const G=M.search.toLowerCase();return j.summary?.toLowerCase().includes(G)||j.description?.toLowerCase().includes(G)||j.location?.toLowerCase().includes(G)}return!0}),ge={total:xe.length,upcoming:xe.filter(Ht).length,today:xe.filter(Gt).length,past:xe.filter(j=>!Ht(j)&&!Gt(j)).length},ve={...Nm,startDate:ia(new Date),startTime:"09:00",endDate:ia(new Date),endTime:"10:00"},V=o?.status==="connected";return e.jsxs("div",{className:"container mx-auto py-8 max-w-7xl space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-3xl font-bold tracking-tight flex items-center gap-3",children:[e.jsx(Ql,{className:"h-8 w-8 text-[#4285F4]"}),"Google Calendar"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Administra tus calendarios y eventos de Google."})]}),e.jsxs("div",{className:"flex gap-2",children:[V&&e.jsxs(e.Fragment,{children:[e.jsxs(K,{variant:"outline",onClick:()=>{ae(),$()},disabled:y||f,children:[e.jsx(ys,{className:`mr-2 h-4 w-4 ${y||f?"animate-spin":""}`}),"Actualizar"]}),e.jsxs(K,{variant:"outline",onClick:()=>t("/conexiones/google-calendar"),children:[e.jsx(Al,{className:"mr-2 h-4 w-4"}),"Configuración"]})]}),w.length>0&&e.jsx(K,{onClick:ne,disabled:v,className:"bg-[#4285F4] hover:bg-[#3367D6] text-white",children:v?e.jsxs(e.Fragment,{children:[e.jsx(ys,{className:"mr-2 h-4 w-4 animate-spin"}),"Conectando..."]}):e.jsxs(e.Fragment,{children:[e.jsx(dt,{className:"mr-2 h-4 w-4"}),"Nueva Conexión"]})})]})]}),w.length>1&&e.jsx(Wt,{children:e.jsx(Qt,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(we,{className:"text-sm font-semibold",children:"Cuenta de Google:"}),e.jsxs(kt,{value:r?.id||"",onValueChange:j=>{const G=w.find(se=>se.id===j);n(G||null)},children:[e.jsx(Ct,{className:"w-[300px]",children:e.jsx(Tt,{placeholder:"Seleccionar cuenta"})}),e.jsx(St,{children:w.map(j=>e.jsx(Me,{value:j.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[j.credentials?.picture&&e.jsx("img",{src:j.credentials.picture,alt:"",className:"w-5 h-5 rounded-full"}),e.jsx("span",{children:j.name})]})},j.id))})]})]})})}),r?V?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx($s,{title:"Total Eventos",value:ge.total,icon:So,iconColor:"text-primary",iconBgColor:"bg-primary/10",loading:f}),e.jsx($s,{title:"Próximos",value:ge.upcoming,icon:bt,iconColor:"text-blue-600",iconBgColor:"bg-blue-100",loading:f}),e.jsx($s,{title:"Hoy",value:ge.today,icon:ma,iconColor:"text-emerald-600",iconBgColor:"bg-emerald-100",loading:f}),e.jsx($s,{title:"Pasados",value:ge.past,icon:ks,iconColor:"text-amber-600",iconBgColor:"bg-amber-100",loading:f})]}),e.jsx(Wt,{children:e.jsx(Qt,{className:"pt-6",children:e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsx("div",{className:"flex-1 min-w-[200px]",children:e.jsxs("div",{className:"relative",children:[e.jsx(Bt,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Te,{placeholder:"Buscar por título, descripción, ubicación...",className:"pl-10",value:M.search,onChange:j=>F(G=>({...G,search:j.target.value}))})]})}),c.length>0&&e.jsxs(kt,{value:M.calendarId,onValueChange:j=>{F(G=>({...G,calendarId:j})),j!=="_all"&&(b(j),re(j))},children:[e.jsx(Ct,{className:"w-[200px]",children:e.jsx(Tt,{placeholder:"Calendario"})}),e.jsxs(St,{children:[e.jsx(Me,{value:"_all",children:"Todos los calendarios"}),c.map(j=>e.jsx(Me,{value:j.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[j.backgroundColor&&e.jsx("span",{className:"w-3 h-3 rounded-full inline-block",style:{backgroundColor:j.backgroundColor}}),e.jsxs("span",{children:[j.summary,j.primary&&" (Principal)"]})]})},j.id))]})]})]})})}),e.jsxs(Wt,{children:[e.jsx(oi,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ci,{className:"text-lg font-medium",children:"Lista de Eventos"}),e.jsxs(K,{size:"sm",onClick:()=>q(!0),className:"bg-[#4285F4] hover:bg-[#3367D6] text-white",children:[e.jsx(dt,{className:"mr-2 h-4 w-4"}),"Nuevo Evento"]})]})}),e.jsx(Qt,{className:"p-0",children:e.jsxs(ko,{children:[e.jsx(Co,{children:e.jsxs(Us,{className:"bg-muted/50",children:[e.jsx(zt,{children:"Título"}),e.jsx(zt,{children:"Fecha y Hora"}),e.jsx(zt,{children:"Ubicación"}),e.jsx(zt,{children:"Invitados"}),e.jsx(zt,{children:"Estado"}),e.jsx(zt,{className:"w-[120px]"})]})}),e.jsx(To,{children:f?Array.from({length:5}).map((j,G)=>e.jsx(Us,{children:Array.from({length:6}).map((se,de)=>e.jsx(Nt,{children:e.jsx(gs,{className:"h-5 w-full"})},de))},G)):xe.length===0?e.jsx(Us,{children:e.jsxs(Nt,{colSpan:6,className:"h-32 text-center",children:[e.jsx(Pt,{className:"mx-auto h-10 w-10 text-muted-foreground/50 mb-2"}),e.jsx("p",{className:"text-muted-foreground",children:"No hay eventos para mostrar"})]})}):xe.map(j=>e.jsxs(Us,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>k(j),children:[e.jsx(Nt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:j.summary||"(Sin título)"}),j.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-md",children:j.description})]})}),e.jsx(Nt,{className:"text-sm",children:On(j)}),e.jsx(Nt,{children:j.location?e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[e.jsx(Cs,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:j.location})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(Nt,{children:j.attendees&&j.attendees.length>0?e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[e.jsx(xa,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{children:j.attendees.length})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(Nt,{children:e.jsx(De,{variant:Ht(j)?"default":Gt(j)?"secondary":"outline",children:Ht(j)?"Próximo":Gt(j)?"Hoy":"Pasado"})}),e.jsx(Nt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(K,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:G=>{G.stopPropagation(),k(j)},children:e.jsx(za,{className:"h-4 w-4"})}),e.jsx(K,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:G=>{G.stopPropagation(),te(j)},children:e.jsx(_r,{className:"h-4 w-4"})}),e.jsxs(Sr,{children:[e.jsx(Er,{asChild:!0,children:e.jsx(K,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:G=>G.stopPropagation(),children:e.jsx(ns,{className:"h-4 w-4"})})}),e.jsxs(Ir,{children:[e.jsxs(Ar,{children:[e.jsx(Mr,{children:"Eliminar evento"}),e.jsxs(Dr,{children:['Se eliminará "',j.summary||"(Sin título)",'" de tu calendario de Google. Esta acción no se puede deshacer.']})]}),e.jsxs(Or,{children:[e.jsx(Ur,{children:"Cancelar"}),e.jsx(Rr,{onClick:()=>Z(j.id),disabled:z===j.id,className:"bg-destructive hover:bg-destructive/90",children:z===j.id?"Eliminando...":"Eliminar"})]})]})]})]})})]},j.id))})]})})]}),e.jsx(yt,{open:!!_,onOpenChange:j=>!j&&k(null),children:e.jsx(jt,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:_&&e.jsxs(e.Fragment,{children:[e.jsx(Ut,{children:e.jsxs(vt,{className:"flex items-center gap-3",children:[e.jsx("span",{children:_.summary||"(Sin título)"}),e.jsx(De,{variant:Ht(_)?"default":Gt(_)?"secondary":"outline",children:Ht(_)?"Próximo":Gt(_)?"Hoy":"Pasado"})]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase tracking-wide",children:"Fecha y Hora"}),e.jsx("p",{className:"font-medium",children:On(_)})]}),_.location&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"text-xs text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(Cs,{className:"h-3 w-3"})," Ubicación"]}),e.jsx("p",{children:_.location})]}),_.created&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase tracking-wide",children:"Creado"}),e.jsx("p",{className:"text-sm",children:Dn(_.created)})]}),_.updated&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase tracking-wide",children:"Actualizado"}),e.jsx("p",{className:"text-sm",children:Dn(_.updated)})]})]}),_.description&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-semibold text-sm uppercase tracking-wide text-muted-foreground",children:"Descripción"}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:_.description})]}),_.attendees&&_.attendees.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"font-semibold text-sm uppercase tracking-wide text-muted-foreground flex items-center gap-2",children:[e.jsx(Ja,{className:"h-4 w-4"})," Invitados"]}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-4 space-y-2",children:_.attendees.map((j,G)=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:j.email}),j.responseStatus&&e.jsx(De,{variant:"outline",className:"text-xs",children:j.responseStatus})]},G))})]}),e.jsxs("div",{className:"flex gap-3 pt-4 border-t",children:[e.jsxs(K,{variant:"outline",onClick:()=>{k(null),te(_)},children:[e.jsx(_r,{className:"mr-2 h-4 w-4"}),"Editar"]}),_.htmlLink&&e.jsx(K,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:_.htmlLink,target:"_blank",rel:"noreferrer",children:[e.jsx(za,{className:"mr-2 h-4 w-4"}),"Ver en Google Calendar"]})}),e.jsxs(Sr,{children:[e.jsx(Er,{asChild:!0,children:e.jsxs(K,{variant:"destructive",children:[e.jsx(ns,{className:"mr-2 h-4 w-4"}),"Eliminar"]})}),e.jsxs(Ir,{children:[e.jsxs(Ar,{children:[e.jsx(Mr,{children:"Eliminar evento"}),e.jsxs(Dr,{children:['Se eliminará "',_.summary||"(Sin título)",'" de tu calendario de Google. Esta acción no se puede deshacer.']})]}),e.jsxs(Or,{children:[e.jsx(Ur,{children:"Cancelar"}),e.jsx(Rr,{onClick:()=>{Z(_.id),k(null)},disabled:z===_.id,className:"bg-destructive hover:bg-destructive/90",children:z===_.id?"Eliminando...":"Eliminar"})]})]})]})]})]})]})})}),e.jsx(Un,{open:W,onOpenChange:q,title:"Crear evento",description:"Agrega un nuevo evento a tu calendario de Google.",initialData:ve,isSubmitting:X,onSubmit:be}),S&&e.jsx(Un,{open:ee,onOpenChange:j=>{le(j),j||P(null)},title:"Editar evento",description:`Editando "${S.summary||"(Sin título)"}"`,initialData:wm(S),isSubmitting:X,onSubmit:D})]}):e.jsx(Wt,{children:e.jsxs(Qt,{className:"p-8 text-center",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-muted flex items-center justify-center mb-4",children:e.jsx(ks,{className:"w-8 h-8 text-muted-foreground"})}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Esta cuenta no está conectada. Ve a Configuración para conectar."}),e.jsx(K,{onClick:()=>t(`/conexiones/google-calendar/${r.id}`),className:"bg-[#4285F4] hover:bg-[#3367D6] text-white",children:"Conectar"})]})}):e.jsx(Wt,{children:e.jsxs(Qt,{className:"p-8 text-center",children:[e.jsx("div",{className:"mx-auto w-16 h-16 rounded-full bg-muted flex items-center justify-center mb-4",children:e.jsx(Pt,{className:"w-8 h-8 text-muted-foreground"})}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No hay conexiones de Google Calendar. Conecta una cuenta para comenzar."}),e.jsx(K,{onClick:ne,disabled:v,className:"bg-[#4285F4] hover:bg-[#3367D6] text-white",children:v?"Conectando...":"Nueva Conexión"})]})})]})},Hx=()=>{const[t,s]=Ml(),[a,r]=i.useState(!1),[n,o]=i.useState(!1),[l,c]=i.useState(!1),{user:u}=Ye(),d=Ft(ue=>ue.currentOrganization),m=um(),x=fe(ue=>ue.filters.channelType),b=x&&["email","facebook","instagram"].includes(x),y=x==="calendar",{data:p,isLoading:f,isError:g,error:v,refetch:h}=dl(),{data:I,fetchNextPage:U,hasNextPage:C,isFetchingNextPage:E,isFetching:M,isError:F,error:_,refetch:k}=bm(m),W=i.useMemo(()=>{if(!(!I||C))return I.pages[I.pages.length-1]?.previousTicket??null},[I,C]),q=vm(m,W),ee=i.useMemo(()=>{if(!I)return p?.messages||[];const ue=I.pages.flatMap(ke=>ke.data);return Array.from(ue.reduce((ke,Q)=>{const ie=Q.channelMessageId||Q.id,O=ke.get(ie);return(!O||O.id.startsWith("temp-redis-")&&!Q.id.startsWith("temp-redis-"))&&ke.set(ie,Q),ke},new Map).values()).sort((ke,Q)=>{const ie=new Date(ke.channelTimestamp||ke.createdAt).getTime(),O=new Date(Q.channelTimestamp||Q.createdAt).getTime();return ie!==O?ie-O:ke.id.localeCompare(Q.id)})},[I,p]),{canScrollLoad:le,loadMoreInTicket:S}=q,P=i.useCallback(()=>{if(C){U();return}le&&S()},[C,U,le,S]),X=i.useMemo(()=>({segments:q.segments,canLoadPrevious:q.canLoadPrevious,canScrollLoad:q.canScrollLoad,isLoading:q.isFetching,isError:q.isError,reachedCap:q.reachedCap,previousTicket:q.previousTicket,onLoadPrevious:q.loadPrevious,onRetry:q.retry}),[q]),A=mm(),z=hm(m),{isLoading:L}=xm();pm();const{initialize:N,cleanup:w,selectConversation:$,sendMessage:ae,fetchConversations:ne,startTyping:re,stopTyping:be,closeTicket:D}=ds(),Z=al(),te=i.useCallback(()=>{r(ue=>!ue)},[]),xe=i.useCallback(()=>{o(ue=>{const je=!ue;return je?document.body.classList.add("inbox-focus-mode"):document.body.classList.remove("inbox-focus-mode"),je})},[]);i.useEffect(()=>{const ue=je=>{(je.ctrlKey||je.metaKey)&&je.key.toLowerCase()==="i"&&(je.preventDefault(),te())};return window.addEventListener("keydown",ue),()=>window.removeEventListener("keydown",ue)},[te]),i.useCallback(()=>{l||A||(c(!0),Pe.reconnect(),setTimeout(()=>{c(!1)},2e3))},[l,A]),i.useEffect(()=>()=>{document.body.classList.remove("inbox-focus-mode")},[]);const ge=i.useCallback(()=>{ne()},[ne]),ve=i.useCallback(ue=>{t.has("ticket")&&(t.delete("ticket"),s(t,{replace:!0})),$(ue)},[$,t,s]),V=t.get("ticket");i.useEffect(()=>{V&&V!==m&&(console.log(`[InboxPage] 🎯 Selecting ticket from URL: ${V}`),$(V),t.delete("ticket"),s(t,{replace:!0}))},[V,m,$,t,s]);const j=t.get("campaign");i.useEffect(()=>(j&&fe.getState().setCampaignFilter(j),()=>{fe.getState().setCampaignFilter(void 0)}),[j]),i.useEffect(()=>{if(m)return Pe.joinTicketRoom(m),()=>{Pe.leaveTicketRoom(m)}},[m]),i.useEffect(()=>{if(!(!d?.id||!u?.id))return N(u.id,d.id),()=>{w()}},[u?.id,d?.id,N,w]);const G=i.useCallback(async(ue,je="TEXT",ke)=>{if(!m)return;const Q=p?.ticket?.status;if(Q==="WAITING"||Q==="WAITING_ASSIGNMENT")throw H.error("No puedes enviar mensajes cuando el ticket está en espera"),new Error("Ticket en espera: el mensaje no se envió");if(p?.contact?.hasLimitTag)throw H.error("No se pueden enviar mensajes a este contacto. Límite de contactos excedido. Actualiza tu plan para continuar."),new Error("Límite de contactos excedido: el mensaje no se envió");const ie=await Z(m,Q);try{await ae({ticketId:ie,content:ue,contentType:je,mediaUrl:ke?.mediaUrl,gcsPath:ke?.gcsPath,mediaMimeType:ke?.mediaMimeType,fileSize:ke?.fileSize,fileHash:ke?.fileHash,fileName:ke?.fileName,templateId:ke?.templateId,metadata:{skipInactivity:ke?.skipInactivity??!1}})}catch(O){const B=O?.response?.data?.message||O?.message||"Error al enviar mensaje";throw H.error(B),O}},[m,p,ae,Z]),se=i.useCallback(async ue=>{if(m){if(sl(p?.ticket?.status))throw H.error("Esta conversación está cerrada. Escríbele al cliente para retomarla y luego deja la nota."),new Error("Conversación cerrada: la nota no se guardó");try{await Ce.addNote(m,ue)}catch(je){const ke=je?.response?.data?.message||je?.message||"No se pudo guardar la nota interna";throw H.error(ke),je}}},[m,p]),de=i.useCallback((ue,je)=>{m&&ae({ticketId:m,content:je,contentType:"TEXT",metadata:{optionId:ue,label:je}})},[m,ae]),Ae=i.useCallback(async()=>{if(m)try{await D(m),await ne(),$(null)}catch(ue){console.error("Failed to close ticket:",ue)}},[m,D,ne,$]);return e.jsxs("div",{className:T("flex flex-col bg-[#F8FAFC]",n?"fixed inset-0 z-50":"h-[calc(100dvh-56px)] lg:h-[calc(100vh-56px)] overflow-hidden"),children:[e.jsx(wo,{title:"Bandeja de Entrada",description:"Gestiona tus conversaciones y atiende a tus clientes.",icon:Dl,fullWidth:!0,compact:n,className:"border-b border-slate-100 bg-white/80 backdrop-blur-sm sticky top-0 z-10",actions:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(K,{variant:"ghost",size:"icon",onClick:te,className:T("h-9 w-9 text-muted-foreground hover:text-foreground hidden lg:flex",m&&"md:flex"),title:a?"Ocultar panel":"Ver detalles",children:a?e.jsx(zo,{className:"w-4 h-4"}):e.jsx(Ho,{className:"w-4 h-4"})}),e.jsx(K,{variant:"ghost",size:"icon",onClick:xe,className:"h-9 w-9 text-muted-foreground hover:text-foreground hidden sm:flex",title:n?"Salir del modo enfocado":"Modo enfocado (pantalla completa)",children:n?e.jsx(vo,{className:"w-4 h-4"}):e.jsx(ii,{className:"w-4 h-4"})})]})}),e.jsx(dm,{}),e.jsx("div",{className:"flex-1 flex overflow-hidden bg-white/50 dark:bg-background backdrop-blur-3xl",children:y?e.jsx("div",{className:"flex-1 w-full h-full overflow-y-auto bg-transparent",children:e.jsx(km,{})}):b?e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center p-8 text-center animate-in fade-in zoom-in duration-500 bg-white dark:bg-card",children:[e.jsx("div",{className:"w-24 h-24 bg-slate-50 dark:bg-slate-800/50 rounded-full flex items-center justify-center mb-6 border border-slate-100 dark:border-slate-800 shadow-sm",children:e.jsx("span",{className:"text-5xl opacity-80 decoration-transparent",children:"🔌"})}),e.jsx("h2",{className:"text-2xl font-bold text-slate-800 dark:text-slate-200 mb-3 tracking-tight",children:"Conecta este canal"}),e.jsx("p",{className:"text-slate-500 dark:text-slate-400 max-w-[420px] mx-auto text-sm leading-relaxed mb-8",children:"Estamos preparando la integración completa. Muy pronto podrás gestionar todos tus mensajes de este canal directamente desde la bandeja unificada."}),e.jsx(K,{className:"rounded-full px-8 shadow-lg shadow-primary/20 h-11 pointer-events-none opacity-90",disabled:!0,children:"Próximamente"})]}):e.jsxs(e.Fragment,{children:[e.jsx(ea,{onReset:ge,children:e.jsxs("div",{className:T("w-full md:w-[380px] lg:w-[420px] flex-shrink-0 border-r border-slate-100/50 dark:border-border bg-white dark:bg-card h-full flex flex-col transition-transform duration-300",m?"hidden md:flex":"flex"),children:[j&&e.jsxs("div",{className:"px-3 py-2 bg-primary/10 border-b border-primary/20 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx("span",{className:"text-lg",children:"📢"}),e.jsx("span",{className:"font-medium",children:"Filtro: Campaña activa"})]}),e.jsx(K,{variant:"ghost",size:"sm",className:"h-6 text-xs text-primary hover:text-primary hover:bg-primary/20",onClick:()=>{fe.getState().setCampaignFilter(void 0),window.history.replaceState({},"","/bandeja")},children:"Limpiar"})]}),e.jsx(Ei,{activeConversationId:m,onSelectConversation:ve})]})}),e.jsx(ea,{onReset:ge,children:e.jsx("div",{className:T("flex-1 flex flex-col min-w-0 h-full bg-slate-50/50 dark:bg-background",m?"flex":"hidden md:flex"),children:e.jsx(cl,{conversation:p??void 0,onOpenProfile:te,onBack:()=>$(null),messages:ee,onSendMessage:G,onSendNote:se,onInteractiveOption:de,typingIndicator:z,onStartTyping:re,onStopTyping:be,onResolve:Ae,onLoadMore:P,hasMore:C,isLoadingMore:E||q.isFetching,isLoadingConversation:f||M&&!I,history:X,loadError:g?v:void 0,messagesError:F?_:void 0,onRetryLoad:h,onRetryMessages:k},m||"no-chat")})}),a&&p?.contact&&e.jsx("div",{className:T("fixed inset-0 z-50 flex bg-background","animate-in slide-in-from-right duration-300","lg:static lg:inset-auto lg:z-20 lg:w-[400px] lg:shrink-0","lg:flex-col lg:border-l lg:border-slate-100 lg:dark:border-border","lg:bg-gradient-to-b lg:from-white lg:to-slate-50/50 lg:dark:bg-card","lg:shadow-sm lg:h-full lg:overflow-hidden","lg:animate-none"),children:e.jsx(ml,{onClose:()=>r(!1),contact:p.contact,ticketId:p.ticket.id,messages:ee,className:"w-full lg:w-auto lg:flex-1"})})]})})]})};export{gi as AdvisorStatusBadge,el as ChatInput,mr as ChatMessage,cl as ChatView,ul as ContactNotes,ml as ContactPanel,Ga as ConversationItem,Ei as ConversationList,Hx as InboxPage,dm as InboxTabs,om as MetadataDisplay,jo as TagSelector,Ce as inboxApi,qx as useAdvisorStatus,fe as useInboxStore,Pe as websocketService};
|