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.
Files changed (272) hide show
  1. package/README.md +6 -5
  2. package/lib/api.mjs +6 -2
  3. package/lib/cloudflare.mjs +13 -12
  4. package/lib/commands/init.mjs +260 -251
  5. package/package.json +1 -1
  6. package/template/.claude/skills/nubot-lite/SKILL.md +7 -1
  7. package/template/panel/PANEL.md +1 -1
  8. package/template/panel/assets/AgendarDemoPage-Bn_BvTp1.js +1 -0
  9. package/template/panel/assets/{AgentDatasetsPage-D8vQhRWO.js → AgentDatasetsPage-wLtBtSB2.js} +2 -2
  10. package/template/panel/assets/AgentKnowledgeGroupsPage-BGHNFj-e.js +1 -0
  11. package/template/panel/assets/AgentListPage-F3ja9_o_.js +1 -0
  12. package/template/panel/assets/AgentQaTrainingPage-CojiU8_W.js +1 -0
  13. package/template/panel/assets/AiAgentWhatsappPage-Bn_BvTp1.js +1 -0
  14. package/template/panel/assets/BlogPage-Bn_BvTp1.js +1 -0
  15. package/template/panel/assets/BlogPostPage-Bn_BvTp1.js +1 -0
  16. package/template/panel/assets/CalculadoraTiempoRespuestaPage-Bn_BvTp1.js +1 -0
  17. package/template/panel/assets/{CampaignDetailPage-DFMctNEj.js → CampaignDetailPage-DUNnckvn.js} +1 -1
  18. package/template/panel/assets/CampaignsPage-CS60yZBd.js +1 -0
  19. package/template/panel/assets/ChannelSelector-C7R9zqrt.js +1 -0
  20. package/template/panel/assets/ChatbotParaWhatsappPage-Bn_BvTp1.js +1 -0
  21. package/template/panel/assets/ConfirmModal-B27OBQdm.js +1 -0
  22. package/template/panel/assets/ContactsPage-CvoDlFUN.js +14 -0
  23. package/template/panel/assets/CreateAgentPage-CbhikMY1.js +19 -0
  24. package/template/panel/assets/CreditLimitBanner-j72L7jgK.js +1 -0
  25. package/template/panel/assets/CrmParaWhatsappPage-Bn_BvTp1.js +1 -0
  26. package/template/panel/assets/DashboardPage-BGWkXY7W.js +1 -0
  27. package/template/panel/assets/{EmojiPicker-BToAe-MT.js → EmojiPicker-ByTMSXTj.js} +1 -1
  28. package/template/panel/assets/{EventTypesSettingsPage-DCedeQzM.js → EventTypesSettingsPage-CLpO1VBL.js} +1 -1
  29. package/template/panel/assets/GeneradorEnlacesPage-Bn_BvTp1.js +1 -0
  30. package/template/panel/assets/GeneradorQrWhatsappPage-Bn_BvTp1.js +1 -0
  31. package/template/panel/assets/{GeneralSettingsPage-B04ozcHb.js → GeneralSettingsPage-CY-5aGgL.js} +1 -1
  32. package/template/panel/assets/GoogleCalendarManagePage-oX7DuErV.js +1 -0
  33. package/template/panel/assets/{InvitationAcceptancePage-BPgtBFl5.js → InvitationAcceptancePage-BYllrAYs.js} +1 -1
  34. package/template/panel/assets/IrAlSitioPublico-Bn_BvTp1.js +1 -0
  35. package/template/panel/assets/LiteAiUsagePage-Dzm8jBL2.js +1 -0
  36. package/template/panel/assets/{LiteSetupPage-42rgAdnG.js → LiteSetupPage-CMSAur_e.js} +1 -1
  37. package/template/panel/assets/MarkdownRenderer-C3TD9KYa.js +3 -0
  38. package/template/panel/assets/MediaProcessingService-CG2DdSyN.js +1 -0
  39. package/template/panel/assets/NewCampaignPage-BfSEd075.js +1 -0
  40. package/template/panel/assets/OrdersConfigPage-BAKKaX0L.js +1 -0
  41. package/template/panel/assets/OrdersPage-CXiPOCXP.js +1 -0
  42. package/template/panel/assets/{PasswordStrengthIndicator-HZK_oU0W.js → PasswordStrengthIndicator-4h-Y0s2r.js} +1 -1
  43. package/template/panel/assets/PlantillaDetailPage-Bn_BvTp1.js +1 -0
  44. package/template/panel/assets/PlantillasIndexPage-Bn_BvTp1.js +1 -0
  45. package/template/panel/assets/PrivacyPolicy-Bn_BvTp1.js +1 -0
  46. package/template/panel/assets/{ProductManagementPage-DNM7DEgt.js → ProductManagementPage-CRkNTicv.js} +4 -4
  47. package/template/panel/assets/PublicFormPage-BxPxJ3Pq.js +1 -0
  48. package/template/panel/assets/QaForm-Px-cmakA.js +5 -0
  49. package/template/panel/assets/SelectPlanPage-Gyo5C1Hq.js +1 -0
  50. package/template/panel/assets/SignatureEditor-DIhmrXow.js +1 -0
  51. package/template/panel/assets/{TagSelector-ChoKzvjW.js → TagSelector-o6tVpRs9.js} +1 -1
  52. package/template/panel/assets/TagsSettingsPage-DT8MfW1H.js +2 -0
  53. package/template/panel/assets/TeamsPage-BuWuGxZo.js +1 -0
  54. package/template/panel/assets/WhatsappBusinessApiPage-Bn_BvTp1.js +1 -0
  55. package/template/panel/assets/WhatsappMultiagentePage-Bn_BvTp1.js +1 -0
  56. package/template/panel/assets/{account-D2ltXC_U.js → account-G3WXxisG.js} +1 -1
  57. package/template/panel/assets/{admin-lEgqZTsa.js → admin-CSMlOMR8.js} +1 -1
  58. package/template/panel/assets/{agent.service-BcAkMU7j.js → agent.service-BE2rJG_o.js} +1 -1
  59. package/template/panel/assets/{alert-dialog-D8P69s-m.js → alert-dialog-gzZZoAiu.js} +2 -2
  60. package/template/panel/assets/{alert-DI3GBLi1.js → alert-seLKo73M.js} +1 -1
  61. package/template/panel/assets/api-keys-BF33GS2N.js +1 -0
  62. package/template/panel/assets/{archive-LUe5bKi5.js → archive-CxUKRJwu.js} +1 -1
  63. package/template/panel/assets/{arrow-left-BeDdBs_Q.js → arrow-left-CI7mH7bD.js} +1 -1
  64. package/template/panel/assets/{arrow-up-BiBq8Pvx.js → arrow-up-DJzXCc8_.js} +1 -1
  65. package/template/panel/assets/{arrow-up-down-CaG2BONN.js → arrow-up-down-DkSCsCjR.js} +1 -1
  66. package/template/panel/assets/audit-slljESxh.js +1 -0
  67. package/template/panel/assets/{authService-Cbm8LdlJ.js → authService-CtvlzCDa.js} +1 -1
  68. package/template/panel/assets/{avatar-CILB1zwS.js → avatar-BXhSKQGY.js} +1 -1
  69. package/template/panel/assets/{billing-IVLNopU2.js → billing-Cy2XUBeY.js} +1 -1
  70. package/template/panel/assets/{brain-B9z7jZ7A.js → brain-BmrjUpsb.js} +1 -1
  71. package/template/panel/assets/{calendar-CIHhMjNy.js → calendar-Bu0aDtW1.js} +1 -1
  72. package/template/panel/assets/{calendar-days-BwJfOz8M.js → calendar-days-CXtOZxOF.js} +1 -1
  73. package/template/panel/assets/{card-DcKsxjXK.js → card-DdbmSh-v.js} +1 -1
  74. package/template/panel/assets/{checkbox-pcbjC0d3.js → checkbox-CuJh5AMO.js} +1 -1
  75. package/template/panel/assets/{chevrons-up-down-DC-BWTrj.js → chevrons-up-down-DNNdNhV8.js} +1 -1
  76. package/template/panel/assets/{circle-check-big-DzPo5zZX.js → circle-check-big-BOZQ_2Kv.js} +1 -1
  77. package/template/panel/assets/{circle-x-BwMKIs8b.js → circle-x-decmm7ip.js} +1 -1
  78. package/template/panel/assets/cloud-B3m0_VpL.js +1 -0
  79. package/template/panel/assets/{code-BMAyHFJe.js → code-C-UH-ZD-.js} +1 -1
  80. package/template/panel/assets/{cog-M7j64wa2.js → cog-BS-_-U4F.js} +1 -1
  81. package/template/panel/assets/{collapsible-B22t1J-V.js → collapsible-Ce_8EeFJ.js} +1 -1
  82. package/template/panel/assets/{command-COdSmSIB.js → command-aHRTWaYV.js} +1 -1
  83. package/template/panel/assets/connectionsService-BJg4S1e9.js +1 -0
  84. package/template/panel/assets/contactsApi-DI5dcMLo.js +1 -0
  85. package/template/panel/assets/creditErrors-DSbswjsG.js +1 -0
  86. package/template/panel/assets/{database-C1qvt3Py.js → database-Brb7Omak.js} +1 -1
  87. package/template/panel/assets/{datapath-C12uI_pT.js → datapath-CHeKabeh.js} +1 -1
  88. package/template/panel/assets/{datetime-BuZosCVk.js → datetime-D72Uxhjs.js} +1 -1
  89. package/template/panel/assets/{download-CiVQHPeB.js → download-CyfdxFCW.js} +1 -1
  90. package/template/panel/assets/{ellipsis-CMEJnUfK.js → ellipsis-GLu0u4ze.js} +1 -1
  91. package/template/panel/assets/{ellipsis-vertical-DTqbEYYp.js → ellipsis-vertical-CskGwbgN.js} +1 -1
  92. package/template/panel/assets/email-inbox-kyJ2qML5.js +1 -0
  93. package/template/panel/assets/es-BDgg6unH.js +1 -0
  94. package/template/panel/assets/external-link-w7K66ae2.js +1 -0
  95. package/template/panel/assets/{eye-HfQCUjxJ.js → eye-CR5C6hVv.js} +1 -1
  96. package/template/panel/assets/{eye-off-v1Z_lKS0.js → eye-off-CBiJXw4j.js} +1 -1
  97. package/template/panel/assets/facebook-D0SQMea2.js +1 -0
  98. package/template/panel/assets/{file-DMzjdlTL.js → file-CTZ8-xmL.js} +1 -1
  99. package/template/panel/assets/file-braces-54MsOnzo.js +1 -0
  100. package/template/panel/assets/file-spreadsheet-DpekIaV8.js +1 -0
  101. package/template/panel/assets/{folder-D0GKakGp.js → folder-DxTHNhQ_.js} +1 -1
  102. package/template/panel/assets/{folder-open-DQFc4qTJ.js → folder-open-BM4rA96e.js} +1 -1
  103. package/template/panel/assets/format-BG1mN6C0.js +1 -0
  104. package/template/panel/assets/{grip-vertical-FN-eTC2C.js → grip-vertical-CS-dU0tJ.js} +1 -1
  105. package/template/panel/assets/{hash-BoTE56iw.js → hash-ByrjK6gt.js} +1 -1
  106. package/template/panel/assets/{help-center-B1MAIBWA.js → help-center-fmvvoAkD.js} +1 -1
  107. package/template/panel/assets/{history-DhHayxUg.js → history-97D1GT_9.js} +1 -1
  108. package/template/panel/assets/house-CXew5LB-.js +1 -0
  109. package/template/panel/assets/{index-DsyZ_FlA.js → index-43NA2pdZ.js} +23 -23
  110. package/template/panel/assets/index-BG59-Kyv.js +6 -0
  111. package/template/panel/assets/{index-DUnioqCT.js → index-BGvtgHY3.js} +1 -1
  112. package/template/panel/assets/index-BL76lyPt.js +2 -0
  113. package/template/panel/assets/index-BUA9lP4J.js +1 -0
  114. package/template/panel/assets/index-Bfvq4Q3v.js +1 -0
  115. package/template/panel/assets/index-CK793Wzl.css +1 -0
  116. package/template/panel/assets/{index-BTxe6gLJ.js → index-ChrvveQm.js} +1 -1
  117. package/template/panel/assets/index-CoJIvJ6y.js +1 -0
  118. package/template/panel/assets/{index-CMEeV9dO.js → index-CsV1u-Y7.js} +2 -2
  119. package/template/panel/assets/{index-BiSc3WD9.js → index-DIxON2Dm.js} +1 -1
  120. package/template/panel/assets/index-DtoSJTyl.js +1 -0
  121. package/template/panel/assets/index-FBuxpbGF.js +36 -0
  122. package/template/panel/assets/index-YR5X3nd4.js +1 -0
  123. package/template/panel/assets/{instagram-CC7iYt7V.js → instagram-Bm17x-Fs.js} +1 -1
  124. package/template/panel/assets/interactiveLimits-C7Sx7s9W.js +1 -0
  125. package/template/panel/assets/landing-CEUFhLJ9.js +1 -0
  126. package/template/panel/assets/{layout-grid-Cm6hfBWZ.js → layout-grid-DN-t2Wjd.js} +1 -1
  127. package/template/panel/assets/{list-BKc6EXnV.js → list-B0uLKf1b.js} +1 -1
  128. package/template/panel/assets/{map-pin-CPmcofD3.js → map-pin-COYHwobx.js} +1 -1
  129. package/template/panel/assets/{maximize-2-WdbM7Kdx.js → maximize-2-SbmXBBYe.js} +1 -1
  130. package/template/panel/assets/mediaLimits-CAYdWqeQ.js +1 -0
  131. package/template/panel/assets/mediaValidation-Bg0xHQrv.js +1 -0
  132. package/template/panel/assets/message-circle-tNSzOeOW.js +1 -0
  133. package/template/panel/assets/{message-square-Dfn16oHc.js → message-square-B1_OirdW.js} +1 -1
  134. package/template/panel/assets/{meta-templates-C7yEjSOI.js → meta-templates-hhDdxBOR.js} +1 -1
  135. package/template/panel/assets/metadataSchemasApi-BmJko2eC.js +1 -0
  136. package/template/panel/assets/{mic-CT4vyzLZ.js → mic-ClFq9hMZ.js} +1 -1
  137. package/template/panel/assets/minus-vh4a51Mn.js +1 -0
  138. package/template/panel/assets/{music-Cu8AQMFp.js → music-CgtkroYi.js} +1 -1
  139. package/template/panel/assets/{page-components-o2TF52HV.js → page-components-DXOKtt_M.js} +1 -1
  140. package/template/panel/assets/{pages-Cj5Qd1QO.js → pages-BcYbyh_-.js} +1 -1
  141. package/template/panel/assets/{pages-B7digtXi.js → pages-BuibyrnC.js} +1 -1
  142. package/template/panel/assets/{pages-Dw7dvmaS.js → pages-CGXCBdff.js} +1 -1
  143. package/template/panel/assets/paperclip-DVRbzE7C.js +1 -0
  144. package/template/panel/assets/{pen-line-DLnhkIuw.js → pen-line-Cr0YFjAs.js} +1 -1
  145. package/template/panel/assets/{pencil-Cx8u1N8t.js → pencil-aqjc7AWb.js} +1 -1
  146. package/template/panel/assets/{popover-MyuU-yAK.js → popover-cWIhNmod.js} +1 -1
  147. package/template/panel/assets/{power-CdR2OkIX.js → power-CVFzhVJx.js} +1 -1
  148. package/template/panel/assets/{product.service-CRLZOQsr.js → product.service-FClit10f.js} +1 -1
  149. package/template/panel/assets/products.types-nZIsk2w8.js +1 -0
  150. package/template/panel/assets/proxy-CvX2KM2u.js +1 -0
  151. package/template/panel/assets/{save-Dua2yhWl.js → save-mwkHDnDL.js} +1 -1
  152. package/template/panel/assets/scroll-area-CSCo4HHB.js +1 -0
  153. package/template/panel/assets/{select-DlB_BbfM.js → select-DCY_lg9j.js} +1 -1
  154. package/template/panel/assets/{send-Dxmdupsl.js → send-DBQH77K9.js} +1 -1
  155. package/template/panel/assets/{separator-CPT3uVRM.js → separator-DznqP68l.js} +1 -1
  156. package/template/panel/assets/{settings-2-C-c8ECWW.js → settings-2-PhKPMrsj.js} +1 -1
  157. package/template/panel/assets/shield-alert-Fv3j9Wbv.js +1 -0
  158. package/template/panel/assets/{skeleton-B0zh8s_y.js → skeleton-CN6xlRXP.js} +1 -1
  159. package/template/panel/assets/{slider-CY71MXOW.js → slider-D0QB_Lme.js} +1 -1
  160. package/template/panel/assets/{square-BuGqLxJB.js → square-Dm5VC71z.js} +1 -1
  161. package/template/panel/assets/{square-pen-CJajoyrm.js → square-pen-Dbn7xmc-.js} +1 -1
  162. package/template/panel/assets/{star-Cuegk1GF.js → star-BMD3HmS6.js} +1 -1
  163. package/template/panel/assets/stat-card-W7s_-fHW.js +1 -0
  164. package/template/panel/assets/storage.api-C0ZJBoSz.js +20 -0
  165. package/template/panel/assets/{switch-ODBa0fCT.js → switch-C7XmAU1c.js} +1 -1
  166. package/template/panel/assets/{table-CvSELOPi.js → table-7NGq0kRw.js} +1 -1
  167. package/template/panel/assets/{tabs-DqXhuAr6.js → tabs-BGCKrmVw.js} +1 -1
  168. package/template/panel/assets/{tags-By_tlh_r.js → tags-HU2fuPFH.js} +1 -1
  169. package/template/panel/assets/{target-DEuCdeUI.js → target-CG_g4_Fj.js} +1 -1
  170. package/template/panel/assets/{textarea-BYtcLsMD.js → textarea-B1anutjq.js} +1 -1
  171. package/template/panel/assets/{ticket-CWba7G1i.js → ticket-CHs1Xojr.js} +1 -1
  172. package/template/panel/assets/{trash-2-Du2vmQCH.js → trash-2-D_kmHMwn.js} +1 -1
  173. package/template/panel/assets/{trending-up-Ba4HSvuW.js → trending-up-BnHeLWFs.js} +1 -1
  174. package/template/panel/assets/{upload-C7TwpdyA.js → upload-CQg4_W5r.js} +1 -1
  175. package/template/panel/assets/{useAiAgentsQuery-Bm6aRHKj.js → useAiAgentsQuery-CXo6TmU6.js} +1 -1
  176. package/template/panel/assets/useFunnelStats-Bk8wTET5.js +1 -0
  177. package/template/panel/assets/useFunnelsQuery-vDrahaDr.js +1 -0
  178. package/template/panel/assets/{useInfiniteQuery-BXUM1Z9V.js → useInfiniteQuery-D0sFT2K2.js} +1 -1
  179. package/template/panel/assets/{useMutation-a5tIBvQY.js → useMutation-0ypmz8SO.js} +1 -1
  180. package/template/panel/assets/useOrgSyncedFetch-FSgwRhpR.js +1 -0
  181. package/template/panel/assets/usePipelineBoardQuery-BysscZXI.js +9 -0
  182. package/template/panel/assets/{useUploadConfig-BuiF0X-3.js → useUploadConfig-CvVmSc6S.js} +1 -1
  183. package/template/panel/assets/{user-DwCALzIG.js → user-l48WDfDH.js} +1 -1
  184. package/template/panel/assets/{user-plus-BiUjcHil.js → user-plus-CWaaUP-O.js} +1 -1
  185. package/template/panel/assets/{video-VfwKgB6z.js → video-CILE66CA.js} +1 -1
  186. package/template/panel/assets/{volume-2-C5DMdOVq.js → volume-2-DfFqN0dw.js} +1 -1
  187. package/template/panel/assets/wrench-Dcbk4scY.js +1 -0
  188. package/template/panel/index.html +2 -2
  189. package/template/panel/version.json +2 -2
  190. package/template/worker/migrations/0006_ai_usage.sql +33 -0
  191. package/template/worker/migrations/0007_channels.sql +18 -0
  192. package/template/worker/src/agent/pricing.ts +37 -0
  193. package/template/worker/src/agent/prompt.ts +137 -134
  194. package/template/worker/src/agent/run.ts +350 -243
  195. package/template/worker/src/agent/sandbox.ts +2 -2
  196. package/template/worker/src/agent/tools.ts +463 -463
  197. package/template/worker/src/channels/accounts.ts +177 -0
  198. package/template/worker/src/channels/zernio.ts +161 -148
  199. package/template/worker/src/inbox/contacts.ts +2 -0
  200. package/template/worker/src/inbox/store.ts +199 -187
  201. package/template/worker/src/index.ts +2 -0
  202. package/template/worker/src/nubot/account.ts +163 -178
  203. package/template/worker/src/nubot/ai-usage.ts +197 -0
  204. package/template/worker/src/nubot/channels.ts +159 -0
  205. package/template/worker/src/nubot/contacts.ts +387 -386
  206. package/template/worker/src/nubot/funnels.ts +672 -670
  207. package/template/worker/src/nubot/inbox.ts +623 -616
  208. package/template/worker/src/nubot/index.ts +127 -122
  209. package/template/worker/src/nubot/mappers.ts +12 -5
  210. package/template/worker/src/routes/channels.ts +13 -0
  211. package/template/worker/src/routes/system.ts +110 -100
  212. package/template/worker/src/webhooks/zernio.ts +154 -125
  213. package/template/panel/assets/AgendarDemoPage-DOiS40FL.js +0 -1
  214. package/template/panel/assets/AgentKnowledgeGroupsPage-DEPS1lsk.js +0 -1
  215. package/template/panel/assets/AgentListPage-DqY9rze5.js +0 -1
  216. package/template/panel/assets/AgentQaTrainingPage-Ecis7xoc.js +0 -1
  217. package/template/panel/assets/AiAgentWhatsappPage-DOiS40FL.js +0 -1
  218. package/template/panel/assets/AiMetricsPage-DEPS1lsk.js +0 -1
  219. package/template/panel/assets/BlogPage-DOiS40FL.js +0 -1
  220. package/template/panel/assets/BlogPostPage-DOiS40FL.js +0 -1
  221. package/template/panel/assets/CalculadoraTiempoRespuestaPage-DOiS40FL.js +0 -1
  222. package/template/panel/assets/CampaignsPage-CLRaXGlj.js +0 -1
  223. package/template/panel/assets/ChannelSelector-q9tTirNo.js +0 -1
  224. package/template/panel/assets/ChatbotParaWhatsappPage-DOiS40FL.js +0 -1
  225. package/template/panel/assets/ConfirmModal-W7VUI3Z_.js +0 -1
  226. package/template/panel/assets/ContactsPage-CsOFsOPw.js +0 -14
  227. package/template/panel/assets/CreateAgentPage-Ifxx6_UX.js +0 -19
  228. package/template/panel/assets/CreditLimitBanner-J49rSVEn.js +0 -1
  229. package/template/panel/assets/CrmParaWhatsappPage-DOiS40FL.js +0 -1
  230. package/template/panel/assets/DashboardPage-3Viy83dd.js +0 -1
  231. package/template/panel/assets/GeneradorEnlacesPage-DOiS40FL.js +0 -1
  232. package/template/panel/assets/GeneradorQrWhatsappPage-DOiS40FL.js +0 -1
  233. package/template/panel/assets/IrAlSitioPublico-DOiS40FL.js +0 -1
  234. package/template/panel/assets/MediaProcessingService-glHGiE_o.js +0 -1
  235. package/template/panel/assets/NewCampaignPage-Cw99m3W8.js +0 -1
  236. package/template/panel/assets/OrdersConfigPage-B6BfM3lf.js +0 -1
  237. package/template/panel/assets/OrdersPage-Du7CJjty.js +0 -1
  238. package/template/panel/assets/PlantillaDetailPage-DOiS40FL.js +0 -1
  239. package/template/panel/assets/PlantillasIndexPage-DOiS40FL.js +0 -1
  240. package/template/panel/assets/PrivacyPolicy-DOiS40FL.js +0 -1
  241. package/template/panel/assets/PublicFormPage-DDb4OXEM.js +0 -1
  242. package/template/panel/assets/QaForm-BDboHNKo.js +0 -5
  243. package/template/panel/assets/SelectPlanPage-DALaf8E5.js +0 -1
  244. package/template/panel/assets/TagsSettingsPage-DYCKveQq.js +0 -2
  245. package/template/panel/assets/TeamsPage-DPUcRdlh.js +0 -1
  246. package/template/panel/assets/WhatsappBusinessApiPage-DOiS40FL.js +0 -1
  247. package/template/panel/assets/WhatsappMultiagentePage-DOiS40FL.js +0 -1
  248. package/template/panel/assets/api-keys-B0UQNR5E.js +0 -1
  249. package/template/panel/assets/audit-BrdHcTNl.js +0 -1
  250. package/template/panel/assets/connections-Dqwd01UI.js +0 -1
  251. package/template/panel/assets/connectionsService-BsJf8pFz.js +0 -3
  252. package/template/panel/assets/contactsApi-B851NME_.js +0 -1
  253. package/template/panel/assets/creditErrors-CrpkwwUI.js +0 -1
  254. package/template/panel/assets/email-inbox-LbGeQCty.js +0 -1
  255. package/template/panel/assets/es-BG480iA5.js +0 -1
  256. package/template/panel/assets/facebook-RxMBweMB.js +0 -1
  257. package/template/panel/assets/index-B183O0S5.js +0 -1
  258. package/template/panel/assets/index-BJCPaymI.css +0 -1
  259. package/template/panel/assets/index-BtxJGfLL.js +0 -6
  260. package/template/panel/assets/index-Bz-ixwph.js +0 -1
  261. package/template/panel/assets/index-CjQSv8hF.js +0 -2
  262. package/template/panel/assets/index-D3vkHHjD.js +0 -9
  263. package/template/panel/assets/index-D4WhIkMN.js +0 -1
  264. package/template/panel/assets/interactiveLimits-CfLJ1O4_.js +0 -1
  265. package/template/panel/assets/landing-If3oVsS0.js +0 -1
  266. package/template/panel/assets/mediaValidation-BR-ZOj5w.js +0 -1
  267. package/template/panel/assets/minus-CyVEzdqL.js +0 -1
  268. package/template/panel/assets/products.types-46xSxBS8.js +0 -1
  269. package/template/panel/assets/scroll-area-CavEOIyz.js +0 -1
  270. package/template/panel/assets/shield-alert-04pSYngI.js +0 -1
  271. package/template/panel/assets/storage.api-CFU3KJNp.js +0 -20
  272. package/template/panel/assets/useFunnelStats-tvjpmWIC.js +0 -1
@@ -1,9 +0,0 @@
1
- import{c as X,j as t,d as We,p as Xe,b as U,a as xe,g as fe,i as ee,h as Ye,t as O,u as Ze,l as E,F as ke,T as $,v as q,x as z,an as Je,ao as et,B as P,ap as tt,as as ce,aB as st,D as at,G as nt,r as Q,a9 as rt,az as _e,o as je,X as le,C as it,Y as ye,I as lt,aC as ot,H as ct,R as dt,Q as ut,aw as mt,w as K}from"./index-DsyZ_FlA.js";import{b as h}from"./recharts-DrC5kNsx.js";import{e as ht,f as pt,u as gt,a as we,D as xt,p as ft,b as bt,K as vt,P as kt}from"./core.esm-Dq12RbIP.js";import{u as J}from"./useMutation-a5tIBvQY.js";import{u as jt}from"./useInfiniteQuery-BXUM1Z9V.js";import{a as yt,f as wt,u as Ct}from"./useFunnelStats-tvjpmWIC.js";import{u as Nt}from"./index-CCTahcpv.js";import{A as de,a as ue,b as me}from"./avatar-CILB1zwS.js";import{M as St,i as It,u as Oe,P as Tt,a as At,b as Mt,L as Dt,U as Et,F as Ft,m as Rt}from"./index-Bz-ixwph.js";import{E as Pt}from"./ellipsis-CMEJnUfK.js";import{E as _t,F as Ot}from"./facebook-RxMBweMB.js";import{M as Qt}from"./message-square-Dfn16oHc.js";import{S as $t}from"./send-Dxmdupsl.js";import{I as qt}from"./instagram-CC7iYt7V.js";import{S as zt}from"./square-BuGqLxJB.js";import{S as he}from"./skeleton-B0zh8s_y.js";import{P as Qe,a as $e,b as qe}from"./popover-MyuU-yAK.js";import{C as Lt,a as Ut,b as Bt,c as Kt,d as Gt,e as Ht}from"./command-COdSmSIB.js";import{A as Vt,b as Wt,c as Xt,d as Yt,e as Zt,f as Jt,g as es,h as ts}from"./alert-dialog-D8P69s-m.js";import{S as te,a as se,b as ae,c as ne,d as _}from"./select-DlB_BbfM.js";import{T as ss,M as as}from"./TagSelector-ChoKzvjW.js";import{C as ns}from"./ChannelSelector-q9tTirNo.js";import{H as rs}from"./history-DhHayxUg.js";import{C as is}from"./calendar-CIHhMjNy.js";import{L as ls}from"./layout-grid-Cm6hfBWZ.js";import{M as os}from"./maximize-2-WdbM7Kdx.js";import{a as cs}from"./datetime-BuZosCVk.js";import"./index-KbFmSzBE.js";import"./folder-D0GKakGp.js";const ds=[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]],us=X("arrow-right-left",ds);const ms=[["path",{d:"m9 7-5 5 5 5",key:"j5w590"}],["path",{d:"m15 7 5 5-5 5",key:"1bl6da"}]],hs=X("chevrons-left-right",ms);const ps=[["path",{d:"m20 17-5-5 5-5",key:"30x0n2"}],["path",{d:"m4 17 5-5-5-5",key:"16spf4"}]],gs=X("chevrons-right-left",ps);const xs=[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M12 10v2",key:"hh53o1"}],["path",{d:"M16 10v6",key:"1d6xys"}]],fs=X("folder-kanban",xs);const bs=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],vs=X("square-check",bs);const ks=[["path",{d:"M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18",key:"gugj83"}]],js=X("table-2",ks);function Ce(e,s){if(typeof e=="function")return e(s);e!=null&&(e.current=s)}function ys(...e){return s=>{let a=!1;const n=e.map(r=>{const o=Ce(r,s);return!a&&typeof o=="function"&&(a=!0),o});if(a)return()=>{for(let r=0;r<n.length;r++){const o=n[r];typeof o=="function"?o():Ce(e[r],null)}}}}function ws(...e){return h.useCallback(ys(...e),e)}class Cs extends h.Component{getSnapshotBeforeUpdate(s){const a=this.props.childRef.current;if(a&&s.isPresent&&!this.props.isPresent){const n=a.offsetParent,r=It(n)&&n.offsetWidth||0,o=this.props.sizeRef.current;o.height=a.offsetHeight||0,o.width=a.offsetWidth||0,o.top=a.offsetTop,o.left=a.offsetLeft,o.right=r-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function Ns({children:e,isPresent:s,anchorX:a,root:n}){const r=h.useId(),o=h.useRef(null),d=h.useRef({width:0,height:0,top:0,left:0,right:0}),{nonce:i}=h.useContext(St),k=e.props?.ref??e?.ref,b=ws(o,k);return h.useInsertionEffect(()=>{const{width:f,height:v,top:u,left:x,right:j}=d.current;if(s||!o.current||!f||!v)return;const S=a==="left"?`left: ${x}`:`right: ${j}`;o.current.dataset.motionPopId=r;const I=document.createElement("style");i&&(I.nonce=i);const T=n??document.head;return T.appendChild(I),I.sheet&&I.sheet.insertRule(`
2
- [data-motion-pop-id="${r}"] {
3
- position: absolute !important;
4
- width: ${f}px !important;
5
- height: ${v}px !important;
6
- ${S}px !important;
7
- top: ${u}px !important;
8
- }
9
- `),()=>{T.contains(I)&&T.removeChild(I)}},[s]),t.jsx(Cs,{isPresent:s,childRef:o,sizeRef:d,children:h.cloneElement(e,{ref:b})})}const Ss=({children:e,initial:s,isPresent:a,onExitComplete:n,custom:r,presenceAffectsLayout:o,mode:d,anchorX:i,root:k})=>{const b=Oe(Is),f=h.useId();let v=!0,u=h.useMemo(()=>(v=!1,{id:f,initial:s,isPresent:a,custom:r,onExitComplete:x=>{b.set(x,!0);for(const j of b.values())if(!j)return;n&&n()},register:x=>(b.set(x,!1),()=>b.delete(x))}),[a,b,n]);return o&&v&&(u={...u}),h.useMemo(()=>{b.forEach((x,j)=>b.set(j,!1))},[a]),h.useEffect(()=>{!a&&!b.size&&n&&n()},[a]),d==="popLayout"&&(e=t.jsx(Ns,{isPresent:a,anchorX:i,root:k,children:e})),t.jsx(Tt.Provider,{value:u,children:e})};function Is(){return new Map}const re=e=>e.key||"";function Ne(e){const s=[];return h.Children.forEach(e,a=>{h.isValidElement(a)&&s.push(a)}),s}const Ts=({children:e,custom:s,initial:a=!0,onExitComplete:n,presenceAffectsLayout:r=!0,mode:o="sync",propagate:d=!1,anchorX:i="left",root:k})=>{const[b,f]=At(d),v=h.useMemo(()=>Ne(e),[e]),u=d&&!b?[]:v.map(re),x=h.useRef(!0),j=h.useRef(v),S=Oe(()=>new Map),I=h.useRef(new Set),[T,M]=h.useState(v),[w,A]=h.useState(v);Mt(()=>{x.current=!1,j.current=v;for(let c=0;c<w.length;c++){const m=re(w[c]);u.includes(m)?(S.delete(m),I.current.delete(m)):S.get(m)!==!0&&S.set(m,!1)}},[w,u.length,u.join("-")]);const g=[];if(v!==T){let c=[...v];for(let m=0;m<w.length;m++){const p=w[m],y=re(p);u.includes(y)||(c.splice(m,0,p),g.push(p))}return o==="wait"&&g.length&&(c=g),A(Ne(c)),M(v),null}const{forceRender:C}=h.useContext(Dt);return t.jsx(t.Fragment,{children:w.map(c=>{const m=re(c),p=d&&!b?!1:v===w||u.includes(m),y=()=>{if(I.current.has(m))return;if(I.current.add(m),S.has(m))S.set(m,!0);else return;let D=!0;S.forEach(F=>{F||(D=!1)}),D&&(C?.(),A(j.current),d&&f?.(),n&&n())};return t.jsx(Ss,{isPresent:p,initial:!x.current||a?void 0:!1,custom:s,presenceAffectsLayout:r,mode:o,root:k,onExitComplete:p?void 0:y,anchorX:i,children:c},m)})})},Se={status:"all",assignedTo:"all",channel:"all",tags:[],dateRange:"all",search:"",includeClosed:!1},N=We()(Xe((e,s)=>({selectedFunnelId:null,view:"kanban",isCompactMode:!1,filters:Se,toggleCompactMode:()=>e(a=>({isCompactMode:!a.isCompactMode})),collapsedStages:new Set,selectedTicketIds:new Set,activeTicketId:null,sidePanelOpen:!1,isDragging:!1,draggedTicketId:null,pendingMove:null,setSelectedFunnel:a=>e({selectedFunnelId:a}),setView:a=>e({view:a}),setFilters:a=>e(n=>({filters:{...n.filters,...a}})),resetFilters:()=>e({filters:Se}),toggleStageCollapse:a=>e(n=>{const r=new Set(n.collapsedStages);return r.has(a)?r.delete(a):r.add(a),{collapsedStages:r}}),collapseAllStages:a=>e({collapsedStages:new Set(a)}),expandAllStages:()=>e({collapsedStages:new Set}),toggleTicketSelection:a=>e(n=>{const r=new Set(n.selectedTicketIds);return r.has(a)?r.delete(a):r.add(a),{selectedTicketIds:r}}),selectAllInStage:(a,n)=>e(r=>({selectedTicketIds:new Set([...r.selectedTicketIds,...n])})),clearSelection:()=>e({selectedTicketIds:new Set}),openTicketPanel:a=>e({activeTicketId:a,sidePanelOpen:!0}),closeTicketPanel:()=>e({sidePanelOpen:!1}),setDragging:(a,n=null)=>e({isDragging:a,draggedTicketId:n}),setPendingMove:a=>e({pendingMove:a}),clearPendingMove:a=>e(n=>!a||n.pendingMove?.ticketId===a?{pendingMove:null}:n)}),{name:"pipeline-store",partialize:e=>({selectedFunnelId:e.selectedFunnelId,view:e.view,collapsedStages:[...e.collapsedStages]}),onRehydrateStorage:()=>e=>{e&&(e.collapsedStages=new Set(e.collapsedStages))}})),oe=e=>e.selectedFunnelId,As=e=>e.view,ze=e=>e.isCompactMode,be=e=>e.filters,Ms=e=>e.isDragging,Ds=e=>e.draggedTicketId,Es=(e,s)=>a=>a.pendingMove?.ticketId===e&&a.pendingMove.fromStageId===s,Le=e=>e.selectedTicketIds,Fs=e=>s=>s.collapsedStages.has(e),B={async getBoard(e,s){const a=new URLSearchParams;s?.status?.length&&a.append("status",s.status.join(",")),s?.assignedAgentId&&a.append("assignedAgentId",s.assignedAgentId),s?.channelId&&a.append("channelId",s.channelId),s?.search&&a.append("search",s.search),s?.dateFrom&&a.append("dateFrom",s.dateFrom),s?.dateTo&&a.append("dateTo",s.dateTo),s?.pageSize&&a.append("pageSize",s.pageSize.toString()),s?.tags?.length&&a.append("tags",s.tags.join(",")),s?.includeClosed&&a.append("includeClosed","true");const n=a.toString()?`?${a.toString()}`:"";return(await U.get(`/funnels/${e}/board${n}`)).data},async getStageTickets(e,s,a){const n=new URLSearchParams;a?.cursor&&n.append("cursor",a.cursor),a?.pageSize&&n.append("pageSize",a.pageSize.toString()),a?.status?.length&&n.append("status",a.status.join(",")),a?.assignedAgentId&&n.append("assignedAgentId",a.assignedAgentId),a?.channelId&&n.append("channelId",a.channelId),a?.search&&n.append("search",a.search),a?.dateFrom&&n.append("dateFrom",a.dateFrom),a?.dateTo&&n.append("dateTo",a.dateTo),a?.tags?.length&&n.append("tags",a.tags.join(",")),a?.includeClosed&&n.append("includeClosed","true");const r=n.toString()?`?${n.toString()}`:"";return(await U.get(`/funnels/${e}/stages/${s}/tickets${r}`)).data},async moveTicketToStage(e,s,a){await U.patch(`/tickets/${e}/funnel/stage`,{stageId:s,reason:a||"Moved via pipeline board"})},async assignTicketToFunnel(e,s,a,n){await U.post(`/tickets/${e}/funnel`,{funnelId:s,stageId:a,reason:n||"Assigned via pipeline board"})},async removeTicketFromFunnel(e,s){await U.delete(`/tickets/${e}/funnel`,{data:{reason:s}})},async bulkAssignToFunnel(e,s,a,n){return(await U.post("/tickets/bulk/funnel",{ticketIds:e,funnelId:s,stageId:a,reason:n||"Bulk assign via pipeline board"})).data},async bulkMoveToStage(e,s,a){return(await U.post("/tickets/bulk/funnel/stage",{ticketIds:e,stageId:s,reason:a||"Bulk move via pipeline board"})).data},async bulkMoveToStageAsync(e,s,a,n){return(await U.post("/tickets/bulk/funnel/stage/async",{ticketIds:e,funnelId:s,stageId:a,reason:n||"Bulk move via pipeline board"})).data},async bulkRemoveFromFunnel(e,s){const a={success:0,failed:0,errors:[]};for(const n of e)try{await U.delete(`/tickets/${n}/funnel`,{data:{reason:s||"Bulk remove via pipeline board"}}),a.success++}catch(r){a.failed++,a.errors.push(`${n}: ${r.message}`)}return a}},G="__unassigned__";function W(e,s,a){const n=[...e.stages],r=n.findIndex(i=>i.id===a);if(r!==-1&&n[r].tickets.some(i=>i.id===s))return e;let o=null,d=-1;for(let i=0;i<n.length;i++){const k=n[i].tickets.findIndex(b=>b.id===s);if(k!==-1){o=n[i].tickets[k],d=i,n[i]={...n[i],tickets:n[i].tickets.filter(b=>b.id!==s),ticketCount:Math.max(0,n[i].ticketCount-1)};break}}if(o&&r!==-1&&r!==d){const i=new Date().toISOString(),k={...o,enteredStageAt:i,timeInStageMs:0};n[r]={...n[r],tickets:[k,...n[r].tickets],ticketCount:n[r].ticketCount+1}}return{...e,stages:n}}function Ie(e,s,a){if(!e.stages.some(o=>o.id===a)&&a===G)return{...e,stages:[{id:G,name:"Sin Asignar",icon:"📥",order:"!",ticketCount:1,tickets:[s],hasMore:!1,active:!0,isUnassigned:!0},...e.stages],meta:{...e.meta,totalTickets:e.meta.totalTickets+1}};const r=e.stages.map(o=>o.id!==a||o.tickets.some(d=>d.id===s.id)?o:{...o,tickets:[s,...o.tickets],ticketCount:o.ticketCount+1});return{...e,stages:r,meta:{...e.meta,totalTickets:e.meta.totalTickets+1}}}function pe(e,s,a){let n=!1;const r=e.stages.map(o=>{const d=o.tickets.findIndex(k=>k.id===s);if(d===-1)return o;n=!0;const i=[...o.tickets];return i[d]={...i[d],...a},{...o,tickets:i}});return n?{...e,stages:r}:e}function V(e,s){let a=!1;const n=e.stages.map(r=>r.tickets.findIndex(d=>d.id===s)===-1?r:(a=!0,{...r,tickets:r.tickets.filter(d=>d.id!==s),ticketCount:Math.max(0,r.ticketCount-1)}));return{...e,stages:n,meta:{...e.meta,totalTickets:a?Math.max(0,e.meta.totalTickets-1):e.meta.totalTickets}}}function Ue(e,s){const a={};if(e.status!=="all"&&Array.isArray(e.status)&&(a.status=e.status),e.assignedTo!=="all"&&(e.assignedTo==="me"&&s?a.assignedAgentId=s:e.assignedTo==="unassigned"?a.assignedAgentId="unassigned":e.assignedTo!=="me"&&(a.assignedAgentId=e.assignedTo)),e.channel!=="all"&&e.channel&&(a.channelId=e.channel),e.includeClosed&&e.status==="all"&&(a.includeClosed=!0),e.tags&&e.tags.length>0&&(a.tags=e.tags),e.search&&(a.search=e.search),e.dateRange&&e.dateRange!=="all"){const n=new Date;let r=0;switch(e.dateRange){case"7d":r=7;break;case"30d":r=30;break;case"90d":r=90;break}if(r>0){const o=new Date(n);o.setDate(n.getDate()-r),o.setHours(0,0,0,0),a.dateFrom=o.toISOString()}}else e.dateFrom&&(a.dateFrom=e.dateFrom),e.dateTo&&(a.dateTo=e.dateTo);return a}function Be(e){const s=N(be),{user:a}=xe(),n=Ue(s,a?.id);return fe({queryKey:["pipeline-board",e,n],queryFn:()=>B.getBoard(e,n),enabled:!!e,staleTime:300*1e3,refetchOnWindowFocus:!0,refetchOnReconnect:!0,gcTime:600*1e3})}function Rs(e,s,a=!1,n){const r=N(be),{user:o}=xe(),d=Ue(r,o?.id);return jt({queryKey:["stage-tickets",e,s,d],queryFn:({pageParam:i})=>B.getStageTickets(e,s,{cursor:i,...d}),getNextPageParam:i=>i.hasMore?i.nextCursor:void 0,initialPageParam:n||void 0,enabled:!!e&&!!s&&a})}function Ps(){const e=ee();return J({mutationFn:async({ticketId:s,toStageId:a,reason:n})=>B.moveTicketToStage(s,a,n),onMutate:async({ticketId:s,toStageId:a})=>{await e.cancelQueries({queryKey:["pipeline-board"]});const n=e.getQueriesData({queryKey:["pipeline-board"]});return e.removeQueries({queryKey:["stage-tickets"]}),e.setQueriesData({queryKey:["pipeline-board"]},r=>r&&W(r,s,a)),{previousData:n}},onError:(s,a,n)=>{n?.previousData&&n.previousData.forEach(([i,k])=>{e.setQueryData(i,k)}),e.invalidateQueries({queryKey:["pipeline-board"]});const r=s?.response?.data,o=r?.error||"Error al mover el ticket",d=r?.message;O.error(o,{description:d})}})}function _s(){const e=ee();return J({mutationFn:async({ticketId:s,funnelId:a,stageId:n,reason:r})=>B.assignTicketToFunnel(s,a,n,r),onMutate:async({ticketId:s,stageId:a})=>{if(!a)return;await e.cancelQueries({queryKey:["pipeline-board"]});const n=e.getQueriesData({queryKey:["pipeline-board"]});return e.setQueriesData({queryKey:["pipeline-board"]},r=>r&&W(r,s,a)),{previousData:n}},onError:(s,a,n)=>{n?.previousData&&n.previousData.forEach(([i,k])=>{e.setQueryData(i,k)}),e.invalidateQueries({queryKey:["pipeline-board"]});const r=s?.response?.data,o=r?.error||"Error al asignar el ticket",d=r?.message;O.error(o,{description:d})}})}function Os(){const e=ee();return J({mutationFn:async({ticketId:s,reason:a})=>B.removeTicketFromFunnel(s,a),onMutate:async({ticketId:s})=>{await e.cancelQueries({queryKey:["pipeline-board"]});const a=e.getQueriesData({queryKey:["pipeline-board"]});return e.removeQueries({queryKey:["stage-tickets"]}),e.setQueriesData({queryKey:["pipeline-board"]},n=>n&&W(n,s,"__unassigned__")),{previousData:a}},onError:(s,a,n)=>{n?.previousData&&n.previousData.forEach(([i,k])=>{e.setQueryData(i,k)}),e.invalidateQueries({queryKey:["pipeline-board"]});const r=s?.response?.data,o=r?.error||"Error al remover el ticket",d=r?.message;O.error(o,{description:d})},onSettled:()=>{e.invalidateQueries({queryKey:["pipeline-board"]})}})}function Qs(){const{currentOrganization:e}=Ye(),s=e?.id||"";return fe({queryKey:yt.withStages(s),queryFn:()=>wt.getAllWithStages(),select:a=>a.filter(n=>n.active!==!1),staleTime:300*1e3,enabled:!!s})}const Te=e=>{switch(e?.toLowerCase()||"web"){case"whatsapp":case"whatsapp_business":case"wa":case"waba":return t.jsx(Ft,{className:"w-2.5 h-2.5 text-white"});case"instagram":return t.jsx(qt,{className:"w-2.5 h-2.5 text-white"});case"facebook":return t.jsx(Ot,{className:"w-2.5 h-2.5 text-white",fill:"currentColor"});case"telegram":return t.jsx($t,{className:"w-2.5 h-2.5 text-white",fill:"currentColor"});case"web":return t.jsx(nt,{className:"w-2.5 h-2.5 text-white"});default:return t.jsx(Qt,{className:"w-2.5 h-2.5 text-white",fill:"currentColor"})}},Ae=e=>{switch(e?.toLowerCase()||"web"){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"}},Me=()=>t.jsx("span",{className:"flex-shrink-0 rounded-full bg-slate-100 dark:bg-slate-800 px-1.5 py-px text-[10px] font-semibold text-slate-500 dark:text-slate-400",children:"Cerrada"}),ve=h.memo(({ticket:e,stageId:s,isSelected:a,isDragOverlay:n})=>{const r=N(w=>w.toggleTicketSelection),o=Ze(),d=N(ze),i=N(h.useMemo(()=>Es(e.id,s),[e.id,s])),{attributes:k,listeners:b,setNodeRef:f,isDragging:v}=ht({id:e.id,data:{type:"ticket",ticketId:e.id,fromStageId:s,ticket:e}}),u=$s(e.timeInStageMs),x=e.channel?.type||"WEB",j=h.useMemo(()=>(e.contact?.name||"?").split(" ").map(A=>A[0]).join("").slice(0,2).toUpperCase(),[e.contact?.name]),S=`/bandeja?ticket=${e.id}`,I=(w=!1)=>{w?window.open(S,"_blank","noopener"):o(S)},T=e.status==="RESOLVED",M=w=>{w.target.closest("[data-no-click]")||I(w.metaKey||w.ctrlKey)};return t.jsx("div",{ref:f,...k,...b,onClick:M,className:E("group relative mx-1 mb-1.5 rounded-2xl cursor-grab active:cursor-grabbing","border border-slate-100 dark:border-slate-800","bg-white dark:bg-slate-900/80","transition-all duration-200","hover:shadow-md hover:border-slate-200 dark:hover:border-slate-700",a&&"bg-primary/5 dark:bg-primary/10 border-primary/20 dark:border-primary/30",(v||i)&&"opacity-0",n&&"shadow-xl shadow-black/10 scale-[1.02] cursor-grabbing border-slate-200",d?"py-2 px-3":"p-3"),children:d?t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("div",{"data-no-click":!0,className:E("flex-shrink-0 transition-opacity duration-150",a?"opacity-100":"opacity-0 group-hover:opacity-100"),onClick:w=>{w.stopPropagation(),r(e.id)},children:t.jsx("div",{className:E("w-4 h-4 rounded border-[1.5px] flex items-center justify-center cursor-pointer","transition-all duration-150",a?"bg-primary border-primary text-white":"border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 hover:border-primary/50"),children:a&&t.jsx(ke,{className:"w-2.5 h-2.5"})})}),t.jsxs("div",{className:"relative flex-shrink-0",children:[t.jsxs(de,{className:"h-6 w-6 border border-slate-100 dark:border-slate-700 shadow-sm",children:[e.contact?.avatarUrl&&t.jsx(ue,{src:e.contact.avatarUrl,alt:e.contact.name}),t.jsx(me,{className:"bg-slate-100 dark:bg-slate-800 text-slate-500 dark:text-slate-400 font-bold text-[9px]",children:j})]}),t.jsx("div",{title:x,className:E("absolute -top-0.5 -right-0.5 w-3 h-3 rounded-full flex items-center justify-center","border border-white dark:border-slate-900 shadow-sm z-10",Ae(x)),children:Te(x)})]}),t.jsxs("div",{className:"flex-1 min-w-0 pr-2 flex items-center gap-1.5",children:[t.jsx("p",{className:"text-xs font-medium text-slate-700 dark:text-slate-300 truncate",children:e.contact?.name||"Sin nombre"}),T&&t.jsx(Me,{})]}),t.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.unreadCount>0&&t.jsx("span",{className:"flex items-center justify-center min-w-[14px] h-[14px] px-0.5 bg-primary text-white text-[9px] font-bold rounded-full",children:e.unreadCount}),u&&t.jsx("span",{className:"text-[10px] text-slate-400 dark:text-slate-500 tabular-nums",children:u})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-no-click":!0,className:E("absolute top-2 left-2 z-20 transition-opacity duration-150",a?"opacity-100":"opacity-0 group-hover:opacity-100"),onClick:w=>{w.stopPropagation(),r(e.id)},children:t.jsx("div",{className:E("w-5 h-5 rounded-md border-2 flex items-center justify-center cursor-pointer","transition-all duration-150",a?"bg-primary border-primary text-white":"border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 hover:border-primary/50"),children:a&&t.jsx(ke,{className:"w-3 h-3"})})}),t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsxs("div",{className:"relative flex-shrink-0",children:[t.jsxs(de,{className:"h-10 w-10 border border-slate-100 dark:border-slate-700 shadow-sm",children:[e.contact?.avatarUrl&&t.jsx(ue,{src:e.contact.avatarUrl,alt:e.contact.name}),t.jsx(me,{className:"bg-slate-100 dark:bg-slate-800 text-slate-500 dark:text-slate-400 font-bold text-xs",children:j})]}),t.jsxs($,{children:[t.jsx(q,{asChild:!0,children:t.jsx("div",{title:x,className:E("absolute -top-1 -right-1 w-[18px] h-[18px] rounded-full flex items-center justify-center","border-2 border-white dark:border-slate-900 shadow-sm z-10",Ae(x)),children:Te(x)})}),t.jsx(z,{side:"top",className:"text-xs capitalize",children:x.toLowerCase().replace("_"," ")})]})]}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[t.jsx("p",{className:"text-[13px] font-semibold text-slate-800 dark:text-slate-200 truncate leading-tight",children:e.contact?.name||"Sin nombre"}),T&&t.jsx(Me,{})]}),e.contact?.phone&&e.contact.phone!==e.contact.name&&t.jsx("p",{className:"text-[11px] text-slate-400 dark:text-slate-500 truncate leading-tight mt-0.5 font-medium",children:e.contact.phone})]}),t.jsx("div",{className:"flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0","data-no-click":!0,children:t.jsxs(Je,{children:[t.jsx(et,{asChild:!0,children:t.jsx(P,{variant:"ghost",size:"icon",className:"h-7 w-7 rounded-lg hover:bg-slate-50 dark:hover:bg-slate-800",children:t.jsx(Pt,{className:"w-3.5 h-3.5 text-slate-400"})})}),t.jsxs(tt,{align:"end",className:"w-48 p-1.5 rounded-2xl shadow-xl",children:[t.jsxs(ce,{onClick:()=>I(),className:"rounded-xl text-[13px] font-medium",children:[t.jsx(_t,{className:"w-3.5 h-3.5 mr-2 text-slate-400"}),"Abrir chat"]}),t.jsxs(ce,{onClick:()=>r(e.id),className:"rounded-xl text-[13px] font-medium",children:[t.jsx(Et,{className:"w-3.5 h-3.5 mr-2 text-slate-400"}),a?"Deseleccionar":"Seleccionar"]}),t.jsxs(ce,{onClick:()=>navigator.clipboard.writeText(e.id),className:"rounded-xl text-[13px] font-medium",children:[t.jsx(st,{className:"w-3.5 h-3.5 mr-2 text-slate-400"}),"Copiar ID"]})]})]})})]}),e.lastMessagePreview&&t.jsx("p",{className:"mt-2 text-[12px] text-slate-500 dark:text-slate-400 line-clamp-1 pl-[52px]",children:e.lastMessagePreview}),t.jsxs("div",{className:"flex items-center gap-2 mt-2 pl-[52px]",children:[u&&t.jsxs($,{children:[t.jsx(q,{asChild:!0,children:t.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-slate-400 dark:text-slate-500 font-medium",children:[t.jsx(at,{className:"w-3 h-3"}),t.jsx("span",{children:u})]})}),t.jsx(z,{side:"bottom",className:"text-xs",children:"Tiempo en esta etapa"})]}),e.unreadCount>0&&t.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",children:e.unreadCount>99?"99+":e.unreadCount}),e.assignedAgent&&t.jsxs($,{children:[t.jsx(q,{asChild:!0,children:t.jsx("div",{className:"ml-auto",children:t.jsxs(de,{className:"h-5 w-5 border border-white dark:border-slate-900 shadow-sm",children:[e.assignedAgent.avatarUrl&&t.jsx(ue,{src:e.assignedAgent.avatarUrl,alt:e.assignedAgent.name}),t.jsx(me,{className:"bg-slate-100 dark:bg-slate-800 text-[8px] font-bold text-slate-500",children:e.assignedAgent.name?.[0]?.toUpperCase()||"?"})]})})}),t.jsx(z,{side:"bottom",className:"text-xs",children:e.assignedAgent.name})]})]})]})})});ve.displayName="PipelineTicketCard";function $s(e){if(e===0)return"Ahora";if(!e||e<0)return null;const s=Math.floor(e/6e4),a=Math.floor(s/60),n=Math.floor(a/24);return n>=7?`${Math.floor(n/7)}sem`:n>0?`${n}d`:a>0?`${a}h`:s>0?`${s}m`:"<1m"}const De=["bg-blue-500","bg-violet-500","bg-amber-500","bg-emerald-500","bg-rose-500","bg-cyan-500","bg-orange-500","bg-pink-500"],Ke=h.memo(({stage:e,funnelId:s,stageIndex:a,totalTickets:n})=>{const r=N(Fs(e.id)),o=N(Le),d=N(Ms),i=N(l=>l.toggleStageCollapse),k=N(l=>l.selectAllInStage),b=N(l=>l.clearSelection),f=e.isUnassigned||e.id===G,v=f?"bg-slate-400":De[a%De.length],u=n>0?Math.round(e.ticketCount/n*100):0,{setNodeRef:x,isOver:j,active:S}=pt({id:e.id,data:{type:"column",stageId:e.id}}),I=S?.data.current?.fromStageId===e.id,[T,M]=h.useState(!1),{data:w,fetchNextPage:A,hasNextPage:g,isFetchingNextPage:C}=Rs(s,e.id,T&&e.hasMore&&!f,e.nextCursor),c=h.useMemo(()=>{const l=e.tickets||[],R=w?.pages?.flatMap(L=>L.tickets).filter(L=>!l.some(Z=>Z.id===L.id))||[];return[...l,...R]},[e.tickets,w]),m=h.useRef(null),p=Nt({count:c.length,getScrollElement:()=>m.current,estimateSize:()=>82,overscan:3}),y=h.useCallback(()=>{const l=m.current;if(!l)return;l.scrollTop+l.clientHeight>=l.scrollHeight-100&&(!T&&e.hasMore&&M(!0),g&&!C&&A())},[g,C,A,T,e.hasMore]);h.useEffect(()=>{const l=m.current;if(l)return l.addEventListener("scroll",y,{passive:!0}),()=>l.removeEventListener("scroll",y)},[y]);const D=h.useMemo(()=>c.map(l=>l.id),[c]),F=D.length>0&&D.every(l=>o.has(l)),H=!F&&D.some(l=>o.has(l)),Y=()=>{F?b():k(e.id,D)};return r?t.jsxs("div",{ref:x,className:E("flex flex-col rounded-[24px] overflow-hidden transition-all duration-300","w-[52px] min-w-[52px] cursor-pointer group","shadow-sm hover:shadow-md",f?"bg-slate-100/80 dark:bg-slate-800/60 border border-slate-300 dark:border-slate-600":"bg-white dark:bg-slate-900 border border-slate-100 dark:border-slate-800",j&&"bg-primary/5"),onClick:()=>i(e.id),children:[t.jsxs("div",{className:"flex flex-col items-center pt-4 pb-2 gap-2",children:[t.jsx("div",{className:E("w-2 h-2 rounded-full",v)}),t.jsx(Q,{variant:"secondary",className:E("text-[10px] px-1.5 h-5 font-bold border-none",f?"bg-slate-200 dark:bg-slate-700 text-slate-600 dark:text-slate-300":"bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300"),children:e.ticketCount})]}),t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx("span",{className:"text-xs font-semibold text-slate-500 dark:text-slate-400 whitespace-nowrap",style:{writingMode:"vertical-rl",textOrientation:"mixed",transform:"rotate(180deg)"},children:e.name})}),t.jsx("div",{className:"p-2 flex justify-center",children:t.jsx(rt,{className:"w-3.5 h-3.5 text-slate-400 group-hover:text-slate-600 transition-colors"})})]}):t.jsxs("div",{ref:x,className:E("flex flex-col rounded-[24px] overflow-hidden transition-all duration-300","w-[300px] min-w-[300px] max-w-[300px]","shadow-sm",f?"bg-slate-100/70 dark:bg-slate-800/50 border border-slate-100 dark:border-slate-600":"bg-white dark:bg-slate-900 border border-slate-100 dark:border-slate-800",!f&&e.active===!1&&"opacity-85 border-dashed border-slate-300 dark:border-slate-700 bg-[repeating-linear-gradient(45deg,transparent,transparent_10px,var(--slate-50)_10px,var(--slate-50)_20px)] dark:bg-[repeating-linear-gradient(45deg,transparent,transparent_10px,var(--slate-900)_10px,var(--slate-900)_20px)]",j&&!d&&(f?"bg-slate-200/60 dark:bg-slate-700/50":"bg-slate-50/50 dark:bg-slate-900/50"),d&&"transition-shadow shadow-xl ring-1 ring-slate-900/5"),children:[t.jsx("div",{className:E("px-4 pt-4 pb-3 border-b backdrop-blur-sm",f?"border-slate-300 dark:border-slate-600 bg-slate-200/50 dark:bg-slate-700/40":"border-slate-100 dark:border-slate-800 bg-white/50 dark:bg-slate-900/50"),children:t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("div",{className:"flex items-center gap-2.5 min-w-0",children:t.jsxs("button",{onClick:()=>i(e.id),className:"flex items-center gap-2 min-w-0 group/header cursor-pointer",children:[t.jsx("div",{className:E("w-2.5 h-2.5 rounded-full flex-shrink-0",v)}),e.icon&&t.jsx("span",{className:"text-sm flex-shrink-0",children:e.icon}),t.jsx("span",{className:E("text-[13px] font-black uppercase tracking-wide truncate",f?"text-slate-600 dark:text-slate-300":e.active===!1?"text-slate-500 line-through decoration-slate-400":"text-slate-700 dark:text-slate-200"),children:e.name}),f&&t.jsx(Q,{variant:"outline",className:"text-[9px] px-1 h-4 border-slate-400 text-slate-500 bg-slate-100 dark:bg-slate-800 dark:border-slate-500 dark:text-slate-400",children:"Limbo"}),!f&&e.active===!1&&t.jsx(Q,{variant:"outline",className:"text-[9px] px-1 h-4 border-amber-300 text-amber-600 bg-amber-50",children:"Inactivo"})]})}),t.jsxs("div",{className:"flex items-center gap-2",children:[u>0&&t.jsxs($,{children:[t.jsx(q,{asChild:!0,children:t.jsxs("span",{className:"text-[11px] font-bold text-slate-400 tabular-nums",children:[u,"%"]})}),t.jsxs(z,{side:"top",children:[u,"% del total de tickets"]})]}),t.jsx(Q,{variant:"secondary",className:E("text-[11px] font-black h-6 min-w-[28px] px-2 justify-center rounded-full border-none transition-all duration-300",f?"bg-slate-200 dark:bg-slate-700 text-slate-600 dark:text-slate-300":"bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300"),children:e.ticketCount}),t.jsxs($,{children:[t.jsx(q,{asChild:!0,children:t.jsx(P,{variant:"ghost",size:"icon",className:"h-6 w-6 rounded-lg text-slate-400 hover:text-primary hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors",onClick:Y,children:F||H?t.jsx(vs,{className:"w-3.5 h-3.5 text-primary"}):t.jsx(zt,{className:"w-3.5 h-3.5"})})}),t.jsx(z,{side:"top",children:F?"Deseleccionar":"Seleccionar todos"})]})]})]})}),t.jsxs("div",{ref:m,className:E("flex-1 overflow-y-auto px-3 pb-3 pt-2 scroll-smooth","scrollbar-thin scrollbar-thumb-slate-200 dark:scrollbar-thumb-slate-700"),style:{maxHeight:"calc(100vh - 160px)"},children:[j&&d&&!I&&t.jsx("div",{className:"mb-2 mx-1 p-3 rounded-lg border-2 border-dashed border-primary/40 bg-primary/5 flex items-center justify-center animate-pulse",children:t.jsx("span",{className:"text-xs font-medium text-primary/60",children:"Soltar aquí"})}),c.length===0?t.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-center min-h-[200px]",children:[t.jsx("div",{className:"w-14 h-14 rounded-2xl bg-slate-50 dark:bg-slate-800/50 flex items-center justify-center mb-3",children:t.jsx(_e,{className:"w-6 h-6 text-slate-300 dark:text-slate-600"})}),t.jsx("p",{className:"text-sm font-semibold text-slate-500 dark:text-slate-400",children:"Sin tickets"}),t.jsx("p",{className:"text-[11px] text-slate-400 dark:text-slate-500 mt-1 max-w-[160px] leading-relaxed",children:"Arrastra tickets aquí para moverlos a esta etapa"})]}):t.jsx("div",{style:{height:`${p.getTotalSize()}px`,width:"100%",position:"relative"},children:p.getVirtualItems().map(l=>{const R=c[l.index];return R?t.jsx("div",{"data-index":l.index,ref:p.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${l.start}px)`},children:t.jsx(ve,{ticket:R,stageId:e.id,isSelected:o.has(R.id)})},R.id):null})}),C&&t.jsx("div",{className:"flex items-center justify-center py-3",children:t.jsx("div",{className:"w-4 h-4 border-2 border-primary/30 border-t-primary rounded-full animate-spin"})})]})]})});Ke.displayName="PipelineStageColumn";function qs(e){if(!e)return null;const s=e.data?.current??void 0;if(s?.type==="ticket"){const n=s.fromStageId;return typeof n=="string"&&n?n:null}const a=s?.stageId;return typeof a=="string"&&a?a:s===void 0&&typeof e.id=="string"?e.id:null}function Ee(e,s){const a=e?.data?.current?.fromStageId;if(typeof a!="string"||!a)return null;const n=qs(s);return!n||n===a?null:n}const zs=100;function Ls(){const e=N(Le),s=N(oe),a=N(c=>c.clearSelection),n=ee(),{data:r,isLoading:o}=Ct(),[d,i]=h.useState(!1),[k,b]=h.useState(!1),[f,v]=h.useState(null),u=e.size,x=5,j=J({mutationFn:async({funnelId:c,stageId:m,stageName:p})=>{const y=Array.from(e),D=c===s;return y.length>=zs?{async:!0,jobId:(await B.bulkMoveToStageAsync(y,c,m,`Bulk ${D?"move":"transfer"} to ${p}`)).jobId,count:y.length,stageName:p}:D?{async:!1,...await B.bulkMoveToStage(y,m,`Bulk move to ${p}`),stageName:p}:{async:!1,...await B.bulkAssignToFunnel(y,c,m,`Bulk transfer to ${p}`),stageName:p}},onMutate:async()=>{await n.cancelQueries({queryKey:["pipeline-board"]});const c=n.getQueriesData({queryKey:["pipeline-board"]});n.removeQueries({queryKey:["stage-tickets"]});const m=Array.from(e);return n.setQueriesData({queryKey:["pipeline-board"]},p=>{if(!p)return p;let y=p;for(const D of m)y=V(y,D);return y}),{previousData:c}},onSuccess:c=>{if(c.async)O.success("🚀 Procesando...",{description:`${c.count} tickets se están moviendo a "${c.stageName}".`});else{const{success:m,failed:p,stageName:y}=c;p>0?O.warning("Proceso parcial",{description:`${m} tickets movidos, ${p} fallaron.`}):O.success(`✅ ${m} tickets movidos a "${y}"`)}a(),n.invalidateQueries({queryKey:["pipeline-board"]}),n.removeQueries({queryKey:["stage-tickets"]}),i(!1)},onError:(c,m,p)=>{p?.previousData&&p.previousData.forEach(([D,F])=>{n.setQueryData(D,F)}),n.invalidateQueries({queryKey:["pipeline-board"]});const y=c?.response?.data?.message||c.message;O.error("Error al mover tickets",{description:y})}}),S=J({mutationFn:async()=>{const c=Array.from(e);return B.bulkRemoveFromFunnel(c,"Bulk remove via pipeline board")},onMutate:async()=>{await n.cancelQueries({queryKey:["pipeline-board"]});const c=n.getQueriesData({queryKey:["pipeline-board"]});n.removeQueries({queryKey:["stage-tickets"]});const m=Array.from(e);return n.setQueriesData({queryKey:["pipeline-board"]},p=>{if(!p)return p;let y=p;for(const D of m)y=V(y,D);return y}),{previousData:c}},onSuccess:c=>{c.failed>0?O.warning("Remoción parcial",{description:`${c.success} tickets removidos, ${c.failed} fallaron.`}):O.success(`✅ ${c.success} tickets enviados a "Sin Asignar"`),a(),n.invalidateQueries({queryKey:["pipeline-board"]}),n.removeQueries({queryKey:["stage-tickets"]})},onError:(c,m,p)=>{p?.previousData&&p.previousData.forEach(([D,F])=>{n.setQueryData(D,F)}),n.invalidateQueries({queryKey:["pipeline-board"]});const y=c?.response?.data?.message||c.message;O.error("Error al remover tickets",{description:y})}}),I=j.isPending||S.isPending,T=(c,m,p)=>{j.mutate({funnelId:c,stageId:m,stageName:p})},M=()=>{S.mutate()},w=h.useCallback((c,m,p)=>{u>x?(v({type:"move",payload:{funnelId:c,stageId:m,stageName:p}}),b(!0)):T(c,m,p)},[u,j]),A=h.useCallback(()=>{u>x?(v({type:"remove"}),b(!0)):M()},[u,S]),g=()=>{f&&(f.type==="move"&&f.payload?T(f.payload.funnelId,f.payload.stageId,f.payload.stageName):f.type==="remove"&&M(),b(!1),v(null))},C=h.useMemo(()=>r?.filter(c=>c.active!==!1)||[],[r]);return u===0?null:t.jsxs(Ts,{children:[t.jsx(Rt.div,{initial:{y:80,opacity:0,scale:.95},animate:{y:0,opacity:1,scale:1},exit:{y:80,opacity:0,scale:.95},transition:{type:"spring",stiffness:400,damping:30},className:"fixed bottom-6 left-1/2 -translate-x-1/2 z-50",children:t.jsxs("div",{className:"bg-slate-900/95 text-white px-7 py-3.5 rounded-full shadow-[0_20px_50px_rgba(0,0,0,0.3)] flex items-center gap-7 border border-slate-800/50 backdrop-blur-xl",children:[t.jsxs("span",{className:"text-[13px] font-bold flex items-center gap-2.5 whitespace-nowrap",children:[t.jsx("div",{className:"bg-primary text-white w-6 h-6 rounded-full flex items-center justify-center text-[11px] font-black shadow-lg shadow-primary/40",children:u}),"Seleccionados"]}),t.jsx("div",{className:"h-5 w-px bg-white/10"}),t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsxs(Qe,{open:d,onOpenChange:i,children:[t.jsxs($,{children:[t.jsx(q,{asChild:!0,children:t.jsx($e,{asChild:!0,children:t.jsxs(P,{variant:"ghost",size:"sm",disabled:I,className:E("h-9 hover:bg-white/10 hover:text-white text-white rounded-xl px-4","transition-all text-[13px] font-medium"),children:[j.isPending?t.jsx(je,{className:"w-4 h-4 mr-2 animate-spin text-blue-400"}):t.jsx(us,{className:"w-4 h-4 mr-2 text-blue-400"}),"Mover a Etapa..."]})})}),t.jsxs(z,{side:"top",children:["Mover ",u," tickets a otra etapa (cualquier funnel)"]})]}),t.jsx(qe,{className:"w-[280px] p-0 rounded-xl border-slate-200 dark:border-slate-700 shadow-xl",align:"center",side:"top",sideOffset:12,children:t.jsxs(Lt,{children:[t.jsx(Ut,{placeholder:"Buscar funnel o etapa..."}),t.jsxs(Bt,{children:[t.jsx(Kt,{children:"No se encontraron resultados."}),C.map(c=>t.jsx(Gt,{heading:c.name,className:"text-slate-500",children:c.stages?.filter(m=>m.active!==!1).sort((m,p)=>m.order-p.order).map(m=>t.jsxs(Ht,{value:`${c.name} ${m.name}`,onSelect:()=>w(c.id,m.id,m.name),className:"gap-2 cursor-pointer aria-selected:bg-slate-100 dark:aria-selected:bg-slate-800",children:[t.jsx("span",{className:"text-sm",children:m.icon||"📋"}),t.jsx("span",{className:"text-sm font-medium",children:m.name}),c.id===s&&t.jsx(Q,{variant:"outline",className:"ml-auto text-[10px] h-5 px-1.5",children:"Actual"})]},m.id))},c.id))]})]})})]}),t.jsxs($,{children:[t.jsx(q,{asChild:!0,children:t.jsxs(P,{variant:"ghost",size:"sm",disabled:I,onClick:A,className:E("h-9 hover:bg-white/10 hover:text-white text-white rounded-xl px-4","transition-all text-[13px] font-medium"),children:[S.isPending?t.jsx(je,{className:"w-4 h-4 mr-2 animate-spin text-amber-400"}):t.jsx(_e,{className:"w-4 h-4 mr-2 text-amber-400"}),"Sin Asignar"]})}),t.jsxs(z,{side:"top",children:["Enviar ",u,' tickets a "Sin Asignar"']})]})]}),t.jsxs($,{children:[t.jsx(q,{asChild:!0,children:t.jsx(P,{variant:"ghost",size:"icon",disabled:I,onClick:a,className:E("h-7 w-7 rounded-full","hover:bg-white/10 transition-all","text-slate-400 hover:text-white"),children:t.jsx(le,{className:"w-4 h-4"})})}),t.jsx(z,{side:"top",children:"Limpiar selección"})]})]})}),t.jsx(Vt,{open:k,onOpenChange:b,children:t.jsxs(Wt,{children:[t.jsxs(Xt,{children:[t.jsx(Yt,{children:"¿Estás seguro?"}),t.jsxs(Zt,{children:["Estás a punto de ",f?.type==="move"?"mover":"remover"," ",t.jsx("strong",{children:u})," tickets. Esta acción afectará a múltiples conversaciones simultáneamente."]})]}),t.jsxs(Jt,{children:[t.jsx(es,{onClick:()=>v(null),children:"Cancelar"}),t.jsx(ts,{onClick:g,children:"Confirmar y Procesar"})]})]})})]})}const Us={duration:200,easing:"ease-out"},Ge=h.memo(()=>{const e=N(oe),s=N(Ds),a=N(g=>g.setDragging),n=N(g=>g.setPendingMove),r=N(g=>g.clearPendingMove),[o,d]=h.useState(!1);h.useEffect(()=>()=>r(),[r]);const{data:i,isLoading:k,error:b,isError:f}=Be(e),v=Ps(),u=_s(),x=Os(),j=gt(we(kt,{activationConstraint:{distance:8}}),we(vt)),S=h.useCallback(g=>{const C=g.active.id;d(!1),a(!0,C)},[a]),I=h.useCallback(g=>{d(Ee(g.active,g.over)!==null)},[]),T=h.useCallback(g=>{const{active:C,over:c}=g;if(a(!1,null),!e)return;const m=Ee(C,c);if(!m)return;const p=C.id,y=C.data.current.fromStageId;n({ticketId:p,fromStageId:y});const D={onSettled:()=>r(p)};m===G?x.mutate({ticketId:p,reason:"Removed from funnel via pipeline board"},D):y===G?u.mutate({ticketId:p,funnelId:e,stageId:m,reason:"Assigned via pipeline board"},D):v.mutate({ticketId:p,toStageId:m,reason:"Moved via pipeline board"},D)},[a,n,r,v,u,x,e]),M=h.useCallback(()=>{a(!1,null)},[a]),w=h.useMemo(()=>{if(!s||!i?.stages)return null;for(const g of i.stages){const C=g.tickets.find(c=>c.id===s);if(C)return{ticket:C,stageId:g.id}}return null},[s,i?.stages]),A=i?.meta?.totalTickets||0;return e?k?t.jsx(Bs,{}):f?t.jsx(Ks,{error:b}):i?.stages?.length?t.jsxs(t.Fragment,{children:[t.jsxs(xt,{sensors:j,collisionDetection:ft,onDragStart:S,onDragOver:I,onDragEnd:T,onDragCancel:M,children:[t.jsx("div",{className:"flex h-full gap-3 overflow-x-auto p-4 pb-6 scroll-smooth",style:{touchAction:"none"},children:[...i.stages].filter(g=>g.active!==!1||g.ticketCount>0).sort((g,C)=>g.order<C.order?-1:g.order>C.order?1:0).map((g,C)=>t.jsx(Ke,{stage:g,funnelId:e,stageIndex:C,totalTickets:A},g.id))}),t.jsx(bt,{dropAnimation:o?null:Us,children:w&&t.jsx("div",{className:"w-[284px]",children:t.jsx(ve,{ticket:w.ticket,stageId:w.stageId,isSelected:!1,isDragOverlay:!0})})})]}),t.jsx(Ls,{})]}):t.jsx(Hs,{}):t.jsx(Gs,{})});Ge.displayName="PipelineBoard";function Bs(){return t.jsx("div",{className:"flex h-full gap-3 p-4",children:[1,2,3,4].map(e=>t.jsxs("div",{className:"flex-shrink-0 w-[300px]",children:[t.jsx(he,{className:"h-1 w-full mb-0 rounded-t-xl"}),t.jsx(he,{className:"h-10 w-full mb-2 rounded-none rounded-b-none"}),t.jsx("div",{className:"space-y-1.5",children:[1,2,3].map(s=>t.jsx(he,{className:"h-20 w-full rounded-lg"},s))})]},e))})}function Ks({error:e}){return t.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-muted-foreground",children:[t.jsx("div",{className:"w-16 h-16 rounded-2xl bg-red-50 dark:bg-red-950/30 flex items-center justify-center mb-4",children:t.jsx(it,{className:"w-8 h-8 text-red-500/60"})}),t.jsx("h3",{className:"text-lg font-semibold mb-1.5 text-slate-800 dark:text-slate-200",children:"Error al cargar el pipeline"}),t.jsx("p",{className:"text-sm text-slate-500 max-w-sm text-center",children:e instanceof Error?e.message:"Ocurrió un error inesperado"})]})}function Gs(){return t.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-muted-foreground",children:[t.jsx("div",{className:"w-20 h-20 rounded-2xl bg-slate-100 dark:bg-slate-800/50 flex items-center justify-center mb-4",children:t.jsx(fs,{className:"w-10 h-10 text-slate-300 dark:text-slate-600"})}),t.jsx("h3",{className:"text-lg font-semibold mb-1.5 text-slate-800 dark:text-slate-200",children:"Selecciona un funnel"}),t.jsx("p",{className:"text-sm text-center max-w-sm text-slate-500",children:"Elige un funnel del selector de arriba para visualizar tus tickets organizados por etapas."})]})}function Hs(){return t.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-muted-foreground",children:[t.jsx("div",{className:"text-5xl mb-4",children:"📊"}),t.jsx("h3",{className:"text-lg font-semibold mb-1.5 text-slate-800 dark:text-slate-200",children:"Sin etapas configuradas"}),t.jsx("p",{className:"text-sm text-center max-w-sm text-slate-500",children:"Este funnel no tiene etapas. Ve a la configuración de funnels para agregar etapas."})]})}const He=h.memo(()=>{const e=N(oe),s=N(be),a=N(As),n=N(ze),r=N(l=>l.collapsedStages),o=N(l=>l.setSelectedFunnel),d=N(l=>l.setFilters),i=N(l=>l.setView),k=N(l=>l.toggleCompactMode),b=N(l=>l.resetFilters),f=N(l=>l.collapseAllStages),v=N(l=>l.expandAllStages),{data:u,isLoading:x}=Qs(),{data:j,refetch:S,isFetching:I}=Be(e),[T,M]=h.useState(!!s.search),w=h.useRef(null);h.useEffect(()=>{u?.length?e&&u.find(l=>l.id===e)||o(u[0].id):u&&u.length===0&&e&&o(null)},[e,u,o]);const A=()=>{T&&!s.search?M(!1):(M(!0),setTimeout(()=>w.current?.focus(),100))},g=()=>{d({search:""}),M(!1)},C=l=>{d(l==="all"?{status:"all"}:{status:[l]})},c=l=>{i(l)},m=()=>{if(!j?.stages)return;const l=j.stages.map(L=>L.id);l.every(L=>r.has(L))?v():f(l)},{data:p}=fe({queryKey:["inbox-tags"],queryFn:()=>ut.getFoldersWithTags(),staleTime:300*1e3}),y=h.useMemo(()=>!p||!s.tags?.length?[]:p.flatMap(R=>R.tags).filter(R=>s.tags.includes(R.id)),[p,s.tags]),D=l=>{d({channel:l})},F=l=>{const R=s.tags||[],L=R.includes(l.id);let Z;L?Z=R.filter(Ve=>Ve!==l.id):Z=[...R,l.id],d({tags:Z})},H=Vs(s),Y=j?.stages?j.stages.length>0&&j.stages.every(l=>r.has(l.id)):!1;return t.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 border-b border-slate-200/60 dark:border-slate-800/60 bg-white/80 dark:bg-slate-950/80 backdrop-blur-xl supports-[backdrop-filter]:bg-white/60",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsxs(te,{value:e||"",onValueChange:o,disabled:x,children:[t.jsx(se,{className:"w-[220px] h-9 rounded-lg border-slate-200/80 dark:border-slate-700/80 bg-white dark:bg-slate-900 shadow-sm text-sm font-semibold",children:t.jsx(ae,{placeholder:"Seleccionar funnel..."})}),t.jsx(ne,{children:u?.map(l=>t.jsx(_,{value:l.id,children:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:l.name}),l.default&&t.jsx(Q,{variant:"secondary",className:"text-[10px] px-1.5 h-4",children:"Default"})]})},l.id))})]}),j&&t.jsxs("div",{className:"hidden md:flex items-center gap-2",children:[t.jsxs(Q,{variant:"outline",className:"font-semibold text-xs h-6 rounded-md bg-slate-50 dark:bg-slate-800/50 border-slate-200 dark:border-slate-700",children:[j.meta.totalTickets," tickets"]}),t.jsxs(Q,{variant:"outline",className:"text-xs h-6 rounded-md bg-slate-50 dark:bg-slate-800/50 border-slate-200 dark:border-slate-700",children:[j.stages.length," etapas"]})]})]}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("div",{className:E("relative transition-all duration-300 ease-out overflow-hidden",T?"w-[220px]":"w-0"),children:[t.jsx(ye,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none"}),t.jsx(lt,{ref:w,placeholder:"Buscar...",value:s.search,onChange:l=>d({search:l.target.value}),className:"pl-8 h-8 text-sm rounded-lg border-slate-200/80 dark:border-slate-700/80"}),s.search&&t.jsx(P,{variant:"ghost",size:"icon",className:"absolute right-0.5 top-1/2 -translate-y-1/2 h-7 w-7",onClick:g,children:t.jsx(le,{className:"w-3.5 h-3.5"})})]}),t.jsx(P,{variant:"ghost",size:"icon",className:E("h-8 w-8 rounded-lg",T&&"text-primary"),onClick:A,children:t.jsx(ye,{className:"w-4 h-4"})}),t.jsx("div",{className:"h-5 w-px bg-slate-200 dark:bg-slate-700"}),t.jsxs(te,{value:s.status==="all"?"all":Array.isArray(s.status)?s.status[0]:"all",onValueChange:C,children:[t.jsx(se,{className:"w-[140px] h-8 text-xs rounded-lg border-slate-200/80 dark:border-slate-700/80",children:t.jsx(ae,{placeholder:"Estado"})}),t.jsxs(ne,{children:[t.jsx(_,{value:"all",children:"Todos los estados"}),t.jsx(_,{value:"WAITING_ASSIGNMENT",children:"Sin asignar"}),t.jsx(_,{value:"IN_PROGRESS_AI",children:"En progreso (IA)"}),t.jsx(_,{value:"IN_PROGRESS_HUMAN",children:"En progreso (Agente)"})]})]}),t.jsxs(P,{variant:"outline",size:"sm","aria-pressed":s.includeClosed&&s.status==="all",disabled:s.status!=="all",title:s.status!=="all"?"Elige «Todos los estados» para ver también las cerradas":"Suma las conversaciones cerradas en los últimos 30 días, una por lead",onClick:()=>d({includeClosed:!s.includeClosed}),className:E("h-8 px-2.5 rounded-lg text-xs gap-1.5 border-slate-200/80 dark:border-slate-700/80",s.includeClosed&&s.status==="all"&&"border-primary/50 bg-primary/5 text-primary"),children:[t.jsx(rs,{className:"w-3.5 h-3.5"}),"Mostrar cerradas"]}),t.jsxs(Qe,{children:[t.jsx($e,{asChild:!0,children:t.jsxs(P,{variant:"outline",size:"sm",className:E("h-8 px-2.5 rounded-lg text-xs gap-1.5 border-slate-200/80 dark:border-slate-700/80",H>0&&"border-primary/50 text-primary"),children:[t.jsx(ot,{className:"w-3.5 h-3.5"}),H>0&&t.jsx(Q,{className:"h-4 w-4 p-0 flex items-center justify-center text-[9px] rounded-full",children:H})]})}),t.jsx(qe,{className:"w-80 p-3",align:"end",children:t.jsxs("div",{className:"space-y-4",children:[t.jsx("h4",{className:"font-semibold text-sm",children:"Filtros Avanzados"}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx("label",{className:"text-xs text-muted-foreground font-medium",children:"Canal / Conexión"}),t.jsx(ns,{value:s.channel||"all",onChange:l=>D(l),className:"h-8 text-xs w-full"})]}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("label",{className:"text-xs text-muted-foreground font-medium",children:"Etiquetas"}),s.tags&&s.tags.length>0&&t.jsx(Q,{variant:"secondary",className:"text-[10px] h-4 px-1",children:s.tags.length})]}),t.jsx("div",{className:"border rounded-md p-1 bg-slate-50 dark:bg-slate-900/50",children:t.jsx(ss,{selectedTags:y,folders:p||[],onToggleTag:F,trigger:t.jsxs(P,{variant:"ghost",size:"sm",className:"w-full justify-start text-xs h-7 text-muted-foreground font-normal",children:[t.jsx(ct,{className:"w-3.5 h-3.5 mr-2"}),y.length>0?`${y.length} seleccionadas`:"Seleccionar etiquetas..."]})})}),y.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1 mt-1.5",children:y.map(l=>t.jsxs(Q,{variant:"secondary",className:"text-[10px] h-5 px-1.5 gap-1 cursor-pointer hover:bg-slate-200 dark:hover:bg-slate-700",style:{backgroundColor:l.color+"20",color:l.color,borderColor:l.color+"40"},onClick:()=>F(l),children:[l.name,t.jsx(le,{className:"w-2.5 h-2.5 opacity-50"})]},l.id))})]}),t.jsx("div",{className:"h-px bg-slate-100 dark:bg-slate-800"}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx("label",{className:"text-xs text-muted-foreground font-medium",children:"Rango de fecha"}),t.jsxs(te,{value:s.dateRange,onValueChange:l=>d({dateRange:l}),children:[t.jsxs(se,{className:"w-full h-8 text-xs",children:[t.jsx(is,{className:"w-3.5 h-3.5 mr-1.5"}),t.jsx(ae,{})]}),t.jsxs(ne,{children:[t.jsx(_,{value:"all",children:"Todo el tiempo"}),t.jsx(_,{value:"7d",children:"Últimos 7 días"}),t.jsx(_,{value:"30d",children:"Últimos 30 días"}),t.jsx(_,{value:"90d",children:"Últimos 90 días"})]})]})]}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx("label",{className:"text-xs text-muted-foreground font-medium",children:"Asignado a"}),t.jsxs(te,{value:s.assignedTo,onValueChange:l=>d({assignedTo:l}),children:[t.jsx(se,{className:"w-full h-8 text-xs",children:t.jsx(ae,{})}),t.jsxs(ne,{children:[t.jsx(_,{value:"all",children:"Todos"}),t.jsx(_,{value:"me",children:"Asignados a mí"}),t.jsx(_,{value:"unassigned",children:"Sin asignar"})]})]})]}),H>0&&t.jsxs(P,{variant:"outline",size:"sm",className:"w-full h-7 text-xs mt-2",onClick:b,children:[t.jsx(le,{className:"w-3 h-3 mr-1.5"}),"Limpiar filtros"]})]})})]}),t.jsx("div",{className:"h-5 w-px bg-slate-200 dark:bg-slate-700"}),t.jsxs($,{children:[t.jsx(q,{asChild:!0,children:t.jsx(P,{variant:"ghost",size:"icon",className:"h-8 w-8 rounded-lg",onClick:()=>S(),disabled:I,children:t.jsx(dt,{className:E("w-3.5 h-3.5",I&&"animate-spin")})})}),t.jsx(z,{children:"Actualizar"})]}),t.jsxs("div",{className:"flex items-center bg-slate-100/80 dark:bg-slate-800/80 rounded-lg p-0.5 gap-0.5",children:[t.jsxs(P,{variant:a==="kanban"?"default":"ghost",size:"sm",className:"h-7 px-2.5 rounded-md text-xs",onClick:()=>c("kanban"),children:[t.jsx(ls,{className:"w-3.5 h-3.5 mr-1"}),"Kanban"]}),t.jsxs(P,{variant:a==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 rounded-md text-xs",onClick:()=>c("table"),disabled:!0,children:[t.jsx(js,{className:"w-3.5 h-3.5 mr-1"}),"Tabla"]}),t.jsx("div",{className:"w-px h-4 bg-slate-200 dark:bg-slate-700 mx-0.5"}),t.jsxs($,{children:[t.jsx(q,{asChild:!0,children:t.jsx(P,{variant:n?"default":"ghost",size:"icon",className:"h-7 w-7 rounded-md",onClick:k,children:n?t.jsx(os,{className:"w-3.5 h-3.5"}):t.jsx(as,{className:"w-3.5 h-3.5"})})}),t.jsx(z,{children:n?"Vista detallada":"Vista compacta"})]}),t.jsxs($,{children:[t.jsx(q,{asChild:!0,children:t.jsx(P,{variant:Y?"default":"ghost",size:"icon",className:"h-7 w-7 rounded-md",onClick:m,children:Y?t.jsx(hs,{className:"w-3.5 h-3.5"}):t.jsx(gs,{className:"w-3.5 h-3.5"})})}),t.jsx(z,{children:Y?"Expandir todas las etapas (Vista detallada)":"Colapsar todas las etapas (Vista general)"})]})]})]})]})});He.displayName="PipelineBoardHeader";function Vs(e){let s=0;return e.status!=="all"&&s++,e.assignedTo!=="all"&&s++,e.channel!=="all"&&s++,e.tags&&e.tags.length>0&&s++,e.dateRange!=="all"&&s++,e.search&&s++,e.includeClosed&&e.status==="all"&&s++,s}const Ws=new Set(["RESOLVED","ARCHIVED","CAMPAIGN_OUTBOUND"]);function ie(e){return e.getQueriesData({queryKey:["pipeline-board"]})}function Xs(e){return e[2]?.includeClosed===!0}function Fe(e){const s=e[1];return typeof s=="string"?s:null}function ge(e,s){return e.stages.some(a=>a.tickets.some(n=>n.id===s))}function Re(e){const s={},a=e.lastMessage?.body||e.lastMessage?.text||e.ticket?.lastMessagePreview;return a!==void 0&&(s.lastMessagePreview=a||null,s.lastMessageAt=new Date().toISOString()),e.unreadCount!==void 0&&(s.unreadCount=e.unreadCount),(e.ticket?.status||e.status)&&(s.status=e.ticket?.status||e.status),e.ticket?.assignedAgentId!==void 0&&(s.assignedAgentId=e.ticket.assignedAgentId||null),e.funnelId!==void 0&&(s.funnelId=e.funnelId||null),s}function Pe(e){return!e.contact||!e.channel||!e.ticket?null:{id:e.ticketId,status:e.ticket.status||e.status||"WAITING_ASSIGNMENT",priority:"MEDIUM",unreadCount:e.unreadCount||0,lastMessageAt:new Date().toISOString(),lastMessagePreview:e.lastMessage?.body||e.lastMessage?.text||e.ticket?.lastMessagePreview||null,enteredStageAt:new Date().toISOString(),timeInStageMs:0,assignedAgentId:e.ticket.assignedAgentId||null,assignedAgent:null,funnelId:e.funnelId||null,contact:{id:e.contact.id,name:e.contact.name,phone:e.contact.phone||null,avatarUrl:null},channel:{id:e.channel.id,type:e.channel.type,name:e.channel.name}}}function Ys(e){const s=ee(),a=h.useRef(!1),n=h.useCallback(i=>{const k=i.status||i.ticket?.status;if(k&&Ws.has(k)){const x=ie(s);let j=!1;x.forEach(([S,I])=>{if(I&&ge(I,i.ticketId)){const T=k==="RESOLVED"&&Xs(S);s.setQueryData(S,M=>M&&(T?pe(M,i.ticketId,{status:"RESOLVED"}):V(M,i.ticketId))),j=!0}}),j&&s.removeQueries({queryKey:["stage-tickets"]});return}const b="funnelId"in i;if(!b&&!i.previousFunnelId&&!i.transitionType)return;const f=b&&i.funnelId===null,v=ie(s);let u=!1;v.forEach(([x,j])=>{if(!j)return;const S=Fe(x);if(!S)return;const I=i.funnelId===S,T=i.previousFunnelId===S&&i.funnelId!==S,M=ge(j,i.ticketId);console.log("[Socket] conversation:update",{ticketId:i.ticketId,funnelId:i.funnelId,prevFunnelId:i.previousFunnelId,boardFunnelId:S,belongsHere:I,leftHere:T,exists:M});const w=!I&&!T&&i.funnelId!==null&&M&&!!i.transitionType;if(T||w){s.setQueryData(x,A=>A&&V(A,i.ticketId)),u=!0;return}if(I){const A=i.funnelStageId||G;if(M){const g=Re(i);s.setQueryData(x,C=>{if(!C)return C;const c=W(C,i.ticketId,A);return Object.keys(g).length>0?pe(c,i.ticketId,g):c}),u=!0}else{const g=Pe(i);g?(s.setQueryData(x,C=>C&&Ie(C,g,A)),u=!0):(console.log("[Socket] Invalidating query - missing ticket data for add"),s.invalidateQueries({queryKey:x}))}return}if(f){if(M){const A=Re(i);s.setQueryData(x,g=>{if(!g)return g;const C=W(g,i.ticketId,G);return Object.keys(A).length>0?pe(C,i.ticketId,A):C})}else{const A=Pe(i);A?s.setQueryData(x,g=>g&&Ie(g,A,G)):s.invalidateQueries({queryKey:x})}u=!0}}),u&&s.removeQueries({queryKey:["stage-tickets"]})},[s]),r=h.useCallback(i=>{ie(s).forEach(([b,f])=>{if(!f)return;const v=Fe(b);v&&(i.funnelId===v&&s.setQueryData(b,u=>u&&W(u,i.ticketId,i.funnelStageId)),i.previousFunnelId===v&&i.funnelId!==v&&s.setQueryData(b,u=>u&&V(u,i.ticketId)))}),s.removeQueries({queryKey:["stage-tickets"]})},[s]),o=h.useCallback(i=>{s.invalidateQueries({queryKey:["pipeline-board"]}),s.removeQueries({queryKey:["stage-tickets"]}),O.info(`${i.ticketIds.length} tickets actualizados`,{duration:3e3})},[s]),d=h.useCallback(i=>{const k=xe.getState().user;if(i.assignedAgentId===null||i.assignedAgentId===k?.id||mt(k))return;let f=!1;ie(s).forEach(([v,u])=>{!u||!ge(u,i.ticketId)||(s.setQueryData(v,x=>x&&V(x,i.ticketId)),f=!0)}),f&&s.removeQueries({queryKey:["stage-tickets"]})},[s]);return h.useEffect(()=>{if(!e)return;let i=null;try{const k=K.onConversationUpdate(n);K.on("ticket:funnel-changed",r),K.on("conversation:bulk-update",o),K.on("conversation:scope",d);const b=K.onConnectionChange(f=>{a.current=f});i=()=>{k(),b(),K.off("ticket:funnel-changed",r),K.off("conversation:bulk-update",o),K.off("conversation:scope",d)}}catch{console.warn("[PipelineSocket] WebSocket service not available")}return()=>i?.()},[e,n,r,o,d]),{isConnectedRef:a}}function Ia(){const e=N(oe);return Ys(e),t.jsxs("div",{className:"flex flex-col h-full bg-gradient-to-br from-slate-50 via-white to-slate-50 dark:from-slate-950 dark:via-slate-900 dark:to-slate-950 animate-in slide-in-from-bottom-4 fade-in duration-500",children:[t.jsx(He,{}),t.jsx("div",{className:"flex-1 overflow-hidden",children:t.jsx(Ge,{})})]})}function Ta(e){if(e<=0)return"Ahora";const s=Math.floor(e/6e4),a=Math.floor(s/60),n=Math.floor(a/24),r=Math.floor(n/7);return r>0?`${r}sem`:n>0?`${n}d`:a>0?`${a}h`:s>0?`${s}m`:"Ahora"}function Aa(e){return e?e.split(" ").map(s=>s[0]).filter(Boolean).join("").slice(0,2).toUpperCase():"??"}function Ma(e){return{WHATSAPP:"W",INSTAGRAM:"IG",FACEBOOK:"FB",TELEGRAM:"TG",WEB:"🌐"}[e]||"?"}function Da(e){return{WHATSAPP:"bg-green-500",INSTAGRAM:"bg-gradient-to-tr from-yellow-500 via-pink-500 to-purple-500",FACEBOOK:"bg-blue-600",TELEGRAM:"bg-sky-500",WEB:"bg-indigo-500"}[e]||"bg-slate-400"}function Ea(e){switch(e){case"URGENT":case"HIGH":return"destructive";case"LOW":return"secondary";default:return"outline"}}function Fa(e){switch(e){case"URGENT":return"🔥";case"HIGH":return"⚠️";case"LOW":return"📋";default:return""}}function Ra(e){return{WAITING_ASSIGNMENT:"bg-yellow-100 text-yellow-800 border-yellow-200",IN_PROGRESS_AI:"bg-blue-100 text-blue-800 border-blue-200",IN_PROGRESS_HUMAN:"bg-green-100 text-green-800 border-green-200",RESOLVED:"bg-gray-100 text-gray-800 border-gray-200",ARCHIVED:"bg-slate-100 text-slate-800 border-slate-200",CAMPAIGN_OUTBOUND:"bg-purple-100 text-purple-800 border-purple-200"}[e]||"bg-gray-100 text-gray-800"}function Pa(e){return{WAITING_ASSIGNMENT:"Sin asignar",IN_PROGRESS_AI:"En progreso (IA)",IN_PROGRESS_HUMAN:"En progreso (Agente)",RESOLVED:"Resuelto",ARCHIVED:"Archivado",CAMPAIGN_OUTBOUND:"Campaña"}[e]||e}function _a(e){const s=new Date(e),n=new Date().getTime()-s.getTime(),r=Math.floor(n/6e4),o=Math.floor(r/60),d=Math.floor(o/24);return d>7?cs(s,{style:"day-month"}):d>0?`hace ${d}d`:o>0?`hace ${o}h`:r>0?`hace ${r}m`:"Ahora"}function Oa(e,s){return!e||e.length<=s?e:`${e.slice(0,s-3)}...`}function Qa(e){if(!e)return"#6366f1";let s=0;for(let n=0;n<e.length;n++)s=e.charCodeAt(n)+((s<<5)-s);const a=["#6366f1","#8b5cf6","#ec4899","#ef4444","#f97316","#eab308","#22c55e","#14b8a6","#06b6d4","#3b82f6"];return a[Math.abs(s)%a.length]}export{Ge as PipelineBoard,He as PipelineBoardHeader,Ia as PipelinePage,Ke as PipelineStageColumn,ve as PipelineTicketCard,_a as formatRelativeDate,Ta as formatTimeInStage,Da as getChannelColor,Ma as getChannelIcon,Aa as getInitials,Fa as getPriorityEmoji,Ea as getPriorityVariant,Ra as getStatusColor,Pa as getStatusLabel,B as pipelineApi,Qa as stringToColor,Oa as truncateText,_s as useAssignTicketMutation,Qs as useFunnelsForSelector,Ps as useMoveTicketMutation,Be as usePipelineBoardQuery,Ys as usePipelineSocket,N as usePipelineStore,Os as useRemoveTicketMutation,Rs as useStageTicketsQuery};
@@ -1 +0,0 @@
1
- import{c as Rt,i as me,t as C,Q as Os,g as _t,j as e,a3 as Re,a4 as _e,a5 as os,a6 as Ae,a7 as Oe,Y as Zs,I as H,o as oe,l as q,av as Ot,r as Y,ad as vs,B as _,$ as zt,ab as ue,X as fe,z as Ys,aa as Dt,h as Js,au as et,P as Vt,w as Lt,b8 as Ft,ba as Gt,bb as qt,b2 as $t,bc as st,bd as Ht,be as Kt,bf as Wt,ak as Qt,a0 as ze,T as be,v as je,U as Xt,x as ve,R as Zt,n as G,F as Ze,a2 as Ns,H as Yt,y as Jt,G as ea,C as zs,ac as Ds,Z as De,aE as sa,a9 as ta,an as tt,ao as at,ap as rt,as as Ne,aB as nt}from"./index-DsyZ_FlA.js";import{b as d,R as Q}from"./recharts-DrC5kNsx.js";import{P as aa,a as ra,b as na,E as la}from"./page-components-o2TF52HV.js";import{C as ia}from"./ConfirmModal-W7VUI3Z_.js";import{C as Ce,a as Te}from"./card-DcKsxjXK.js";import{S as cs,a as ds,b as us,c as ms,d as re}from"./select-DlB_BbfM.js";import{S as Ue}from"./skeleton-B0zh8s_y.js";import{t as J,h as K,i as oa,R as ys,g as ca,m as da,n as le,d as ws,o as ua,f as ma,P as xs,l as Vs,V as Ye,j as xa,S as ye,a as pa,k as ge,F as Je,H as es,b as ne,I as ha,q as lt,r as ga}from"./interactiveLimits-CfLJ1O4_.js";import{e as Gn}from"./interactiveLimits-CfLJ1O4_.js";import{u as xe}from"./useMutation-a5tIBvQY.js";import{u as fa}from"./useUploadConfig-BuiF0X-3.js";import{T as ba,a as ja,b as Ls,c as Fs}from"./tabs-DqXhuAr6.js";import{T as Ee}from"./textarea-BYtcLsMD.js";import{a as Cs}from"./datetime-BuZosCVk.js";import{f as Ve,b as va,a as it,g as Na}from"./storage.api-CFU3KJNp.js";import{S as ya,M as wa}from"./scroll-area-CavEOIyz.js";import{A as Ca,b as Ta,c as Ea,d as Aa,e as ka,f as Ia,g as Sa,h as Pa}from"./alert-dialog-D8P69s-m.js";import{T as ke}from"./trash-2-Du2vmQCH.js";import{I as Gs}from"./MediaProcessingService-glHGiE_o.js";import{c as ot,a as Ma,T as Ua,C as Ba,R as Ra}from"./index-DUnioqCT.js";import{S as _a}from"./separator-CPT3uVRM.js";import{S as qs}from"./switch-ODBa0fCT.js";import{P as ss,a as ts,b as as}from"./popover-MyuU-yAK.js";import{S as rs,E as ns}from"./EmojiPicker-BToAe-MT.js";import{T as Ts}from"./trending-up-Ba4HSvuW.js";import{U as Oa}from"./upload-C7TwpdyA.js";import{M as ps}from"./mic-CT4vyzLZ.js";import{S as za}from"./square-BuGqLxJB.js";import{M as hs}from"./message-square-Dfn16oHc.js";import{L as gs}from"./list-BKc6EXnV.js";import{L as ct}from"./layout-grid-Cm6hfBWZ.js";import{I as Da}from"./instagram-CC7iYt7V.js";import{F as Va}from"./facebook-RxMBweMB.js";import{I as dt,V as La}from"./video-VfwKgB6z.js";import{F as fs}from"./folder-open-DQFc4qTJ.js";import{P as Es}from"./pencil-Cx8u1N8t.js";import{A as Fa}from"./arrow-left-BeDdBs_Q.js";import{E as ut}from"./ellipsis-vertical-DTqbEYYp.js";import{F as Ga}from"./file-DMzjdlTL.js";import"./index-KbFmSzBE.js";import"./download-CiVQHPeB.js";import"./useDebounce-Bfcb_jpD.js";import"./eye-HfQCUjxJ.js";const qa=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]],$a=Rt("grid-3x3",qa);function Ha(){const s=me();return xe({mutationFn:t=>J.create(t),onSuccess:t=>{s.invalidateQueries({queryKey:K.lists()}),s.invalidateQueries({queryKey:K.stats("current")}),C.success(`Plantilla "${t.name}" creada`)},onError:t=>{const a=t.response?.data?.message||t.message||"Error desconocido";C.error(a)}})}function Ka(){const s=me();return xe({mutationFn:({id:t,data:a})=>J.update(t,a),onSuccess:t=>{s.invalidateQueries({queryKey:K.detail(t.id)}),s.invalidateQueries({queryKey:K.lists()}),s.invalidateQueries({queryKey:K.stats("current")}),C.success("Plantilla actualizada")},onError:t=>{const a=t.response?.data?.message||t.message||"Error desconocido";C.error(a)}})}function Wa(){const s=me();return xe({mutationFn:t=>J.delete(t),onSuccess:()=>{s.invalidateQueries({queryKey:K.all}),C.success("Plantilla eliminada")},onError:t=>{C.error(`Error al eliminar: ${t.message}`)}})}function On(){const s=me();return xe({mutationFn:({id:t,metadata:a})=>J.trackUsage(t,a),onMutate:async()=>{await s.cancelQueries({queryKey:K.stats("current")});const t=s.getQueryData(K.stats("current"));return s.setQueryData(K.stats("current"),a=>({...a,totalUsage:(a?.totalUsage||0)+1})),{previousStats:t}},onError:(t,a,r)=>{r?.previousStats&&s.setQueryData(K.stats("current"),r.previousStats)}})}function Qa(){const s=me();return xe({mutationFn:t=>J.createCategory(t),onSuccess:t=>{s.invalidateQueries({queryKey:K.categories("current")}),C.success(`Categoría "${t.name}" creada`)},onError:t=>{C.error(`Error al crear categoría: ${t.message}`)}})}function Xa(){const s=me();return xe({mutationFn:({id:t,data:a})=>J.updateCategory(t,a),onSuccess:()=>{s.invalidateQueries({queryKey:K.categories("current")}),C.success("Categoría actualizada")},onError:t=>{C.error(`Error al actualizar categoría: ${t.message}`)}})}function Za(){const s=me();return xe({mutationFn:t=>J.deleteCategory(t),onSuccess:()=>{s.invalidateQueries({queryKey:K.categories("current")}),C.success("Categoría eliminada")},onError:t=>{C.error(`Error al eliminar categoría: ${t.message}`)}})}const Ya=["WHATSAPP","WEB","INSTAGRAM","FACEBOOK","SMS","EMAIL"],Ja=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function mt(s,t){if(!s)return null;const a=Ja.test(s)?t.find(l=>l.channelId===s)?.channelType:s;if(!a)return null;const r=a.toUpperCase();return Ya.includes(r)?r:null}function bs(s,t){const a=[];for(const r of s??[]){const l=mt(r,t);l&&!a.includes(l)&&a.push(l)}return a}function er(s,t){if(!s?.length)return!1;const a=t.channelType.toUpperCase();return s.some(r=>r===t.channelId||(r??"").toUpperCase()===a)}function sr(s){return s?s.startsWith("image/")?"image":s.startsWith("video/")?"video":"document":"document"}const tr=({formData:s,contentType:t,mediaData:a,interactiveData:r,sendAsDocument:l,compatibleChannels:m,selectedTemplate:u,createTemplate:v,updateTemplate:S,onSuccess:T,onButtonErrors:P})=>{const[A,M]=d.useState(!1);return{handleSubmit:async()=>{if(!s.name?.trim())return C.error("El nombre es requerido");if(t==="MEDIA"&&!a)return C.error("Falta el archivo multimedia");if(t==="INTERACTIVE"&&r.displayMode==="carousel"){const g=r.carouselCards||[];if(g.length<2)return C.error("El carrusel necesita al menos 2 tarjetas");if(g.length>10)return C.error("El carrusel admite máximo 10 tarjetas");if(g.some(j=>!j.imageGcsPath))return C.error("Cada tarjeta del carrusel necesita una imagen");if(g.some(j=>!(j.buttons&&j.buttons.length)&&!j.urlButton))return C.error("Cada tarjeta necesita al menos un botón");if(g.some(j=>j.urlButton&&!j.urlButton.url?.trim()))return C.error("Cada tarjeta de enlace necesita una URL");if(g.some(j=>j.urlButton&&!j.urlButton.title?.trim()))return C.error("Cada botón de enlace necesita un título");if(g.some(j=>!j.urlButton&&(j.buttons||[]).some(U=>!(U.label||"").trim())))return C.error("Cada botón de respuesta rápida necesita un título");const p=oa(g.map(j=>j.urlButton?[]:(j.buttons||[]).map(U=>U.label||"")));if(p!==-1)return C.error(`La tarjeta ${p+1} tiene botones con títulos duplicados. WhatsApp requiere que sean únicos dentro de cada tarjeta.`);P?.(new Set)}else if(t==="INTERACTIVE"){const g=r.displayMode==="list"||r.buttons.length>3;if(r.buttons.length===0)return C.error(g?"Agrega al menos una opción":"Agrega al menos un botón");const p=r.buttons.map(f=>(f.text||"").trim()),j=p.map((f,B)=>f.length===0?B:-1).filter(f=>f!==-1),U=g?[]:(()=>{const f=p.map(x=>x.toLowerCase()),B=new Map;return f.forEach(x=>{x&&B.set(x,(B.get(x)??0)+1)}),f.map((x,h)=>x&&(B.get(x)??0)>1?h:-1).filter(x=>x!==-1)})();if(j.length>0||U.length>0)return P?.(new Set([...j,...U])),j.length>0?C.error(g?"Hay opciones sin título. Complétalas o elimínalas.":"Hay botones sin texto. Completa o elimina los botones vacíos."):C.error("Los botones tienen títulos duplicados. WhatsApp requiere que sean únicos.");P?.(new Set)}M(!0);try{const g={...s,shortcut:s.shortcut?`/${s.shortcut}`:void 0,contentType:l&&t==="MEDIA"?"DOCUMENT":t==="MEDIA"?a.detectedType:t,content:t==="INTERACTIVE"?r.body:s.content,mediaGcsPath:a?.gcsPath,thumbnailGcsPath:a?.thumbnailGcsPath,mediaMimeType:a?.mimeType,mediaOriginalName:a?.originalName,mediaCaption:t==="MEDIA"?s.content:void 0,interactive:t==="INTERACTIVE"?(()=>{if(r.displayMode==="carousel")return{type:"carousel",body:{text:r.body},cards:(r.carouselCards||[]).map(x=>({imageGcsPath:x.imageGcsPath,...x.cardBody?{cardBody:x.cardBody}:{},...x.urlButton?{urlButton:x.urlButton}:{buttons:(x.buttons||[]).map(h=>({id:h.id,label:h.label}))}}))};const p=r.displayMode==="list"||r.buttons.length>3,j=r.media?{type:sr(r.media.mimeType),mediaGcsPath:r.media.gcsPath,mediaMimeType:r.media.mimeType,mediaOriginalName:r.media.originalName}:void 0,U=r.header?{type:"text",text:r.header}:void 0,f={text:r.body},B=r.footer?{text:r.footer}:void 0;return p?{type:"list",header:U,body:f,footer:B,menuButton:r.menuButton?.trim()||void 0,sections:[{rows:r.buttons.map(x=>({id:x.id,title:x.text,...x.description?.trim()?{description:x.description.trim()}:{}}))}]}:{type:"buttons",header:j??U,body:f,footer:B,buttons:r.buttons.map(x=>({type:"reply",title:x.text,id:x.id}))}})():void 0,supportedChannels:bs(s.supportedChannels,m)};if(t==="MEDIA"&&a&&a.file&&a.hash){const p=a.file,j=a.hash;try{const U=l&&a.optimizationStats;let f=!1,B,x;if(!U){const h=await Os.checkDuplicate(j);f=h.exists,B=h.gcsPath,x=h.thumbnailGcsPath}if(f&&B)g.mediaGcsPath=B,g.thumbnailGcsPath=x;else{const h=l&&a.originalFile?a.originalFile:p;C.info(l?"Subiendo documento original...":"Subiendo archivo multimedia...");const D=await Os.uploadMedia(h);g.mediaGcsPath=D.gcsPath,g.thumbnailGcsPath=D.thumbnailGcsPath,g.mediaMimeType=D.mimeType}}catch(U){console.error("Upload failed:",U),C.error("Error al subir la multimedia. Inténtalo de nuevo."),M(!1);return}}if(t==="MEDIA"&&!g.mediaGcsPath)throw new Error("No se pudo procesar el archivo multimedia. Por favor intenta grabar o subir nuevamente.");u?(await S({...g}),C.success("Plantilla actualizada")):(await v(g),C.success("Plantilla creada")),T()}catch(g){console.error("Error saving template:",g)}finally{M(!1)}},isSaving:A}};function ar(s){return(s.interactive?.cards??[]).some(a=>a.urlButton)?"cta_url":"quick_reply"}function rr(s){return(s.interactive?.body?.text||s.content||"").trim().slice(0,1024)}const $s=s=>`${s}-${crypto.randomUUID().slice(0,8)}`;function nr(s,t){return(s.interactive?.cards??[]).map(r=>({id:$s("card"),imageGcsPath:r.imageGcsPath,thumbnailUrl:r.thumbnailUrl,cardBody:r.cardBody,...t==="cta_url"?{urlButton:{title:r.urlButton?.title||"Ver",url:r.urlButton?.url||""}}:{buttons:(r.buttons??[]).slice(0,2).map(l=>({id:$s("btn"),label:l.label}))}}))}function lr({mode:s,open:t,onOpenChange:a,onImport:r}){const[l,m]=d.useState(""),[u,v]=d.useState(null),{data:S,isLoading:T}=_t({queryKey:[...K.lists(),"carousel-import"],queryFn:()=>J.getAll({contentType:"INTERACTIVE",status:"ACTIVE",limit:100}),enabled:t,staleTime:6e4}),P=d.useMemo(()=>{const N=S?.data??[],g=l.trim().toLowerCase();return N.filter(p=>p.interactive?.type==="carousel"&&(p.interactive?.cards?.length??0)>=2&&ar(p)===s).filter(p=>!g||p.name.toLowerCase().includes(g))},[S,l,s]),A=async N=>{v(N.id);try{const g=await J.getById(N.id),p=nr(g,s);if(p.length<2){C.error("La plantilla no tiene tarjetas válidas.");return}r(p,rr(g)),a(!1)}catch{C.error("No se pudo cargar la plantilla.")}finally{v(null)}},M=s==="cta_url"?"enlace (URL)":"respuesta rápida";return e.jsx(Re,{open:t,onOpenChange:a,children:e.jsxs(_e,{className:"sm:max-w-[520px]",children:[e.jsxs(os,{children:[e.jsx(Ae,{children:"Autocompletar desde plantilla"}),e.jsxs(Oe,{children:["Copia el contenido de una plantilla de carrusel a este nodo (imágenes, textos y botones). No queda vinculada: es una copia editable. Solo se muestran plantillas de"," ",M,"."]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Zs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(H,{value:l,onChange:N=>m(N.target.value),placeholder:"Buscar plantilla…",className:"pl-8"})]}),e.jsx(ya,{className:"max-h-[360px] pr-3 -mr-3",children:T?e.jsxs("div",{className:"py-10 flex items-center justify-center text-muted-foreground text-sm gap-2",children:[e.jsx(oe,{className:"w-4 h-4 animate-spin"})," Cargando plantillas…"]}):P.length===0?e.jsxs("div",{className:"py-10 text-center text-sm text-muted-foreground px-4",children:["No hay plantillas de carrusel de ",M,".",e.jsx("br",{}),"Crea una en ",e.jsx("span",{className:"font-medium",children:"Plantillas de NuBot"}),"."]}):e.jsx("div",{className:"space-y-1.5",children:P.map(N=>{const g=N.interactive?.cards?.length??0,p=u===N.id;return e.jsxs("button",{type:"button",disabled:!!u,onClick:()=>A(N),className:q("w-full flex items-center gap-3 p-2.5 rounded-lg border border-border text-left transition-colors","hover:bg-accent disabled:opacity-60 disabled:cursor-not-allowed"),children:[e.jsx("div",{className:"w-9 h-9 rounded bg-primary/10 text-primary flex items-center justify-center shrink-0",children:p?e.jsx(oe,{className:"w-4 h-4 animate-spin"}):e.jsx(Ot,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:N.name}),e.jsxs("div",{className:"mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[g," tarjetas"]}),e.jsxs(Y,{variant:"secondary",className:"h-4 px-1 text-[9px] gap-0.5 font-normal",children:[s==="cta_url"?e.jsx(vs,{className:"w-2.5 h-2.5"}):e.jsx(ys,{className:"w-2.5 h-2.5"}),s==="cta_url"?"Enlace":"Respuesta"]})]})]})]},N.id)})})})]})})}const{CAROUSEL_MIN_CARDS:ls,CAROUSEL_MAX_CARDS:we,CAROUSEL_CARD_BODY:Hs,CAROUSEL_MAX_CARD_BUTTONS:Ks,CAROUSEL_BUTTON_TITLE:Ws,CAROUSEL_BUTTON_URL:ir}=da,Be=s=>`${s}_${crypto.randomUUID().slice(0,8)}`,Qs="image/jpeg,image/png",or=(s,t=1)=>s==="cta_url"?{id:Be("card"),imageGcsPath:void 0,cardBody:"",urlButton:{title:"Ver",url:""}}:{id:Be("card"),imageGcsPath:void 0,cardBody:"",buttons:Array.from({length:Math.max(1,t)},(a,r)=>({id:Be("btn"),label:r===0?"Elegir":r===1?"Opción":`Opción ${r}`}))},xt=d.memo(({mode:s,cards:t,onChange:a,onImportFromTemplate:r})=>{const[l,m]=d.useState(new Set),[u,v]=d.useState({}),S=d.useRef(t);S.current=t;const{uploadFile:T,feedback:P}=ca({mediaLimits:va,onError:i=>C.error("Error al subir imagen",{description:i.message})}),A=d.useCallback((i,k)=>{a(t.map((L,o)=>o===i?{...L,...k}:L))},[t,a]),M=()=>{t.length<we&&a([...t,or(s,t[0]?.buttons?.length??1)])},N=i=>{t.length>ls&&a(t.filter((k,L)=>L!==i))},g=async(i,k)=>{const L=S.current[i],o=L?.id;m(b=>new Set(b).add(i));try{const b=await T(k);b&&(a(S.current.map(W=>(o?W.id===o:W===L)?{...W,imageGcsPath:b.gcsPath,thumbnailUrl:b.thumbnailUrl||b.signedUrl}:W)),v(W=>({...W,[b.gcsPath]:{sizeKB:Math.max(1,Math.round(b.size/1024)),optimized:b.isOptimized,fileName:k.name,originalSize:b.optimizationStats?.originalSize}})),b.isDuplicate&&C.info(`Imagen reutilizada (tarjeta ${i+1})`))}catch{}finally{m(b=>{const W=new Set(b);return W.delete(i),W})}},p=i=>k=>{const L=k.target.files?.[0];L&&g(i,L),k.target.value=""},j=()=>{a(t.map(i=>({...i,buttons:[...i.buttons??[],{id:Be("btn"),label:"Opción"}].slice(0,Ks)})))},U=i=>{a(t.map(k=>({...k,buttons:(k.buttons??[]).filter((L,o)=>o!==i)})))},f=s==="quick_reply"?t[0]?.buttons?.length??1:1,B=t.length>=we,[x,h]=d.useState(!1),[D,z]=d.useState(null),$=d.useCallback((i,k)=>{const L=i.slice(0,we);r?r(L,k):a(L),C.success(`Autocompletado: ${L.length} tarjetas`)},[a,r]),I=d.useCallback((i,k)=>{t.length>0?z({cards:i,body:k}):$(i,k)},[t.length,$]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-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:q("text-[10px] tabular-nums px-1.5 py-0.5 rounded-full font-medium",B?"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:[t.length,"/",we]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(_,{variant:"ghost",size:"sm",onClick:()=>h(!0),className:"h-6 px-1.5 text-[11px] gap-1 text-slate-500 hover:text-primary",title:"Copia el contenido de una plantilla de carrusel a este nodo",children:[e.jsx(zt,{className:"w-3 h-3"})," Autocompletar"]}),s==="quick_reply"&&f<Ks&&e.jsxs(_,{variant:"ghost",size:"sm",onClick:j,className:"h-6 px-1.5 text-[11px] gap-1 text-slate-500 hover:text-primary",children:[e.jsx(ue,{className:"w-3 h-3"})," 2.º botón"]})]})]}),e.jsx("div",{className:"space-y-2.5",children:t.map((i,k)=>{const L=l.has(k);return e.jsxs("div",{className:"group/card rounded-xl border border-slate-200 dark:border-slate-700/70 bg-white dark:bg-slate-800/40 overflow-hidden shadow-sm transition-colors hover:border-slate-300 dark:hover:border-slate-600",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/50",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:k+1}),"Tarjeta ",k+1]}),t.length>ls&&e.jsx("button",{type:"button",onClick:()=>N(k),className:"text-slate-400 hover:text-red-500 p-0.5 rounded transition-colors",title:"Eliminar tarjeta",children:e.jsx(ke,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"p-2.5 space-y-2",children:[i.thumbnailUrl?e.jsxs("div",{className:"relative group/img rounded-lg overflow-hidden bg-slate-100 dark:bg-slate-900",children:[e.jsx("img",{src:i.thumbnailUrl,alt:"",className:"w-full aspect-[1.91/1] object-cover"}),e.jsxs("label",{className:q("absolute inset-0 flex items-center justify-center gap-1.5 text-white text-[11px] font-medium cursor-pointer transition-opacity","bg-black/45 opacity-0 group-hover/img:opacity-100"),children:[e.jsx(Gs,{className:"w-4 h-4"})," Cambiar imagen",e.jsx("input",{type:"file",accept:Qs,className:"hidden",onChange:p(k)})]}),e.jsx("button",{type:"button",onClick:()=>A(k,{imageGcsPath:void 0,thumbnailUrl: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(fe,{className:"w-3 h-3"})}),L&&e.jsx("div",{className:"absolute inset-0 bg-black/55 flex items-center justify-center",children:e.jsx(oe,{className:"w-5 h-5 text-white animate-spin"})})]}):e.jsxs("label",{className:"relative 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",children:[L?e.jsx(oe,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Gs,{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:Qs,className:"hidden",onChange:p(k)})]}),L?e.jsxs("p",{className:"flex items-center gap-1.5 text-[9px] text-primary",children:[e.jsx(oe,{className:"w-2.5 h-2.5 animate-spin shrink-0"}),e.jsx("span",{className:"truncate",children:P||"Procesando imagen…"})]}):i.imageGcsPath&&u[i.imageGcsPath]?e.jsxs("p",{className:"flex items-center gap-1 text-[9px] text-slate-400 truncate",title:u[i.imageGcsPath].fileName,children:[e.jsx(Ys,{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:u[i.imageGcsPath].optimized?"Optimizada":"Lista"}),u[i.imageGcsPath].optimized&&u[i.imageGcsPath].originalSize?e.jsxs("span",{children:["· ",Ve(u[i.imageGcsPath].originalSize)," → ",u[i.imageGcsPath].sizeKB," KB"]}):e.jsxs("span",{children:["· ",u[i.imageGcsPath].sizeKB," KB"]}),u[i.imageGcsPath].fileName&&e.jsxs("span",{className:"truncate",children:["· ",u[i.imageGcsPath].fileName]})]}):null,e.jsxs("div",{className:"relative",children:[e.jsx(Ee,{value:i.cardBody||"",onChange:o=>A(k,{cardBody:o.target.value.slice(0,Hs)}),placeholder:"Descripción (opcional)",rows:2,className:"resize-none text-xs pb-4"}),e.jsxs("span",{className:"absolute bottom-1.5 right-2 text-[9px] tabular-nums text-slate-400 pointer-events-none",children:[(i.cardBody||"").length,"/",Hs]})]}),s==="cta_url"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"relative",children:[e.jsx(vs,{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(H,{value:i.urlButton?.title||"",onChange:o=>A(k,{urlButton:{title:o.target.value.slice(0,Ws),url:i.urlButton?.url||""}}),placeholder:"Texto del botón",className:"h-8 text-xs pl-7 font-medium"})]}),e.jsx(H,{value:i.urlButton?.url||"",onChange:o=>A(k,{urlButton:{title:i.urlButton?.title||"Ver",url:o.target.value.slice(0,ir)}}),placeholder:"https://…",className:"h-8 text-xs"})]}):e.jsx("div",{className:"space-y-1.5",children:(i.buttons??[]).map((o,b)=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ys,{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(H,{value:o.label,onChange:W=>{const ie=[...i.buttons??[]];ie[b]={...ie[b],label:W.target.value.slice(0,Ws)},A(k,{buttons:ie})},placeholder:`Botón ${b+1}`,className:"h-8 text-xs pl-7 font-medium"})]}),f>1&&k===0&&e.jsx("button",{type:"button",onClick:()=>U(b),className:"text-slate-400 hover:text-red-500 shrink-0 p-1 rounded transition-colors",title:"Quitar este botón de todas las tarjetas",children:e.jsx(ke,{className:"w-3.5 h-3.5"})})]},o.id))})]})]},k)})}),e.jsxs("button",{type:"button",onClick:M,disabled:B,className:"w-full h-9 rounded-xl border border-dashed border-slate-300 dark:border-slate-600 flex items-center justify-center gap-1.5 text-xs font-medium text-slate-500 hover:border-primary/50 hover:text-primary hover:bg-primary/5 disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:text-slate-500 transition-colors",children:[e.jsx(ue,{className:"w-4 h-4"})," Agregar tarjeta"]}),e.jsxs("p",{className:"text-[10px] leading-relaxed text-slate-400 dark:text-slate-500 flex items-start gap-1.5",children:[e.jsx(Dt,{className:"w-3 h-3 mt-0.5 shrink-0"}),e.jsxs("span",{children:[ls,"–",we," tarjetas · imagen obligatoria ·"," ",s==="cta_url"?"cada tarjeta lleva un botón que abre su enlace.":`cada tarjeta lleva ${f} bot${f===1?"ón que dirige":"ones que dirigen"} a una rama del flujo.`]})]}),e.jsx(lr,{mode:s,open:x,onOpenChange:h,onImport:I}),e.jsx(Ca,{open:D!==null,onOpenChange:i=>!i&&z(null),children:e.jsxs(Ta,{children:[e.jsxs(Ea,{children:[e.jsx(Aa,{children:"¿Reemplazar las tarjetas actuales?"}),e.jsxs(ka,{children:["Este nodo ya tiene ",t.length," tarjeta",t.length===1?"":"s",". Autocompletar las reemplazará por las ",D?.cards.length??0," de la plantilla",s==="quick_reply"?" (se perderán las conexiones de salida de las tarjetas actuales).":"."]})]}),e.jsxs(Ia,{children:[e.jsx(Sa,{children:"Cancelar"}),e.jsx(Pa,{onClick:()=>{D&&$(D.cards,D.body),z(null)},children:"Reemplazar"})]})]})})]})});xt.displayName="CarouselCardsEditor";const cr=(s,t=!1)=>{const a=Js(M=>M.currentOrganization),{channels:r,fetchChannels:l,isLoading:m}=et(Vt(M=>({channels:M.channels,fetchChannels:M.fetchChannels,isLoading:M.isLoading}))),[u,v]=d.useState(!0),[S,T]=d.useState([]);d.useEffect(()=>{a?.id&&r.length===0&&l({withDeleted:!1})},[a?.id,r.length,l]);const P=new Set(["CALENDAR","calendar","google-calendar"]),A=d.useMemo(()=>r.filter(M=>M.isActive&&!M.deletedAt&&!M.disconnectedFromMetaAt&&!M.deactivatedAt&&!M.archivedAt&&!P.has(M.type)),[r]);return d.useEffect(()=>{if(!s){T(A.map(p=>({channelId:p.id,channelName:p.name,channelType:p.type,isCompatible:!0})));return}const N=t?"document":it(s.mimeType);if(!N){T(A.map(p=>({channelId:p.id,channelName:p.name,channelType:p.type,isCompatible:!1,reason:"Tipo de archivo no soportado"})));return}const g=A.map(p=>{const j=Na(p.type),U=p.config?.mediaLimits?.outbound?.[N]?.maxBytes??j.outbound[N]?.maxBytes??0;let f=s?.fileSize??0;t&&s.optimizationStats?.originalSize?f=s.optimizationStats.originalSize:t&&s.originalFile?.size&&(f=s.originalFile.size);const B=f<=U;let x;if(B)U===0&&(x=`Este canal no soporta archivos tipo ${N}`);else{const h=Ve(U),D=Ve(f);x=`Límite de ${h} para ${p.type} excedido (Archivo: ${D})`}return{channelId:p.id,channelName:p.name,channelType:p.type,isCompatible:B&&U>0,reason:x}});T(g)},[A,s,t]),{channels:S,isLoading:m,allowAll:u,setAllowAll:v}},dr=()=>{const s=et(t=>t.fetchChannels);d.useEffect(()=>{const t=Lt.onChannelsUpdate(a=>{console.log("[useChannelSocket] Received channel update, refreshing store..."),s()});return()=>{t()}},[s])};function ur(s){const t=mr(s),a=d.forwardRef((r,l)=>{const{children:m,...u}=r,v=d.Children.toArray(m),S=v.find(pr);if(S){const T=S.props.children,P=v.map(A=>A===S?d.Children.count(T)>1?d.Children.only(null):d.isValidElement(T)?T.props.children:null:A);return e.jsx(t,{...u,ref:l,children:d.isValidElement(T)?d.cloneElement(T,void 0,P):null})}return e.jsx(t,{...u,ref:l,children:m})});return a.displayName=`${s}.Slot`,a}function mr(s){const t=d.forwardRef((a,r)=>{const{children:l,...m}=a;if(d.isValidElement(l)){const u=gr(l),v=hr(m,l.props);return l.type!==d.Fragment&&(v.ref=r?Ft(r,u):u),d.cloneElement(l,v)}return d.Children.count(l)>1?d.Children.only(null):null});return t.displayName=`${s}.SlotClone`,t}var xr=Symbol("radix.slottable");function pr(s){return d.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===xr}function hr(s,t){const a={...t};for(const r in t){const l=s[r],m=t[r];/^on[A-Z]/.test(r)?l&&m?a[r]=(...v)=>{const S=m(...v);return l(...v),S}:l&&(a[r]=l):r==="style"?a[r]={...l,...m}:r==="className"&&(a[r]=[l,m].filter(Boolean).join(" "))}return{...s,...a}}function gr(s){let t=Object.getOwnPropertyDescriptor(s.props,"ref")?.get,a=t&&"isReactWarning"in t&&t.isReactWarning;return a?s.ref:(t=Object.getOwnPropertyDescriptor(s,"ref")?.get,a=t&&"isReactWarning"in t&&t.isReactWarning,a?s.props.ref:s.props.ref||s.ref)}var fr=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],pt=fr.reduce((s,t)=>{const a=ur(`Primitive.${t}`),r=d.forwardRef((l,m)=>{const{asChild:u,...v}=l,S=u?a:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),e.jsx(S,{...v,ref:m})});return r.displayName=`Primitive.${t}`,{...s,[t]:r}},{}),te="Accordion",br=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[As,jr,vr]=Gt(te),[Ge]=qt(te,[vr,ot]),ks=ot(),ht=Q.forwardRef((s,t)=>{const{type:a,...r}=s,l=r,m=r;return e.jsx(As.Provider,{scope:s.__scopeAccordion,children:a==="multiple"?e.jsx(Cr,{...m,ref:t}):e.jsx(wr,{...l,ref:t})})});ht.displayName=te;var[gt,Nr]=Ge(te),[ft,yr]=Ge(te,{collapsible:!1}),wr=Q.forwardRef((s,t)=>{const{value:a,defaultValue:r,onValueChange:l=()=>{},collapsible:m=!1,...u}=s,[v,S]=st({prop:a,defaultProp:r??"",onChange:l,caller:te});return e.jsx(gt,{scope:s.__scopeAccordion,value:Q.useMemo(()=>v?[v]:[],[v]),onItemOpen:S,onItemClose:Q.useCallback(()=>m&&S(""),[m,S]),children:e.jsx(ft,{scope:s.__scopeAccordion,collapsible:m,children:e.jsx(bt,{...u,ref:t})})})}),Cr=Q.forwardRef((s,t)=>{const{value:a,defaultValue:r,onValueChange:l=()=>{},...m}=s,[u,v]=st({prop:a,defaultProp:r??[],onChange:l,caller:te}),S=Q.useCallback(P=>v((A=[])=>[...A,P]),[v]),T=Q.useCallback(P=>v((A=[])=>A.filter(M=>M!==P)),[v]);return e.jsx(gt,{scope:s.__scopeAccordion,value:u,onItemOpen:S,onItemClose:T,children:e.jsx(ft,{scope:s.__scopeAccordion,collapsible:!0,children:e.jsx(bt,{...m,ref:t})})})}),[Tr,qe]=Ge(te),bt=Q.forwardRef((s,t)=>{const{__scopeAccordion:a,disabled:r,dir:l,orientation:m="vertical",...u}=s,v=Q.useRef(null),S=Ht(v,t),T=jr(a),A=Kt(l)==="ltr",M=Wt(s.onKeyDown,N=>{if(!br.includes(N.key))return;const g=N.target,p=T().filter($=>!$.ref.current?.disabled),j=p.findIndex($=>$.ref.current===g),U=p.length;if(j===-1)return;N.preventDefault();let f=j;const B=0,x=U-1,h=()=>{f=j+1,f>x&&(f=B)},D=()=>{f=j-1,f<B&&(f=x)};switch(N.key){case"Home":f=B;break;case"End":f=x;break;case"ArrowRight":m==="horizontal"&&(A?h():D());break;case"ArrowDown":m==="vertical"&&h();break;case"ArrowLeft":m==="horizontal"&&(A?D():h());break;case"ArrowUp":m==="vertical"&&D();break}const z=f%U;p[z].ref.current?.focus()});return e.jsx(Tr,{scope:a,disabled:r,direction:l,orientation:m,children:e.jsx(As.Slot,{scope:a,children:e.jsx(pt.div,{...u,"data-orientation":m,ref:S,onKeyDown:r?void 0:M})})})}),Le="AccordionItem",[Er,Is]=Ge(Le),jt=Q.forwardRef((s,t)=>{const{__scopeAccordion:a,value:r,...l}=s,m=qe(Le,a),u=Nr(Le,a),v=ks(a),S=$t(),T=r&&u.value.includes(r)||!1,P=m.disabled||s.disabled;return e.jsx(Er,{scope:a,open:T,disabled:P,triggerId:S,children:e.jsx(Ma,{"data-orientation":m.orientation,"data-state":Tt(T),...v,...l,ref:t,disabled:P,open:T,onOpenChange:A=>{A?u.onItemOpen(r):u.onItemClose(r)}})})});jt.displayName=Le;var vt="AccordionHeader",Nt=Q.forwardRef((s,t)=>{const{__scopeAccordion:a,...r}=s,l=qe(te,a),m=Is(vt,a);return e.jsx(pt.h3,{"data-orientation":l.orientation,"data-state":Tt(m.open),"data-disabled":m.disabled?"":void 0,...r,ref:t})});Nt.displayName=vt;var js="AccordionTrigger",yt=Q.forwardRef((s,t)=>{const{__scopeAccordion:a,...r}=s,l=qe(te,a),m=Is(js,a),u=yr(js,a),v=ks(a);return e.jsx(As.ItemSlot,{scope:a,children:e.jsx(Ua,{"aria-disabled":m.open&&!u.collapsible||void 0,"data-orientation":l.orientation,id:m.triggerId,...v,...r,ref:t})})});yt.displayName=js;var wt="AccordionContent",Ct=Q.forwardRef((s,t)=>{const{__scopeAccordion:a,...r}=s,l=qe(te,a),m=Is(wt,a),u=ks(a);return e.jsx(Ba,{role:"region","aria-labelledby":m.triggerId,"data-orientation":l.orientation,...u,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...s.style}})});Ct.displayName=wt;function Tt(s){return s?"open":"closed"}var Ar=ht,kr=jt,Ir=Nt,Sr=yt,Pr=Ct;function Mr({...s}){return e.jsx(Ar,{"data-slot":"accordion",...s})}function Ur({className:s,...t}){return e.jsx(kr,{"data-slot":"accordion-item",className:q("border-b last:border-b-0",s),...t})}function Br({className:s,children:t,...a}){return e.jsx(Ir,{className:"flex",children:e.jsxs(Sr,{"data-slot":"accordion-trigger",className:q("focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",s),...a,children:[t,e.jsx(Qt,{className:"text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200"})]})})}function Rr({className:s,children:t,...a}){return e.jsx(Pr,{"data-slot":"accordion-content",className:"data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm",...a,children:e.jsx("div",{className:q("pt-0 pb-4",s),children:t})})}const ae=3,is=20,_r=[{value:"TEXT",label:"Texto Simple",icon:e.jsx(xs,{className:"h-4 w-4"}),description:"Mensaje de texto básico"},{value:"MEDIA",label:"Multimedia",icon:e.jsx(dt,{className:"h-4 w-4"}),description:"Imagen, video o documento"},{value:"INTERACTIVE",label:"Interactivo",icon:e.jsx(Ns,{className:"h-4 w-4"}),description:"Botones y respuestas rápidas"}],Or=()=>{const s=le(n=>n.isEditorOpen),t=le(n=>n.selectedTemplateId),a=le(n=>n.closeEditor),{data:r=[]}=ws(),{data:l,isLoading:m,error:u,refetch:v,isFetching:S}=ua(t),T=Ha(),P=Ka(),{data:A}=fa(),{currentOrganization:M}=Js(),[N,g]=d.useState(null),[p,j]=d.useState(!1),[U,f]=d.useState(null),[B,x]=d.useState(!1),[h,D]=d.useState("TEXT"),[z,$]=d.useState({name:"",categoryId:"",shortcut:"",content:"",tags:[],supportedChannels:["WHATSAPP","WEB","INSTAGRAM","FACEBOOK"],visibility:"ORGANIZATION",teamIds:[],status:"ACTIVE"}),[I,i]=d.useState(null),[k,L]=d.useState(!1),[o,b]=d.useState({header:"",body:"",footer:"",displayMode:"buttons",menuButton:"",buttons:[],media:null,carouselCards:[]}),[W,ie]=d.useState(new Set),[Ie,Ss]=d.useState("quick_reply"),Ps=d.useCallback(n=>{Ss(n),b(c=>({...c,carouselCards:(c.carouselCards||[]).map(y=>n==="cta_url"?{id:y.id,imageGcsPath:y.imageGcsPath,thumbnailUrl:y.thumbnailUrl,cardBody:y.cardBody,urlButton:y.urlButton||{title:"Ver",url:""}}:{id:y.id,imageGcsPath:y.imageGcsPath,thumbnailUrl:y.thumbnailUrl,cardBody:y.cardBody,buttons:y.buttons?.length?y.buttons:[{id:`btn-${crypto.randomUUID().slice(0,8)}`,label:"Elegir"}]})}))},[]),X=o.displayMode==="list"||o.buttons.length>ae,Z=o.displayMode==="carousel",Ms=10,At=24,$e=72;dr();const F=ma({maxDurationSeconds:300}),kt=async()=>{i(null),await F.startRecording()},It=async()=>{if(!F.audioBlob||!F.audioUrl)return;const n=await F.audioBlob.arrayBuffer(),c=await crypto.subtle.digest("SHA-256",n),E=Array.from(new Uint8Array(c)).map(V=>V.toString(16).padStart(2,"0")).join(""),R=new File([F.audioBlob],`audio_note_${Date.now()}.webm`,{type:F.audioBlob.type,lastModified:Date.now()});i({file:R,previewUrl:F.audioUrl,detectedType:"AUDIO",mimeType:R.type,originalName:R.name,fileSize:R.size,signedUrl:F.audioUrl,gcsPath:"",hash:E}),F.cancelRecording()},{channels:ee,isLoading:Se,allowAll:ce,setAllowAll:He}=cr(I,k);d.useEffect(()=>{if(!ce||Se||ee.length===0)return;const n=bs(ee.map(y=>y.channelType),ee),c=z.supportedChannels||[];(n.length!==c.length||!n.every(y=>c.includes(y)))&&se("supportedChannels",n)},[ce,Se,ee,z.supportedChannels]);const Ke=d.useRef({}),[Us,Bs]=d.useState("");d.useEffect(()=>{u&&t&&(C.error("Error al cargar la plantilla"),a())},[u,t,a]),d.useEffect(()=>{if(l)if(He(!1),$({name:l.name,categoryId:l.categoryId,shortcut:l.shortcut?l.shortcut.replace(/^\/+/,""):"",content:l.content||"",tags:l.tags||[],supportedChannels:l.supportedChannels||["WHATSAPP","WEB"],visibility:l.visibility||"ORGANIZATION",teamIds:l.teamIds||[],status:l.status||"ACTIVE"}),l.contentType==="INTERACTIVE"){if(D("INTERACTIVE"),l.interactive){const n=l.interactive.header,c=String(n?.type||"").toLowerCase(),y=c==="image"||c==="video"||c==="document",E=l.interactive.type==="list",R=l.interactive.type==="carousel";if(R){const w=l.interactive.cards||[];Ss(w.some(O=>O.urlButton)?"cta_url":"quick_reply")}const V=E?(l.interactive.sections||[]).flatMap(w=>w.rows||[]):[];b({header:y?"":n?.text||"",body:l.interactive.body?.text||l.content||"",footer:l.interactive.footer?.text||"",displayMode:R?"carousel":E?"list":"buttons",carouselCards:R?(l.interactive.cards||[]).map(w=>({imageGcsPath:w.imageGcsPath,thumbnailUrl:w.thumbnailUrl,cardBody:w.cardBody,buttons:w.buttons,urlButton:w.urlButton})):[],menuButton:l.interactive.menuButton||"",buttons:E?V.map((w,O)=>({id:w.id||`btn-${O}`,text:w.title||"",description:w.description})):l.interactive.buttons?.map((w,O)=>({id:w.id||`btn-${O}`,text:w.title||""}))||[],media:y&&n?.mediaGcsPath?{gcsPath:n.mediaGcsPath,signedUrl:n.mediaUrl||"",previewUrl:n.mediaUrl||"",mimeType:n.mediaMimeType||"",detectedType:c.toUpperCase(),originalName:n.mediaOriginalName}:null})}}else if(l.mediaGcsPath){const n=l.contentType==="DOCUMENT";D("MEDIA"),L(n),i({gcsPath:l.mediaGcsPath,signedUrl:l.mediaUrl||"",mimeType:l.mediaMimeType||"",detectedType:n?"DOCUMENT":it(l.mediaMimeType||"")?.toUpperCase()||"IMAGE",fileSize:l.fileSize?Number(l.fileSize):void 0,originalName:l.mediaOriginalName,thumbnailUrl:l.thumbnailUrl})}else D("TEXT");else He(!0),$({name:"",categoryId:r[0]?.id||"",shortcut:"",content:"",tags:[],supportedChannels:["WHATSAPP","WEB","INSTAGRAM","FACEBOOK"],visibility:"ORGANIZATION",teamIds:[],status:"ACTIVE"}),D("TEXT"),i(null),L(!1),b({header:"",body:"",footer:"",displayMode:"buttons",menuButton:"",buttons:[],media:null}),ie(new Set);j(!1)},[l,s,r]),d.useEffect(()=>{s&&t?(x(!0),J.getTemplateUsageHistory(t,30,!1).then(n=>{f({totalUsage:n.totalUsage,uniqueUsers:n.uniqueUsers})}).catch(n=>{console.error("Failed to fetch template analytics:",n),f(null)}).finally(()=>{x(!1)})):f(null)},[s,t]);const St=d.useCallback(()=>{t&&(x(!0),J.clearAnalyticsCache(t),J.getTemplateUsageHistory(t,30,!0).then(n=>{f({totalUsage:n.totalUsage,uniqueUsers:n.uniqueUsers}),C.success("Estadísticas actualizadas")}).catch(()=>{C.error("Error al actualizar estadísticas")}).finally(()=>{x(!1)}))},[t]),se=(n,c)=>{$(y=>({...y,[n]:c}))},pe=n=>c=>{Ke.current[n]=c},he=n=>{g(n)},We=n=>{if(!N){C.info("Haz click en un campo de texto para insertar la variable");return}const c=Ke.current[N];if(!c)return;const y=c.selectionStart||0,E=c.selectionEnd||0,R=c.value,V=`{{ ${n}}}`,w=R.substring(0,y)+V+R.substring(E);if(N==="content")se("content",w);else if(N.startsWith("int_")){const O=N.replace("int_","");if(O==="buttons")return;b(de=>({...de,[O]:w}))}else if(N.startsWith("btn_")){const O=parseInt(N.split("_")[1]),de=[...o.buttons];de[O]&&(de[O].text=w.slice(0,is),b(Bt=>({...Bt,buttons:de})))}setTimeout(()=>{c.focus(),c.setSelectionRange(y+V.length,y+V.length)},0)},[Qe,Pe]=d.useState(!1),Xe=n=>{if(!N){C.info("Haz click en un campo de texto para insertar el emoji");return}const c=Ke.current[N];if(!c)return;const y=c.selectionStart||0,E=c.selectionEnd||0,R=c.value,V=R.substring(0,y)+n+R.substring(E);if(N==="content")se("content",V);else if(N.startsWith("int_")){const w=N.replace("int_","");if(w==="buttons")return;b(O=>({...O,[w]:V}))}else if(N.startsWith("btn_")){const w=parseInt(N.split("_")[1]),O=[...o.buttons];O[w]&&(O[w].text=V.slice(0,is),b(de=>({...de,buttons:O})))}Pe(!1),setTimeout(()=>{c.focus(),c.setSelectionRange(y+n.length,y+n.length)},0)},{handleSubmit:Pt,isSaving:Rs}=tr({formData:z,contentType:h,mediaData:I,interactiveData:o,sendAsDocument:k,compatibleChannels:ee,selectedTemplate:l,createTemplate:T.mutateAsync,updateTemplate:n=>P.mutateAsync({id:l?.id||"",data:n}),onButtonErrors:ie,onSuccess:()=>{a()}}),_s=Cs(new Date,{style:"time-only"}),Mt=z.name&&z.categoryId,Ut=()=>{const n=h==="INTERACTIVE"?o.body:z.content;ge(n||"",ne),h==="INTERACTIVE"&&o.header&&ge(o.header,ne),h==="INTERACTIVE"&&o.footer&&ge(o.footer,ne);const c=I?I.previewUrl||I.thumbnailUrl||I.signedUrl:null;I?.detectedType;const y=Z?{kind:"carousel",body:"",cards:(o.carouselCards||[]).map(E=>({header:{type:"image",thumbnailUrl:E.thumbnailUrl},body:E.cardBody,buttons:E.urlButton?[{type:"cta_url",title:E.urlButton.title,url:E.urlButton.url}]:(E.buttons||[]).map(R=>({type:"quick_reply",title:R.label,id:R.id}))}))}:null;return!n&&!I&&h!=="INTERACTIVE"?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-center p-8 text-muted-foreground/60",children:[e.jsx(xs,{className:"h-12 w-12 mb-3 opacity-20"}),e.jsx("p",{className:"text-sm",children:"Configura tu plantilla para ver la vista previa en tiempo real"})]}):e.jsxs("div",{className:"flex flex-col items-end gap-1 animate-in fade-in slide-in-from-bottom-4 duration-500 w-full",children:[e.jsxs("div",{className:"bg-white dark:bg-[#005C4B] rounded-xl shadow-sm min-w-[50%] max-w-[85%] overflow-hidden relative group/bubble self-end mr-1",children:[h==="MEDIA"&&I&&e.jsx("div",{className:"relative overflow-hidden cursor-pointer group/media bg-[#e8e8e8] dark:bg-[#1a2a32]",onClick:()=>j(!0),children:I.detectedType==="IMAGE"?e.jsx(ye,{src:c||"",className:"w-full h-auto max-h-[200px] object-cover",alt:"Media"}):I.detectedType==="VIDEO"?e.jsxs("div",{className:"w-full aspect-video bg-[#1a1a1a] relative",children:[I.thumbnailUrl?e.jsx(ye,{src:I.thumbnailUrl,className:"w-full h-full object-cover",alt:""}):e.jsx("div",{className:"w-full h-full bg-gradient-to-br from-gray-700 to-gray-900 flex items-center justify-center",children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"w-12 h-12 text-white/30",children:e.jsx("path",{d:"M18 4l2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4h-4z"})})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:e.jsx("div",{className:"bg-black/50 backdrop-blur-sm rounded-full p-3 shadow-lg",children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"w-6 h-6 text-white",children:e.jsx("path",{d:"M8 5v14l11-7z"})})})})]}):e.jsxs("div",{className:"bg-[#f0f2f5] dark:bg-[#202c33] flex items-center gap-3 w-full p-3",children:[e.jsx("div",{className:"h-10 w-8 shrink-0",children:I.detectedType==="AUDIO"?e.jsx(Je,{type:"AUDIO",className:"h-full w-full"}):e.jsx(Je,{type:"DOCUMENT",subtype:I.mimeType,className:"h-full w-full"})}),e.jsxs("div",{className:"flex-1 min-w-0 pr-1",children:[e.jsx("p",{className:"text-[13px] font-normal truncate text-[#111b21] dark:text-[#e9edef] leading-tight block w-full",children:I.originalName||"documento.pdf"}),e.jsxs("p",{className:"text-[11px] opacity-60 text-[#111b21] dark:text-[#e9edef] truncate",children:[I.fileSize?Ve(I.fileSize):"—"," • ",I.mimeType.split("/")[1]?.toUpperCase()||"PDF"]})]})]})}),h==="INTERACTIVE"&&o.media&&(()=>{const E=o.media,R=E.previewUrl||E.thumbnailUrl||E.signedUrl||"",V=String(E.detectedType||"").toUpperCase();return e.jsx("div",{className:"relative overflow-hidden bg-[#e8e8e8] dark:bg-[#1a2a32]",children:V==="IMAGE"?e.jsx(ye,{src:R,className:"w-full h-auto max-h-[200px] object-cover",alt:"Header media"}):V==="VIDEO"?e.jsxs("div",{className:"w-full aspect-video bg-[#1a1a1a] relative",children:[E.thumbnailUrl?e.jsx(ye,{src:E.thumbnailUrl,className:"w-full h-full object-cover",alt:""}):e.jsx("div",{className:"w-full h-full bg-gradient-to-br from-gray-700 to-gray-900"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:e.jsx("div",{className:"bg-black/50 backdrop-blur-sm rounded-full p-3 shadow-lg",children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"w-6 h-6 text-white",children:e.jsx("path",{d:"M8 5v14l11-7z"})})})})]}):e.jsxs("div",{className:"bg-[#f0f2f5] dark:bg-[#202c33] flex items-center gap-3 w-full p-3",children:[e.jsx("div",{className:"h-10 w-8 shrink-0",children:e.jsx(Je,{type:"DOCUMENT",subtype:E.mimeType,className:"h-full w-full"})}),e.jsxs("div",{className:"flex-1 min-w-0 pr-1",children:[e.jsx("p",{className:"text-[13px] font-normal truncate text-[#111b21] dark:text-[#e9edef] leading-tight block w-full",children:E.originalName||"documento.pdf"}),e.jsx("p",{className:"text-[11px] opacity-60 text-[#111b21] dark:text-[#e9edef] truncate",children:E.mimeType?.split("/")[1]?.toUpperCase()||"DOC"})]})]})})})(),h==="INTERACTIVE"&&!Z&&!o.media&&o.header&&e.jsx("div",{className:"px-3 pt-3 pb-1",children:e.jsx("p",{className:"font-bold text-sm text-[#111b21] dark:text-[#e9edef] break-words",children:e.jsx(es,{content:o.header,context:ne})})}),n&&e.jsx("div",{className:"px-3 py-2",children:e.jsx("p",{className:"text-[13px] text-[#111b21] dark:text-[#e9edef] whitespace-pre-wrap leading-relaxed break-words",children:e.jsx(es,{content:n,context:ne})})}),h==="INTERACTIVE"&&!Z&&o.footer&&e.jsx("div",{className:"px-3 pb-1",children:e.jsx("p",{className:"text-[11px] text-[#667781] dark:text-[#8696a0] break-words",children:e.jsx(es,{content:o.footer,context:ne})})}),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:[_s," ",e.jsx(Ze,{className:"h-2.5 w-2.5"})]})})]}),h==="INTERACTIVE"&&!Z&&o.buttons.length>0&&(X?e.jsxs("div",{className:"w-full max-w-[85%] mt-1 self-end mr-1 bg-white dark:bg-[#1F2C34] rounded-lg shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 py-2 px-4 text-[#00A884] font-medium text-[13px] border-b border-black/5 dark:border-white/10",children:[e.jsx(gs,{className:"h-3.5 w-3.5"})," ",o.menuButton?.trim()||"Ver opciones"]}),e.jsx("div",{className:"max-h-[220px] overflow-y-auto",children:o.buttons.map(E=>e.jsxs("div",{className:"px-4 py-2 border-b border-black/5 dark:border-white/10 last:border-b-0",children:[e.jsx("p",{className:"text-[13px] font-medium text-[#111b21] dark:text-[#e9edef] truncate",children:ge(E.text||"Opción",ne)}),E.description?.trim()&&e.jsx("p",{className:"text-[11px] text-[#667781] dark:text-[#8696a0] truncate",children:ge(E.description,ne)})]},E.id))})]}):e.jsx("div",{className:"w-full max-w-[85%] space-y-1 mt-1 self-end mr-1",children:o.buttons.map(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 cursor-pointer hover:bg-gray-50 transition-colors truncate",children:ge(E.text||"Botón",ne)},E.id))})),h==="INTERACTIVE"&&y&&y.cards.length>0&&e.jsx("div",{className:"w-full max-w-[92%] mt-1 self-end mr-1",children:e.jsx(ha,{content:y,disabled:!0})})]})};return e.jsxs(Re,{open:s,onOpenChange:a,children:[e.jsxs(_e,{className:"sm:max-w-[1100px] h-[90vh] max-h-[90vh] p-0 gap-0 overflow-hidden flex flex-col bg-background/95 backdrop-blur-xl",children:[e.jsxs("div",{className:"h-16 border-b flex items-center justify-between px-6 bg-background/50 z-20 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary",children:l?e.jsx(xs,{className:"h-5 w-5"}):e.jsx(ue,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx(Ae,{className:"text-lg font-semibold tracking-tight",children:l?"Editar Plantilla":"Nueva Plantilla"}),e.jsx(Oe,{className:"text-xs",children:l?"Modifica los parámetros de tu plantilla":"Crea una respuesta predefinida"})]})]}),l&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ze,{children:e.jsxs(be,{children:[e.jsx(je,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 cursor-help",children:[e.jsxs(Y,{variant:"outline",className:"gap-1.5 py-1 px-2.5 bg-purple-500/10 border-purple-500/30",children:[e.jsx(Ts,{className:"h-3 w-3 text-purple-500"}),e.jsxs("span",{className:"text-xs font-medium",children:[B?"...":U?.totalUsage??0," usos"]})]}),e.jsxs(Y,{variant:"outline",className:"gap-1.5 py-1 px-2.5 bg-blue-500/10 border-blue-500/30",children:[e.jsx(Xt,{className:"h-3 w-3 text-blue-500"}),e.jsxs("span",{className:"text-xs font-medium",children:[B?"...":U?.uniqueUsers??0," usuarios"]})]})]})}),e.jsx(ve,{children:e.jsx("p",{children:"Estadísticas de los últimos 30 días"})})]})}),e.jsx(_,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:St,disabled:B,title:"Actualizar estadísticas",children:e.jsx(Zt,{className:q("h-4 w-4",B&&"animate-spin")})})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_,{variant:"ghost",onClick:a,children:"Cancelar"}),e.jsxs(_,{onClick:Pt,disabled:Rs||!Mt,className:"px-6",children:[Rs&&e.jsx(oe,{className:"h-4 w-4 animate-spin mr-2"}),l?"Guardar Cambios":"Crear Plantilla"]})]})]}),e.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[e.jsxs("div",{className:"flex-1 overflow-y-auto custom-scrollbar bg-background",children:[e.jsxs("div",{className:"p-8 max-w-2xl mx-auto space-y-8",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsxs("h3",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2",children:[e.jsx("span",{className:"h-px bg-border flex-1"}),"Configuración General",e.jsx("span",{className:"h-px bg-border flex-1"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-5",children:[e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(G,{children:"Nombre de la plantilla"}),e.jsx(H,{value:z.name,onChange:n=>se("name",n.target.value),placeholder:"Ej: Bienvenida Clientes 2024",className:"h-11 bg-muted/30",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{children:"Categoría"}),e.jsxs(cs,{value:z.categoryId,onValueChange:n=>se("categoryId",n),children:[e.jsx(ds,{className:"h-11 bg-muted/30",children:e.jsx(us,{placeholder:"Seleccionar..."})}),e.jsx(ms,{children:r.map(n=>e.jsx(re,{value:n.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2 w-2 rounded-full",style:{backgroundColor:n.color??void 0}}),n.name]})},n.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{children:"Atajo Rápido (Slash Command)"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground font-mono",children:"/"}),e.jsx(H,{value:z.shortcut,onChange:n=>se("shortcut",n.target.value.replace(/[/\s"'.,]/g,"")),placeholder:"bienvenida",className:"h-11 pl-7 bg-muted/30 font-mono text-sm"})]})]})]})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("h3",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2",children:[e.jsx("span",{className:"h-px bg-border flex-1"}),"Diseño del Mensaje",e.jsx("span",{className:"h-px bg-border flex-1"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3 p-1 bg-muted/40 rounded-xl border border-border/50",children:_r.map(n=>e.jsxs("button",{type:"button",onClick:()=>{D(n.value)},className:q("flex flex-col items-center justify-center gap-1.5 py-3 px-2 rounded-lg transition-all duration-200",h===n.value?"bg-white dark:bg-zinc-800 shadow-sm text-primary ring-1 ring-border":"text-muted-foreground hover:bg-muted/50 hover:text-foreground"),children:[n.icon,e.jsx("span",{className:"text-xs font-medium",children:n.label})]},n.value))}),e.jsxs("div",{className:"space-y-6 pt-2",children:[h==="MEDIA"&&e.jsxs("div",{className:"animate-in fade-in zoom-in-95 duration-300",children:[e.jsx(G,{className:"mb-2 block",children:"Multimedia"}),e.jsxs(ba,{defaultValue:"upload",className:"w-full",children:[e.jsxs(ja,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(Ls,{value:"upload",className:"flex items-center gap-2",children:[e.jsx(Oa,{className:"h-4 w-4"}),"Subir Archivo"]}),e.jsxs(Ls,{value:"record",className:"flex items-center gap-2",children:[e.jsx(ps,{className:"h-4 w-4"}),"Grabar Audio"]})]}),e.jsx(Fs,{value:"upload",className:"mt-0",children:e.jsx(Vs,{onUpload:i,currentMedia:I,onRemove:()=>i(null),maxSizeMB:A?.maxSizeMB||100,compatibleChannels:ee,forceOriginal:k})}),e.jsx(Fs,{value:"record",className:"mt-0",children:e.jsx("div",{className:"border-2 border-dashed border-muted-foreground/25 rounded-xl p-8 flex flex-col items-center justify-center gap-4 bg-muted/5 min-h-[220px]",children:F.status==="idle"||F.status==="requesting"?e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx(_,{variant:"outline",size:"lg",className:"h-20 w-20 rounded-full border-4 border-primary/20 hover:border-primary/40 hover:bg-primary/5 transition-all",onClick:kt,children:e.jsx(ps,{className:"h-8 w-8 text-primary"})}),e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Click para grabar"})]}):F.status==="recording"||F.status==="paused"?e.jsxs("div",{className:"flex flex-col items-center gap-4 w-full max-w-xs",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:"h-2.5 w-2.5 rounded-full bg-red-500 animate-pulse"}),e.jsxs("span",{className:"font-mono text-xl font-bold tabular-nums",children:[Math.floor(F.recordingTime/60),":",(F.recordingTime%60).toString().padStart(2,"0")]})]}),e.jsx("div",{className:"flex items-center gap-1 h-12 w-full justify-center opacity-50",children:[...Array(12)].map((n,c)=>e.jsx("div",{className:"w-1.5 bg-primary rounded-full animate-bounce",style:{height:`${Math.random()*100}%`,animationDelay:`${c*.1}s`,animationDuration:"0.8s"}},c))}),e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx(_,{variant:"destructive",size:"icon",className:"rounded-full h-12 w-12 hover:scale-105 transition-transform",onClick:F.cancelRecording,title:"Cancelar",children:e.jsx(fe,{className:"h-5 w-5"})}),e.jsxs(_,{variant:"default",className:"flex-1 rounded-full h-12 text-base font-semibold bg-red-500 hover:bg-red-600 hover:scale-105 transition-all text-white border-none",onClick:F.stopRecording,children:[e.jsx(za,{className:"h-4 w-4 mr-2 fill-current"}),"Detener"]})]})]}):e.jsxs("div",{className:"flex flex-col items-center gap-4 w-full",children:[e.jsxs("div",{className:"w-full bg-background rounded-xl p-4 border shadow-sm flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Ys,{className:"h-4 w-4 text-green-500"}),"Audio grabado"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:[Math.floor(F.recordingTime/60),":",(F.recordingTime%60).toString().padStart(2,"0")]})]}),F.audioUrl&&e.jsx("audio",{src:F.audioUrl,controls:!0,className:"w-full h-8"})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsxs(_,{variant:"outline",className:"flex-1 gap-2",onClick:F.cancelRecording,children:[e.jsx(Ra,{className:"h-4 w-4"}),"Reintentar"]}),e.jsxs(_,{variant:"default",className:"flex-1 gap-2",onClick:It,children:[e.jsx(Ze,{className:"h-4 w-4"}),"Usar Audio"]})]})]})})})]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[I&&["IMAGE","VIDEO"].includes(I.detectedType)&&e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/30 border border-border/50",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(G,{htmlFor:"send-as-doc",className:"text-sm font-medium cursor-pointer",children:"Enviar como documento"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Envía el archivo sin compresión (calidad original)"})]}),e.jsx(qs,{id:"send-as-doc",checked:k,onCheckedChange:L})]}),e.jsx(G,{className:"mb-2 block",children:"Caption (Texto acompañante)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-1",children:e.jsx(Ye,{onInsert:We})}),e.jsxs(ss,{open:Qe,onOpenChange:Pe,children:[e.jsx(ts,{asChild:!0,children:e.jsx(_,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(rs,{className:"h-4 w-4"})})}),e.jsx(as,{side:"bottom",align:"end",className:"w-[420px] p-0 shadow-xl rounded-xl overflow-hidden bg-card",children:e.jsx(ns,{onSelect:Xe})})]})]}),e.jsx("div",{className:"relative",children:e.jsx(Ee,{ref:pe("content"),value:z.content,onChange:n=>se("content",n.target.value),onFocus:()=>he("content"),placeholder:"Escribe el mensaje que acompaña la imagen...",className:"min-h-[100px] resize-none pr-2 bg-muted/20 focus:bg-background transition-colors"})})]})]}),h==="TEXT"&&e.jsxs("div",{className:"animate-in fade-in zoom-in-95 duration-300 space-y-3",children:[e.jsx(G,{className:"mb-2 block",children:"Contenido del Mensaje"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-1",children:e.jsx(Ye,{onInsert:We})}),e.jsxs(ss,{open:Qe,onOpenChange:Pe,children:[e.jsx(ts,{asChild:!0,children:e.jsx(_,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(rs,{className:"h-4 w-4"})})}),e.jsx(as,{side:"bottom",align:"end",className:"w-[420px] p-0 shadow-xl rounded-xl overflow-hidden bg-card",children:e.jsx(ns,{onSelect:Xe})})]})]}),e.jsx(Ee,{ref:pe("content"),value:z.content,onChange:n=>se("content",n.target.value),onFocus:()=>he("content"),placeholder:"Hola {{contact.name}}, te escribimos para...",className:"min-h-[180px] text-base p-4 resize-y bg-muted/20 focus:bg-background transition-colors shadow-sm"})]}),h==="INTERACTIVE"&&e.jsxs("div",{className:"space-y-4 animate-in fade-in zoom-in-95 duration-300",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-1",children:e.jsx(Ye,{onInsert:We})}),e.jsxs(ss,{open:Qe,onOpenChange:Pe,children:[e.jsx(ts,{asChild:!0,children:e.jsx(_,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(rs,{className:"h-4 w-4"})})}),e.jsx(as,{side:"bottom",align:"end",className:"w-[420px] p-0 shadow-xl rounded-xl overflow-hidden bg-card",children:e.jsx(ns,{onSelect:Xe})})]})]}),e.jsxs("div",{className:"flex gap-1 p-0.5 rounded-lg bg-muted",children:[e.jsxs("button",{type:"button",onClick:()=>b(n=>({...n,displayMode:"buttons",buttons:n.buttons.length>ae?n.buttons.slice(0,ae):n.buttons})),disabled:o.buttons.length>ae,title:o.buttons.length>ae?`Con más de ${ae} opciones solo cabe el menú`:void 0,className:q("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",!X&&!Z?"bg-background shadow-sm text-foreground font-medium":"text-muted-foreground hover:text-foreground"),children:[e.jsx(hs,{className:"h-3.5 w-3.5"})," Botones"]}),e.jsxs("button",{type:"button",onClick:()=>b(n=>({...n,displayMode:"list"})),className:q("flex-1 flex items-center justify-center gap-1.5 h-8 rounded-md text-[13px] transition-colors",X&&!Z?"bg-background shadow-sm text-foreground font-medium":"text-muted-foreground hover:text-foreground"),children:[e.jsx(gs,{className:"h-3.5 w-3.5"})," Menú (lista)"]}),e.jsxs("button",{type:"button",onClick:()=>b(n=>({...n,displayMode:"carousel"})),className:q("flex-1 flex items-center justify-center gap-1.5 h-8 rounded-md text-[13px] transition-colors",Z?"bg-background shadow-sm text-foreground font-medium":"text-muted-foreground hover:text-foreground"),children:[e.jsx(ct,{className:"h-3.5 w-3.5"})," Carousel"]})]}),!X&&!Z&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Multimedia (Opcional)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Acompaña tu mensaje con imagen, video o documento. Aparecerá arriba del texto y los botones."}),e.jsx(Vs,{onUpload:n=>b(c=>({...c,media:n,header:""})),currentMedia:o.media||null,onRemove:()=>b(n=>({...n,media:null})),maxSizeMB:A?.maxSizeMB||100,compatibleChannels:ee,acceptedTypes:{"image/*":[".jpg",".jpeg",".png",".webp"],"video/*":[".mp4",".3gp"],"application/pdf":[".pdf"],"application/msword":[".doc"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":[".docx"],"application/vnd.ms-excel":[".xls"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":[".xlsx"],"text/plain":[".txt"]}})]}),!Z&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Encabezado (Opcional)"}),e.jsx(H,{ref:pe("int_header"),value:o.header,onChange:n=>b(c=>({...c,header:n.target.value})),onFocus:()=>he("int_header"),placeholder:o.media?"Deshabilitado: ya hay multimedia adjunta":"Ej: ¡Oferta Especial!",disabled:!!o.media,className:"font-medium"}),o.media&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"WhatsApp no permite combinar header de texto con multimedia. Quita el archivo para usar texto."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Mensaje Principal *"}),e.jsx(Ee,{ref:pe("int_body"),value:o.body,onChange:n=>b(c=>({...c,body:n.target.value})),onFocus:()=>he("int_body"),placeholder:"Escribe tu mensaje interactivo aquí...",className:"min-h-[120px] resize-none"})]}),Z&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tarjetas del carrusel"}),e.jsxs("div",{className:"flex gap-1 p-0.5 rounded-lg bg-muted w-fit",children:[e.jsxs("button",{type:"button",onClick:()=>Ps("quick_reply"),className:q("flex items-center gap-1.5 h-7 px-3 rounded-md text-[12px] transition-colors",Ie==="quick_reply"?"bg-background shadow-sm text-foreground font-medium":"text-muted-foreground hover:text-foreground"),children:[e.jsx(ys,{className:"h-3 w-3"})," Respuesta rápida"]}),e.jsxs("button",{type:"button",onClick:()=>Ps("cta_url"),className:q("flex items-center gap-1.5 h-7 px-3 rounded-md text-[12px] transition-colors",Ie==="cta_url"?"bg-background shadow-sm text-foreground font-medium":"text-muted-foreground hover:text-foreground"),children:[e.jsx(vs,{className:"h-3 w-3"})," Enlace (URL)"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["2 a 10 tarjetas, cada una con imagen + ",Ie==="cta_url"?"un botón de enlace (URL)":"botones de respuesta rápida",". Se envía como carrusel de sesión (gratis dentro de la ventana de 24h)."]}),e.jsx(xt,{mode:Ie,cards:o.carouselCards||[],onChange:n=>b(c=>({...c,carouselCards:n}))})]}),!Z&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Pie de página (Opcional)"}),e.jsx(H,{ref:pe("int_footer"),value:o.footer,onChange:n=>b(c=>({...c,footer:n.target.value})),onFocus:()=>he("int_footer"),placeholder:"Ej: Responder 'STOP' para cancelar",className:"text-xs text-muted-foreground"})]}),X&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(G,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Texto del botón del menú"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(o.menuButton||"").length,"/20"]})]}),e.jsx(H,{value:o.menuButton||"",onChange:n=>b(c=>({...c,menuButton:n.target.value.slice(0,20)})),placeholder:"Ver opciones"})]}),!Z&&e.jsxs(e.Fragment,{children:[e.jsx(_a,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(G,{children:X?"Opciones del menú":"Botones de Respuesta"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[o.buttons.length,"/",X?Ms:ae]})]}),o.displayMode!=="list"&&o.buttons.length>ae&&e.jsxs("div",{className:"rounded-md border border-sky-200 bg-sky-50 dark:border-sky-800 dark:bg-sky-950/30 px-3 py-2 text-[11px] text-sky-700 dark:text-sky-300",children:[o.buttons.length," opciones — WhatsApp solo admite ",ae," botones; se enviará como ",e.jsx("strong",{children:"menú"}),"."]}),o.buttons.map((n,c)=>{const y=W.has(c),E=X?At:is;return e.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-2 space-y-1.5",children:[e.jsxs("div",{className:"flex gap-2 items-center",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:c+1}),e.jsx(H,{ref:pe(`btn_${c}`),value:n.text,onChange:R=>{const V=R.target.value.slice(0,E);b(w=>{const O=[...w.buttons];return O[c]={...O[c],text:V},{...w,buttons:O}}),y&&ie(w=>{const O=new Set(w);return O.delete(c),O})},onFocus:()=>he(`btn_${c}`),placeholder:X?`Opción ${c+1}`:`Botón ${c+1}`,maxLength:E,"aria-invalid":y,className:q("h-9 flex-1",y&&"border-destructive focus-visible:ring-destructive/30")}),e.jsxs("span",{className:"text-[10px] tabular-nums text-muted-foreground shrink-0 w-9 text-right",children:[n.text.length,"/",E]}),e.jsx(_,{variant:"ghost",size:"icon",onClick:()=>{b(R=>({...R,buttons:R.buttons.filter((V,w)=>w!==c)})),ie(R=>{const V=new Set;return R.forEach(w=>{w<c?V.add(w):w>c&&V.add(w-1)}),V})},className:"h-8 w-8 shrink-0 text-destructive hover:bg-destructive/10",children:e.jsx(fe,{className:"h-4 w-4"})})]}),X&&e.jsxs("div",{className:"flex gap-2 items-center pl-[26px]",children:[e.jsx(H,{value:n.description||"",onChange:R=>{const V=R.target.value.slice(0,$e);b(w=>{const O=[...w.buttons];return O[c]={...O[c],description:V||void 0},{...w,buttons:O}})},placeholder:"Descripción (opcional)",maxLength:$e,className:"h-7 text-xs flex-1"}),e.jsxs("span",{className:"text-[10px] tabular-nums text-muted-foreground shrink-0 w-9 text-right",children:[(n.description||"").length,"/",$e]})]})]},n.id)}),o.buttons.length<(X?Ms:ae)&&e.jsxs(_,{type:"button",variant:"outline",size:"sm",onClick:()=>b(n=>({...n,buttons:[...n.buttons,{id:`btn-${crypto.randomUUID().slice(0,8)}`,text:""}]})),className:"w-full border-dashed text-muted-foreground",children:[e.jsx(ue,{className:"h-4 w-4 mr-2"})," ",X?"Agregar opción":"Agregar Botón"]})]})]})]})]})]})]}),e.jsx("div",{className:"max-w-2xl mx-auto px-8 pb-10",children:e.jsx(Mr,{type:"single",collapsible:!0,className:"w-full",children:e.jsxs(Ur,{value:"advanced",className:"border-none bg-muted/20 rounded-xl px-4",children:[e.jsx(Br,{className:"hover:no-underline py-4",children:e.jsxs("span",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ns,{className:"h-4 w-4 text-amber-500"})," Opciones Avanzadas"]})}),e.jsxs(Rr,{className:"pt-2 pb-4 space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(G,{children:"Etiquetas de organización"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(H,{value:Us,onChange:n=>Bs(n.target.value),onKeyDown:n=>{if(n.key==="Enter"){n.preventDefault();const c=Us.trim().toLowerCase();c&&!z.tags?.includes(c)&&(se("tags",[...z.tags||[],c]),Bs(""))}},placeholder:"Agregar etiqueta y presionar Enter",className:"h-9"})}),e.jsx("div",{className:"flex flex-wrap gap-2",children:z.tags?.map(n=>e.jsxs(Y,{variant:"outline",className:"gap-1.5 py-1.5 px-3 text-sm font-medium bg-primary/5 text-primary border-primary/20 hover:bg-primary/10 hover:border-primary/30 transition-all group",children:[e.jsx(Yt,{className:"h-3.5 w-3.5 opacity-70"}),n,e.jsx("div",{className:"ml-1 h-4 w-4 rounded-full flex items-center justify-center hover:bg-primary/20 cursor-pointer transition-colors",onClick:()=>se("tags",z.tags?.filter(c=>c!==n)),children:e.jsx(fe,{className:"h-3 w-3"})})]},n))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(G,{children:"Canales Disponibles"}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(qs,{id:"allow-all",checked:ce,onCheckedChange:He}),e.jsx(G,{htmlFor:"allow-all",className:"text-xs font-normal",children:"Permitir en todos"})]})]}),ce&&h==="MEDIA"&&I&&e.jsxs("div",{className:"bg-amber-50 text-amber-800 text-[11px] p-2.5 rounded-lg border border-amber-100 flex items-start gap-2.5 shadow-sm",children:[e.jsx(Jt,{className:"h-4 w-4 shrink-0 text-amber-500"}),e.jsxs("p",{className:"leading-normal",children:[e.jsx("span",{className:"font-bold",children:"Modo de Compatibilidad Extendida:"})," Al habilitar todos los canales, la validación se realizará al enviar. El mensaje podría fallar si excede los límites nativos del canal."]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pb-2",children:[Se?e.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center text-muted-foreground gap-2 bg-muted/5 rounded-xl border border-dashed text-xs italic",children:[e.jsx(oe,{className:"h-4 w-4 animate-spin text-primary/40"}),"Cargando canales..."]}):ee.map(n=>{const c=n.channelType.toLowerCase(),y=er(z.supportedChannels,n),E=!ce&&!n.isCompatible,R=y&&!n.isCompatible&&!ce;return e.jsx(ze,{children:e.jsxs(be,{delayDuration:0,children:[e.jsx(je,{asChild:!0,children:e.jsxs("div",{className:q("flex items-center gap-3 p-3 rounded-xl border transition-all cursor-pointer relative group",E?"bg-gray-50/50 border-gray-100 opacity-60 grayscale cursor-not-allowed":y?"border-primary/40 bg-primary/[0.03] shadow-sm":"bg-card border-border hover:border-border-hover hover:bg-muted/5",R&&"border-destructive/40 bg-destructive/[0.02] shadow-destructive/5"),onClick:()=>{if(E||ce)return;const V=mt(n.channelType,ee);if(!V)return;const w=bs(z.supportedChannels,ee);se("supportedChannels",y?w.filter(O=>O!==V):[...w,V])},children:[e.jsxs("div",{className:q("h-8 w-8 rounded-lg flex items-center justify-center shrink-0 border",y?"bg-primary text-primary-foreground border-primary":"bg-muted/30 text-muted-foreground"),children:[c==="whatsapp"&&e.jsx(wa,{className:"h-4 w-4"}),c==="instagram"&&e.jsx(Da,{className:"h-4 w-4"}),c==="facebook"&&e.jsx(Va,{className:"h-4 w-4"}),c==="web"&&e.jsx(ea,{className:"h-4 w-4"}),!["whatsapp","instagram","facebook","web"].includes(c)&&e.jsx(hs,{className:"h-4 w-4"})]}),e.jsxs("div",{className:"flex-1 min-w-0 pr-6",children:[e.jsx("p",{className:"text-[13px] font-semibold truncate leading-tight",children:n.channelName}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-tight font-medium opacity-70",children:n.channelType}),!n.isCompatible&&e.jsx("p",{className:"text-[9px] text-destructive font-medium leading-tight animate-in fade-in slide-in-from-left-1",children:n.reason?.split("(")[0]})]})]}),e.jsxs("div",{className:"absolute top-3 right-3",children:[y&&e.jsx("div",{className:q("h-4 w-4 rounded-full flex items-center justify-center animate-in zoom-in-50",R?"bg-destructive text-destructive-foreground shadow-sm shadow-destructive/20":"bg-primary text-primary-foreground shadow-sm shadow-primary/20"),children:R?e.jsx(fe,{className:"h-2.5 w-2.5"}):e.jsx(Ze,{className:"h-2.5 w-2.5"})}),!y&&!n.isCompatible&&e.jsx(zs,{className:"h-4 w-4 text-amber-500 opacity-60 group-hover:opacity-100 transition-opacity"})]})]})}),!n.isCompatible&&e.jsx(ve,{side:"top",className:"max-w-[240px] text-[11px] p-2 border-destructive/20 shadow-lg",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(zs,{className:"h-3.5 w-3.5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-bold text-destructive underline decoration-destructive/20",children:"Incompatible con multimedia"}),e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:n.reason||"Este archivo excede los límites definidos para este canal."})]})]})})]})},n.channelId)}),ee.length===0&&!Se&&e.jsx("div",{className:"text-xs text-muted-foreground italic",children:"No hay canales configurados en la organización."})]})]})]})]})})})]}),e.jsxs("div",{className:"w-[420px] bg-muted/10 border-l relative hidden lg:flex flex-col items-center justify-center p-8 bg-[radial-gradient(#e5e7eb_1px,transparent_1px)] dark:bg-[radial-gradient(#1f2937_1px,transparent_1px)] [background-size:16px_16px]",children:[e.jsx("div",{className:"absolute top-6 right-6",children:e.jsx(Y,{variant:"outline",className:"bg-background/80 backdrop-blur text-xs font-normal text-muted-foreground",children:"Vista Previa en Vivo"})}),e.jsx(xa,{time:_s,children:e.jsx("div",{className:"flex justify-end pr-2 pt-4",children:Ut()})}),e.jsx("div",{className:"mt-8 text-center space-y-2",children:e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Esta vista es una aproximación de cómo se verá en WhatsApp.",e.jsx("br",{}),"Los saltos de línea y el formato pueden variar ligeramente."]})})]})]})]}),e.jsx(Re,{open:p,onOpenChange:j,children:e.jsxs(_e,{className:"max-w-[90vw] max-h-[90vh] p-0 overflow-hidden bg-black border-none flex items-center justify-center",children:[e.jsx(Ae,{className:"sr-only",children:"Vista previa de multimedia"}),e.jsxs("div",{className:"relative w-full h-full flex items-center justify-center bg-black",children:[I?.detectedType==="IMAGE"&&e.jsx(ye,{src:I.signedUrl||I.previewUrl||I.thumbnailUrl||"",alt:"Full view",className:"max-w-full max-h-[85vh] object-contain"}),I?.detectedType==="VIDEO"&&e.jsx("div",{className:"w-full max-w-5xl aspect-video",children:e.jsx(pa,{src:I.signedUrl||I.previewUrl||"",className:"w-full h-full",controls:!0,autoPlay:!0})})]}),e.jsx("button",{onClick:()=>j(!1),className:"absolute top-4 right-4 p-2 bg-black/50 text-white rounded-full hover:bg-black/70 transition-colors",children:e.jsx(fe,{className:"h-6 w-6"})})]})})]})},Me=["#3B82F6","#10B981","#F59E0B","#EF4444","#8B5CF6","#EC4899","#06B6D4","#F97316"],zr=({isOpen:s,onClose:t})=>{const{data:a=[]}=ws(),{data:r}=lt(),l=r?.data??[],m=Qa(),u=Xa(),v=Za(),[S,T]=d.useState("list"),[P,A]=d.useState(null),[M,N]=d.useState(!1),[g,p]=d.useState(""),[j,U]=d.useState(""),[f,B]=d.useState(Me[0]),[x,h]=d.useState("");d.useEffect(()=>{s&&(T("list"),A(null))},[s]),d.useEffect(()=>{P?(p(P.name),U(P.description||""),B(P.color||Me[0]),h(P.shortcut||"")):(p(""),U(""),B(Me[0]),h(""))},[P]);const D=o=>l.filter(b=>b.categoryId===o).length,z=()=>{A(null),T("form")},$=o=>{A(o),T("form")},I=()=>{T("list"),A(null)},i=async o=>{const b=D(o.id);if(b>0){C.error(`No se puede eliminar: tiene ${b} plantillas asociadas`);return}confirm(`¿Eliminar categoría "${o.name}"?`)&&v.mutate(o.id)},k=async()=>{if(!g.trim()){C.error("El nombre es requerido");return}N(!0);try{const o={name:g,description:j,color:f,shortcut:x.trim()||void 0};P?await u.mutateAsync({id:P.id,data:o}):await m.mutateAsync(o),T("list"),A(null)}catch{C.error("Error al guardar categoría")}finally{N(!1)}},L=()=>{T("list"),A(null),t()};return e.jsx(Re,{open:s,onOpenChange:L,children:e.jsx(_e,{className:"sm:max-w-lg",children:S==="list"?e.jsxs(e.Fragment,{children:[e.jsxs(os,{children:[e.jsx(Ae,{children:"Gestionar Categorías"}),e.jsx(Oe,{children:"Organiza tus plantillas en categorías para encontrarlas más fácil"})]}),e.jsx("div",{className:"space-y-2 max-h-[350px] overflow-y-auto py-2",children:a.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(fs,{className:"h-12 w-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No hay categorías creadas"}),e.jsx("p",{className:"text-xs mt-1",children:"Crea tu primera categoría para organizar plantillas"})]}):a.map(o=>{const b=D(o.id);return e.jsxs("div",{className:"flex items-center justify-between p-3 border border-border rounded-lg hover:bg-muted/50 transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:o.color||"#3B82F6"},children:e.jsx(fs,{className:"h-4 w-4 text-white"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:o.name}),o.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:o.description}),o.shortcut&&e.jsxs("p",{className:"text-xs text-primary/70 font-mono",children:["/",o.shortcut,"/"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{variant:"secondary",className:"text-xs shrink-0",children:b}),e.jsx(_,{variant:"ghost",size:"sm",onClick:()=>$(o),className:"h-8 w-8 p-0 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Es,{className:"h-4 w-4"})}),e.jsx(_,{variant:"ghost",size:"sm",onClick:()=>i(o),className:"h-8 w-8 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive",disabled:b>0,children:e.jsx(ke,{className:"h-4 w-4"})})]})]},o.id)})}),e.jsxs(Ds,{children:[e.jsx(_,{variant:"outline",onClick:L,children:"Cerrar"}),e.jsxs(_,{onClick:z,className:"gap-2",children:[e.jsx(ue,{className:"h-4 w-4"}),"Nueva Categoría"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(os,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(_,{variant:"ghost",size:"sm",onClick:I,className:"h-8 w-8 p-0 shrink-0",children:e.jsx(Fa,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx(Ae,{children:P?"Editar Categoría":"Nueva Categoría"}),e.jsx(Oe,{children:P?"Modifica los detalles de la categoría":"Crea una nueva categoría para organizar plantillas"})]})]})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{htmlFor:"cat-name",children:"Nombre *"}),e.jsx(H,{id:"cat-name",value:g,onChange:o=>p(o.target.value),placeholder:"Ej: Saludos, Despedidas, FAQ",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{htmlFor:"cat-desc",children:"Descripción"}),e.jsx(Ee,{id:"cat-desc",value:j,onChange:o=>U(o.target.value),placeholder:"Descripción opcional de la categoría",rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(G,{htmlFor:"cat-shortcut",children:["Atajo de búsqueda",e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:"(auto-generado si se deja vacío)"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"/"}),e.jsx(H,{id:"cat-shortcut",value:x,onChange:o=>h(o.target.value.toLowerCase().replace(/[^a-z0-9]/g,"")),placeholder:g?g.toLowerCase().replace(/[^a-z0-9]/g,""):"ejemplo",className:"font-mono"}),e.jsx("span",{className:"text-muted-foreground",children:"/"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Usa este atajo para buscar rápido: /",x||g.toLowerCase().replace(/[^a-z0-9]/g,"")||"ejemplo","/"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{children:"Color"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Me.map(o=>e.jsx("button",{type:"button",onClick:()=>B(o),className:`h-8 w-8 rounded-lg transition-all ${f===o?"ring-2 ring-offset-2 ring-primary scale-110":"hover:scale-105"}`,style:{backgroundColor:o}},o))})]})]}),e.jsxs(Ds,{children:[e.jsx(_,{variant:"outline",onClick:I,children:"Cancelar"}),e.jsxs(_,{onClick:k,disabled:M,children:[M&&e.jsx(oe,{className:"h-4 w-4 mr-2 animate-spin"}),P?"Guardar Cambios":"Crear Categoría"]})]})]})})})},Fe=({type:s,className:t="h-4 w-4"})=>({TEXT:e.jsx(hs,{className:t}),IMAGE:e.jsx(dt,{className:t}),VIDEO:e.jsx(La,{className:t}),AUDIO:e.jsx(ps,{className:t}),DOCUMENT:e.jsx(Ga,{className:t}),INTERACTIVE:e.jsx(ct,{className:t})})[s]||e.jsx(De,{className:t}),Dr=s=>({TEXT:"Texto",IMAGE:"Imagen",VIDEO:"Video",AUDIO:"Audio",DOCUMENT:"Documento",INTERACTIVE:"Interactivo"})[s]||s,Et=s=>({TEXT:"bg-slate-500/10 text-slate-500",IMAGE:"bg-blue-500/10 text-blue-600",VIDEO:"bg-purple-500/10 text-purple-600",AUDIO:"bg-pink-500/10 text-pink-600",DOCUMENT:"bg-orange-500/10 text-orange-600",INTERACTIVE:"bg-indigo-500/10 text-indigo-600"})[s]||"bg-muted text-muted-foreground",Vr=({totalTemplates:s,totalActive:t,totalUsage:a,isLoading:r})=>e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4",children:e.jsxs(ze,{children:[e.jsxs(be,{children:[e.jsx(je,{asChild:!0,children:e.jsx(Ce,{className:"hover:shadow-md transition-shadow cursor-help",children:e.jsx(Te,{className:"pt-4 sm:pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground",children:"Total Plantillas"}),e.jsx("div",{className:"text-2xl sm:text-3xl font-bold text-foreground",children:r?e.jsx(Ue,{className:"h-8 w-16"}):s})]}),e.jsx("div",{className:"p-2 sm:p-3 bg-gradient-to-br from-blue-500/30 to-blue-600/20 rounded-xl",children:e.jsx(De,{className:"w-5 h-5 sm:w-6 sm:h-6 text-blue-500"})})]})})})}),e.jsx(ve,{side:"bottom",children:e.jsx("p",{children:"Número total de plantillas creadas en tu organización"})})]}),e.jsxs(be,{children:[e.jsx(je,{asChild:!0,children:e.jsx(Ce,{className:"hover:shadow-md transition-shadow cursor-help",children:e.jsx(Te,{className:"pt-4 sm:pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground",children:"Activas"}),e.jsx("div",{className:"text-2xl sm:text-3xl font-bold text-foreground",children:r?e.jsx(Ue,{className:"h-8 w-16"}):t})]}),e.jsx("div",{className:"p-2 sm:p-3 bg-gradient-to-br from-green-500/30 to-emerald-600/20 rounded-xl",children:e.jsx(Ns,{className:"w-5 h-5 sm:w-6 sm:h-6 text-green-500"})})]})})})}),e.jsx(ve,{side:"bottom",children:e.jsx("p",{children:"Plantillas habilitadas y listas para usar"})})]}),e.jsxs(be,{children:[e.jsx(je,{asChild:!0,children:e.jsx(Ce,{className:"sm:col-span-2 lg:col-span-1 hover:shadow-md transition-shadow cursor-help",children:e.jsx(Te,{className:"pt-4 sm:pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground",children:"Usos Totales"}),e.jsx("div",{className:"text-2xl sm:text-3xl font-bold text-foreground",children:r?e.jsx(Ue,{className:"h-8 w-16"}):a===0?e.jsx("span",{className:"text-lg font-medium text-muted-foreground",children:"Sin uso aún"}):a.toLocaleString()})]}),e.jsx("div",{className:"p-2 sm:p-3 bg-gradient-to-br from-purple-500/30 to-violet-600/20 rounded-xl",children:e.jsx(Ts,{className:"w-5 h-5 sm:w-6 sm:h-6 text-purple-500"})})]})})})}),e.jsx(ve,{side:"bottom",className:"max-w-xs",children:e.jsx("p",{children:a===0?"Usa /atajo en el chat o selecciona una plantilla para incrementar este contador":"Número total de veces que se han usado todas las plantillas"})})]})]})}),Lr=({template:s,onEdit:t,onDelete:a})=>{const r=()=>{s.shortcut&&(navigator.clipboard.writeText(s.shortcut),C.success("Atajo copiado al portapapeles"))};return e.jsxs("tr",{className:"hover:bg-muted/50 cursor-pointer transition-colors",onClick:t,children:[e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`h-10 w-10 rounded-lg flex items-center justify-center ${Et(s.contentType)}`,children:e.jsx(Fe,{type:s.contentType,className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-sm text-foreground truncate",children:s.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:s.content||s.mediaCaption||"Sin contenido"})]})]})}),e.jsx("td",{className:"px-4 py-3",children:s.category&&e.jsx(Y,{variant:"outline",className:"text-xs",children:s.category.name})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs(Y,{variant:"secondary",className:"text-xs h-6 gap-1.5 pl-1.5 bg-muted/50 hover:bg-muted font-normal",children:[e.jsx(Fe,{type:s.contentType,className:"h-3.5 w-3.5 text-muted-foreground"}),Dr(s.contentType)]})}),e.jsx("td",{className:"px-4 py-3",children:s.shortcut&&e.jsx("code",{className:"text-xs bg-muted px-2 py-1 rounded font-mono text-muted-foreground border border-border/50",children:s.shortcut})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(Y,{variant:s.status==="ACTIVE"?"default":"outline",className:s.status==="ACTIVE"?"bg-green-500/15 text-green-600 dark:text-green-400 hover:bg-green-500/25 border-green-200 dark:border-green-900":"text-muted-foreground",children:s.status==="ACTIVE"?"Activa":s.status==="DRAFT"?"Borrador":"Archivada"})}),e.jsx("td",{className:"px-4 py-3",onClick:l=>l.stopPropagation(),children:e.jsxs(tt,{children:[e.jsx(at,{asChild:!0,children:e.jsx(_,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:e.jsx(ut,{className:"h-4 w-4"})})}),e.jsxs(rt,{align:"end",children:[e.jsxs(Ne,{onClick:t,children:[e.jsx(Es,{className:"h-4 w-4 mr-2"}),"Editar"]}),s.shortcut&&e.jsxs(Ne,{onClick:r,children:[e.jsx(nt,{className:"h-4 w-4 mr-2"}),"Copiar atajo"]}),e.jsxs(Ne,{onClick:a,className:"text-destructive",children:[e.jsx(ke,{className:"h-4 w-4 mr-2"}),"Eliminar"]})]})]})})]})},Fr=({template:s,onEdit:t,onDelete:a})=>{const r=()=>{s.shortcut&&(navigator.clipboard.writeText(s.shortcut),C.success("Atajo copiado al portapapeles"))},l=["IMAGE","VIDEO","AUDIO","DOCUMENT"].includes(s.contentType),m=s.thumbnailUrl||s.mediaUrl;return e.jsxs(Ce,{className:"group cursor-pointer hover:shadow-lg transition-all hover:border-primary/30 overflow-hidden",onClick:t,children:[l&&m&&e.jsxs("div",{className:"relative h-32 bg-muted/30 overflow-hidden",children:[e.jsx("img",{src:m,alt:s.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",onError:u=>{u.target.style.display="none"}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/40 to-transparent"}),e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs(Y,{variant:"secondary",className:"bg-black/50 text-white text-[10px] backdrop-blur-sm",children:[e.jsx(Fe,{type:s.contentType,className:"h-3 w-3 mr-1"}),s.contentType]})})]}),e.jsxs(Te,{className:`p-4 ${l&&m?"pt-3":""}`,children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[!(l&&m)&&e.jsx("div",{className:`h-10 w-10 rounded-lg flex items-center justify-center shrink-0 ${Et(s.contentType)}`,children:e.jsx(Fe,{type:s.contentType,className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"font-medium text-sm text-foreground truncate max-w-[180px]",children:s.name}),s.category&&e.jsx("span",{className:"text-xs text-muted-foreground",children:s.category.name})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[(s.usageCount??0)>0&&e.jsx(ze,{children:e.jsxs(be,{children:[e.jsx(je,{asChild:!0,children:e.jsxs(Y,{variant:"outline",className:"text-[10px] px-1.5 py-0.5 bg-primary/5 border-primary/20",children:[e.jsx(Ts,{className:"h-2.5 w-2.5 mr-0.5"}),s.usageCount]})}),e.jsx(ve,{side:"top",children:e.jsxs("p",{children:["Usada ",s.usageCount," ",s.usageCount===1?"vez":"veces"]})})]})}),e.jsxs(tt,{children:[e.jsx(at,{asChild:!0,onClick:u=>u.stopPropagation(),children:e.jsx(_,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(ut,{className:"h-4 w-4"})})}),e.jsxs(rt,{align:"end",children:[e.jsxs(Ne,{onClick:u=>{u.stopPropagation(),t()},children:[e.jsx(Es,{className:"h-4 w-4 mr-2"}),"Editar"]}),s.shortcut&&e.jsxs(Ne,{onClick:u=>{u.stopPropagation(),r()},children:[e.jsx(nt,{className:"h-4 w-4 mr-2"}),"Copiar atajo"]}),e.jsxs(Ne,{onClick:u=>{u.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(ke,{className:"h-4 w-4 mr-2"}),"Eliminar"]})]})]})]})]}),!(l&&m)&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mb-4 min-h-[32px]",children:s.content||s.mediaCaption||"Sin contenido de texto"}),l&&m&&s.mediaCaption&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1 mb-3",children:s.mediaCaption}),e.jsx("div",{className:"flex items-center justify-between pt-3 border-t border-border/50",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[s.shortcut&&e.jsxs("code",{className:"text-[10px] bg-muted px-1.5 py-0.5 rounded font-mono",children:["/",s.shortcut.replace(/^\/+/,"")]}),e.jsx(Y,{variant:s.status==="ACTIVE"?"default":"outline",className:`text-[10px] ${s.status==="ACTIVE"?"bg-green-500/20 text-green-500 border-green-500/30":""}`,children:s.status==="ACTIVE"?"Activa":s.status})]})})]})]})},Gr=({searchInput:s,onSearchChange:t,categoryId:a,onCategoryChange:r,contentType:l,onContentTypeChange:m,categories:u,viewMode:v,onViewModeChange:S})=>e.jsx("div",{className:"p-4 border-b bg-card/50 backdrop-blur-sm",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(H,{placeholder:"Buscar plantillas...",value:s,onChange:T=>t(T.target.value),className:"pl-10 bg-background"})]}),e.jsxs(cs,{value:a||"all",onValueChange:r,children:[e.jsx(ds,{className:"w-full sm:w-[180px] bg-background",children:e.jsx(us,{placeholder:"Categoría"})}),e.jsxs(ms,{children:[e.jsx(re,{value:"all",children:"Todas las categorías"}),u.map(T=>e.jsx(re,{value:T.id,children:T.name},T.id))]})]}),e.jsxs(cs,{value:l||"all",onValueChange:m,children:[e.jsx(ds,{className:"w-full sm:w-[150px] bg-background",children:e.jsx(us,{placeholder:"Tipo"})}),e.jsxs(ms,{children:[e.jsx(re,{value:"all",children:"Todos los tipos"}),e.jsx(re,{value:"TEXT",children:"Texto"}),e.jsx(re,{value:"IMAGE",children:"Imagen"}),e.jsx(re,{value:"VIDEO",children:"Video"}),e.jsx(re,{value:"AUDIO",children:"Audio"}),e.jsx(re,{value:"DOCUMENT",children:"Documento"}),e.jsx(re,{value:"INTERACTIVE",children:"Interactivo"})]})]}),e.jsxs("div",{className:"flex gap-1 border border-border rounded-md p-1 bg-background",children:[e.jsx(_,{variant:v==="grid"?"secondary":"ghost",size:"sm",onClick:()=>S("grid"),className:"h-8 w-8 p-0",children:e.jsx($a,{className:"h-4 w-4"})}),e.jsx(_,{variant:v==="list"?"secondary":"ghost",size:"sm",onClick:()=>S("list"),className:"h-8 w-8 p-0",children:e.jsx(gs,{className:"h-4 w-4"})})]})]})}),zn=()=>{const{data:s,isLoading:t}=lt(),{data:a,isLoading:r}=ga(),{data:l=[]}=ws(),m=Wa(),u=le(i=>i.filters),v=le(i=>i.setFilters),S=le(i=>i.setPage),T=le(i=>i.viewMode),P=le(i=>i.setViewMode),A=le(i=>i.openEditor),[M,N]=d.useState(""),[g,p]=d.useState(!1),[j,U]=d.useState(null),f=s?.data??[],B=l,x={page:s?.meta?.page??1,total:s?.meta?.total??0,totalPages:s?.meta?.totalPages??1},h={total:a?.total??0,active:a?.active??0,draft:a?.draft??0,archived:a?.archived??0,totalUsage:a?.totalUsage??0};d.useEffect(()=>{const i=setTimeout(()=>{M!==u.search&&v({search:M})},300);return()=>clearTimeout(i)},[M,u.search,v]);const D=i=>{A(i.id)},z=i=>{U(i)},$=async()=>{j&&(await m.mutateAsync(j.id),U(null))},I=()=>{A()};return e.jsxs(aa,{children:[e.jsx(ra,{title:"Plantillas de Respuesta",description:"Gestiona plantillas reutilizables para agentes y automatizaciones",icon:De,actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(_,{variant:"outline",size:"sm",onClick:()=>p(!0),children:[e.jsx(fs,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Categorías"})]}),e.jsxs(_,{size:"sm",onClick:I,children:[e.jsx(ue,{className:"h-4 w-4 sm:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Nueva Plantilla"})]})]})}),e.jsxs(na,{className:"space-y-4 sm:space-y-6",children:[e.jsx(Vr,{totalTemplates:h.total,totalActive:h.active,totalUsage:h.totalUsage,isLoading:r}),e.jsx("div",{className:"mt-6",children:e.jsxs(Ce,{className:"border-border/60 shadow-sm",children:[e.jsx(Gr,{searchInput:M,onSearchChange:N,categoryId:u.categoryId??"",onCategoryChange:i=>v({categoryId:i==="all"?null:i}),contentType:u.contentType??"",onContentTypeChange:i=>v({contentType:i==="all"?null:i}),categories:B,viewMode:T,onViewModeChange:P}),e.jsx("div",{className:"px-4 pb-3 border-b bg-card/30",children:e.jsx("div",{className:"flex gap-1 p-1 bg-muted/30 rounded-lg w-fit",children:[{value:null,label:"Todas",count:h.total-h.archived},{value:"ACTIVE",label:"Activas",count:h.active},{value:"DRAFT",label:"Borradores",count:h.draft},{value:"ARCHIVED",label:"Archivadas",count:h.archived}].map(i=>e.jsxs(_,{variant:u.status===i.value?"secondary":"ghost",size:"sm",onClick:()=>v({status:i.value}),className:u.status===i.value?"gap-1.5 h-8 bg-background shadow-sm hover:bg-background":"gap-1.5 h-8 hover:bg-transparent hover:text-foreground text-muted-foreground",children:[i.label,i.count>0&&e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full ${u.status===i.value?"bg-primary/10 text-primary":"bg-muted text-muted-foreground"}`,children:i.count})]},i.value??"all"))})}),e.jsxs(Te,{className:"p-0",children:[t?e.jsx("div",{className:"p-6",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:Array.from({length:8}).map((i,k)=>e.jsx(Ue,{className:"h-[160px] rounded-lg"},k))})}):f.length===0?e.jsx("div",{className:"py-16",children:e.jsx(la,{icon:e.jsx(De,{className:"h-12 w-12 text-muted-foreground/50"}),title:"No hay plantillas",description:"Crea tu primera plantilla para agilizar las respuestas",action:e.jsxs(_,{onClick:I,className:"gap-2 shadow-lg shadow-primary/25",children:[e.jsx(ue,{className:"h-4 w-4"}),"Crear Plantilla"]})})}):T==="list"?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-muted/30 border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Plantilla"}),e.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Categoría"}),e.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Tipo"}),e.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Atajo"}),e.jsx("th",{className:"px-4 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Estado"}),e.jsx("th",{className:"px-4 py-3 w-10"})]})}),e.jsx("tbody",{className:"divide-y divide-border/50",children:f.map(i=>e.jsx(Lr,{template:i,onEdit:()=>D(i),onDelete:()=>z(i)},i.id))})]})}):e.jsx("div",{className:"p-4 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 bg-muted/10",children:f.map(i=>e.jsx(Fr,{template:i,onEdit:()=>D(i),onDelete:()=>z(i)},i.id))}),!t&&f.length>0&&e.jsxs("div",{className:"p-3 border-t bg-muted/10 flex flex-col sm:flex-row items-center justify-between gap-3",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Mostrando ",f.length," de ",x.total," plantillas"]}),x.totalPages>1&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_,{variant:"outline",size:"sm",onClick:()=>S(x.page-1),disabled:x.page===1||t,className:"h-8 w-8 p-0",children:e.jsx(sa,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium min-w-[3rem] text-center",children:[x.page," / ",x.totalPages]}),e.jsx(_,{variant:"outline",size:"sm",onClick:()=>S(x.page+1),disabled:x.page>=x.totalPages||t,className:"h-8 w-8 p-0",children:e.jsx(ta,{className:"h-4 w-4"})})]})]})]})]})})]}),e.jsx(Or,{}),e.jsx(zr,{isOpen:g,onClose:()=>p(!1)}),e.jsx(ia,{open:!!j,onOpenChange:i=>!i&&U(null),onConfirm:$,title:"Eliminar plantilla",description:`¿Estás seguro que deseas eliminar la plantilla "${j?.name}"? Esta acción no se puede deshacer.`,confirmText:"Eliminar",cancelText:"Cancelar",variant:"destructive",loading:m.isPending})]})},qr={"contact.name":"Nombre del contacto","contact.firstName":"Primer nombre del contacto","contact.lastName":"Apellido del contacto","contact.phone":"Teléfono del contacto","contact.email":"Email del contacto","ticket.id":"ID del ticket","ticket.number":"Número del ticket","ticket.subject":"Asunto del ticket","ticket.createdAt":"Fecha de creación","agent.name":"Nombre del agente","agent.email":"Email del agente","org.name":"Nombre de la organización","date.today":"Fecha de hoy","date.now":"Fecha y hora actual","time.greeting":"Saludo según hora (Buenos días/tardes/noches)"};function $r(){const s=new Date().getHours();return s<12?"Buenos días":s<18?"Buenas tardes":"Buenas noches"}function Xs(s){if(!s)return"";const t=typeof s=="string"?new Date(s):s;return Cs(t,{style:"date-long"})}function Hr(s,t){const a=s.split(".");if(a[0]==="date"){if(a[1]==="today")return Xs(new Date);if(a[1]==="now")return Cs(new Date,{style:"short"})}if(a[0]==="time"&&a[1]==="greeting")return $r();if(a[0]==="contact"&&t.contact){const r=a[1];return t.contact[r]||""}if(a[0]==="ticket"&&t.ticket){if(a[1]==="createdAt")return Xs(t.ticket.createdAt);const r=a[1],l=t.ticket[r];return typeof l=="string"?l:""}if(a[0]==="agent"&&t.agent){const r=a[1];return t.agent[r]||""}if(a[0]==="org"&&t.org){const r=a[1];return t.org[r]||""}return""}function Dn(s,t={}){if(!s)return"";const a=/\{\{([a-zA-Z_.]+)\}\}/g;return s.replace(a,(r,l)=>Hr(l.trim(),t)||r)}function Kr(s){if(!s)return[];const t=/\{\{([a-zA-Z_.]+)\}\}/g,a=[];let r;for(;(r=t.exec(s))!==null;){const l=r[1].trim();a.includes(l)||a.push(l)}return a}function Vn(s){const t=Kr(s),a=Object.keys(qr),r=t.filter(l=>!a.includes(l));return{valid:r.length===0,unknownVariables:r}}export{zr as CategoryManager,qr as TEMPLATE_VARIABLES,Or as TemplateEditor,zn as TemplatesListPage,Kr as extractTemplateVariables,Dn as processTemplateContent,J as templatesApi,K as templatesKeys,ws as useCategoriesQuery,Qa as useCreateCategory,Ha as useCreateTemplate,Za as useDeleteCategory,Wa as useDeleteTemplate,ua as useTemplateDetailQuery,Gn as useTemplateSearch,ga as useTemplateStatsQuery,tr as useTemplateSubmit,lt as useTemplatesQuery,le as useTemplatesUiStore,On as useTrackTemplateUsage,Xa as useUpdateCategory,Ka as useUpdateTemplate,Vn as validateTemplateVariables};
@@ -1 +0,0 @@
1
- import{c as F,j as e,l as j,a2 as H,X as ae,a9 as ne,Z as le,b,d as ie,P as Z,g as O,k as oe,o as q,B as G,y as ce,C as W,t as de}from"./index-DsyZ_FlA.js";import{b as p,f as ue}from"./recharts-DrC5kNsx.js";import{D as Y}from"./download-CiVQHPeB.js";import{L as me}from"./list-BKc6EXnV.js";import{I as $,V}from"./video-VfwKgB6z.js";import{E as pe}from"./facebook-RxMBweMB.js";import{u as he}from"./useDebounce-Bfcb_jpD.js";import{m as xe}from"./MediaProcessingService-glHGiE_o.js";import{f as B}from"./storage.api-CFU3KJNp.js";import{E as fe}from"./eye-HfQCUjxJ.js";import{T as ge}from"./trash-2-Du2vmQCH.js";import{U as be}from"./upload-C7TwpdyA.js";const ye=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]],tt=F("panels-top-left",ye);const ve=[["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}],["path",{d:"m9 17-5-5 5-5",key:"nvlc11"}]],je=F("reply",ve);const we=[["path",{d:"M2 21a8 8 0 0 1 13.292-6",key:"bjp14o"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M19 16v6",key:"tddt3s"}],["path",{d:"M22 19h-6",key:"vcuq98"}]],Ne=F("user-round-plus",we);const ke=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],Se=F("zoom-in",ke),J=t=>({url:t||null,loading:!1,error:!1}),X=({src:t,alt:s,className:r,fallback:a,...l})=>{const{url:n}=J(t),[i,c]=p.useState(!1);return p.useEffect(()=>{c(!1)},[n]),i?e.jsx("div",{className:j("flex items-center justify-center bg-slate-100 dark:bg-slate-800 text-slate-400",r),children:a||e.jsx($,{className:"h-6 w-6"})}):n?e.jsx("img",{src:n,className:r,alt:s,onError:()=>c(!0),...l}):null},st=({src:t,className:s,fallback:r,...a})=>{const{url:l}=J(t);return l?e.jsx("video",{src:l,className:s,...a}):null},Te={"contact.name":"Nombre del contacto","contact.phone":"Teléfono","contact.email":"Email","ticket.id":"ID del Ticket","agent.name":"Nombre Agente","org.name":"Empresa"},rt={"contact.name":"Maria García","contact.phone":"+52 55 1234 5678","contact.email":"maria@example.com","ticket.id":"TKT-2024","agent.name":"Carlos López","org.name":"Mi Empresa"},at=({content:t,context:s})=>{const r=t.split(/({{[^}]+}})/g);return e.jsx(e.Fragment,{children:r.map((a,l)=>{const n=a.match(/^{{(.+)}}$/);if(n){const c=n[1].trim(),d=s[c];return d?e.jsx("span",{className:"bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300 px-1.5 py-0.5 rounded-md text-[13px] font-medium mx-0.5 inline-block align-middle",title:`Variable: {{${c}}}`,children:d},l):e.jsx("span",{className:"bg-amber-500/20 text-amber-700 dark:text-amber-400 px-1 rounded text-xs",title:`Variable desconocida: ${a}`,children:a},l)}const i=c=>c.split(/\*([^*]+)\*/g).map((f,m)=>m%2===1?e.jsx("strong",{className:"font-bold",children:f},m):f.split(/_([^_]+)_/g).map((g,o)=>o%2===1?e.jsx("em",{className:"italic",children:g},o):g.split(/~([^~]+)~/g).map((T,N)=>N%2===1?e.jsx("span",{className:"line-through",children:T},N):T.split(/```([^`]+)```/g).map((R,E)=>E%2===1?e.jsx("code",{className:"font-mono bg-black/10 dark:bg-white/10 px-1 rounded",children:R},E):e.jsx("span",{children:R},E)))));return e.jsx("span",{children:i(a)},l)})})},nt=({onInsert:t})=>e.jsxs("div",{className:"flex flex-wrap gap-1.5 p-3 bg-muted/20 rounded-lg border border-dashed border-border/60",children:[e.jsxs("div",{className:"w-full flex items-center gap-2 mb-1.5",children:[e.jsx(H,{className:"h-3.5 w-3.5 text-amber-500"}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Variables Dinámicas"})]}),Object.entries(Te).map(([s,r])=>e.jsx("button",{type:"button",onClick:()=>t(s),className:"flex items-center gap-1.5 px-2 py-1 bg-background hover:bg-primary/10 hover:text-primary hover:border-primary/30 border rounded text-[11px] transition-colors cursor-pointer group",title:r,children:e.jsx("code",{className:"text-[10px] font-mono opacity-70 group-hover:opacity-100",children:`{{${s}}}`})},s))]}),lt=({children:t,time:s,businessName:r="Mi Negocio"})=>e.jsxs("div",{className:"relative mx-auto w-[300px] h-[600px] bg-[#111b21] rounded-[40px] p-2 shadow-xl border-4 border-[#222]",children:[e.jsx("div",{className:"absolute top-0 left-1/2 -translate-x-1/2 w-24 h-6 bg-[#111b21] rounded-b-2xl z-50"}),e.jsxs("div",{className:"w-full h-full bg-[#efeae2] dark:bg-[#0b141a] rounded-[32px] overflow-hidden flex flex-col relative",children:[e.jsxs("div",{className:"h-6 w-full bg-[#075E54] dark:bg-[#1f2c34] flex items-center justify-between px-6 text-[10px] text-white/80 shrink-0",children:[e.jsx("span",{className:"font-medium",children:s}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M2 22h3V10H2v12zm5 0h3V7H7v15zm5 0h3V2h-3v20zm5 0h3v-8h-3v8z"})}),e.jsx("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M1 9l2 2c4.97-4.97 13.03-4.97 18 0l2-2C16.93 2.93 7.08 2.93 1 9zm8 8l3 3 3-3c-1.65-1.66-4.34-1.66-6 0zm-4-4l2 2c2.76-2.76 7.24-2.76 10 0l2-2C15.14 9.14 8.87 9.14 5 13z"})}),e.jsx("svg",{className:"w-4 h-3.5",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M17 4H7a4 4 0 00-4 4v8a4 4 0 004 4h10a4 4 0 004-4V8a4 4 0 00-4-4zm2 12a2 2 0 01-2 2H7a2 2 0 01-2-2V8a2 2 0 012-2h10a2 2 0 012 2v8zm3-7v6h1a1 1 0 001-1v-4a1 1 0 00-1-1h-1z"})})]})]}),e.jsxs("div",{className:"h-12 w-full bg-[#075E54] dark:bg-[#1f2c34] flex items-center px-3 gap-2 text-white shrink-0",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-[#00a884] flex items-center justify-center text-xs font-bold",children:r[0].toUpperCase()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[14px] font-semibold leading-tight truncate",children:r}),e.jsx("p",{className:"text-[11px] opacity-70",children:"en línea"})]})]}),e.jsxs("div",{className:"flex-1 overflow-hidden relative",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.04] pointer-events-none",style:{backgroundImage:'url("https://user-images.githubusercontent.com/15075759/28719144-86dc0f70-73b1-11e7-911d-60d70fcded21.png")',backgroundRepeat:"repeat",backgroundSize:"350px"}}),e.jsx("div",{className:"h-full overflow-y-auto custom-scrollbar p-3 relative z-0 flex flex-col",children:t})]}),e.jsxs("div",{className:"p-2 bg-[#f0f2f5] dark:bg-[#1f2c34] shrink-0 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 bg-white dark:bg-[#2a3942] rounded-full h-10 flex items-center px-3 gap-2",children:e.jsx("span",{className:"flex-1 text-[14px] text-[#8696a0]",children:"Mensaje"})}),e.jsx("div",{className:"h-10 w-10 rounded-full bg-[#00a884] flex items-center justify-center shrink-0",children:e.jsx(H,{className:"w-5 h-5 text-white"})})]})]})]}),Ee=({src:t,type:s,className:r,...a})=>t?e.jsxs("video",{className:r,controls:!0,playsInline:!0,muted:!0,...a,children:[e.jsx("source",{src:t,type:s||"video/mp4"}),"Tu navegador no soporta el elemento de video."]},t):null,ee=p.memo(({isOpen:t,onClose:s,url:r,thumbnailUrl:a,type:l,caption:n,showDownload:i=!0})=>{const[c,d]=p.useState(!0),f=p.useRef(s);return f.current=s,p.useEffect(()=>{if(!t||!r)return;const m=document.body.style.overflow;document.body.style.overflow="hidden";const y=g=>{g.key==="Escape"&&(g.stopPropagation(),f.current())};return document.addEventListener("keydown",y,!0),()=>{document.body.style.overflow=m,document.removeEventListener("keydown",y,!0)}},[t,r]),!t||!r?null:ue.createPortal(e.jsxs("div",{"data-lightbox-overlay":!0,className:"fixed inset-0 z-[9999] pointer-events-auto flex items-center justify-center animate-in fade-in duration-200",onClick:s,children:[e.jsx("div",{className:"absolute inset-0 bg-black/95 backdrop-blur-sm"}),e.jsxs("div",{className:"relative z-10 max-w-[90vw] max-h-[90vh] flex flex-col items-center justify-center",onClick:m=>m.stopPropagation(),children:[l==="IMAGE"&&c&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"w-12 h-12 rounded-full border-3 border-white/20 border-t-white animate-spin"})}),l==="IMAGE"&&e.jsxs("div",{className:"relative",children:[a&&c&&e.jsx("img",{src:a,alt:"",className:"max-w-full max-h-[90vh] object-contain rounded-lg blur-sm opacity-50"}),e.jsx("img",{src:r,alt:n||"Vista previa",className:j("max-w-full max-h-[90vh] object-contain rounded-lg shadow-2xl transition-opacity duration-300",c?a?"absolute inset-0 opacity-0":"opacity-0":"opacity-100"),onLoad:()=>d(!1)})]}),l==="VIDEO"&&e.jsx("div",{className:"relative group/video-container",children:e.jsx(Ee,{src:r,poster:a,controls:!0,autoPlay:!0,className:"max-w-full max-h-[90vh] rounded-lg shadow-2xl",onLoadedData:()=>d(!1)})}),l==="AUDIO"&&e.jsx("div",{className:"bg-white/10 backdrop-blur-md p-8 rounded-2xl flex items-center justify-center w-[300px]",children:e.jsx("audio",{src:r,controls:!0,className:"w-full"})}),n&&!c&&e.jsx("div",{className:"absolute -bottom-16 left-0 right-0 p-4 text-center",children:e.jsx("p",{className:"text-white text-sm bg-black/50 inline-block px-4 py-2 rounded-full backdrop-blur-md",children:n})})]}),e.jsxs("div",{className:"absolute top-4 right-4 flex items-center gap-2 z-20",children:[i&&e.jsx("button",{onClick:m=>{m.stopPropagation(),window.open(r,"_blank")},className:"h-10 w-10 rounded-full bg-white/10 backdrop-blur-sm flex items-center justify-center text-white hover:bg-white/20 transition-colors",title:"Descargar",children:e.jsx(Y,{className:"w-5 h-5"})}),e.jsx("button",{onClick:s,className:"h-10 w-10 rounded-full bg-white/10 backdrop-blur-sm flex items-center justify-center text-white hover:bg-white/20 transition-colors",title:"Cerrar (Esc)",children:e.jsx(ae,{className:"w-5 h-5"})})]})]}),document.body)});ee.displayName="MediaLightbox";function Ce(t){let s=t;if(typeof t=="string"){const l=t.trim();if(!l.startsWith("{"))return null;try{s=JSON.parse(l)}catch{return null}}return!s||typeof s!="object"||String(s.kind||s.type||"").toLowerCase()!=="request_contact_info"?null:String(s.body?.text??s.body??"").trim()||null}function te(t){let s=t;if(typeof t=="string"){const n=t.trim();if(!n.startsWith("{"))return null;try{s=JSON.parse(n)}catch{return null}}if(!s||typeof s!="object")return null;const r=String(s.kind||s.type||s.interactiveType||"").toLowerCase(),a=s.cards||s.action?.cards;if(r!=="carousel"&&!Array.isArray(a)||!Array.isArray(a)||a.length===0)return null;const l=a.map(n=>{const i=n.header||{},c=String(i.type||"image").toLowerCase(),d=c==="video"?"video":"image",f=i.thumbnailUrl||i.mediaUrl||i.link||i[c]?.link||void 0,m=i.mediaUrl||i.link||i[c]?.link||i.thumbnailUrl||void 0,g=(Array.isArray(n.buttons)?n.buttons:n.action?.buttons||(n.action?.name==="cta_url"?[{type:"cta_url",title:n.action.parameters?.display_text,url:n.action.parameters?.url}]:[])).map(o=>{if(o.type==="cta_url"||o.url||o.parameters?.url)return{type:"cta_url",title:String(o.title||o.text||o.parameters?.display_text||"Ver"),url:o.url||o.parameters?.url};const u=o.quick_reply||o;return{type:"quick_reply",title:String(u.title||o.title||o.text||""),id:String(u.id||o.id||"")}});return{imageUrl:f,fullUrl:m,mediaType:d,body:n.body?.text||(typeof n.body=="string"?n.body:void 0),buttons:g}});return{body:s.body?.text||s.body||"",cards:l}}function it(t){const s={};for(const r of t||[]){const l=(r?.metadata||{}).carousel||(typeof r?.content=="string"&&r.content.trim().startsWith("{")?r.content:null);if(!l)continue;const n=te(l);if(!n)continue;const i=n.cards.length;n.cards.forEach((c,d)=>{const f={label:(c.body||"").trim(),imageUrl:c.imageUrl,fullUrl:c.fullUrl,mediaType:c.mediaType,cardIndex:d,cardCount:i};for(const m of c.buttons)m.id&&(s[m.id]=f)})}return s}function Re(t){return t?t.replace(/\s*\[Opciones:[^\]]*\]\s*$/i,"").replace(/\n\n(\d+\.\s+.+(\n|$))+$/,"").trim():""}function _(t){if(!t)return null;const s=t.label??t.title??t.reply?.title??t.text??"";if(!String(s).trim())return null;const r=t.id??t.reply?.id??String(s),a=t.description?String(t.description):void 0;return{id:String(r),label:String(s),description:a}}function Ae(t){const{content:s}=t;let r={},a="";if(typeof s=="string"){const g=s.trim();if(g.startsWith("{"))try{r=JSON.parse(g)}catch{a=s}else a=s}else s&&typeof s=="object"&&(r=s);const l=Re(r.body||r.text||a||""),n=r.buttons||r.action?.buttons||[],i=r.sections||t.sections,c=Array.isArray(i)?i.flatMap(g=>Array.isArray(g?.rows)?g.rows:[]):[];let d=[];Array.isArray(r.options)&&r.options.length>0?d=r.options.map(_).filter(Boolean):c.length>0?d=c.map(_).filter(Boolean):n.length>0?d=n.map(_).filter(Boolean):Array.isArray(t.options)&&t.options.length>0&&(d=t.options.map(_).filter(Boolean));const f=String(r.menuButton||r.button||r.action?.button||t.menuButton||"Ver opciones"),y=String(r.type||r.interactiveType||t.interactiveType||"").toLowerCase()==="list"||c.length>0||!!(r.menuButton||r.button||t.menuButton)||d.length>3;return{body:l,footer:r.footer?.text||r.footer||void 0,header:r.header,options:d,isList:y,menuButton:f}}function De(t){if(!t||typeof t!="object")return null;const s=String(t.type||"").toLowerCase();if(s!=="image"&&s!=="video"&&s!=="document")return null;const r=t.thumbnailUrl||t.mediaUrl||t[s]?.link,a=t.mediaOriginalName||t[s]?.filename;return s==="image"?r?e.jsx("img",{src:r,alt:a||"Header",className:"w-full max-h-48 object-cover rounded-lg bg-black/5"}):e.jsx("div",{className:"w-full h-32 bg-black/10 rounded-lg flex items-center justify-center text-white/70",children:e.jsx($,{className:"w-8 h-8"})}):s==="video"?e.jsxs("div",{className:"w-full h-32 bg-black/10 rounded-lg flex items-center justify-center relative overflow-hidden",children:[r&&(t.thumbnailUrl?e.jsx("img",{src:t.thumbnailUrl,alt:a||"Video",className:"w-full h-full object-cover rounded-lg"}):e.jsx("video",{src:r,className:"w-full h-full object-cover rounded-lg"})),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:e.jsx("div",{className:"bg-black/50 rounded-full p-2",children:e.jsx(V,{className:"w-5 h-5 text-white"})})})]}):e.jsxs("div",{className:"bg-black/10 rounded-lg px-2 py-2 flex items-center gap-2",children:[e.jsx(le,{className:"w-5 h-5 shrink-0 text-current opacity-80"}),e.jsx("span",{className:"text-xs truncate",children:a||"Documento"})]})}function Ue({card:t,disabled:s,onOptionClick:r}){const[a,l]=p.useState(!1),n=t.fullUrl||t.imageUrl;return e.jsxs("div",{className:"w-[200px] shrink-0 rounded-xl overflow-hidden bg-white/95 dark:bg-slate-800 ring-1 ring-black/5 dark:ring-white/10 shadow-sm flex flex-col",children:[t.imageUrl?e.jsxs("button",{type:"button",onClick:()=>n&&l(!0),className:"relative w-full h-28 overflow-hidden bg-black/5 group/img cursor-pointer","aria-label":"Ver imagen completa",children:[t.mediaType==="video"?e.jsx("video",{src:t.imageUrl,className:"w-full h-full object-cover"}):e.jsx("img",{src:t.imageUrl,alt:"",className:"w-full h-full object-cover transition-transform duration-200 group-hover/img:scale-105"}),e.jsx("span",{className:"absolute inset-0 flex items-center justify-center bg-black/0 group-hover/img:bg-black/25 transition-colors",children:e.jsx("span",{className:"opacity-0 group-hover/img:opacity-100 transition-opacity bg-black/55 rounded-full p-1.5",children:t.mediaType==="video"?e.jsx(V,{className:"w-4 h-4 text-white"}):e.jsx(Se,{className:"w-4 h-4 text-white"})})})]}):e.jsx("div",{className:"w-full h-28 bg-black/10 flex items-center justify-center text-slate-400",children:t.mediaType==="video"?e.jsx(V,{className:"w-7 h-7"}):e.jsx($,{className:"w-7 h-7"})}),e.jsxs("div",{className:"p-2.5 flex flex-col gap-2 flex-1",children:[t.body&&e.jsx("p",{className:"text-[12px] text-slate-700 dark:text-slate-200 whitespace-pre-wrap break-words line-clamp-4",children:t.body}),e.jsx("div",{className:"mt-auto flex flex-col gap-1.5",children:t.buttons.map((i,c)=>i.type==="cta_url"?e.jsxs("a",{href:s?void 0:i.url,target:"_blank",rel:"noopener noreferrer",className:j("w-full py-1.5 px-2 rounded-lg text-[12px] font-medium text-blue-600 dark:text-blue-300 ring-1 ring-black/5 dark:ring-white/10 flex items-center justify-center gap-1",s?"cursor-default opacity-90":"hover:bg-slate-50 dark:hover:bg-slate-700"),children:[i.title,e.jsx(pe,{className:"w-3 h-3"})]},c):e.jsxs("button",{type:"button",disabled:s,onClick:()=>!s&&r?.(i.id||i.title,i.title),className:j("w-full py-1.5 px-2 rounded-lg text-[12px] font-medium text-blue-600 dark:text-blue-300 ring-1 ring-black/5 dark:ring-white/10 flex items-center justify-center gap-1.5",s?"cursor-default":"hover:bg-slate-50 dark:hover:bg-slate-700 cursor-pointer"),children:[e.jsx(je,{className:"w-3 h-3 shrink-0"}),i.title]},c))})]}),e.jsx(ee,{isOpen:a,onClose:()=>l(!1),url:n||"",thumbnailUrl:t.imageUrl,type:t.mediaType==="video"?"VIDEO":"IMAGE",caption:t.body,showDownload:!0})]})}const Ie=p.memo(t=>{const{onOptionClick:s,disabled:r}=t,a=te(t.content);if(a)return e.jsxs("div",{className:"space-y-2 min-w-[220px] max-w-[420px]",children:[a.body&&e.jsx("div",{className:"text-sm whitespace-pre-wrap break-words",children:a.body}),e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-1 -mx-1 px-1 snap-x",children:a.cards.map((o,u)=>e.jsx("div",{className:"snap-start",children:e.jsx(Ue,{card:o,disabled:r,onOptionClick:s})},u))})]});const l=Ce(t.content);if(l)return e.jsxs("div",{className:"space-y-2 min-w-[220px]",children:[e.jsx("div",{className:"text-sm whitespace-pre-wrap break-words",children:l}),e.jsxs("div",{className:"flex items-center justify-center gap-1.5 rounded-xl bg-white/95 dark:bg-slate-800 px-3 py-2 text-[13px] font-medium text-blue-600 dark:text-blue-300 shadow-sm ring-1 ring-black/5 dark:ring-white/10",children:[e.jsx(Ne,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:"Compartir número"})]})]});const{body:n,footer:i,header:c,options:d,isList:f,menuButton:m}=Ae(t),y=De(c),g=o=>{r||s?.(o.id,o.label)};return e.jsxs("div",{className:"space-y-2 min-w-[220px]",children:[y,n&&e.jsx("div",{className:"text-sm whitespace-pre-wrap break-words",children:n}),i&&e.jsx("p",{className:"text-[11px] text-current opacity-70 -mt-1",children:i}),d.length>0&&(f?e.jsxs("div",{className:"rounded-xl overflow-hidden bg-white/95 dark:bg-slate-800 mt-0.5 shadow-sm ring-1 ring-black/5 dark:ring-white/10",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-slate-200/80 dark:border-slate-700 text-[13px] font-medium text-blue-600 dark:text-blue-300",children:[e.jsx(me,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:m})]}),e.jsx("div",{className:"max-h-[240px] overflow-y-auto",children:d.map(o=>e.jsxs("button",{type:"button",onClick:()=>g(o),disabled:r,className:j("w-full text-left px-3 py-2 flex items-center justify-between gap-2 border-b border-slate-100 dark:border-slate-700/70 last:border-b-0 transition-colors",r?"cursor-default":"hover:bg-slate-50 dark:hover:bg-slate-700/50 cursor-pointer"),children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[13px] font-medium text-slate-800 dark:text-slate-100 truncate",children:o.label}),o.description&&e.jsx("span",{className:"block text-[11px] text-slate-500 dark:text-slate-400 truncate",children:o.description})]}),e.jsx(ne,{className:"w-4 h-4 text-slate-300 dark:text-slate-500 shrink-0"})]},o.id))})]}):e.jsx("div",{className:"flex flex-col gap-1.5 mt-0.5",children:d.map(o=>e.jsx("button",{type:"button",onClick:()=>g(o),disabled:r,className:j("w-full py-2 px-3 rounded-lg text-[13px] font-medium bg-white/95 dark:bg-slate-800 text-blue-600 dark:text-blue-300 ring-1 ring-black/5 dark:ring-white/10 flex items-center justify-center gap-1.5 transition-colors",r?"cursor-default":"hover:bg-white dark:hover:bg-slate-700 cursor-pointer"),children:o.label},o.id))}))]})});Ie.displayName="InteractiveMessage";const ze=300*1e3,z=new Map;function Oe(t,s){const r=s.get(t);return r&&r.expiresAt>Date.now()?r.data:(s.delete(t),null)}function Me(t,s,r){r.set(t,{data:s,expiresAt:Date.now()+ze})}const M={async searchForChat(t){const s=new URLSearchParams;return t.q&&s.set("q",t.q),t.categoryId&&s.set("categoryId",t.categoryId),t.limit&&s.set("limit",String(t.limit)),t.channelType&&s.set("channelType",t.channelType),(await b.get(`/templates/search?${s.toString()}`)).data},async fetchExternal(t){return(await b.post("/templates/fetch-external",t)).data},async fetchFromChannel(t){return(await b.post("/templates/fetch-channel",{channelId:t})).data},async syncExternal(t){return(await b.post("/templates/sync-external",t)).data},async uploadMedia(t,s,r,a){const l=new FormData;return l.append("phoneNumberId",s),l.append("accessToken",r),a&&l.append("originalHash",a),l.append("file",t,t.name),(await b.post("/templates/upload-media",l,{headers:{"Content-Type":"multipart/form-data"}})).data},async getAll(t){const s=new URLSearchParams;t?.search&&s.set("search",t.search),t?.categoryId&&s.set("categoryId",t.categoryId),t?.contentType&&s.set("contentType",t.contentType),t?.status&&s.set("status",t.status),t?.channelId&&s.set("channelId",t.channelId),t?.tags&&t.tags.length>0&&s.set("tags",t.tags.join(",")),t?.page&&s.set("page",String(t.page)),t?.limit&&s.set("limit",String(t.limit));const r=s.toString(),a=r?`/templates?${r}`:"/templates";return(await b.get(a)).data},async getStats(){return(await b.get("/templates/stats")).data},async getById(t){return(await b.get(`/templates/${t}`)).data},async create(t){return(await b.post("/templates",t)).data},async update(t,s){return(await b.patch(`/templates/${t}`,s)).data},async delete(t){await b.delete(`/templates/${t}`)},async getByShortcut(t){try{return(await b.get(`/templates/shortcut/${encodeURIComponent(t)}`)).data}catch{return null}},async trackUsage(t,s){try{await b.post(`/templates/${t}/use`,s||{})}catch(r){console.warn("Failed to track template usage:",r)}},async getUsageStats(t){const s=new URLSearchParams;t?.periodDays&&s.set("periodDays",String(t.periodDays)),t?.sortBy&&s.set("sortBy",t.sortBy),t?.limit&&s.set("limit",String(t.limit));const r=s.toString(),a=r?`/templates/analytics/usage?${r}`:"/templates/analytics/usage";return(await b.get(a)).data},async getTemplateUsageHistory(t,s=30,r=!1){const a=`${t}:${s}`;if(!r){const c=Oe(a,z);if(c)return console.debug(`[TemplatesApi] Analytics cache hit for template ${t.slice(0,8)}...`),c}const l=`?periodDays=${s}`,i=(await b.get(`/templates/analytics/usage/${t}${l}`)).data;return Me(a,i,z),console.debug(`[TemplatesApi] Analytics ${r?"re-":""}cached for template ${t.slice(0,8)}...`),i},clearAnalyticsCache(t){if(t)for(const s of z.keys())s.startsWith(t)&&z.delete(s);else z.clear()},async getUsageSummary(t){const s=t?`?periodDays=${t}`:"";return(await b.get(`/templates/analytics/summary${s}`)).data},async getCategories(){return(await b.get("/templates/categories/list")).data},async getCategoryById(t){return(await b.get(`/templates/categories/${t}`)).data},async createCategory(t){return(await b.post("/templates/categories",t)).data},async updateCategory(t,s){return(await b.patch(`/templates/categories/${t}`,s)).data},async deleteCategory(t){await b.delete(`/templates/categories/${t}`)}},K={search:"",categoryId:null,contentType:null,status:null},se=ie(t=>({filters:K,page:1,limit:20,selectedTemplateId:null,isEditorOpen:!1,viewMode:"list",setFilters:s=>t(r=>({filters:{...r.filters,...s},page:1})),setPage:s=>t({page:s}),resetFilters:()=>t({filters:K,page:1}),openEditor:s=>t({selectedTemplateId:s??null,isEditorOpen:!0}),closeEditor:()=>t({selectedTemplateId:null,isEditorOpen:!1}),setViewMode:s=>t({viewMode:s})})),Le=()=>se(Z(t=>t.filters)),Pe=()=>se(Z(t=>({page:t.page,limit:t.limit}))),S={all:["templates"],lists:()=>[...S.all,"list"],list:t=>[...S.lists(),t],details:()=>[...S.all,"detail"],detail:t=>[...S.details(),t],stats:t=>[...S.all,"stats",t],categories:t=>[...S.all,"categories",t],search:(t,s,r)=>[...S.all,"search",{query:t,categoryId:s,channelType:r}]};function ot(){const t=Le(),{page:s,limit:r}=Pe(),a={search:t.search||void 0,categoryId:t.categoryId??void 0,contentType:t.contentType??void 0,status:t.status??void 0,page:s,limit:r,sortBy:"updatedAt",sortOrder:"DESC"};return O({queryKey:S.list(a),queryFn:()=>M.getAll(a),placeholderData:oe,staleTime:120*1e3,retry:2,retryDelay:l=>Math.min(1e3*2**l,3e4)})}function ct(){return O({queryKey:S.stats("current"),queryFn:()=>M.getStats(),staleTime:60*1e3})}function dt(){return O({queryKey:S.categories("current"),queryFn:()=>M.getCategories(),staleTime:300*1e3,gcTime:1800*1e3})}function ut(t){return O({queryKey:t?S.detail(t):["templates","detail","none"],queryFn:()=>t?M.getById(t):null,enabled:!!t,staleTime:120*1e3})}function mt({query:t,categoryId:s,enabled:r=!0,limit:a=10,channelType:l}){const n=he(t,400),i=n.length===0||n.length>=2;return O({queryKey:S.search(n,s,l),queryFn:()=>M.searchForChat({q:n,categoryId:s,limit:a,channelType:l}),enabled:r&&i,placeholderData:c=>c,staleTime:30*1e3})}const Be=["audio/webm;codecs=opus","audio/webm","audio/mp4","audio/ogg;codecs=opus","audio/ogg"],Q=()=>{if(typeof MediaRecorder>"u")return null;for(const t of Be)if(MediaRecorder.isTypeSupported(t))return t;return null},_e=120;function pt(t={}){const s=t.maxDurationSeconds??_e,[r,a]=p.useState("idle"),[l,n]=p.useState("prompt"),[i,c]=p.useState(0),[d,f]=p.useState(null),[m,y]=p.useState(null),[g,o]=p.useState(null),u=p.useRef(null),T=p.useRef(null),N=p.useRef([]),v=p.useRef(null),R=p.useRef(0),E=p.useRef(!1),I=typeof navigator<"u"&&!!navigator.mediaDevices&&!!navigator.mediaDevices.getUserMedia&&typeof MediaRecorder<"u"&&Q()!==null,k=p.useCallback(()=>{if(v.current&&(clearInterval(v.current),v.current=null),u.current&&u.current.state!=="inactive")try{console.log("[AudioRecorder] 🔒 Forcing recorder stop during cleanup"),u.current.stop()}catch{}T.current&&(T.current.getTracks().forEach(x=>{x.stop(),console.log(`[AudioRecorder] 🔒 Track ${x.kind} stopped for security`)}),T.current=null),u.current=null,N.current=[]},[]);p.useEffect(()=>()=>{m&&URL.revokeObjectURL(m)},[m]),p.useEffect(()=>()=>{console.log("[AudioRecorder] 🛡️ Component unmounting, enforcing safety cleanup"),k(),m&&URL.revokeObjectURL(m)},[k,m]);const A=p.useCallback(async()=>{if(k(),!I){o("Tu navegador no soporta grabación de audio"),a("error");return}a("requesting"),o(null),f(null),E.current=!1,m&&(URL.revokeObjectURL(m),y(null));try{const x=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}});T.current=x,n("granted");const P=Q(),D=new MediaRecorder(x,{mimeType:P});u.current=D,N.current=[],D.ondataavailable=w=>{w.data.size>0&&(console.log(`[AudioRecorder] 🟣 Chunk received: ${w.data.size} bytes`),N.current.push(w.data))},D.onstop=()=>{if(console.log("[AudioRecorder] 🛑 Event: onstop triggered"),E.current){console.log("[AudioRecorder] ⚠️ Recording Cancelled - Cleaning up"),k();return}const w=new Blob(N.current,{type:P});console.log("[AudioRecorder] ✅ Final Blob Created:",{size:w.size,type:w.type});const re=URL.createObjectURL(w);f(w),y(re),a("stopped"),k()},D.onerror=w=>{console.error("[AudioRecorder] ❌ Recorder Error:",w),o("Error durante la grabación"),a("error"),k()},D.start(100),console.log("[AudioRecorder] 🟢 Started Recording Session"),R.current=Date.now(),c(0),a("recording"),v.current=setInterval(()=>{const w=Math.floor((Date.now()-R.current)/1e3);c(w),w>=s&&(console.log("[AudioRecorder] ⏳ Max duration reached, stopping..."),u.current&&u.current.state!=="inactive"&&u.current.stop())},1e3)}catch(x){console.error("[AudioRecorder] ❌ getUserMedia Error:",x),x.name==="NotAllowedError"||x.name==="PermissionDeniedError"?(n("denied"),o("Permiso de micrófono denegado.")):x.name==="NotFoundError"?(n("unavailable"),o("No se encontró micrófono.")):o("Error al acceder al micrófono."),a("error"),k()}},[I,m,k,s]),L=p.useCallback(()=>{u.current&&u.current.state!=="inactive"&&(console.log("[AudioRecorder] 🛑 Manually stopping recorder..."),u.current.stop()),v.current&&(clearInterval(v.current),v.current=null)},[]),U=p.useCallback(()=>{E.current=!0,console.log("[AudioRecorder] ⚠️ Manual Cancel Triggered"),u.current&&u.current.state!=="inactive"&&u.current.stop(),a("idle"),c(0),f(null),m&&(URL.revokeObjectURL(m),y(null)),o(null),k()},[k,m]),C=p.useCallback(()=>{u.current&&u.current.state==="recording"&&(u.current.pause(),a("paused"),v.current&&(clearInterval(v.current),v.current=null))},[]),h=p.useCallback(()=>{if(u.current&&u.current.state==="paused"){u.current.resume(),a("recording");const x=i,P=Date.now();v.current=setInterval(()=>{const D=Math.floor((Date.now()-P)/1e3);c(x+D)},1e3)}},[i]);return{status:r,permissionStatus:l,recordingTime:i,audioBlob:d,audioUrl:m,error:g,startRecording:A,stopRecording:L,cancelRecording:U,pauseRecording:C,resumeRecording:h,isSupported:I,maxDuration:s,isAtLimit:i>=s}}function Fe(t={}){const[s,r]=p.useState("IDLE"),[a,l]=p.useState(0),[n,i]=p.useState(""),[c,d]=p.useState(null),f=p.useCallback(async(y,g)=>{r("HASHING"),l(0),d(null),i("Iniciando proceso...");try{const o=await xe.processFile(y,{limits:t.mediaLimits,channelId:t.channelId,uploadStrategy:g||t.uploadStrategy,onProgress:(u,T)=>{switch(r(u),l(T),u){case"HASHING":i("Calculando identidad (Hash)...");break;case"CHECKING_DEDUP":i("Verificando existencia...");break;case"OPTIMIZING":i("Optimizando peso (Smart Compress)...");break;case"GENERATING_THUMB":i("Generando vista previa...");break;case"UPLOADING":i("Subiendo a la nube...");break;case"CONFIRMING":i("Confirmando carga...");break;case"DONE":i("¡Carga completada!");break}}});return r("DONE"),t.onSuccess?.(o),o}catch(o){const u=o;throw console.error("[SmartUpload] Error:",u),d(u),i("Error: "+(u.message||"Error desconocido")),r("ERROR"),t.onError?.(u),u}},[t]),m=p.useCallback(()=>{r("IDLE"),l(0),i(""),d(null)},[]);return{uploadState:s,progress:a,feedback:n,error:c,uploadFile:f,reset:m,isUploading:s!=="IDLE"&&s!=="DONE"&&s!=="ERROR"}}function ht(t){return t.findIndex(s=>{const r=s.map(a=>(a||"").trim().toLowerCase()).filter(a=>a.length>0);return new Set(r).size!==r.length})}const xt=(t,s)=>{let r=t;return Object.entries(s).forEach(([a,l])=>{r=r.replace(new RegExp(`{{${a}}}`,"g"),l)}),r.replace(/{{[^}]+}}/g,"...")},Ve=({type:t,subtype:s,className:r})=>{const a=()=>{if(!s)return"GENERIC";const n=s.toLowerCase();return n.includes("pdf")?"PDF":n.includes("csv")?"CSV":n.includes("excel")||n.includes("spreadsheet")||n.includes("sheet")||n.includes("xls")?"EXCEL":n.includes("powerpoint")||n.includes("presentation")||n.includes("ppt")?"PPT":n.includes("wordprocessing")||n.includes("msword")?"WORD":n.includes("text/")||n.includes("txt")||n.includes("plain")?"TEXT":"GENERIC"},l=()=>{if(!s)return"FILE";const n=s.split("/");let d=(n[1]||n[0]).replace(/^x-|vnd\.|openxmlformats-officedocument\./g,"").substring(0,4).toUpperCase();return d.includes("WORD")&&(d="DOC"),d.includes("SHEE")&&(d="XLS"),d.includes("PRES")&&(d="PPT"),d.includes("TEXT")&&(d="TXT"),d};switch(t){case"AUDIO":return e.jsxs("svg",{viewBox:"0 0 40 48",className:j("drop-shadow-sm",r),children:[e.jsx("path",{d:"M7 0h21l12 12v36H7c-2.2 0-4-1.8-4-4V4c0-2.2 1.8-4 4-4z",fill:"#7be1c2"}),e.jsx("path",{d:"M28 0v12h12",fill:"#5ac0a0"}),e.jsx("path",{d:"M20 33l-5-4h4v-8h2v8h4l-5 4z",fill:"#fff"}),e.jsx("circle",{cx:"20",cy:"24",r:"6",fill:"white",fillOpacity:"0.3"})]});case"DOCUMENT":const n=a();return n==="PDF"?e.jsxs("svg",{viewBox:"0 0 40 48",className:j("drop-shadow-sm",r),children:[e.jsx("path",{d:"M7 0h21l12 12v36H7c-2.2 0-4-1.8-4-4V4c0-2.2 1.8-4 4-4z",fill:"#ff6b6b"}),e.jsx("path",{d:"M28 0v12h12",fill:"#d65a5a"}),e.jsx("text",{x:"50%",y:"32",textAnchor:"middle",fill:"white",fontSize:"11",fontFamily:"sans-serif",fontWeight:"bold",children:"PDF"})]}):n==="WORD"?e.jsxs("svg",{viewBox:"0 0 40 48",className:j("drop-shadow-sm",r),children:[e.jsx("path",{d:"M7 0h21l12 12v36H7c-2.2 0-4-1.8-4-4V4c0-2.2 1.8-4 4-4z",fill:"#2b579a"}),e.jsx("path",{d:"M28 0v12h12",fill:"#1e3d6b"}),e.jsx("text",{x:"50%",y:"32",textAnchor:"middle",fill:"white",fontSize:"11",fontFamily:"sans-serif",fontWeight:"bold",children:"DOC"}),e.jsx("path",{d:"M12 20h16v2H12zM12 24h16v2H12zM12 28h10v2H12z",fill:"white",fillOpacity:"0.6"})]}):n==="EXCEL"?e.jsxs("svg",{viewBox:"0 0 40 48",className:j("drop-shadow-sm",r),children:[e.jsx("path",{d:"M7 0h21l12 12v36H7c-2.2 0-4-1.8-4-4V4c0-2.2 1.8-4 4-4z",fill:"#217346"}),e.jsx("path",{d:"M28 0v12h12",fill:"#154a2d"}),e.jsx("text",{x:"50%",y:"32",textAnchor:"middle",fill:"white",fontSize:"11",fontFamily:"sans-serif",fontWeight:"bold",children:"XLS"}),e.jsx("rect",{x:"13",y:"18",width:"14",height:"2",fill:"white",fillOpacity:"0.6"}),e.jsx("rect",{x:"13",y:"22",width:"14",height:"2",fill:"white",fillOpacity:"0.6"}),e.jsx("rect",{x:"13",y:"26",width:"14",height:"2",fill:"white",fillOpacity:"0.6"})]}):n==="CSV"?e.jsxs("svg",{viewBox:"0 0 40 48",className:j("drop-shadow-sm",r),children:[e.jsx("path",{d:"M7 0h21l12 12v36H7c-2.2 0-4-1.8-4-4V4c0-2.2 1.8-4 4-4z",fill:"#0f766e"}),e.jsx("path",{d:"M28 0v12h12",fill:"#0d5f58"}),e.jsx("text",{x:"50%",y:"32",textAnchor:"middle",fill:"white",fontSize:"11",fontFamily:"sans-serif",fontWeight:"bold",children:"CSV"}),e.jsx("rect",{x:"13",y:"18",width:"14",height:"2",fill:"white",fillOpacity:"0.6"}),e.jsx("rect",{x:"13",y:"22",width:"14",height:"2",fill:"white",fillOpacity:"0.6"}),e.jsx("path",{d:"M13 26h14v2h-14z",fill:"white",fillOpacity:"0.6"})]}):n==="PPT"?e.jsxs("svg",{viewBox:"0 0 40 48",className:j("drop-shadow-sm",r),children:[e.jsx("path",{d:"M7 0h21l12 12v36H7c-2.2 0-4-1.8-4-4V4c0-2.2 1.8-4 4-4z",fill:"#d24726"}),e.jsx("path",{d:"M28 0v12h12",fill:"#a03218"}),e.jsx("text",{x:"50%",y:"32",textAnchor:"middle",fill:"white",fontSize:"11",fontFamily:"sans-serif",fontWeight:"bold",children:"PPT"}),e.jsx("circle",{cx:"20",cy:"22",r:"5",fill:"white",fillOpacity:"0.4"})]}):n==="TEXT"?e.jsxs("svg",{viewBox:"0 0 40 48",className:j("drop-shadow-sm",r),children:[e.jsx("path",{d:"M7 0h21l12 12v36H7c-2.2 0-4-1.8-4-4V4c0-2.2 1.8-4 4-4z",fill:"#757575"}),e.jsx("path",{d:"M28 0v12h12",fill:"#505050"}),e.jsx("text",{x:"50%",y:"34",textAnchor:"middle",fill:"white",fontSize:"10",fontFamily:"sans-serif",fontWeight:"bold",children:"TXT"}),e.jsx("path",{d:"M12 14h16v2H12zM12 18h16v2H12zM12 22h16v2H12z",fill:"white",fillOpacity:"0.7"})]}):e.jsxs("svg",{viewBox:"0 0 40 48",className:j("drop-shadow-sm",r),children:[e.jsx("path",{d:"M7 0h21l12 12v36H7c-2.2 0-4-1.8-4-4V4c0-2.2 1.8-4 4-4z",fill:"#94a3b8"}),e.jsx("path",{d:"M28 0v12h12",fill:"#64748b"}),e.jsx("text",{x:"50%",y:"32",textAnchor:"middle",fill:"white",fontSize:"10",fontFamily:"sans-serif",fontWeight:"bold",children:l()})]});case"VIDEO":return e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:r,children:e.jsx("path",{d:"M18 4l2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4h-4z"})});case"IMAGE":default:return e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:r,children:e.jsx("path",{d:"M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"})})}},ft=({onUpload:t,currentMedia:s,onRemove:r,maxSizeMB:a,compatibleChannels:l=[],forceOriginal:n=!1,acceptedTypes:i,onPreviewClick:c,mediaLimits:d})=>{const f=p.useRef(null),[m,y]=p.useState(!1),{uploadFile:g,uploadState:o,feedback:u,error:T}=Fe({mediaLimits:d||{image:{maxBytes:a*1024*1024},video:{maxBytes:a*1024*1024},audio:{maxBytes:a*1024*1024},document:{maxBytes:a*1024*1024}},onError:h=>{console.error("[MediaDropzone] Error:",h),de.error("Error al subir multimedia",{description:h.message})}}),N=o!=="IDLE"&&o!=="DONE"&&o!=="ERROR",v=o==="OPTIMIZING",R=o==="ERROR",E=async h=>{try{const x=await g(h);x&&t({id:x.id,detectedType:x.mimeType.startsWith("image/")?"IMAGE":x.mimeType.startsWith("video/")?"VIDEO":"DOCUMENT",previewUrl:x.signedUrl,signedUrl:x.signedUrl,thumbnailUrl:x.thumbnailUrl||void 0,mimeType:x.mimeType,originalName:h.name,gcsPath:x.gcsPath,fileSize:x.size,hash:x.hash,isDuplicate:x.isDuplicate,optimizationStats:x.optimizationStats,file:h,originalFile:h})}catch{}},I=h=>{h.target.files&&h.target.files[0]&&E(h.target.files[0])},k=h=>{h.preventDefault(),y(!1),h.dataTransfer.files&&h.dataTransfer.files[0]&&E(h.dataTransfer.files[0])},A=s?.detectedType,L=s?.previewUrl||s?.thumbnailUrl||s?.signedUrl,U=l.filter(h=>!h.isCompatible),C=N;return s?e.jsxs("div",{className:j("relative group overflow-hidden rounded-xl border border-border bg-background shadow-sm transition-all hover:shadow-md",c&&"cursor-pointer"),onClick:()=>c?.(s),children:[e.jsxs("div",{className:"h-40 w-full bg-muted/20 flex items-center justify-center relative overflow-hidden",children:[N&&e.jsx("div",{className:"absolute inset-0 z-20 bg-background/60 backdrop-blur-[1px] flex items-center justify-center transition-all duration-300",children:e.jsx("div",{className:"bg-background/80 p-2 rounded-full shadow-lg border border-border/50",children:e.jsx(q,{className:"h-5 w-5 text-primary animate-spin"})})}),A==="IMAGE"&&L?e.jsx(X,{src:L,alt:"Preview",className:"w-full h-full object-contain"}):A==="VIDEO"?e.jsxs("div",{className:"relative w-full h-full flex items-center justify-center bg-gradient-to-br from-purple-50 to-blue-50 dark:from-purple-900/20 dark:to-blue-900/20",children:[s.thumbnailUrl?e.jsx(X,{src:s.thumbnailUrl,className:"absolute inset-0 w-full h-full object-cover",alt:"Video thumbnail"}):null,e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10 pointer-events-none",children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 rounded-full bg-gradient-to-tr from-purple-500 to-blue-500 opacity-20 blur-md animate-pulse"}),e.jsx("div",{className:"relative h-16 w-16 rounded-full bg-gradient-to-br from-purple-500 to-blue-500 flex items-center justify-center shadow-lg",children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"w-8 h-8 text-white ml-1",children:e.jsx("path",{d:"M8 5v14l11-7z"})})})]})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-3 text-muted-foreground w-full px-6",children:[e.jsx("div",{className:"h-16 w-14 flex items-center justify-center relative shrink-0",children:e.jsx(Ve,{type:A,subtype:s.mimeType,className:"h-full w-full"})}),e.jsxs("div",{className:"flex flex-col items-center gap-1 w-full",children:[e.jsx("span",{className:"text-sm font-semibold truncate max-w-full text-foreground/80",children:s.originalName||"Archivo sin nombre"}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] uppercase tracking-wider font-medium opacity-60",children:[e.jsx("span",{children:s.fileSize?B(s.fileSize):"–"}),e.jsx("span",{className:"w-0.5 h-0.5 rounded-full bg-current"}),e.jsx("span",{children:s.mimeType.split("/")[1]})]})]})]}),c&&e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center opacity-0 group-hover:opacity-100 z-10",children:A==="DOCUMENT"?e.jsx(Y,{className:"w-8 h-8 text-white drop-shadow-md"}):e.jsx(fe,{className:"w-8 h-8 text-white drop-shadow-md"})})]}),e.jsx("div",{className:"absolute top-2 right-2 z-30 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(G,{variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full shadow-lg border border-white/20 hover:scale-105 transition-transform",onClick:h=>{h.stopPropagation(),r()},children:e.jsx(ge,{className:"h-4 w-4"})})}),e.jsxs("div",{className:"px-3 py-2 bg-card text-xs border-t relative overflow-hidden",children:[C&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-1 bg-muted",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-500 ease-out",style:{width:`${s.uploadProgress||0}%`}})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("span",{className:"font-medium text-muted-foreground flex items-center gap-2",children:[A,e.jsx("span",{className:"w-1 h-1 rounded-full bg-muted-foreground/30"}),e.jsx("span",{className:C?"text-primary animate-pulse":v?"text-amber-500 animate-pulse":"",children:C?"Subiendo...":v?"Optimizando...":"Listo"}),s.isDuplicate&&!C&&!v&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-muted-foreground/30"}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-bold text-[#00A884] bg-[#00A884]/10 px-1.5 py-0.5 rounded-md border border-[#00A884]/20 animate-in fade-in zoom-in duration-500",children:[e.jsx(H,{className:"h-2.5 w-2.5 fill-current"}),"CLOUD REUSED"]})]})]}),!C&&!v&&s.fileSize&&e.jsxs("span",{className:"text-[10px] opacity-60",children:[s.optimizationStats&&!n?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"line-through opacity-70",children:B(s.optimizationStats.originalSize)})," -> ",e.jsx("span",{className:"text-green-600 dark:text-green-400 font-medium",children:B(s.optimizationStats.optimizedSize)})]}):B(n&&s.optimizationStats?s.optimizationStats.originalSize:s.fileSize)," • ",n?"DOCUMENT":s.mimeType.split("/")[1]?.toUpperCase()]})]}),U.length>0&&!C&&e.jsxs("div",{className:"flex items-center gap-1.5 text-amber-600 dark:text-amber-500 bg-amber-50 dark:bg-amber-900/20 px-2 py-0.5 rounded-full border border-amber-100 dark:border-amber-800/30",children:[e.jsx(ce,{className:"h-3 w-3"}),e.jsxs("span",{className:"font-medium",children:[U.length," alertas"]})]})]}),U.length>0&&!C&&e.jsx("div",{className:"mt-2 space-y-1 pb-1",children:U.map(h=>e.jsxs("div",{className:"flex items-start gap-1.5 text-[10px] text-amber-600/90 dark:text-amber-400",children:[e.jsx(W,{className:"h-3 w-3 shrink-0 mt-0.5"}),e.jsxs("span",{children:[e.jsxs("span",{className:"font-semibold",children:[h.channelName,":"]})," ",h.reason]})]},h.channelId))})]})]}):e.jsxs("div",{className:j("relative border-2 border-dashed rounded-xl transition-all duration-200 ease-in-out cursor-pointer group",m?"border-primary bg-primary/5 scale-[1.01]":R?"border-red-500 bg-red-500/5":"border-border hover:border-primary/50 hover:bg-muted/30",N?"pointer-events-none opacity-50":""),onDragOver:h=>{h.preventDefault(),y(!0)},onDragLeave:()=>y(!1),onDrop:k,onClick:()=>f.current?.click(),children:[e.jsx("input",{ref:f,type:"file",className:"hidden",accept:i?Object.keys(i).join(","):"image/*,video/*,audio/*,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,text/plain,text/csv,application/zip,application/x-zip-compressed,application/x-rar-compressed,application/json,application/rtf",onChange:I}),e.jsx("div",{className:"flex flex-col items-center justify-center py-10 px-4 text-center",children:N?e.jsxs("div",{className:"flex flex-col items-center animate-in fade-in duration-300",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-primary/20"}),e.jsx(q,{className:"h-8 w-8 text-primary animate-spin"})]}),e.jsx("p",{className:"mt-3 text-xs font-medium text-muted-foreground animate-pulse",children:v?"Optimizando...":"Procesando..."})]}):R?e.jsxs("div",{className:"flex flex-col items-center animate-in fade-in duration-300",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-red-500/10 text-red-500 flex items-center justify-center mb-4 border border-red-500/20",children:e.jsx(W,{className:"h-6 w-6"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-semibold text-red-600 dark:text-red-400",children:"Fallo en la carga"}),e.jsx("p",{className:"text-xs text-muted-foreground max-w-[280px] line-clamp-2",children:T?.message||u})]}),e.jsx(G,{variant:"link",size:"sm",className:"mt-4 text-primary h-auto p-0 font-semibold",onClick:h=>{h.stopPropagation(),f.current?.click()},children:"Intentar de nuevo"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:j("h-12 w-12 rounded-full flex items-center justify-center mb-4 transition-transform duration-300 group-hover:scale-110",m?"bg-primary/10 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(be,{className:"h-6 w-6"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:m?"Suelta el archivo aquí":"Haz clic o arrastra un archivo"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Soporta Multimedia, Office, PDF y ZIP",d?" (según límites del canal)":` hasta ${a}MB`]})]})]})})]})},gt={BODY_TEXT:1024,CAROUSEL_MIN_CARDS:2,CAROUSEL_MAX_CARDS:10,CAROUSEL_CARD_BODY:160,CAROUSEL_MAX_CARD_BUTTONS:2,CAROUSEL_BUTTON_TITLE:20,CAROUSEL_BUTTON_URL:2e3};export{Ve as F,at as H,Ie as I,ee as M,tt as P,je as R,X as S,nt as V,st as a,rt as b,it as c,dt as d,mt as e,pt as f,Fe as g,S as h,ht as i,lt as j,xt as k,ft as l,gt as m,se as n,ut as o,te as p,ot as q,ct as r,M as t,J as u};
@@ -1 +0,0 @@
1
- import{aA as a}from"./index-DsyZ_FlA.js";import"./recharts-DrC5kNsx.js";const t=a;export{t as LandingPage,a as default};
@@ -1 +0,0 @@
1
- import{c as r}from"./index-DsyZ_FlA.js";import{b as m,a as d,f as t}from"./storage.api-CFU3KJNp.js";const u=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],z=r("message-circle-question-mark",u);const l=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],v=r("paperclip",l);function h(a,o=m){const e=d(a.type);if(!e)return{isValid:!1,action:"REJECT",userMessage:"Este tipo de archivo no es compatible.",suggestion:"Intenta con una imagen, video, audio o documento.",originalSize:a.size,maxAllowed:0};const i=o[e].maxBytes,s=t(a.size),c=t(i);if(a.size<=i)return{isValid:!0,action:"SEND",originalSize:a.size,maxAllowed:i};const n={image:"imagen",video:"video",audio:"audio",document:"documento"}[e];return e==="image"?{isValid:!0,action:"SEND",userMessage:`La imagen (${s}) se optimizará automáticamente.`,originalSize:a.size,maxAllowed:i}:{isValid:!1,action:"REJECT",userMessage:`${n.charAt(0).toUpperCase()+n.slice(1)} demasiado grande (${s}). Límite: ${c}.`,suggestion:p(e,i),originalSize:a.size,maxAllowed:i}}function p(a,o){const e=t(o);switch(a){case"image":return"Reduce el tamaño de la imagen o usa formato JPEG.";case"video":return`Comprime el video o reduce su resolución. Máximo: ${e}.`;case"audio":return`Reduce la duración del audio. Máximo: ${e}.`;case"document":return`Divide el documento en partes más pequeñas. Máximo: ${e}.`;default:return`El archivo debe ser menor a ${e}.`}}export{z as M,v as P,h as v};
@@ -1 +0,0 @@
1
- import{c as o}from"./index-DsyZ_FlA.js";const c=[["path",{d:"M5 12h14",key:"1ays0h"}]],e=o("minus",c);export{e as M};