@salla.sa/twilight-components 2.14.509 → 2.14.510

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 (341) hide show
  1. package/dist/cjs/{filepond-Dn8WkI9_.js → filepond-COZHgu78.js} +1 -1
  2. package/dist/cjs/{filepond-plugin-file-poster-mufjzLbD.js → filepond-plugin-file-poster-Bi4mWImr.js} +1 -1
  3. package/dist/cjs/{filepond-plugin-file-validate-size-BC6t5UPj.js → filepond-plugin-file-validate-size-CtrIas22.js} +1 -1
  4. package/dist/cjs/{filepond-plugin-file-validate-type-CaQ5Kqok.js → filepond-plugin-file-validate-type-Djj5o2ks.js} +1 -1
  5. package/dist/cjs/{filepond-plugin-image-edit-DvSmfnUl.js → filepond-plugin-image-edit-CaVm_-Xi.js} +1 -1
  6. package/dist/cjs/{filepond-plugin-image-exif-orientation-Br5ovpCW.js → filepond-plugin-image-exif-orientation-BD44-lrC.js} +1 -1
  7. package/dist/cjs/{filepond-plugin-image-preview-C71ogaak.js → filepond-plugin-image-preview-BlHYB_rk.js} +1 -1
  8. package/dist/cjs/{functions-DgFPxTJv.js → functions-D7e0oMZu.js} +1 -1
  9. package/dist/cjs/{index-CeEhEVDJ.js → index-D6MQobeP.js} +2 -2
  10. package/dist/cjs/{index-DHuZTkix.js → index-KhpPkTL1.js} +1 -1
  11. package/dist/cjs/loader.cjs.js +2 -2
  12. package/dist/cjs/salla-accordion-body_2.cjs.entry.js +1 -1
  13. package/dist/cjs/salla-accordion_6.cjs.entry.js +1 -1
  14. package/dist/cjs/salla-add-product-button_5.cjs.entry.js +1 -1
  15. package/dist/cjs/salla-advertisement.cjs.entry.js +1 -1
  16. package/dist/cjs/salla-alert_2.cjs.entry.js +1 -1
  17. package/dist/cjs/salla-app-install-alert.cjs.entry.js +1 -1
  18. package/dist/cjs/salla-apps-icons.cjs.entry.js +1 -1
  19. package/dist/cjs/salla-badge.cjs.entry.js +1 -1
  20. package/dist/cjs/salla-basket-gap.cjs.entry.js +1 -1
  21. package/dist/cjs/salla-booking-field_7.cjs.entry.js +10 -10
  22. package/dist/cjs/salla-bullet-delivery_2.cjs.entry.js +1 -1
  23. package/dist/cjs/salla-cart-coupons.cjs.entry.js +36 -16
  24. package/dist/cjs/salla-cart-item-offers_2.cjs.entry.js +1 -1
  25. package/dist/cjs/salla-cart-summary-card.cjs.entry.js +1 -1
  26. package/dist/cjs/salla-cashback-banner.cjs.entry.js +1 -1
  27. package/dist/cjs/salla-comment-factors.cjs.entry.js +1 -1
  28. package/dist/cjs/salla-comment-form_8.cjs.entry.js +1 -1
  29. package/dist/cjs/salla-conditional-offer.cjs.entry.js +1 -1
  30. package/dist/cjs/salla-contacts.cjs.entry.js +1 -1
  31. package/dist/cjs/salla-cookies-bar.cjs.entry.js +1 -1
  32. package/dist/cjs/salla-count-down_2.cjs.entry.js +1 -1
  33. package/dist/cjs/salla-custom-fields.cjs.entry.js +1 -1
  34. package/dist/cjs/salla-delivery-promise.cjs.entry.js +1 -1
  35. package/dist/cjs/salla-edit-order-button.cjs.entry.js +1 -1
  36. package/dist/cjs/salla-filters-widget.cjs.entry.js +1 -1
  37. package/dist/cjs/salla-filters.cjs.entry.js +1 -1
  38. package/dist/cjs/salla-fulfillment-methods.cjs.entry.js +1 -1
  39. package/dist/cjs/salla-gifting.cjs.entry.js +1 -1
  40. package/dist/cjs/salla-hook.cjs.entry.js +1 -1
  41. package/dist/cjs/salla-infinite-scroll.cjs.entry.js +1 -1
  42. package/dist/cjs/salla-installment.cjs.entry.js +1 -1
  43. package/dist/cjs/salla-list-tile.cjs.entry.js +1 -1
  44. package/dist/cjs/salla-localization-modal.cjs.entry.js +1 -1
  45. package/dist/cjs/salla-login-modal.cjs.entry.js +1 -1
  46. package/dist/cjs/salla-loyalty-banner.cjs.entry.js +2 -2
  47. package/dist/cjs/salla-loyalty-exchange-product-card_5.cjs.entry.js +3 -3
  48. package/dist/cjs/salla-loyalty-hero_2.cjs.entry.js +2 -2
  49. package/dist/cjs/salla-loyalty-panel.cjs.entry.js +3 -3
  50. package/dist/cjs/salla-loyalty-points-banner.cjs.entry.js +1 -1
  51. package/dist/cjs/salla-loyalty-points-history.cjs.entry.js +1 -1
  52. package/dist/cjs/salla-loyalty-prize-item.cjs.entry.js +1 -1
  53. package/dist/cjs/salla-loyalty-program.cjs.entry.js +3 -3
  54. package/dist/cjs/salla-loyalty-reward.cjs.entry.js +2 -2
  55. package/dist/cjs/salla-loyalty.cjs.entry.js +1 -1
  56. package/dist/cjs/salla-maintenance-alert.cjs.entry.js +1 -1
  57. package/dist/cjs/salla-map_2.cjs.entry.js +1 -1
  58. package/dist/cjs/salla-menu.cjs.entry.js +1 -1
  59. package/dist/cjs/salla-metadata.cjs.entry.js +1 -1
  60. package/dist/cjs/salla-multiple-bundle-product-cart_2.cjs.entry.js +1 -1
  61. package/dist/cjs/salla-multiple-bundle-product-options-modal_2.cjs.entry.js +1 -1
  62. package/dist/cjs/salla-multiple-bundle-product.cjs.entry.js +1 -1
  63. package/dist/cjs/salla-next-order-coupon.cjs.entry.js +1 -1
  64. package/dist/cjs/salla-notification-item.cjs.entry.js +1 -1
  65. package/dist/cjs/salla-notifications.cjs.entry.js +1 -1
  66. package/dist/cjs/salla-offer-modal.cjs.entry.js +1 -1
  67. package/dist/cjs/salla-offer.cjs.entry.js +1 -1
  68. package/dist/cjs/salla-order-branch.cjs.entry.js +1 -1
  69. package/dist/cjs/salla-order-cancel.cjs.entry.js +1 -1
  70. package/dist/cjs/salla-order-details-multiple-bundle-product.cjs.entry.js +1 -1
  71. package/dist/cjs/salla-order-details-options.cjs.entry.js +1 -1
  72. package/dist/cjs/salla-order-details.cjs.entry.js +1 -1
  73. package/dist/cjs/salla-order-edit-item.cjs.entry.js +1 -1
  74. package/dist/cjs/salla-order-edit-product-card.cjs.entry.js +1 -1
  75. package/dist/cjs/salla-order-edit.cjs.entry.js +1 -1
  76. package/dist/cjs/salla-order-summary.cjs.entry.js +1 -1
  77. package/dist/cjs/salla-order-totals-card.cjs.entry.js +1 -1
  78. package/dist/cjs/salla-orders.cjs.entry.js +1 -1
  79. package/dist/cjs/salla-payments.cjs.entry.js +1 -1
  80. package/dist/cjs/salla-placeholder.cjs.entry.js +1 -1
  81. package/dist/cjs/salla-price-range.cjs.entry.js +1 -1
  82. package/dist/cjs/salla-product-card-embed.cjs.entry.js +1 -1
  83. package/dist/cjs/salla-product-card_2.cjs.entry.js +36 -6
  84. package/dist/cjs/salla-product-size-guide.cjs.entry.js +1 -1
  85. package/dist/cjs/salla-products-list.cjs.entry.js +26 -3
  86. package/dist/cjs/salla-quick-order.cjs.entry.js +1 -1
  87. package/dist/cjs/salla-rating-modal-v2.cjs.entry.js +1 -1
  88. package/dist/cjs/salla-rating-modal.cjs.entry.js +1 -1
  89. package/dist/cjs/salla-review-factors-tags.cjs.entry.js +1 -1
  90. package/dist/cjs/salla-scopes.cjs.entry.js +1 -1
  91. package/dist/cjs/salla-search.cjs.entry.js +1 -1
  92. package/dist/cjs/salla-skeleton.cjs.entry.js +1 -1
  93. package/dist/cjs/salla-slider.cjs.entry.js +1 -1
  94. package/dist/cjs/salla-social-share.cjs.entry.js +1 -1
  95. package/dist/cjs/salla-social.cjs.entry.js +1 -1
  96. package/dist/cjs/salla-tab-content_3.cjs.entry.js +1 -1
  97. package/dist/cjs/salla-tiered-offer.cjs.entry.js +1 -1
  98. package/dist/cjs/salla-tooltip.cjs.entry.js +1 -1
  99. package/dist/cjs/salla-trust-badges.cjs.entry.js +1 -1
  100. package/dist/cjs/salla-user-menu.cjs.entry.js +1 -1
  101. package/dist/cjs/salla-user-profile.cjs.entry.js +1 -1
  102. package/dist/cjs/salla-user-settings.cjs.entry.js +1 -1
  103. package/dist/cjs/salla-verify.cjs.entry.js +1 -1
  104. package/dist/cjs/salla-wallet.cjs.entry.js +1 -1
  105. package/dist/cjs/salla-wishlist-actions.cjs.entry.js +1 -1
  106. package/dist/cjs/{tracked-promise-DDnavSzb.js → tracked-promise-Dmb45-BD.js} +1 -1
  107. package/dist/cjs/twilight.cjs.js +2 -2
  108. package/dist/cjs/{vanilla-picker-CyrLIKBL.js → vanilla-picker-B_OQkkn3.js} +1 -1
  109. package/dist/collection/components/salla-cart-coupons/salla-cart-coupons.js +36 -15
  110. package/dist/collection/components/salla-products-list/salla-products-list.js +25 -2
  111. package/dist/collection/components/salla-products-slider/salla-products-slider.js +35 -5
  112. package/dist/components/index.js +2 -2
  113. package/dist/components/salla-cart-coupons.js +36 -15
  114. package/dist/components/salla-products-list2.js +25 -2
  115. package/dist/components/salla-products-slider2.js +35 -5
  116. package/dist/esm/{filepond-Cu0hGP46.js → filepond-B1eTr-KK.js} +1 -1
  117. package/dist/esm/{filepond-plugin-file-poster-DBfLrjkx.js → filepond-plugin-file-poster-exJROlFk.js} +1 -1
  118. package/dist/esm/{filepond-plugin-file-validate-size-Cq0e60aE.js → filepond-plugin-file-validate-size-CZY_F4BF.js} +1 -1
  119. package/dist/esm/{filepond-plugin-file-validate-type-CpRmNAFC.js → filepond-plugin-file-validate-type-D8z0FHfz.js} +1 -1
  120. package/dist/esm/{filepond-plugin-image-edit-C-7yhkPK.js → filepond-plugin-image-edit-CACbacvT.js} +1 -1
  121. package/dist/esm/{filepond-plugin-image-exif-orientation-CTn5LeXC.js → filepond-plugin-image-exif-orientation-DwS9XuCo.js} +1 -1
  122. package/dist/esm/{filepond-plugin-image-preview-BsETbqVf.js → filepond-plugin-image-preview-BYy-d2mY.js} +1 -1
  123. package/dist/esm/{functions-DtC2lEvS.js → functions-DEUWeLq4.js} +1 -1
  124. package/dist/esm/{index-BEjZOd--.js → index-Bt0ajKaf.js} +2 -2
  125. package/dist/esm/{index-DskkoO4T.js → index-FMb5OkaH.js} +1 -1
  126. package/dist/esm/loader.js +3 -3
  127. package/dist/esm/salla-accordion-body_2.entry.js +1 -1
  128. package/dist/esm/salla-accordion_6.entry.js +1 -1
  129. package/dist/esm/salla-add-product-button_5.entry.js +1 -1
  130. package/dist/esm/salla-advertisement.entry.js +1 -1
  131. package/dist/esm/salla-alert_2.entry.js +1 -1
  132. package/dist/esm/salla-app-install-alert.entry.js +1 -1
  133. package/dist/esm/salla-apps-icons.entry.js +1 -1
  134. package/dist/esm/salla-badge.entry.js +1 -1
  135. package/dist/esm/salla-basket-gap.entry.js +1 -1
  136. package/dist/esm/salla-booking-field_7.entry.js +10 -10
  137. package/dist/esm/salla-bullet-delivery_2.entry.js +1 -1
  138. package/dist/esm/salla-cart-coupons.entry.js +36 -16
  139. package/dist/esm/salla-cart-item-offers_2.entry.js +1 -1
  140. package/dist/esm/salla-cart-summary-card.entry.js +1 -1
  141. package/dist/esm/salla-cashback-banner.entry.js +1 -1
  142. package/dist/esm/salla-comment-factors.entry.js +1 -1
  143. package/dist/esm/salla-comment-form_8.entry.js +1 -1
  144. package/dist/esm/salla-conditional-offer.entry.js +1 -1
  145. package/dist/esm/salla-contacts.entry.js +1 -1
  146. package/dist/esm/salla-cookies-bar.entry.js +1 -1
  147. package/dist/esm/salla-count-down_2.entry.js +1 -1
  148. package/dist/esm/salla-custom-fields.entry.js +1 -1
  149. package/dist/esm/salla-delivery-promise.entry.js +1 -1
  150. package/dist/esm/salla-edit-order-button.entry.js +1 -1
  151. package/dist/esm/salla-filters-widget.entry.js +1 -1
  152. package/dist/esm/salla-filters.entry.js +1 -1
  153. package/dist/esm/salla-fulfillment-methods.entry.js +1 -1
  154. package/dist/esm/salla-gifting.entry.js +1 -1
  155. package/dist/esm/salla-hook.entry.js +1 -1
  156. package/dist/esm/salla-infinite-scroll.entry.js +1 -1
  157. package/dist/esm/salla-installment.entry.js +1 -1
  158. package/dist/esm/salla-list-tile.entry.js +1 -1
  159. package/dist/esm/salla-localization-modal.entry.js +1 -1
  160. package/dist/esm/salla-login-modal.entry.js +1 -1
  161. package/dist/esm/salla-loyalty-banner.entry.js +2 -2
  162. package/dist/esm/salla-loyalty-exchange-product-card_5.entry.js +3 -3
  163. package/dist/esm/salla-loyalty-hero_2.entry.js +2 -2
  164. package/dist/esm/salla-loyalty-panel.entry.js +3 -3
  165. package/dist/esm/salla-loyalty-points-banner.entry.js +1 -1
  166. package/dist/esm/salla-loyalty-points-history.entry.js +1 -1
  167. package/dist/esm/salla-loyalty-prize-item.entry.js +1 -1
  168. package/dist/esm/salla-loyalty-program.entry.js +3 -3
  169. package/dist/esm/salla-loyalty-reward.entry.js +2 -2
  170. package/dist/esm/salla-loyalty.entry.js +1 -1
  171. package/dist/esm/salla-maintenance-alert.entry.js +1 -1
  172. package/dist/esm/salla-map_2.entry.js +1 -1
  173. package/dist/esm/salla-menu.entry.js +1 -1
  174. package/dist/esm/salla-metadata.entry.js +1 -1
  175. package/dist/esm/salla-multiple-bundle-product-cart_2.entry.js +1 -1
  176. package/dist/esm/salla-multiple-bundle-product-options-modal_2.entry.js +1 -1
  177. package/dist/esm/salla-multiple-bundle-product.entry.js +1 -1
  178. package/dist/esm/salla-next-order-coupon.entry.js +1 -1
  179. package/dist/esm/salla-notification-item.entry.js +1 -1
  180. package/dist/esm/salla-notifications.entry.js +1 -1
  181. package/dist/esm/salla-offer-modal.entry.js +1 -1
  182. package/dist/esm/salla-offer.entry.js +1 -1
  183. package/dist/esm/salla-order-branch.entry.js +1 -1
  184. package/dist/esm/salla-order-cancel.entry.js +1 -1
  185. package/dist/esm/salla-order-details-multiple-bundle-product.entry.js +1 -1
  186. package/dist/esm/salla-order-details-options.entry.js +1 -1
  187. package/dist/esm/salla-order-details.entry.js +1 -1
  188. package/dist/esm/salla-order-edit-item.entry.js +1 -1
  189. package/dist/esm/salla-order-edit-product-card.entry.js +1 -1
  190. package/dist/esm/salla-order-edit.entry.js +1 -1
  191. package/dist/esm/salla-order-summary.entry.js +1 -1
  192. package/dist/esm/salla-order-totals-card.entry.js +1 -1
  193. package/dist/esm/salla-orders.entry.js +1 -1
  194. package/dist/esm/salla-payments.entry.js +1 -1
  195. package/dist/esm/salla-placeholder.entry.js +1 -1
  196. package/dist/esm/salla-price-range.entry.js +1 -1
  197. package/dist/esm/salla-product-card-embed.entry.js +1 -1
  198. package/dist/esm/salla-product-card_2.entry.js +36 -6
  199. package/dist/esm/salla-product-size-guide.entry.js +1 -1
  200. package/dist/esm/salla-products-list.entry.js +26 -3
  201. package/dist/esm/salla-quick-order.entry.js +1 -1
  202. package/dist/esm/salla-rating-modal-v2.entry.js +1 -1
  203. package/dist/esm/salla-rating-modal.entry.js +1 -1
  204. package/dist/esm/salla-review-factors-tags.entry.js +1 -1
  205. package/dist/esm/salla-scopes.entry.js +1 -1
  206. package/dist/esm/salla-search.entry.js +1 -1
  207. package/dist/esm/salla-skeleton.entry.js +1 -1
  208. package/dist/esm/salla-slider.entry.js +1 -1
  209. package/dist/esm/salla-social-share.entry.js +1 -1
  210. package/dist/esm/salla-social.entry.js +1 -1
  211. package/dist/esm/salla-tab-content_3.entry.js +1 -1
  212. package/dist/esm/salla-tiered-offer.entry.js +1 -1
  213. package/dist/esm/salla-tooltip.entry.js +1 -1
  214. package/dist/esm/salla-trust-badges.entry.js +1 -1
  215. package/dist/esm/salla-user-menu.entry.js +1 -1
  216. package/dist/esm/salla-user-profile.entry.js +1 -1
  217. package/dist/esm/salla-user-settings.entry.js +1 -1
  218. package/dist/esm/salla-verify.entry.js +1 -1
  219. package/dist/esm/salla-wallet.entry.js +1 -1
  220. package/dist/esm/salla-wishlist-actions.entry.js +1 -1
  221. package/dist/esm/{tracked-promise-DzdT8znx.js → tracked-promise-T29mWxDS.js} +1 -1
  222. package/dist/esm/twilight.js +3 -3
  223. package/dist/esm/{vanilla-picker-DzKX2qA5.js → vanilla-picker-Dpp89BQ6.js} +1 -1
  224. package/dist/twilight/{p-557609aa.entry.js → p-055187ca.entry.js} +1 -1
  225. package/dist/twilight/{p-858f485b.entry.js → p-09ea780c.entry.js} +1 -1
  226. package/dist/twilight/{p-3350c805.entry.js → p-0adbdc90.entry.js} +1 -1
  227. package/dist/twilight/{p-8f982a91.entry.js → p-1071ea00.entry.js} +1 -1
  228. package/dist/twilight/{p-2643952e.entry.js → p-139c80a0.entry.js} +1 -1
  229. package/dist/twilight/{p-193cccd3.entry.js → p-1b0d555a.entry.js} +1 -1
  230. package/dist/twilight/{p-113e7032.entry.js → p-1e225a23.entry.js} +1 -1
  231. package/dist/twilight/{p-3ccbdb7a.entry.js → p-1f3d6151.entry.js} +1 -1
  232. package/dist/twilight/{p-925af19b.entry.js → p-22712655.entry.js} +1 -1
  233. package/dist/twilight/{p-42c57314.entry.js → p-22d6c097.entry.js} +1 -1
  234. package/dist/twilight/{p-3791a8d0.entry.js → p-23bfb6be.entry.js} +1 -1
  235. package/dist/twilight/{p-62abd25a.entry.js → p-277d5788.entry.js} +1 -1
  236. package/dist/twilight/{p-6ba99048.entry.js → p-2a4b20fa.entry.js} +1 -1
  237. package/dist/twilight/{p-d66af968.entry.js → p-2e6b6fbb.entry.js} +1 -1
  238. package/dist/twilight/{p-41ac2dc0.entry.js → p-2f7ddf17.entry.js} +1 -1
  239. package/dist/twilight/{p-b25fd5f0.entry.js → p-300e6aef.entry.js} +1 -1
  240. package/dist/twilight/{p-384febda.entry.js → p-301e3802.entry.js} +1 -1
  241. package/dist/twilight/{p-6d970be9.entry.js → p-346af34c.entry.js} +1 -1
  242. package/dist/twilight/{p-fc18bd83.entry.js → p-37e88d81.entry.js} +1 -1
  243. package/dist/twilight/{p-758894b7.entry.js → p-41269041.entry.js} +1 -1
  244. package/dist/twilight/{p-2c7e18c5.entry.js → p-4136f4d5.entry.js} +1 -1
  245. package/dist/twilight/{p-de07b85c.entry.js → p-42fc42d6.entry.js} +1 -1
  246. package/dist/twilight/{p-4317eeb9.entry.js → p-4328bd24.entry.js} +1 -1
  247. package/dist/twilight/{p-0a3e9f94.entry.js → p-44c94e17.entry.js} +1 -1
  248. package/dist/twilight/{p-b847e008.entry.js → p-457be53a.entry.js} +1 -1
  249. package/dist/twilight/{p-734dfd28.entry.js → p-49c926d2.entry.js} +1 -1
  250. package/dist/twilight/{p-8fcc4bb0.entry.js → p-4e7b8137.entry.js} +1 -1
  251. package/dist/twilight/{p-8ddfe69e.entry.js → p-4eb47f77.entry.js} +1 -1
  252. package/dist/twilight/{p-d76f186c.entry.js → p-4f61e580.entry.js} +1 -1
  253. package/dist/twilight/{p-3d44e1e9.entry.js → p-5255bb4a.entry.js} +1 -1
  254. package/dist/twilight/{p-4d76cd8f.entry.js → p-549b56f5.entry.js} +1 -1
  255. package/dist/twilight/{p-09cd7f70.entry.js → p-57919fb4.entry.js} +1 -1
  256. package/dist/twilight/{p-86df9649.entry.js → p-5a62369e.entry.js} +1 -1
  257. package/dist/twilight/{p-d53f9574.entry.js → p-5b9c3427.entry.js} +1 -1
  258. package/dist/twilight/{p-6c3b50e2.entry.js → p-5e02c7e7.entry.js} +1 -1
  259. package/dist/twilight/{p-74c84c67.entry.js → p-5e1140fb.entry.js} +1 -1
  260. package/dist/twilight/{p-33756c72.entry.js → p-5e851bce.entry.js} +1 -1
  261. package/dist/twilight/{p-37310557.entry.js → p-5f2f9351.entry.js} +1 -1
  262. package/dist/twilight/{p-0959b41c.entry.js → p-65ba2211.entry.js} +1 -1
  263. package/dist/twilight/{p-da441555.entry.js → p-67bd9271.entry.js} +1 -1
  264. package/dist/twilight/{p-effae25c.entry.js → p-6dd674c3.entry.js} +1 -1
  265. package/dist/twilight/{p-48cf6b68.entry.js → p-6ed50846.entry.js} +1 -1
  266. package/dist/twilight/{p-9807935d.entry.js → p-70a1619e.entry.js} +1 -1
  267. package/dist/twilight/{p-ed698e64.entry.js → p-70a9d197.entry.js} +1 -1
  268. package/dist/twilight/{p-27acb426.entry.js → p-75500766.entry.js} +1 -1
  269. package/dist/twilight/{p-9eade28d.entry.js → p-774fece9.entry.js} +1 -1
  270. package/dist/twilight/{p-f3f0ee9b.entry.js → p-7992cf55.entry.js} +1 -1
  271. package/dist/twilight/{p-296df4c6.entry.js → p-7d5855f2.entry.js} +1 -1
  272. package/dist/twilight/{p-12c571d7.entry.js → p-7d978fbc.entry.js} +1 -1
  273. package/dist/twilight/{p-518b6032.entry.js → p-7dfe0786.entry.js} +1 -1
  274. package/dist/twilight/p-7ebd07e6.entry.js +4 -0
  275. package/dist/twilight/{p-52c0a1b5.entry.js → p-86ec92b8.entry.js} +1 -1
  276. package/dist/twilight/{p-0950cbbb.entry.js → p-8775397b.entry.js} +1 -1
  277. package/dist/twilight/{p-03505fdd.entry.js → p-8a0d3cc9.entry.js} +1 -1
  278. package/dist/twilight/p-8a80f76c.entry.js +4 -0
  279. package/dist/twilight/{p-abd00b41.entry.js → p-8db02f76.entry.js} +1 -1
  280. package/dist/twilight/{p-bec996fb.entry.js → p-90de004a.entry.js} +1 -1
  281. package/dist/twilight/{p-bbb48f58.entry.js → p-91804117.entry.js} +1 -1
  282. package/dist/twilight/{p-fef39c48.entry.js → p-9310e773.entry.js} +1 -1
  283. package/dist/twilight/{p-8c6730a9.entry.js → p-95b32475.entry.js} +1 -1
  284. package/dist/twilight/{p-804cfed5.entry.js → p-97bb4320.entry.js} +1 -1
  285. package/dist/twilight/{p-7e4fea4b.entry.js → p-98b482a2.entry.js} +1 -1
  286. package/dist/twilight/p-9c12fd69.entry.js +4 -0
  287. package/dist/twilight/{p-30d6436e.entry.js → p-9c220b6d.entry.js} +1 -1
  288. package/dist/twilight/p-9cbf61c6.entry.js +4 -0
  289. package/dist/twilight/{p-Da0xrmo3.js → p-BBv-zo85.js} +2 -2
  290. package/dist/twilight/{p-Dv2SelMn.js → p-BF-dDqac.js} +1 -1
  291. package/dist/twilight/{p-CxQVHI3A.js → p-BFxb7lGH.js} +1 -1
  292. package/dist/twilight/{p-CCH8joDb.js → p-BUfV-mlp.js} +1 -1
  293. package/dist/twilight/p-Bt0ajKaf.js +5 -0
  294. package/dist/twilight/{p-BTVc7r-Z.js → p-C1E96uk_.js} +1 -1
  295. package/dist/twilight/p-CUg7C93N.js +4 -0
  296. package/dist/twilight/{p-CGahPnsw.js → p-CdRScS-B.js} +1 -1
  297. package/dist/twilight/{p-BDLhoSt2.js → p-CgGcK4mo.js} +1 -1
  298. package/dist/twilight/{p-COwpiJQt.js → p-DInaMMrI.js} +1 -1
  299. package/dist/twilight/p-DSxQpYYV.js +9 -0
  300. package/dist/twilight/{p-D2_JplO8.js → p-NoY5Pdvf.js} +1 -1
  301. package/dist/twilight/{p-725eeeed.entry.js → p-a660aacc.entry.js} +1 -1
  302. package/dist/twilight/{p-d6d8d12e.entry.js → p-a7e8ac45.entry.js} +1 -1
  303. package/dist/twilight/{p-8c03c0d2.entry.js → p-a8f28e45.entry.js} +1 -1
  304. package/dist/twilight/{p-27252d50.entry.js → p-aea5b09b.entry.js} +1 -1
  305. package/dist/twilight/{p-a476f7b2.entry.js → p-afd24c2b.entry.js} +1 -1
  306. package/dist/twilight/{p-e1842675.entry.js → p-b09fcdb4.entry.js} +1 -1
  307. package/dist/twilight/{p-fa7c213b.entry.js → p-b197fad7.entry.js} +1 -1
  308. package/dist/twilight/{p-8b9c8776.entry.js → p-b37ea19f.entry.js} +1 -1
  309. package/dist/twilight/{p-62a86556.entry.js → p-b626976f.entry.js} +1 -1
  310. package/dist/twilight/{p-7edc5c88.entry.js → p-bd847c2e.entry.js} +1 -1
  311. package/dist/twilight/{p-d6fbb91c.entry.js → p-c5d7a901.entry.js} +1 -1
  312. package/dist/twilight/{p-1bec8b0a.entry.js → p-cfc4cfaa.entry.js} +1 -1
  313. package/dist/twilight/{p-25f8d253.entry.js → p-d172feb2.entry.js} +1 -1
  314. package/dist/twilight/{p-b6322bba.entry.js → p-d18e08bd.entry.js} +1 -1
  315. package/dist/twilight/{p-017a1a77.entry.js → p-d4b2ce41.entry.js} +1 -1
  316. package/dist/twilight/{p-ad8eda9d.entry.js → p-d60ce89d.entry.js} +1 -1
  317. package/dist/twilight/{p-69758093.entry.js → p-dd87bf9c.entry.js} +1 -1
  318. package/dist/twilight/{p-e69c2c35.entry.js → p-e13fc06b.entry.js} +1 -1
  319. package/dist/twilight/{p-05f01920.entry.js → p-e232c59b.entry.js} +1 -1
  320. package/dist/twilight/{p-8d199be5.entry.js → p-e2693453.entry.js} +1 -1
  321. package/dist/twilight/{p-21870458.entry.js → p-e3e9a105.entry.js} +1 -1
  322. package/dist/twilight/{p-516e9179.entry.js → p-e57d1b21.entry.js} +1 -1
  323. package/dist/twilight/{p-6681db6a.entry.js → p-e8070f83.entry.js} +1 -1
  324. package/dist/twilight/{p-e78fe137.entry.js → p-e8a86f16.entry.js} +1 -1
  325. package/dist/twilight/{p-1df6827d.entry.js → p-ea0ca518.entry.js} +1 -1
  326. package/dist/twilight/{p-b2789ab4.entry.js → p-f0d1222d.entry.js} +1 -1
  327. package/dist/twilight/{p-1c03607d.entry.js → p-f61c0f39.entry.js} +1 -1
  328. package/dist/twilight/{p-5201eb4f.entry.js → p-f6efad0a.entry.js} +1 -1
  329. package/dist/twilight/{p-47a7f1a5.entry.js → p-f7a0c179.entry.js} +1 -1
  330. package/dist/twilight/twilight.esm.js +1 -1
  331. package/dist/types/components/salla-cart-coupons/salla-cart-coupons.d.ts +5 -0
  332. package/dist/types/components/salla-products-list/salla-products-list.d.ts +13 -0
  333. package/dist/types/components/salla-products-slider/salla-products-slider.d.ts +13 -0
  334. package/package.json +5 -5
  335. package/dist/twilight/p--UKCKF-7.js +0 -4
  336. package/dist/twilight/p-19388aef.entry.js +0 -4
  337. package/dist/twilight/p-5958986c.entry.js +0 -4
  338. package/dist/twilight/p-BEjZOd--.js +0 -5
  339. package/dist/twilight/p-Dw58JgkP.js +0 -9
  340. package/dist/twilight/p-c4f379a8.entry.js +0 -4
  341. package/dist/twilight/p-e7b03751.entry.js +0 -4
@@ -1,4 +1,4 @@
1
1
  /*!
2
2
  * Crafted with ❤ by Salla
3
3
  */
4
- import{r as t,f as a,h as s,H as i,a as e}from"./p-BEjZOd--.js";import{S as r}from"./p-CeFAfcTv.js";import{S as n}from"./p-lMgMt31Q.js";import{C as o}from"./p-BV4kqbdL.js";import{H as l}from"./p-XnA1YTjA.js";import{I as d}from"./p-C-tzSDxw.js";import{W as h}from"./p-CgR-T_ZS.js";import{e as g}from"./p-DzAIgzdz.js";import"./p-CgtvEd63.js";const m=class{constructor(a){t(this,a),this.hasError=!1,this.showContactWidget=!0,this.images=[],this.productImages={},this.editItemImages=[],this.productReviewFactors={},this.editFactorRatings={},this.productMainRatings={},this.productFactorRatings={},this.contact_body=(t,a,s)=>salla.lang.get("pages.rating.contact_subject",{store:t,id:a,customer:s}),this.editMode=!1,this.defaultMode=!1,this.deleteMode=!1,this.shouldOpenDeleteModal=!1,this.editItem=null,this.allowAttachImages=!1,this.allowContactSupport=!1,this.loyaltyImageRatingPoints=0,this.dragAndDropFilesLabel=salla.lang.get("common.uploader.drag_and_drop_files"),this.contactSubjectLabel=salla.lang.get("pages.rating.contact_subject"),this.editReviewLabel=salla.lang.get("pages.rating.edit_review"),this.allowedImagesTypesLabel=salla.lang.get("common.uploader.allowed_images_types"),this.threeImagesMax=salla.lang.get("common.uploader.max_three_images"),this.areYouSureLabel=salla.lang.get("pages.rating.are_you_sure_you_want_to_delete_review"),this.confirmDeletionLabel=salla.lang.get("pages.rating.confirm_deletion"),this.cancelLabel=salla.lang.get("common.elements.cancel"),this.confirmDeleteBtn=salla.lang.get("common.elements.confirm_delete"),this.updatedSuccessfullyLabel=salla.lang.get("pages.rating.review_updated_successfully"),this.deletedSuccessfullyLabel=salla.lang.get("pages.rating.review_deleted_successfully"),this.contactUsLabel=salla.lang.get("blocks.footer.social"),this.requiredFactorsLabel=salla.lang.get("pages.rating.rate_required_factors"),this.overallProductRatingLabel=salla.lang.get("pages.rating.overall_product_rating"),this.loyaltyPointsForImagesLabel=salla.lang.get("pages.rating.loyalty_points_for_images",{points:":points"}),this.contentRefs=[],this.hiddenInputs=[],this.userFilledFactorKeys={},this.boundRatingRows=new WeakSet,this.stepsCount=0,this.currentIndex=0,this.submitted=[],this.MAX_UPLOAD_LIMIT=3,this.thanksCountdownInterval=null,this.scheduleWizardSetup=!1,salla.lang.onLoaded((()=>{this.contactUsLabel=salla.lang.get("blocks.footer.social");const t=(t,a,s)=>new Promise((i=>{salla.helpers.setNested(salla.lang.messages[t],a,s),i(!0)}));(async()=>{await t("ar.trans","common.uploader.drag_and_drop_files","اسحب الملفات وأفلتها هنا"),await t("en.trans","common.uploader.drag_and_drop_files","Drag and drop files here"),await t("ar.trans","common.uploader.allowed_images_types"," .jpg أو jpeg أو png يُسمح بإضافة صور بصيغة"),await t("en.trans","common.uploader.allowed_images_types","Images in jpg, jpeg, or png format are allowed."),await t("ar.trans","pages.rating.add_images","اضافة صور"),await t("en.trans","pages.rating.add_images","Add Images"),await t("ar.trans","pages.rating.edit_images","تعديل الصور"),await t("en.trans","pages.rating.edit_images","Edit Images"),await t("ar.trans","pages.rating.edit_review","تعديل التقييم"),await t("en.trans","pages.rating.edit_review","Edit review"),await t("ar.trans","pages.rating.confirm_deletion","تأكيد حذف التقييم"),await t("en.trans","pages.rating.confirm_deletion","Confirm review deletion"),await t("ar.trans","pages.rating.are_you_sure_you_want_to_delete_review","هل أنت متأكد من حذف تقييمك؟"),await t("en.trans","pages.rating.are_you_sure_you_want_to_delete_review","Are you sure you want to delete your review?"),await t("ar.trans","pages.rating.review_updated_successfully","تم تعديل التقييم بنجاح"),await t("en.trans","pages.rating.review_updated_successfully","The review has been successfully updated."),await t("ar.trans","pages.rating.review_deleted_successfully","تم حذف التقييم بنجاح"),await t("en.trans","pages.rating.review_deleted_successfully","The review has been successfully deleted."),await t("ar.trans","pages.rating.images_count","الصور ( :current من أصل :total )"),await t("en.trans","pages.rating.images_count","Images ( :current of :total )"),await t("ar.trans","common.uploader.max_three_images",`.أضف ${this.MAX_UPLOAD_LIMIT} صور كحد أقصى`),await t("en.trans","common.uploader.max_three_images",`Add up to ${this.MAX_UPLOAD_LIMIT} images maximum.`),await t("ar.trans","common.elements.confirm_delete","تأكيد الحذف"),await t("en.trans","common.elements.confirm_delete","Confirm deletion"),await t("ar.trans","pages.rating.rate_required_factors","يرجى تقييم جميع المعايير لإتمام مراجعتك."),await t("en.trans","pages.rating.rate_required_factors","Please rate all required factors to complete your review."),await t("ar.trans","pages.rating.overall_product_rating","التقييم العام للمنتج"),await t("en.trans","pages.rating.overall_product_rating","Overall product rating"),await t("ar.trans","pages.rating.loyalty_points_for_images","اكسب :points نقطة ولاء عند إضافة صور لتقييمك!"),await t("en.trans","pages.rating.loyalty_points_for_images","Earn :points loyalty points when adding photos to your review!"),this.dragAndDropFilesLabel=salla.lang.get("common.uploader.drag_and_drop_files"),this.allowedImagesTypesLabel=salla.lang.get("common.uploader.allowed_images_types"),this.threeImagesMax=salla.lang.get("common.uploader.max_three_images"),this.contactSubjectLabel=salla.lang.get("pages.rating.contact_subject"),this.editReviewLabel=salla.lang.get("pages.rating.edit_review"),this.areYouSureLabel=salla.lang.get("pages.rating.are_you_sure_you_want_to_delete_review"),this.confirmDeletionLabel=salla.lang.get("pages.rating.confirm_deletion"),this.cancelLabel=salla.lang.get("common.elements.cancel"),this.updatedSuccessfullyLabel=salla.lang.get("pages.rating.review_updated_successfully"),this.deletedSuccessfullyLabel=salla.lang.get("pages.rating.review_deleted_successfully"),this.confirmDeleteBtn=salla.lang.get("common.elements.confirm_delete"),this.requiredFactorsLabel=salla.lang.get("pages.rating.rate_required_factors"),this.overallProductRatingLabel=salla.lang.get("pages.rating.overall_product_rating"),this.loyaltyPointsForImagesLabel=salla.lang.get("pages.rating.loyalty_points_for_images",{points:":points"}),this.contact_body=(t,a,s)=>salla.lang.get("pages.rating.contact_body",{store:t,id:a,customer:s})})()}))}syncStoreSettings(){this.orderId||(this.orderId=salla.config.get("page.id")),this.allowAttachImages=!!salla.config.get("store.settings.rating.allow_attach_images"),this.allowContactSupport=!!salla.config.get("store.settings.rating.allow_contact_support")}getRatingOrderId(){return this.orderId||salla.config.get("page.id")}getSubmitOrderId(){return this.orderId}isCustomerOrderShape(t){if(!t||"object"!=typeof t)return!1;const a=t;return!!a.rating&&(Array.isArray(a.items)||Array.isArray(a.products)||Array.isArray(a.rating?.product)||Array.isArray(a.rating?.products))}getBootstrapOrder(){const t=salla.config.get("page");if(this.isCustomerOrderShape(t))return t;if(t&&"object"==typeof t){const a=t;if(Array.isArray(a.products))return t;const s=a.order;if(this.isCustomerOrderShape(s))return s}}async loadCustomerOrderForEdit(){const t=this.getBootstrapOrder();if(t?.rating?.product||t?.rating?.products)this.order=t;else try{const t=await salla.api.withoutNotifier((()=>salla.order.api.getDetails(this.getRatingOrderId())));t?.data&&(this.order=t.data)}catch(t){if(!this.order){const t=await salla.api.withoutNotifier((()=>salla.rating.api.order(this.getRatingOrderId())));this.order=t.data}}}getOrderProductRatings(t=this.order){return t?.rating?[...this.normalizeToArray(t.rating.product),...this.normalizeToArray(t.rating.products)]:[]}getMatchedProductRating(t=this.order,a,s){return this.getOrderProductRatings(t).find((t=>Number(t?.id??t?.feedback_id)===Number(s)||Number(t?.product_id??t?.product?.id)===Number(a)))}hasRatingFeedback(t){const a=t?.rating;return null!=a&&""!==a&&Number(a)>0}isTestimonialsEnabled(t=this.order){return!(!1===t?.testimonials_enabled||this.hasRatingFeedback(t?.store?.feedback)||!0!==t?.testimonials_enabled&&!t?.allowed_ratings?.testimonials_enabled)}isProductsEnabled(t=this.order){return!1!==t?.products_enabled&&this.getRateableProducts(t).length>0}isShippingEnabled(t=this.order){return!(!1===t?.shipping_enabled||this.hasRatingFeedback(t?.shipping?.feedback)||!t?.shipping?.company||!0!==t?.shipping_enabled&&!t?.allowed_ratings?.shipping_enabled)}getOrderProducts(t=this.order){return Array.isArray(t?.products)?t.products.filter((t=>t?.product?.id)):[]}getRateableProducts(t=this.order){return this.getOrderProducts(t).filter((t=>!this.hasRatingFeedback(t?.feedback)))}getStepsCount(t=this.order){if(!t)return 0;let a=0;return this.isTestimonialsEnabled(t)&&a++,this.isProductsEnabled(t)&&(a+=this.getRateableProducts(t).length),this.isShippingEnabled(t)&&t.shipping?.company&&a++,a}afterOrderLoaded(){this.stepsCount=this.getStepsCount(),this.scheduleWizardSetup=!0,a(this)}async open(){return await salla.onReady(),this.syncStoreSettings(),this.defaultMode=!0,this.currentIndex=0,this.submitted=[],new Promise((t=>{setTimeout((()=>{this.modal.open().then((()=>this.order||salla.api.withoutNotifier((()=>salla.rating.api.order(this.getRatingOrderId()))).then((async t=>{this.order=t.data,this.productReviewFactors=await this.fetchAllProductReviewFactors(t.data)})))).then((()=>this.readyUpLoyaltyPoints())).then((()=>this.modal.setTitle(`${salla.lang.get("pages.rating.rate_order")} <span class="unicode">(#${this.order.id})</span>`))).then((()=>{const t={};for(const a of this.getRateableProducts())t[a.product.id]=[];this.productImages=t})).then((()=>this.modal.stopLoading())).then((()=>this.afterOrderLoaded())).catch((a=>{t(!1),this.hasError=!0,this.errorMessage=a.response?.data?.error?.message||a.response?.data,this.modal.stopLoading()})),t(!0)}),50)}))}async openEditModal(t){await salla.onReady(),this.syncStoreSettings(),this.defaultMode=!1,this.editMode=!0,this.editType=t.type,this.editFeedbackId=t.feedback_id;try{await this.fetchEditItem(t.feedback_id),await this.readyUpLoyaltyPoints(),"product"===this.editType&&this.editItem?.product?.id&&(await this.loadCustomerOrderForEdit(),await this.ensureProductFactorsLoaded(this.editItem.product.id),this.editFactorRatings={...this.buildEditFactorRatings(this.editItem.product.id)},this.markExistingFactorRatingsAsUserFilled(this.editItem.product.id,this.editFactorRatings)),this.editModal.open()}catch(t){this.hasError=!0,this.errorMessage=t.response?.data?.error?.message||t.response?.data}}async fetchEditItem(t){const a=`rating/${t}/show`,s=await salla.api.request(a);this.editItem=s.data,this.allowAttachImages&&"product"==this.editType&&this.editItem.images.length&&(this.editItemImages=this.editItem.images.map((t=>({id:`${Math.floor(100+900*Math.random())}`,url:t}))))}async editReview(){const t=`rating/${this.editFeedbackId}`;let a;if("product"===this.editType){const t=this.editModal.querySelector('[data-type="products"]')||this.currentTab;a=this.buildProductRatingPayload(this.collectFormData(t),t),!a.product_id&&this.editItem?.product?.id&&(a.product_id=String(this.editItem.product.id))}else a=this.collectFormData(this.editModal),a.images&&(a.images=a.images.split(","));await salla.api.request(t,a,"put").then((t=>{this.editModal.close(),salla.notify.success(t.message||this.updatedSuccessfullyLabel),setTimeout((()=>{window.location.reload()}),500)}))}async openDeleteModal(t){return this.defaultMode=!1,this.deleteMode=!0,this.deleteFeedbackId=t.feedback_id,this.shouldOpenDeleteModal=!0,new Promise((t=>{setTimeout((()=>{this.deleteModal.open().then((()=>t(!0)))}),50)}))}async deleteReview(){const t=`rating/${this.deleteFeedbackId}`;await salla.api.request(t,null,"delete").then((()=>{this.deleteModal.close(),salla.notify.success(this.deletedSuccessfullyLabel),setTimeout((()=>{window.location.reload()}),500)}))}async close(){return this.modal.close()}handleWizard(){this.steps=this.modal.querySelectorAll(".s-rating-modal-step"),this.dots=this.modal.querySelectorAll(".s-rating-modal-step-dot"),0!==this.stepsCount?this.showActiveStep():this.showThankYou()}refreshWizardRefs(){this.modal&&(this.steps=this.modal.querySelectorAll(".s-rating-modal-step"),this.dots=this.modal.querySelectorAll(".s-rating-modal-step-dot"))}showActiveStep(t=null){if(this.refreshWizardRefs(),this.currentTab=t||this.steps[this.currentIndex],!this.currentTab)return;l.toggleClassIf(".s-rating-modal-step-dot","s-rating-modal-bg-gray","s-rating-modal-bg-primary",(t=>t!=this.dots[this.currentIndex])).toggleClassIf(".s-rating-modal-step","s-rating-modal-active","s-rating-modal-hidden",(t=>t==this.currentTab)),0!==this.currentIndex&&(l.toggleElementClassIf(this.currentTab,"s-rating-modal-unactive","s-rating-modal-hidden",(()=>!0)),setTimeout((()=>l.toggleElementClassIf(this.currentTab,"s-rating-modal-active","s-rating-modal-unactive",(()=>!0))),300));const a=this.steps[this.currentIndex+1]?.dataset.type;this.nextBtn?.setText(a?`${salla.lang.get("pages.rating.rate")} ${salla.lang.get(`pages.rating.${a}`)}`:salla.lang.get("pages.rating.send_ratings")),setTimeout((()=>this.updateBodyHeight()),0),setTimeout((()=>this.updateBodyHeight()),150)}updateBodyHeight(){this.body&&this.currentTab&&(this.body.style.height="products"!==this.currentTab.dataset.type?`${this.currentTab.offsetHeight+(this.editMode?60:0)}px`:"auto")}previousTab(){this.currentIndex>0&&this.currentIndex--,l.toggleElementClassIf(this.backBtn,"s-rating-modal-unvisiable","block",(()=>0==this.currentIndex)),this.showActiveStep()}async submit(){this.refreshWizardRefs();try{this.submittedBefore()||this.validate(),salla.config.canLeave=!1,await this.nextBtn.load(),this.submittedBefore()||await this.sendFeedback(),this.currentTab?.querySelectorAll("[name],.s-rating-modal-btn-star").forEach((t=>t.setAttribute("disabled",""))),this.currentIndex<this.stepsCount&&this.currentIndex++,this.showActiveStep(),l.toggleClassIf("#prev-btn","block","s-rating-modal-unvisiable",(()=>!0)),this.currentIndex===this.stepsCount&&(this.showThankYou(),this.showContactWidget=!1)}finally{this.nextBtn.stop(),salla.config.canLeave=!0}}submittedBefore(){return this.submitted.includes(this.currentIndex)}getRatingHiddenInput(t){const a=t,s=a.querySelector?.(".rating_hidden_input");if(s?.name)return s;const i=a.querySelector?.("salla-rating-stars");return i?.shadowRoot?.querySelector(".rating_hidden_input")||null}collectNamedInputs(t){const a=new Set,s=[],i=t=>{t?.name&&!a.has(t)&&(a.add(t),s.push(t))};return t.querySelectorAll("[name]").forEach((t=>{i(t)})),t.querySelectorAll("salla-rating-stars").forEach((t=>{i(this.getRatingHiddenInput(t))})),s}normalizeFactorsList(t){return t?Array.isArray(t)?t:"object"==typeof t?Object.values(t).filter((t=>t&&"object"==typeof t)):[]:[]}validate(t=null,a=null){if(!t&&"products"===this.currentTab.dataset.type)return void this.currentTab.querySelectorAll(".rating-outer-form").forEach((t=>this.validate(t,"product")));const s=(t=t||this.currentTab).querySelector(".s-rating-modal-product-rating-row-main"),i=this.getRatingHiddenInput(s||t),e=i?.value,r=t.querySelector(".s-rating-modal-validation-msg");if(a=a||t.dataset.type,!e)throw r.innerHTML=salla.lang.get(`pages.rating.rate_${a}_stars`).replace(" (:item)",""),new Error(r.innerHTML);if("product"===a&&Array.from(t.querySelectorAll('.s-rating-modal-product-factor-row[data-required="true"]')).some((t=>{const a=this.getRatingHiddenInput(t);return!a?.value})))throw r.innerHTML=this.requiredFactorsLabel,new Error(r.innerHTML);r.innerHTML=""}collectFormData(t=this.currentTab){const a={};return this.collectNamedInputs(t).forEach((t=>{const s=salla.helpers.inputData(t.name,t.value,a);a[s.name]=s.value})),a}buildProductRatingPayload(t,a=this.currentTab){if(!t.rating){const s=a.querySelector(".s-rating-modal-product-rating-row-main"),i=this.getRatingHiddenInput(s||a);i?.value&&(t.rating=i.value)}const s=Number(t.product_id);let i=[];t.images?i="string"==typeof t.images?t.images.split(",").filter(Boolean):t.images:this.editMode&&this.allowAttachImages&&s?i=this.editItemImages.map((t=>t.url)):this.allowAttachImages&&s&&(i=(this.productImages[s]||[]).map((t=>t.url)));const e=this.normalizeFactorsList(t.factors).filter((t=>t?.id&&t?.rating)).map((t=>({id:String(t.id),rating:String(t.rating)})));return{order_id:this.getSubmitOrderId(),product_id:String(t.product_id),rating:String(t.rating),comment:t.comment||t.content||"",images:i,factors:e,type:"products"}}async sendFeedback(){this.refreshWizardRefs();const t=this.currentTab?.dataset?.type;if("products"===t){const t=this.collectFormData(this.currentTab),a=this.buildProductRatingPayload(t,this.currentTab);if(!a.product_id||!a.rating)throw new Error("Missing product rating data");const s=await salla.rating.api.products(a);return this.submitted.push(this.currentIndex),s}const a=this.collectFormData(this.currentTab);if(0===Object.keys(a).length)return;a.order_id=this.getSubmitOrderId(),a.type=t;const s=await salla.rating.api[t](a);return this.submitted.push(this.currentIndex),s}clearThanksCountdown(){null!==this.thanksCountdownInterval&&(clearInterval(this.thanksCountdownInterval),this.thanksCountdownInterval=null)}showThankYou(){let t=10;this.clearThanksCountdown(),this.thanksCountdownInterval=setInterval((()=>{this.thanksTime.innerHTML="00:0"+t--,t>0||(this.clearThanksCountdown(),this.thanksTime.remove(),this.close().then((()=>window.location.reload())))}),1e3),this.modal.querySelector(".s-rating-modal-footer").classList.add("s-rating-modal-unvisiable"),this.showActiveStep(this.thanksTab)}getFilepondPlaceholder(){return`<div class="s-rating-modal-filepond-placeholder"><span class="s-rating-modal-filepond-placeholder-icon">${d}</span><p class="s-rating-modal-filepond-placeholder-text">${this.dragAndDropFilesLabel}<br>\n <span> ${this.allowedImagesTypesLabel} <br> ${this.threeImagesMax} </span></p></div>`}getCustomerName(){return`${salla.config.get("user.first_name")||salla.storage.get("user.first_name")||""} ${salla.config.get("user.last_name")||salla.storage.get("user.last_name")||""}`}async readyUpLoyaltyPoints(){const t=salla.loyalty?.isFeatureEnabled?.();if(!t)return void(this.loyaltyImageRatingPoints=0);const a=salla.config.get("store.settings.rating.rating_product_points")||0,s=salla.config.get("store.settings.rating.rating_product_with_image_points")||0;this.loyaltyImageRatingPoints=Number(s)+Number(a)}loyaltyPointsNote(){if(!this.loyaltyImageRatingPoints||!this.loyaltyPointsForImagesLabel)return null;const t=s("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s("path",{d:"M10 0C13.6819 0 16.6667 2.98477 16.6667 6.66664C16.6667 9.37047 15.057 11.6984 12.7437 12.7444C11.6978 15.0575 9.3701 16.6666 6.66668 16.6666C2.98477 16.6666 0 13.6819 0 9.99998C0 7.29656 1.60918 4.96894 3.92195 3.92276C4.96827 1.60964 7.29618 0 10 0ZM6.66668 5C3.90524 5 1.66667 7.23856 1.66667 9.99998C1.66667 12.7614 3.90524 15 6.66668 15C9.4281 15 11.6667 12.7614 11.6667 9.99998C11.6667 7.23856 9.4281 5 6.66668 5ZM7.50002 5.83333V6.66664H9.16668V8.33331H5.83333C5.60322 8.33331 5.41667 8.51989 5.41667 8.74998C5.41667 8.95456 5.56407 9.12464 5.75844 9.15998L5.83333 9.16664H7.50002C8.6506 9.16664 9.58335 10.0994 9.58335 11.25C9.58335 12.4006 8.6506 13.3333 7.50002 13.3333V14.1666H5.83333V13.3333H4.16667V11.6666H7.50002C7.7301 11.6666 7.91668 11.4801 7.91668 11.25C7.91668 11.0455 7.76927 10.8753 7.57493 10.8401L7.50002 10.8333H5.83333C4.68274 10.8333 3.75 9.90056 3.75 8.74998C3.75 7.59939 4.68274 6.66664 5.83333 6.66664V5.83333H7.50002ZM10 1.66667C8.51377 1.66667 7.17893 2.31513 6.26313 3.34457C6.39704 3.33736 6.53138 3.33333 6.66668 3.33333C10.3486 3.33333 13.3333 6.3181 13.3333 9.99998C13.3333 10.1356 13.3293 10.2702 13.3213 10.4037C14.3513 9.48814 15 8.15314 15 6.66664C15 3.90524 12.7614 1.66667 10 1.66667Z",fill:"#008C56"}));return s("div",{class:"s-rating-modal-loyalty-points-note-container"},s("span",{class:"s-rating-modal-loyalty-points-note-icon"},t),s("p",{class:"s-rating-modal-loyalty-points-note-text"},this.loyaltyPointsForImagesLabel.replace(":points",String(this.loyaltyImageRatingPoints))))}normalizeReviewFactorsPayload(t){const a=t?.data??t?.factors;return Array.isArray(a)?a.flatMap((t=>{const a=Array.isArray(t?.items)?[...t.items]:null;if(a?.length){a.sort(((t,a)=>(Number(t?.sort)||0)-(Number(a?.sort)||0)));const s=!!t?.is_required;return a.filter((t=>null!=t?.id&&""!==t?.id)).map((t=>({id:t.id,name:t?.name,required:s})))}return null==t?.id||""===t?.id?[]:[{id:t.id,name:t?.name,required:t?.required??t?.is_required??!1}]})):[]}async fetchProductReviewFactors(t){try{const a=await salla.api.request(`review/factors/${t}/form`);return this.normalizeReviewFactorsPayload(a)}catch(t){return[]}}async fetchAllProductReviewFactors(t){const a=this.getRateableProducts(t);if(!a.length)return{};const s=await Promise.all(a.map((async t=>{const a=await this.fetchProductReviewFactors(t.product.id);return[t.product.id,a]})));return Object.fromEntries(s)}async ensureProductFactorsLoaded(t){if(!t||this.productReviewFactors[t])return;const a=await this.fetchProductReviewFactors(t);this.productReviewFactors={...this.productReviewFactors,[t]:a}}getFactorFieldName(t,a,s){return t?`${t}[factors][${a}][${s}]`:`factors[${a}][${s}]`}normalizeToArray(t){return null==t?[]:Array.isArray(t)?t:[t]}isFactorReviewsList(t){return Array.isArray(t)&&t.length>0&&t.every((t=>t&&"object"==typeof t&&(void 0!==t.rating||void 0!==t.stars||void 0!==t.value)))}getFactorReviewsFromRecord(t){if(!t)return[];for(const a of["factor_reviews","review_factors","factors"]){const s=t[a];if(this.isFactorReviewsList(s))return s}return[]}getEditFactorReviewsList(t){const a=[this.order,this.getBootstrapOrder()].filter(Boolean);for(const s of a){const a=this.getMatchedProductRating(s,t,this.editFeedbackId),i=this.getFactorReviewsFromRecord(a);if(i.length)return i}const s=this.getOrderProducts(this.order).find((a=>Number(a.product?.id)===Number(t))),i=[this.editItem?.factor_reviews,this.editItem?.review_factors,this.editItem?.product?.review_factors,this.editItem?.product?.factor_reviews,this.editItem?.factors,s?.factor_reviews,s?.review_factors,s?.feedback?.factor_reviews];for(const t of i)if(Array.isArray(t)&&t.length>0)return t;return[]}getFactorKey(t,a){return null!=t.id&&""!==t.id?`id:${t.id}`:t.name?`name:${t.name.trim()}`:`index:${a}`}getFactorRatingsForProduct(t){return this.editMode?this.editFactorRatings:this.productFactorRatings[t]||{}}setFactorRatingsForProduct(t,a){this.editMode?this.editFactorRatings=a:this.productFactorRatings={...this.productFactorRatings,[t]:a}}markExistingFactorRatingsAsUserFilled(t,a){const s=this.productReviewFactors[t]||[],i=new Set;s.forEach(((t,s)=>{const e=this.getFactorKey(t,s),r=void 0!==t.id?a[String(t.id)]:void 0,n=t.name?a[t.name.trim()]:void 0;void 0===r&&void 0===n&&void 0===a[`__index_${s}`]||i.add(e)})),this.userFilledFactorKeys[t]=i}shouldAutofillFactors(t){return 4===t||5===t}autofillUnfilledFactors(t,a){const s=this.productReviewFactors[t]||[];if(!s.length)return;const i=this.userFilledFactorKeys[t]||new Set,e={...this.getFactorRatingsForProduct(t)},r=this.shouldAutofillFactors(a);let n=!1;s.forEach(((t,s)=>{const o=this.getFactorKey(t,s);if(!i.has(o)){if(r)return void 0!==t.id&&(e[String(t.id)]=a),t.name&&(e[t.name.trim()]=a),e[`__index_${s}`]=a,void(n=!0);void 0!==t.id&&void 0!==e[String(t.id)]&&(delete e[String(t.id)],n=!0),t.name&&void 0!==e[t.name.trim()]&&(delete e[t.name.trim()],n=!0),void 0!==e[`__index_${s}`]&&(delete e[`__index_${s}`],n=!0)}})),n&&this.setFactorRatingsForProduct(t,e)}handleMainRatingChange(t,a){this.editMode?this.editMainRating=a:this.productMainRatings={...this.productMainRatings,[t]:a},this.autofillUnfilledFactors(t,a)}handleFactorRatingChange(t,a,s){this.userFilledFactorKeys[t]||(this.userFilledFactorKeys[t]=new Set),this.userFilledFactorKeys[t].add(a);const i=this.productReviewFactors[t]||[],e=i.findIndex(((t,s)=>this.getFactorKey(t,s)===a));if(e<0)return;const r=i[e],n={...this.getFactorRatingsForProduct(t)};void 0!==r.id&&(n[String(r.id)]=s),r.name&&(n[r.name.trim()]=s),n[`__index_${e}`]=s,this.setFactorRatingsForProduct(t,n)}setupProductRatingAutofill(t,a){t&&!this.boundRatingRows.has(t)&&(this.boundRatingRows.add(t),t.addEventListener("click",(s=>{const i=s.target;if(!i.closest(".s-rating-stars-btn-star"))return;const e=i.closest(".s-rating-modal-product-rating-row-main"),r=i.closest(".s-rating-modal-product-factor-row");requestAnimationFrame((()=>{if(e&&t.contains(e)){const t=Number(this.getRatingHiddenInput(e)?.value);t>0&&this.handleMainRatingChange(a,t)}else if(r&&t.contains(r)){const t=r.getAttribute("data-factor-key"),s=Number(this.getRatingHiddenInput(r)?.value);t&&s>0&&this.handleFactorRatingChange(a,t,s)}}))})))}buildEditFactorRatings(t){return this.getEditFactorReviewsList(t).reduce(((t,a,s)=>{const i=Number(a?.rating??a?.stars??a?.value);if(Number.isNaN(i))return t;const e=a?.id??a?.factor_id;return null!=e&&""!==e&&(t[String(e)]=i),a?.name&&(t[a.name.trim()]=i),t[`__index_${s}`]=i,t}),{})}renderProductStep(t,a){return s("section",{class:"s-rating-modal-step s-rating-modal-hidden","data-type":"products","data-product-id":t.product.id,key:t.product.id},s("div",{class:"s-rating-modal-product"},this.allowAttachImages&&this.loyaltyPointsNote(),s("div",{class:"rating-outer-form","data-stars-error":salla.lang.get("pages.rating.rate_product_stars")},s("div",{class:"s-rating-modal-product-details"},s("div",{class:"s-rating-modal-product-info-row"},s("div",{class:"s-rating-modal-product-img-wrap"},s("img",{src:t.product.thumbnail,alt:t.product.name,class:"s-rating-modal-product-img"})),s("h3",{class:"s-rating-modal-product-title"},t.product.name)),this.renderProductReviewFactors(t.product.id,0,{fieldPrefix:""}),s("input",{type:"hidden",name:"product_id",value:t.product.id}),s("textarea",{placeholder:salla.lang.get("pages.rating.write_product_rate"),name:"comment",class:"s-rating-modal-comment"}),s("small",{class:"s-rating-modal-validation-msg"}))),this.allowAttachImages&&s("div",{class:"s-rating-modal-uploader is-opened",ref:t=>this.contentRefs[a]=t},s("salla-file-upload",{name:"image",maxFilesCount:this.MAX_UPLOAD_LIMIT,imagePreviewHeight:117,"instant-upload":!0,type:"feedback",payloadName:"files[]",id:`file-${t.product.id}`,title:t.product.name,allowMultiple:!0,instantUpload:!0,accept:"image/png, image/jpeg, image/jpg",url:salla.url.api("upload"),onUploaded:s=>{this.productImages={...this.productImages,[t.product.id]:[...this.productImages[t.product.id]||[],s.detail]},this.hiddenInputs[a].value=this.productImages[t.product.id].map((t=>t.url)).join(",")},onRemoved:s=>{const i=s.detail;i&&this.productImages[t.product.id]&&(this.productImages={...this.productImages,[t.product.id]:this.productImages[t.product.id].filter((t=>t.id!==i))},this.hiddenInputs[a].value=this.productImages[t.product.id].map((t=>t.url)).join(","))},labelIdle:this.getFilepondPlaceholder()}),s("input",{type:"hidden",name:"images",value:(this.productImages[t.product.id]||[]).map((t=>t.url)).join(","),ref:t=>this.hiddenInputs[a]=t}),this.renderUploadedImagesCount(t.product.id))))}renderProductReviewFactors(t,a,i={}){const e=this.productReviewFactors[t]||[],r=i.fieldPrefix??`products[${a}]`,n=r?`${r}[rating]`:"rating",o={...this.editMode?{}:this.productFactorRatings[t]||{},...i.factorRatings||{}},l=Number(i.mainRating??(this.editMode?this.editMainRating:this.productMainRatings[t])),d=!Number.isNaN(l),h=(t,a)=>{const s=void 0!==t.id?o[String(t.id)]:void 0,i=t.name?o[t.name.trim()]:void 0,e=Number(s??i??o[`__index_${a}`]);return Number.isNaN(e)?void 0:e};return s("div",{class:"s-rating-modal-product-rating-rows",ref:a=>this.setupProductRatingAutofill(a,t)},s("div",{class:"s-rating-modal-product-rating-row s-rating-modal-product-rating-row-main"},s("span",{class:"s-rating-modal-product-factor-name"},this.overallProductRatingLabel,s("span",{class:"s-rating-modal-product-factor-required"},"*")),s("salla-rating-stars",{size:"medium",name:n,key:d?`main-rating-${l}`:"main-rating-empty",value:d?l:void 0,editable:d,withLabel:!0,labelBeforeStars:!0,tag:!1})),e.map(((t,a)=>s("div",{class:"s-rating-modal-product-rating-row s-rating-modal-product-factor-row px-3","data-required":t.required?"true":"false","data-factor-key":this.getFactorKey(t,a)},s("input",{type:"hidden",name:this.getFactorFieldName(r,a,"name"),value:t.name}),!!t.id&&s("input",{type:"hidden",name:this.getFactorFieldName(r,a,"id"),value:String(t.id)}),s("span",{class:"s-rating-modal-product-factor-name"},t.name,t.required?s("span",{class:"s-rating-modal-product-factor-required"},"*"):""),s("salla-rating-stars",{size:"medium",name:this.getFactorFieldName(r,a,"rating"),key:`factor-rating-${t.id??a}-${h(t,a)??0}`,value:h(t,a),editable:i.alwaysEditable||"number"==typeof h(t,a),withLabel:!0,labelBeforeStars:!0,tag:!1})))))}handleSendEmail(){const t=`${this.contactSubjectLabel} #${this.order.id}`,a=this.contact_body(salla.config.get("store.name"),this.order.id,this.getCustomerName()),s=`mailto:${salla.config.get("store.contacts.email")}?subject=${encodeURIComponent(t)}&body=${encodeURIComponent(a)}`;window.open(s,"_blank")}handleSendWhatsApp(){const t=this.contact_body(salla.config.get("store.name"),this.order.id,this.getCustomerName()),a=`https://wa.me/${salla.config.get("store.contacts.whatsapp")}?text=${encodeURIComponent(t)}`;window.open(a,"_blank")}resetData(t){t.detail||(this.clearThanksCountdown(),this.modal?.close(),this.editItem=null,this.editItemImages=[],this.editFactorRatings={},this.productMainRatings={},this.productFactorRatings={},this.editMainRating=void 0,this.userFilledFactorKeys={},this.hiddenInputs[1]&&(this.hiddenInputs[1].value=""),this.deleteFeedbackId=null,this.editFeedbackId=null,this.shouldOpenDeleteModal=!1,this.editMode=!1,this.deleteMode=!1,this.defaultMode=!1,this.currentIndex=0,this.submitted=[],this.scheduleWizardSetup=!1,this.loyaltyImageRatingPoints=0)}getDeleteModal(){return s("salla-modal",{ref:t=>this.deleteModal=t,width:"xs",onModalVisibilityChanged:t=>this.resetData(t)},s("div",{class:"s-rating-modal-delete-wrapper",ref:t=>this.body=t},s("h3",null,this.confirmDeletionLabel),s("p",null,this.areYouSureLabel),s("div",{class:"s-rating-modal-delete-actions"},s("salla-button",{loaderPosition:"center",onClick:()=>this.deleteReview()},this.confirmDeleteBtn),s("salla-button",{color:"danger",fill:"outline",onClick:()=>this.deleteModal.close()},this.cancelLabel))))}renderUploadedImagesCount(t){const a=this.editMode?this.editItemImages.length:(this.productImages[t]||[]).length;return s("span",{class:"s-rating-modal-upload-count"},salla.lang.choice("pages.rating.images_count",a,{current:a,total:this.MAX_UPLOAD_LIMIT}))}getEditModal(){return s("salla-modal",{ref:t=>this.editModal=t,width:"md",onModalVisibilityChanged:t=>this.resetData(t)},s("div",{class:"s-rating-modal-edit-wrapper",ref:t=>this.body=t},"store"===this.editType&&this.editItem?s("div",{class:"rating-outer-form s-rating-modal-step-wrap s-rating-modal-step","data-type":"store",ref:t=>this.currentTab=t},s("div",{class:"s-rating-modal-rounded-icon"},s("img",{src:salla.config.get("store.logo","https://assets.salla.sa/cp/assets/images/logo-new.png"),alt:"store name",class:"s-rating-modal-store-logo"})),s("h2",{class:"s-rating-modal-title"},salla.lang.get("pages.rating.rate_the_store")),s("div",{class:"s-rating-modal-stars-company"},s("salla-rating-stars",{withLabel:!0,size:"large",editable:!0,value:this.editItem.stars})),s("textarea",{name:"content",value:this.editItem.content,class:"s-rating-modal-comment",placeholder:salla.lang.get("pages.rating.write_store_rate")}),s("small",{class:"s-rating-modal-validation-msg"})):null,"shipping"===this.editType&&this.editItem?s("div",{class:"rating-outer-form s-rating-modal-step-wrap s-rating-modal-step","data-type":"shipping",ref:t=>this.currentTab=t},this.editItem.shipping.logo?s("div",{class:"s-rating-modal-rounded-icon"},s("img",{src:this.editItem.shipping.logo,class:"s-rating-modal-shipping-logo",alt:this.editItem.shipping.name})):s("span",{class:"s-rating-modal-icon",innerHTML:n}),s("div",{class:"s-rating-modal-title"}," ",`${salla.lang.get("pages.rating.rate_shipping")} ${this.editItem.shipping.name}`),s("div",{class:"s-rating-modal-stars-company"},s("salla-rating-stars",{withLabel:!0,size:"large",editable:!0,value:this.editItem.stars})),s("textarea",{name:"content",class:"s-rating-modal-comment",value:this.editItem.content,placeholder:salla.lang.get("pages.rating.write_shipping_rate")}),s("small",{class:"s-rating-modal-validation-msg"})):null,"product"==this.editType&&this.editItem?s("section",{class:"s-rating-modal-step","data-type":"products",ref:t=>this.currentTab=t},s("div",{class:"s-rating-modal-product"},this.allowAttachImages&&this.loyaltyPointsNote(),s("div",{class:"rating-outer-form","data-stars-error":salla.lang.get("pages.rating.rate_product_stars")},s("div",{class:"s-rating-modal-product-details"},s("div",{class:"s-rating-modal-product-info-row"},s("div",{class:"s-rating-modal-product-img-wrap"},s("img",{src:this.editItem.product.image.url,alt:this.editItem.product.name,class:"s-rating-modal-product-img"})),s("h3",{class:"s-rating-modal-product-title"},this.editItem.product.name)),this.renderProductReviewFactors(this.editItem.product.id,0,{fieldPrefix:"",mainRating:this.editMainRating??Number(this.editItem.stars??this.editItem.rating),factorRatings:this.editFactorRatings,alwaysEditable:!0}),s("input",{type:"hidden",name:"product_id",value:this.editItem.product.id}),s("textarea",{value:this.editItem.content,placeholder:salla.lang.get("pages.rating.write_product_rate"),name:"comment",class:"s-rating-modal-comment"}),s("small",{class:"s-rating-modal-validation-msg"}))),this.allowAttachImages&&s("div",{class:"s-rating-modal-uploader is-opened",ref:t=>this.contentRefs[1]=t},s("salla-file-upload",{name:"images",allowMultiple:!0,maxFilesCount:this.MAX_UPLOAD_LIMIT,imagePreviewHeight:117,filePosterHeight:117,"instant-upload":!0,type:"feedback",files:JSON.stringify(this.editItemImages),payloadName:"files[]",id:`file-${this.editItem.product.id}`,title:this.editItem.product.name,instantUpload:!0,accept:"image/png, image/jpeg, image/jpg",url:salla.url.api("upload"),onUploaded:t=>{this.editItemImages=[...this.editItemImages,t.detail],this.hiddenInputs[1].value=this.editItemImages.map((t=>t.url)).join()},onRemoved:t=>{const a=t.detail;a&&(this.editItemImages=this.editItemImages.filter((t=>t.id!==a)),this.hiddenInputs[1].value=this.editItemImages.map((t=>t.url)).join())},labelIdle:this.getFilepondPlaceholder()}),s("input",{type:"hidden",name:"images",value:this.editItemImages.map((t=>t.url)).join(","),ref:t=>this.hiddenInputs[1]=t}),this.renderUploadedImagesCount(this.editItem.product.id)))):null,s("div",{class:"s-rating-modal-footer s-rating-modal-footer-end"},s("salla-button",{"loader-position":"center",onClick:()=>this.editReview()},this.editReviewLabel))))}render(){return this.deleteMode?s(i,{class:"s-rating-modal"},this.getDeleteModal()):this.editMode?s(i,{class:"s-rating-modal"},this.getEditModal()):this.defaultMode?s(i,{class:"s-rating-modal"},s("salla-modal",{class:"s-rating-modal-wrap",onModalVisibilityChanged:t=>this.resetData(t),isLoading:!0,width:"md",ref:t=>this.modal=t},s("div",{slot:"loading"},s("div",{class:"s-rating-modal-skeleton"},s("salla-skeleton",{type:"circle",height:"80px",width:"80px"}),s("salla-skeleton",{height:"15px",width:"60%"}),s("salla-skeleton",{height:"10px",width:"30%"}),s("div",{class:"s-rating-modal-skeleton-stars"},[...Array(5)].map((t=>s("div",{key:t,innerHTML:r})))),s("salla-skeleton",{height:"100px",width:"100%"}),s("div",{class:"s-rating-modal-skeleton-footer"},s("salla-skeleton",{height:"40px",width:"30%"})))),!this.hasError&&this.order?[s("div",{class:"s-rating-modal-wrapper",ref:t=>this.body=t},this.isTestimonialsEnabled()?s("div",{class:"rating-outer-form s-rating-modal-step-wrap s-rating-modal-step s-rating-modal-hidden","data-type":"store"},s("div",{class:"s-rating-modal-rounded-icon"},s("img",{src:salla.config.get("store.logo","https://assets.salla.sa/cp/assets/images/logo-new.png"),alt:"store name",class:"s-rating-modal-store-logo"})),s("h2",{class:"s-rating-modal-title"},salla.lang.get("pages.rating.rate_the_store")),s("div",{class:"s-rating-modal-stars-company"},s("salla-rating-stars",{withLabel:!0,size:"large"})),s("textarea",{name:"comment",class:"s-rating-modal-comment",placeholder:salla.lang.get("pages.rating.write_store_rate")}),s("small",{class:"s-rating-modal-validation-msg"})):"",this.isProductsEnabled()&&this.getRateableProducts().map(((t,a)=>this.renderProductStep(t,a))),this.isShippingEnabled()&&this.order.shipping?.company?s("div",{class:"rating-outer-form s-rating-modal-step-wrap s-rating-modal-step s-rating-modal-hidden","data-type":"shipping"},s("input",{type:"hidden",name:"shipping_company_id",value:this.order.shipping.company.id}),this.order.shipping.company.logo?s("div",{class:"s-rating-modal-rounded-icon"},s("img",{src:this.order.shipping.company.logo,class:"s-rating-modal-shipping-logo",alt:this.order.shipping.company.name})):s("span",{class:"s-rating-modal-icon",innerHTML:n}),s("div",{class:"s-rating-modal-title"}," ",`${salla.lang.get("pages.rating.rate_shipping")} ${this.order.shipping.company.name}`),s("div",{class:"s-rating-modal-stars-company"},s("salla-rating-stars",{withLabel:!0,size:"large"})),s("textarea",{name:"comment",class:"s-rating-modal-comment",placeholder:salla.lang.get("pages.rating.write_shipping_rate")}),s("small",{class:"s-rating-modal-validation-msg"})):"",s("div",{class:"s-rating-modal-thanks s-rating-modal-hidden",ref:t=>this.thanksTab=t},s("span",{class:"s-rating-modal-icon",innerHTML:o}),s("h3",{class:"s-rating-modal-thanks-title"},salla.lang.get("pages.rating.thanks")),s("div",{class:"s-rating-modal-thanks-msg",innerHTML:this.order.thanks_message}),s("time",{class:"s-rating-modal-thanks-time",ref:t=>this.thanksTime=t}))),this.allowContactSupport&&this.showContactWidget&&(salla.config.get("store.contacts.whatsapp")||salla.config.get("store.contacts.email"))?s("div",{class:"s-rating-modal-contact"},s("p",null,this.contactUsLabel),s("div",{class:"s-rating-modal-contact-icons"},salla.config.get("store.contacts.whatsapp")&&s("span",{onClick:()=>this.handleSendWhatsApp(),innerHTML:h}),salla.config.get("store.contacts.email")&&s("span",{onClick:()=>this.handleSendEmail(),innerHTML:g}))):"",s("div",{class:"s-rating-modal-footer"},s("button",{ref:t=>this.backBtn=t,onClick:()=>this.previousTab(),class:"s-rating-modal-btn s-rating-modal-unvisiable"},salla.lang.get("common.elements.back")),this.stepsCount>1?s("ul",{class:"s-rating-modal-dots"},[...Array(this.stepsCount)].map(((t,a)=>s("li",{key:a,class:"s-rating-modal-bg-gray s-rating-modal-step-dot"})))):"",s("salla-button",{"loader-position":"center",ref:t=>this.nextBtn=t,onClick:()=>this.submit()},salla.lang.get("common.elements.next")))]:s("salla-placeholder",{alignment:"center"}))):void 0}async componentWillLoad(){await salla.onReady(),this.syncStoreSettings()}componentDidRender(){this.scheduleWizardSetup&&this.defaultMode&&this.order&&(this.scheduleWizardSetup=!1,requestAnimationFrame((()=>this.handleWizard())))}disconnectedCallback(){this.clearThanksCountdown()}get host(){return e(this)}};m.style=".s-rating-modal-product-details{padding-bottom:0.5rem}.s-rating-modal-comment{margin-top:0.35rem}.s-rating-modal-product{margin-bottom:1rem}.s-rating-modal-product-img{position:absolute !important;inset:0;display:block;width:100% !important;max-width:100% !important;height:100% !important;object-fit:cover}.s-rating-modal-product-title{font-size:0.95rem;font-weight:600;line-height:1.5;margin:0}.s-rating-modal-stars-product{margin-top:0.5rem}.s-rating-modal-loyalty-points-note-container{display:flex;align-items:center;gap:0.625rem;width:100%;margin-top:1.5rem;margin-bottom:0.75rem;padding:0.75rem;border-radius:0.5rem;background-color:#E6F4EA}.s-rating-modal-loyalty-points-note-icon{display:flex;flex-shrink:0;align-items:center;justify-content:center;width:1.25rem;height:1.25rem;color:#1B7F5C}.s-rating-modal-loyalty-points-note-icon svg{width:1.5rem;height:1.5rem;fill:currentColor}.s-rating-modal-loyalty-points-note-text{flex:1;margin:0;font-size:0.875rem;line-height:1.25rem;color:#1f2937}.s-rating-modal-product-details-main{display:flex;align-items:center;margin-bottom:0.5rem;padding-bottom:0;border-bottom:0}.s-rating-modal-product-info-row{display:flex;align-items:center;gap:0.6rem;margin-bottom:0.5rem;padding-bottom:0;border-bottom:0}.s-rating-modal-product-main-review{width:100%;text-align:right}.s-rating-modal-product-rating-rows{display:grid;gap:0.45rem;margin:0.2rem 0 0.7rem}.s-rating-modal-product-rating-row{display:flex;align-items:center;justify-content:space-between;gap:0.75rem;min-height:2rem}.s-rating-modal-product-rating-row salla-rating-stars{flex-shrink:0}.s-rating-modal-product-rating-row .s-rating-stars-wrapper{align-items:center;min-height:1.75rem}.s-rating-modal-product-rating-row .s-rating-stars-label,.s-rating-modal-product-rating-row .s-rating-stars-label-without-tag{min-width:auto;min-height:1.25rem;line-height:1.25rem;font-size:0.8rem;color:#5b6470;white-space:nowrap;text-align:end;transition:opacity 0.15s ease}.s-rating-modal-product-rating-row .s-rating-stars-label--empty,.s-rating-modal-product-rating-row .s-rating-stars-label-without-tag--empty{opacity:0}.s-rating-modal-product-rating-row-main{margin-bottom:0.35rem;padding:0.5rem 0.6rem;border:1px solid #d1d5db;border-radius:0.45rem;background:transparent}.s-rating-modal-product-factor-name{color:#5b6470;font-size:0.9rem;line-height:1.25}.s-rating-modal-product-rating-row-main .s-rating-modal-product-factor-name{font-size:1rem;color:#5b6470}.s-rating-modal-product-factor-required{color:#f87171;margin-inline-start:0.2rem}.s-rating-modal-product-img-wrap{position:relative;width:5rem !important;min-width:5rem !important;max-width:5rem !important;height:3.5rem !important;flex-shrink:0 !important;overflow:hidden;border-radius:0.375rem;background:#f3f4f6}.s-rating-modal-uploader.is-opened{height:auto !important;opacity:1 !important;overflow:visible !important;pointer-events:auto !important;margin-bottom:1rem}";export{m as salla_rating_modal_v2}
4
+ import{r as t,f as a,h as s,H as i,a as e}from"./p-Bt0ajKaf.js";import{S as r}from"./p-CeFAfcTv.js";import{S as n}from"./p-lMgMt31Q.js";import{C as o}from"./p-BV4kqbdL.js";import{H as l}from"./p-XnA1YTjA.js";import{I as d}from"./p-C-tzSDxw.js";import{W as h}from"./p-CgR-T_ZS.js";import{e as g}from"./p-DzAIgzdz.js";import"./p-CgtvEd63.js";const m=class{constructor(a){t(this,a),this.hasError=!1,this.showContactWidget=!0,this.images=[],this.productImages={},this.editItemImages=[],this.productReviewFactors={},this.editFactorRatings={},this.productMainRatings={},this.productFactorRatings={},this.contact_body=(t,a,s)=>salla.lang.get("pages.rating.contact_subject",{store:t,id:a,customer:s}),this.editMode=!1,this.defaultMode=!1,this.deleteMode=!1,this.shouldOpenDeleteModal=!1,this.editItem=null,this.allowAttachImages=!1,this.allowContactSupport=!1,this.loyaltyImageRatingPoints=0,this.dragAndDropFilesLabel=salla.lang.get("common.uploader.drag_and_drop_files"),this.contactSubjectLabel=salla.lang.get("pages.rating.contact_subject"),this.editReviewLabel=salla.lang.get("pages.rating.edit_review"),this.allowedImagesTypesLabel=salla.lang.get("common.uploader.allowed_images_types"),this.threeImagesMax=salla.lang.get("common.uploader.max_three_images"),this.areYouSureLabel=salla.lang.get("pages.rating.are_you_sure_you_want_to_delete_review"),this.confirmDeletionLabel=salla.lang.get("pages.rating.confirm_deletion"),this.cancelLabel=salla.lang.get("common.elements.cancel"),this.confirmDeleteBtn=salla.lang.get("common.elements.confirm_delete"),this.updatedSuccessfullyLabel=salla.lang.get("pages.rating.review_updated_successfully"),this.deletedSuccessfullyLabel=salla.lang.get("pages.rating.review_deleted_successfully"),this.contactUsLabel=salla.lang.get("blocks.footer.social"),this.requiredFactorsLabel=salla.lang.get("pages.rating.rate_required_factors"),this.overallProductRatingLabel=salla.lang.get("pages.rating.overall_product_rating"),this.loyaltyPointsForImagesLabel=salla.lang.get("pages.rating.loyalty_points_for_images",{points:":points"}),this.contentRefs=[],this.hiddenInputs=[],this.userFilledFactorKeys={},this.boundRatingRows=new WeakSet,this.stepsCount=0,this.currentIndex=0,this.submitted=[],this.MAX_UPLOAD_LIMIT=3,this.thanksCountdownInterval=null,this.scheduleWizardSetup=!1,salla.lang.onLoaded((()=>{this.contactUsLabel=salla.lang.get("blocks.footer.social");const t=(t,a,s)=>new Promise((i=>{salla.helpers.setNested(salla.lang.messages[t],a,s),i(!0)}));(async()=>{await t("ar.trans","common.uploader.drag_and_drop_files","اسحب الملفات وأفلتها هنا"),await t("en.trans","common.uploader.drag_and_drop_files","Drag and drop files here"),await t("ar.trans","common.uploader.allowed_images_types"," .jpg أو jpeg أو png يُسمح بإضافة صور بصيغة"),await t("en.trans","common.uploader.allowed_images_types","Images in jpg, jpeg, or png format are allowed."),await t("ar.trans","pages.rating.add_images","اضافة صور"),await t("en.trans","pages.rating.add_images","Add Images"),await t("ar.trans","pages.rating.edit_images","تعديل الصور"),await t("en.trans","pages.rating.edit_images","Edit Images"),await t("ar.trans","pages.rating.edit_review","تعديل التقييم"),await t("en.trans","pages.rating.edit_review","Edit review"),await t("ar.trans","pages.rating.confirm_deletion","تأكيد حذف التقييم"),await t("en.trans","pages.rating.confirm_deletion","Confirm review deletion"),await t("ar.trans","pages.rating.are_you_sure_you_want_to_delete_review","هل أنت متأكد من حذف تقييمك؟"),await t("en.trans","pages.rating.are_you_sure_you_want_to_delete_review","Are you sure you want to delete your review?"),await t("ar.trans","pages.rating.review_updated_successfully","تم تعديل التقييم بنجاح"),await t("en.trans","pages.rating.review_updated_successfully","The review has been successfully updated."),await t("ar.trans","pages.rating.review_deleted_successfully","تم حذف التقييم بنجاح"),await t("en.trans","pages.rating.review_deleted_successfully","The review has been successfully deleted."),await t("ar.trans","pages.rating.images_count","الصور ( :current من أصل :total )"),await t("en.trans","pages.rating.images_count","Images ( :current of :total )"),await t("ar.trans","common.uploader.max_three_images",`.أضف ${this.MAX_UPLOAD_LIMIT} صور كحد أقصى`),await t("en.trans","common.uploader.max_three_images",`Add up to ${this.MAX_UPLOAD_LIMIT} images maximum.`),await t("ar.trans","common.elements.confirm_delete","تأكيد الحذف"),await t("en.trans","common.elements.confirm_delete","Confirm deletion"),await t("ar.trans","pages.rating.rate_required_factors","يرجى تقييم جميع المعايير لإتمام مراجعتك."),await t("en.trans","pages.rating.rate_required_factors","Please rate all required factors to complete your review."),await t("ar.trans","pages.rating.overall_product_rating","التقييم العام للمنتج"),await t("en.trans","pages.rating.overall_product_rating","Overall product rating"),await t("ar.trans","pages.rating.loyalty_points_for_images","اكسب :points نقطة ولاء عند إضافة صور لتقييمك!"),await t("en.trans","pages.rating.loyalty_points_for_images","Earn :points loyalty points when adding photos to your review!"),this.dragAndDropFilesLabel=salla.lang.get("common.uploader.drag_and_drop_files"),this.allowedImagesTypesLabel=salla.lang.get("common.uploader.allowed_images_types"),this.threeImagesMax=salla.lang.get("common.uploader.max_three_images"),this.contactSubjectLabel=salla.lang.get("pages.rating.contact_subject"),this.editReviewLabel=salla.lang.get("pages.rating.edit_review"),this.areYouSureLabel=salla.lang.get("pages.rating.are_you_sure_you_want_to_delete_review"),this.confirmDeletionLabel=salla.lang.get("pages.rating.confirm_deletion"),this.cancelLabel=salla.lang.get("common.elements.cancel"),this.updatedSuccessfullyLabel=salla.lang.get("pages.rating.review_updated_successfully"),this.deletedSuccessfullyLabel=salla.lang.get("pages.rating.review_deleted_successfully"),this.confirmDeleteBtn=salla.lang.get("common.elements.confirm_delete"),this.requiredFactorsLabel=salla.lang.get("pages.rating.rate_required_factors"),this.overallProductRatingLabel=salla.lang.get("pages.rating.overall_product_rating"),this.loyaltyPointsForImagesLabel=salla.lang.get("pages.rating.loyalty_points_for_images",{points:":points"}),this.contact_body=(t,a,s)=>salla.lang.get("pages.rating.contact_body",{store:t,id:a,customer:s})})()}))}syncStoreSettings(){this.orderId||(this.orderId=salla.config.get("page.id")),this.allowAttachImages=!!salla.config.get("store.settings.rating.allow_attach_images"),this.allowContactSupport=!!salla.config.get("store.settings.rating.allow_contact_support")}getRatingOrderId(){return this.orderId||salla.config.get("page.id")}getSubmitOrderId(){return this.orderId}isCustomerOrderShape(t){if(!t||"object"!=typeof t)return!1;const a=t;return!!a.rating&&(Array.isArray(a.items)||Array.isArray(a.products)||Array.isArray(a.rating?.product)||Array.isArray(a.rating?.products))}getBootstrapOrder(){const t=salla.config.get("page");if(this.isCustomerOrderShape(t))return t;if(t&&"object"==typeof t){const a=t;if(Array.isArray(a.products))return t;const s=a.order;if(this.isCustomerOrderShape(s))return s}}async loadCustomerOrderForEdit(){const t=this.getBootstrapOrder();if(t?.rating?.product||t?.rating?.products)this.order=t;else try{const t=await salla.api.withoutNotifier((()=>salla.order.api.getDetails(this.getRatingOrderId())));t?.data&&(this.order=t.data)}catch(t){if(!this.order){const t=await salla.api.withoutNotifier((()=>salla.rating.api.order(this.getRatingOrderId())));this.order=t.data}}}getOrderProductRatings(t=this.order){return t?.rating?[...this.normalizeToArray(t.rating.product),...this.normalizeToArray(t.rating.products)]:[]}getMatchedProductRating(t=this.order,a,s){return this.getOrderProductRatings(t).find((t=>Number(t?.id??t?.feedback_id)===Number(s)||Number(t?.product_id??t?.product?.id)===Number(a)))}hasRatingFeedback(t){const a=t?.rating;return null!=a&&""!==a&&Number(a)>0}isTestimonialsEnabled(t=this.order){return!(!1===t?.testimonials_enabled||this.hasRatingFeedback(t?.store?.feedback)||!0!==t?.testimonials_enabled&&!t?.allowed_ratings?.testimonials_enabled)}isProductsEnabled(t=this.order){return!1!==t?.products_enabled&&this.getRateableProducts(t).length>0}isShippingEnabled(t=this.order){return!(!1===t?.shipping_enabled||this.hasRatingFeedback(t?.shipping?.feedback)||!t?.shipping?.company||!0!==t?.shipping_enabled&&!t?.allowed_ratings?.shipping_enabled)}getOrderProducts(t=this.order){return Array.isArray(t?.products)?t.products.filter((t=>t?.product?.id)):[]}getRateableProducts(t=this.order){return this.getOrderProducts(t).filter((t=>!this.hasRatingFeedback(t?.feedback)))}getStepsCount(t=this.order){if(!t)return 0;let a=0;return this.isTestimonialsEnabled(t)&&a++,this.isProductsEnabled(t)&&(a+=this.getRateableProducts(t).length),this.isShippingEnabled(t)&&t.shipping?.company&&a++,a}afterOrderLoaded(){this.stepsCount=this.getStepsCount(),this.scheduleWizardSetup=!0,a(this)}async open(){return await salla.onReady(),this.syncStoreSettings(),this.defaultMode=!0,this.currentIndex=0,this.submitted=[],new Promise((t=>{setTimeout((()=>{this.modal.open().then((()=>this.order||salla.api.withoutNotifier((()=>salla.rating.api.order(this.getRatingOrderId()))).then((async t=>{this.order=t.data,this.productReviewFactors=await this.fetchAllProductReviewFactors(t.data)})))).then((()=>this.readyUpLoyaltyPoints())).then((()=>this.modal.setTitle(`${salla.lang.get("pages.rating.rate_order")} <span class="unicode">(#${this.order.id})</span>`))).then((()=>{const t={};for(const a of this.getRateableProducts())t[a.product.id]=[];this.productImages=t})).then((()=>this.modal.stopLoading())).then((()=>this.afterOrderLoaded())).catch((a=>{t(!1),this.hasError=!0,this.errorMessage=a.response?.data?.error?.message||a.response?.data,this.modal.stopLoading()})),t(!0)}),50)}))}async openEditModal(t){await salla.onReady(),this.syncStoreSettings(),this.defaultMode=!1,this.editMode=!0,this.editType=t.type,this.editFeedbackId=t.feedback_id;try{await this.fetchEditItem(t.feedback_id),await this.readyUpLoyaltyPoints(),"product"===this.editType&&this.editItem?.product?.id&&(await this.loadCustomerOrderForEdit(),await this.ensureProductFactorsLoaded(this.editItem.product.id),this.editFactorRatings={...this.buildEditFactorRatings(this.editItem.product.id)},this.markExistingFactorRatingsAsUserFilled(this.editItem.product.id,this.editFactorRatings)),this.editModal.open()}catch(t){this.hasError=!0,this.errorMessage=t.response?.data?.error?.message||t.response?.data}}async fetchEditItem(t){const a=`rating/${t}/show`,s=await salla.api.request(a);this.editItem=s.data,this.allowAttachImages&&"product"==this.editType&&this.editItem.images.length&&(this.editItemImages=this.editItem.images.map((t=>({id:`${Math.floor(100+900*Math.random())}`,url:t}))))}async editReview(){const t=`rating/${this.editFeedbackId}`;let a;if("product"===this.editType){const t=this.editModal.querySelector('[data-type="products"]')||this.currentTab;a=this.buildProductRatingPayload(this.collectFormData(t),t),!a.product_id&&this.editItem?.product?.id&&(a.product_id=String(this.editItem.product.id))}else a=this.collectFormData(this.editModal),a.images&&(a.images=a.images.split(","));await salla.api.request(t,a,"put").then((t=>{this.editModal.close(),salla.notify.success(t.message||this.updatedSuccessfullyLabel),setTimeout((()=>{window.location.reload()}),500)}))}async openDeleteModal(t){return this.defaultMode=!1,this.deleteMode=!0,this.deleteFeedbackId=t.feedback_id,this.shouldOpenDeleteModal=!0,new Promise((t=>{setTimeout((()=>{this.deleteModal.open().then((()=>t(!0)))}),50)}))}async deleteReview(){const t=`rating/${this.deleteFeedbackId}`;await salla.api.request(t,null,"delete").then((()=>{this.deleteModal.close(),salla.notify.success(this.deletedSuccessfullyLabel),setTimeout((()=>{window.location.reload()}),500)}))}async close(){return this.modal.close()}handleWizard(){this.steps=this.modal.querySelectorAll(".s-rating-modal-step"),this.dots=this.modal.querySelectorAll(".s-rating-modal-step-dot"),0!==this.stepsCount?this.showActiveStep():this.showThankYou()}refreshWizardRefs(){this.modal&&(this.steps=this.modal.querySelectorAll(".s-rating-modal-step"),this.dots=this.modal.querySelectorAll(".s-rating-modal-step-dot"))}showActiveStep(t=null){if(this.refreshWizardRefs(),this.currentTab=t||this.steps[this.currentIndex],!this.currentTab)return;l.toggleClassIf(".s-rating-modal-step-dot","s-rating-modal-bg-gray","s-rating-modal-bg-primary",(t=>t!=this.dots[this.currentIndex])).toggleClassIf(".s-rating-modal-step","s-rating-modal-active","s-rating-modal-hidden",(t=>t==this.currentTab)),0!==this.currentIndex&&(l.toggleElementClassIf(this.currentTab,"s-rating-modal-unactive","s-rating-modal-hidden",(()=>!0)),setTimeout((()=>l.toggleElementClassIf(this.currentTab,"s-rating-modal-active","s-rating-modal-unactive",(()=>!0))),300));const a=this.steps[this.currentIndex+1]?.dataset.type;this.nextBtn?.setText(a?`${salla.lang.get("pages.rating.rate")} ${salla.lang.get(`pages.rating.${a}`)}`:salla.lang.get("pages.rating.send_ratings")),setTimeout((()=>this.updateBodyHeight()),0),setTimeout((()=>this.updateBodyHeight()),150)}updateBodyHeight(){this.body&&this.currentTab&&(this.body.style.height="products"!==this.currentTab.dataset.type?`${this.currentTab.offsetHeight+(this.editMode?60:0)}px`:"auto")}previousTab(){this.currentIndex>0&&this.currentIndex--,l.toggleElementClassIf(this.backBtn,"s-rating-modal-unvisiable","block",(()=>0==this.currentIndex)),this.showActiveStep()}async submit(){this.refreshWizardRefs();try{this.submittedBefore()||this.validate(),salla.config.canLeave=!1,await this.nextBtn.load(),this.submittedBefore()||await this.sendFeedback(),this.currentTab?.querySelectorAll("[name],.s-rating-modal-btn-star").forEach((t=>t.setAttribute("disabled",""))),this.currentIndex<this.stepsCount&&this.currentIndex++,this.showActiveStep(),l.toggleClassIf("#prev-btn","block","s-rating-modal-unvisiable",(()=>!0)),this.currentIndex===this.stepsCount&&(this.showThankYou(),this.showContactWidget=!1)}finally{this.nextBtn.stop(),salla.config.canLeave=!0}}submittedBefore(){return this.submitted.includes(this.currentIndex)}getRatingHiddenInput(t){const a=t,s=a.querySelector?.(".rating_hidden_input");if(s?.name)return s;const i=a.querySelector?.("salla-rating-stars");return i?.shadowRoot?.querySelector(".rating_hidden_input")||null}collectNamedInputs(t){const a=new Set,s=[],i=t=>{t?.name&&!a.has(t)&&(a.add(t),s.push(t))};return t.querySelectorAll("[name]").forEach((t=>{i(t)})),t.querySelectorAll("salla-rating-stars").forEach((t=>{i(this.getRatingHiddenInput(t))})),s}normalizeFactorsList(t){return t?Array.isArray(t)?t:"object"==typeof t?Object.values(t).filter((t=>t&&"object"==typeof t)):[]:[]}validate(t=null,a=null){if(!t&&"products"===this.currentTab.dataset.type)return void this.currentTab.querySelectorAll(".rating-outer-form").forEach((t=>this.validate(t,"product")));const s=(t=t||this.currentTab).querySelector(".s-rating-modal-product-rating-row-main"),i=this.getRatingHiddenInput(s||t),e=i?.value,r=t.querySelector(".s-rating-modal-validation-msg");if(a=a||t.dataset.type,!e)throw r.innerHTML=salla.lang.get(`pages.rating.rate_${a}_stars`).replace(" (:item)",""),new Error(r.innerHTML);if("product"===a&&Array.from(t.querySelectorAll('.s-rating-modal-product-factor-row[data-required="true"]')).some((t=>{const a=this.getRatingHiddenInput(t);return!a?.value})))throw r.innerHTML=this.requiredFactorsLabel,new Error(r.innerHTML);r.innerHTML=""}collectFormData(t=this.currentTab){const a={};return this.collectNamedInputs(t).forEach((t=>{const s=salla.helpers.inputData(t.name,t.value,a);a[s.name]=s.value})),a}buildProductRatingPayload(t,a=this.currentTab){if(!t.rating){const s=a.querySelector(".s-rating-modal-product-rating-row-main"),i=this.getRatingHiddenInput(s||a);i?.value&&(t.rating=i.value)}const s=Number(t.product_id);let i=[];t.images?i="string"==typeof t.images?t.images.split(",").filter(Boolean):t.images:this.editMode&&this.allowAttachImages&&s?i=this.editItemImages.map((t=>t.url)):this.allowAttachImages&&s&&(i=(this.productImages[s]||[]).map((t=>t.url)));const e=this.normalizeFactorsList(t.factors).filter((t=>t?.id&&t?.rating)).map((t=>({id:String(t.id),rating:String(t.rating)})));return{order_id:this.getSubmitOrderId(),product_id:String(t.product_id),rating:String(t.rating),comment:t.comment||t.content||"",images:i,factors:e,type:"products"}}async sendFeedback(){this.refreshWizardRefs();const t=this.currentTab?.dataset?.type;if("products"===t){const t=this.collectFormData(this.currentTab),a=this.buildProductRatingPayload(t,this.currentTab);if(!a.product_id||!a.rating)throw new Error("Missing product rating data");const s=await salla.rating.api.products(a);return this.submitted.push(this.currentIndex),s}const a=this.collectFormData(this.currentTab);if(0===Object.keys(a).length)return;a.order_id=this.getSubmitOrderId(),a.type=t;const s=await salla.rating.api[t](a);return this.submitted.push(this.currentIndex),s}clearThanksCountdown(){null!==this.thanksCountdownInterval&&(clearInterval(this.thanksCountdownInterval),this.thanksCountdownInterval=null)}showThankYou(){let t=10;this.clearThanksCountdown(),this.thanksCountdownInterval=setInterval((()=>{this.thanksTime.innerHTML="00:0"+t--,t>0||(this.clearThanksCountdown(),this.thanksTime.remove(),this.close().then((()=>window.location.reload())))}),1e3),this.modal.querySelector(".s-rating-modal-footer").classList.add("s-rating-modal-unvisiable"),this.showActiveStep(this.thanksTab)}getFilepondPlaceholder(){return`<div class="s-rating-modal-filepond-placeholder"><span class="s-rating-modal-filepond-placeholder-icon">${d}</span><p class="s-rating-modal-filepond-placeholder-text">${this.dragAndDropFilesLabel}<br>\n <span> ${this.allowedImagesTypesLabel} <br> ${this.threeImagesMax} </span></p></div>`}getCustomerName(){return`${salla.config.get("user.first_name")||salla.storage.get("user.first_name")||""} ${salla.config.get("user.last_name")||salla.storage.get("user.last_name")||""}`}async readyUpLoyaltyPoints(){const t=salla.loyalty?.isFeatureEnabled?.();if(!t)return void(this.loyaltyImageRatingPoints=0);const a=salla.config.get("store.settings.rating.rating_product_points")||0,s=salla.config.get("store.settings.rating.rating_product_with_image_points")||0;this.loyaltyImageRatingPoints=Number(s)+Number(a)}loyaltyPointsNote(){if(!this.loyaltyImageRatingPoints||!this.loyaltyPointsForImagesLabel)return null;const t=s("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",xmlns:"http://www.w3.org/2000/svg"},s("path",{d:"M10 0C13.6819 0 16.6667 2.98477 16.6667 6.66664C16.6667 9.37047 15.057 11.6984 12.7437 12.7444C11.6978 15.0575 9.3701 16.6666 6.66668 16.6666C2.98477 16.6666 0 13.6819 0 9.99998C0 7.29656 1.60918 4.96894 3.92195 3.92276C4.96827 1.60964 7.29618 0 10 0ZM6.66668 5C3.90524 5 1.66667 7.23856 1.66667 9.99998C1.66667 12.7614 3.90524 15 6.66668 15C9.4281 15 11.6667 12.7614 11.6667 9.99998C11.6667 7.23856 9.4281 5 6.66668 5ZM7.50002 5.83333V6.66664H9.16668V8.33331H5.83333C5.60322 8.33331 5.41667 8.51989 5.41667 8.74998C5.41667 8.95456 5.56407 9.12464 5.75844 9.15998L5.83333 9.16664H7.50002C8.6506 9.16664 9.58335 10.0994 9.58335 11.25C9.58335 12.4006 8.6506 13.3333 7.50002 13.3333V14.1666H5.83333V13.3333H4.16667V11.6666H7.50002C7.7301 11.6666 7.91668 11.4801 7.91668 11.25C7.91668 11.0455 7.76927 10.8753 7.57493 10.8401L7.50002 10.8333H5.83333C4.68274 10.8333 3.75 9.90056 3.75 8.74998C3.75 7.59939 4.68274 6.66664 5.83333 6.66664V5.83333H7.50002ZM10 1.66667C8.51377 1.66667 7.17893 2.31513 6.26313 3.34457C6.39704 3.33736 6.53138 3.33333 6.66668 3.33333C10.3486 3.33333 13.3333 6.3181 13.3333 9.99998C13.3333 10.1356 13.3293 10.2702 13.3213 10.4037C14.3513 9.48814 15 8.15314 15 6.66664C15 3.90524 12.7614 1.66667 10 1.66667Z",fill:"#008C56"}));return s("div",{class:"s-rating-modal-loyalty-points-note-container"},s("span",{class:"s-rating-modal-loyalty-points-note-icon"},t),s("p",{class:"s-rating-modal-loyalty-points-note-text"},this.loyaltyPointsForImagesLabel.replace(":points",String(this.loyaltyImageRatingPoints))))}normalizeReviewFactorsPayload(t){const a=t?.data??t?.factors;return Array.isArray(a)?a.flatMap((t=>{const a=Array.isArray(t?.items)?[...t.items]:null;if(a?.length){a.sort(((t,a)=>(Number(t?.sort)||0)-(Number(a?.sort)||0)));const s=!!t?.is_required;return a.filter((t=>null!=t?.id&&""!==t?.id)).map((t=>({id:t.id,name:t?.name,required:s})))}return null==t?.id||""===t?.id?[]:[{id:t.id,name:t?.name,required:t?.required??t?.is_required??!1}]})):[]}async fetchProductReviewFactors(t){try{const a=await salla.api.request(`review/factors/${t}/form`);return this.normalizeReviewFactorsPayload(a)}catch(t){return[]}}async fetchAllProductReviewFactors(t){const a=this.getRateableProducts(t);if(!a.length)return{};const s=await Promise.all(a.map((async t=>{const a=await this.fetchProductReviewFactors(t.product.id);return[t.product.id,a]})));return Object.fromEntries(s)}async ensureProductFactorsLoaded(t){if(!t||this.productReviewFactors[t])return;const a=await this.fetchProductReviewFactors(t);this.productReviewFactors={...this.productReviewFactors,[t]:a}}getFactorFieldName(t,a,s){return t?`${t}[factors][${a}][${s}]`:`factors[${a}][${s}]`}normalizeToArray(t){return null==t?[]:Array.isArray(t)?t:[t]}isFactorReviewsList(t){return Array.isArray(t)&&t.length>0&&t.every((t=>t&&"object"==typeof t&&(void 0!==t.rating||void 0!==t.stars||void 0!==t.value)))}getFactorReviewsFromRecord(t){if(!t)return[];for(const a of["factor_reviews","review_factors","factors"]){const s=t[a];if(this.isFactorReviewsList(s))return s}return[]}getEditFactorReviewsList(t){const a=[this.order,this.getBootstrapOrder()].filter(Boolean);for(const s of a){const a=this.getMatchedProductRating(s,t,this.editFeedbackId),i=this.getFactorReviewsFromRecord(a);if(i.length)return i}const s=this.getOrderProducts(this.order).find((a=>Number(a.product?.id)===Number(t))),i=[this.editItem?.factor_reviews,this.editItem?.review_factors,this.editItem?.product?.review_factors,this.editItem?.product?.factor_reviews,this.editItem?.factors,s?.factor_reviews,s?.review_factors,s?.feedback?.factor_reviews];for(const t of i)if(Array.isArray(t)&&t.length>0)return t;return[]}getFactorKey(t,a){return null!=t.id&&""!==t.id?`id:${t.id}`:t.name?`name:${t.name.trim()}`:`index:${a}`}getFactorRatingsForProduct(t){return this.editMode?this.editFactorRatings:this.productFactorRatings[t]||{}}setFactorRatingsForProduct(t,a){this.editMode?this.editFactorRatings=a:this.productFactorRatings={...this.productFactorRatings,[t]:a}}markExistingFactorRatingsAsUserFilled(t,a){const s=this.productReviewFactors[t]||[],i=new Set;s.forEach(((t,s)=>{const e=this.getFactorKey(t,s),r=void 0!==t.id?a[String(t.id)]:void 0,n=t.name?a[t.name.trim()]:void 0;void 0===r&&void 0===n&&void 0===a[`__index_${s}`]||i.add(e)})),this.userFilledFactorKeys[t]=i}shouldAutofillFactors(t){return 4===t||5===t}autofillUnfilledFactors(t,a){const s=this.productReviewFactors[t]||[];if(!s.length)return;const i=this.userFilledFactorKeys[t]||new Set,e={...this.getFactorRatingsForProduct(t)},r=this.shouldAutofillFactors(a);let n=!1;s.forEach(((t,s)=>{const o=this.getFactorKey(t,s);if(!i.has(o)){if(r)return void 0!==t.id&&(e[String(t.id)]=a),t.name&&(e[t.name.trim()]=a),e[`__index_${s}`]=a,void(n=!0);void 0!==t.id&&void 0!==e[String(t.id)]&&(delete e[String(t.id)],n=!0),t.name&&void 0!==e[t.name.trim()]&&(delete e[t.name.trim()],n=!0),void 0!==e[`__index_${s}`]&&(delete e[`__index_${s}`],n=!0)}})),n&&this.setFactorRatingsForProduct(t,e)}handleMainRatingChange(t,a){this.editMode?this.editMainRating=a:this.productMainRatings={...this.productMainRatings,[t]:a},this.autofillUnfilledFactors(t,a)}handleFactorRatingChange(t,a,s){this.userFilledFactorKeys[t]||(this.userFilledFactorKeys[t]=new Set),this.userFilledFactorKeys[t].add(a);const i=this.productReviewFactors[t]||[],e=i.findIndex(((t,s)=>this.getFactorKey(t,s)===a));if(e<0)return;const r=i[e],n={...this.getFactorRatingsForProduct(t)};void 0!==r.id&&(n[String(r.id)]=s),r.name&&(n[r.name.trim()]=s),n[`__index_${e}`]=s,this.setFactorRatingsForProduct(t,n)}setupProductRatingAutofill(t,a){t&&!this.boundRatingRows.has(t)&&(this.boundRatingRows.add(t),t.addEventListener("click",(s=>{const i=s.target;if(!i.closest(".s-rating-stars-btn-star"))return;const e=i.closest(".s-rating-modal-product-rating-row-main"),r=i.closest(".s-rating-modal-product-factor-row");requestAnimationFrame((()=>{if(e&&t.contains(e)){const t=Number(this.getRatingHiddenInput(e)?.value);t>0&&this.handleMainRatingChange(a,t)}else if(r&&t.contains(r)){const t=r.getAttribute("data-factor-key"),s=Number(this.getRatingHiddenInput(r)?.value);t&&s>0&&this.handleFactorRatingChange(a,t,s)}}))})))}buildEditFactorRatings(t){return this.getEditFactorReviewsList(t).reduce(((t,a,s)=>{const i=Number(a?.rating??a?.stars??a?.value);if(Number.isNaN(i))return t;const e=a?.id??a?.factor_id;return null!=e&&""!==e&&(t[String(e)]=i),a?.name&&(t[a.name.trim()]=i),t[`__index_${s}`]=i,t}),{})}renderProductStep(t,a){return s("section",{class:"s-rating-modal-step s-rating-modal-hidden","data-type":"products","data-product-id":t.product.id,key:t.product.id},s("div",{class:"s-rating-modal-product"},this.allowAttachImages&&this.loyaltyPointsNote(),s("div",{class:"rating-outer-form","data-stars-error":salla.lang.get("pages.rating.rate_product_stars")},s("div",{class:"s-rating-modal-product-details"},s("div",{class:"s-rating-modal-product-info-row"},s("div",{class:"s-rating-modal-product-img-wrap"},s("img",{src:t.product.thumbnail,alt:t.product.name,class:"s-rating-modal-product-img"})),s("h3",{class:"s-rating-modal-product-title"},t.product.name)),this.renderProductReviewFactors(t.product.id,0,{fieldPrefix:""}),s("input",{type:"hidden",name:"product_id",value:t.product.id}),s("textarea",{placeholder:salla.lang.get("pages.rating.write_product_rate"),name:"comment",class:"s-rating-modal-comment"}),s("small",{class:"s-rating-modal-validation-msg"}))),this.allowAttachImages&&s("div",{class:"s-rating-modal-uploader is-opened",ref:t=>this.contentRefs[a]=t},s("salla-file-upload",{name:"image",maxFilesCount:this.MAX_UPLOAD_LIMIT,imagePreviewHeight:117,"instant-upload":!0,type:"feedback",payloadName:"files[]",id:`file-${t.product.id}`,title:t.product.name,allowMultiple:!0,instantUpload:!0,accept:"image/png, image/jpeg, image/jpg",url:salla.url.api("upload"),onUploaded:s=>{this.productImages={...this.productImages,[t.product.id]:[...this.productImages[t.product.id]||[],s.detail]},this.hiddenInputs[a].value=this.productImages[t.product.id].map((t=>t.url)).join(",")},onRemoved:s=>{const i=s.detail;i&&this.productImages[t.product.id]&&(this.productImages={...this.productImages,[t.product.id]:this.productImages[t.product.id].filter((t=>t.id!==i))},this.hiddenInputs[a].value=this.productImages[t.product.id].map((t=>t.url)).join(","))},labelIdle:this.getFilepondPlaceholder()}),s("input",{type:"hidden",name:"images",value:(this.productImages[t.product.id]||[]).map((t=>t.url)).join(","),ref:t=>this.hiddenInputs[a]=t}),this.renderUploadedImagesCount(t.product.id))))}renderProductReviewFactors(t,a,i={}){const e=this.productReviewFactors[t]||[],r=i.fieldPrefix??`products[${a}]`,n=r?`${r}[rating]`:"rating",o={...this.editMode?{}:this.productFactorRatings[t]||{},...i.factorRatings||{}},l=Number(i.mainRating??(this.editMode?this.editMainRating:this.productMainRatings[t])),d=!Number.isNaN(l),h=(t,a)=>{const s=void 0!==t.id?o[String(t.id)]:void 0,i=t.name?o[t.name.trim()]:void 0,e=Number(s??i??o[`__index_${a}`]);return Number.isNaN(e)?void 0:e};return s("div",{class:"s-rating-modal-product-rating-rows",ref:a=>this.setupProductRatingAutofill(a,t)},s("div",{class:"s-rating-modal-product-rating-row s-rating-modal-product-rating-row-main"},s("span",{class:"s-rating-modal-product-factor-name"},this.overallProductRatingLabel,s("span",{class:"s-rating-modal-product-factor-required"},"*")),s("salla-rating-stars",{size:"medium",name:n,key:d?`main-rating-${l}`:"main-rating-empty",value:d?l:void 0,editable:d,withLabel:!0,labelBeforeStars:!0,tag:!1})),e.map(((t,a)=>s("div",{class:"s-rating-modal-product-rating-row s-rating-modal-product-factor-row px-3","data-required":t.required?"true":"false","data-factor-key":this.getFactorKey(t,a)},s("input",{type:"hidden",name:this.getFactorFieldName(r,a,"name"),value:t.name}),!!t.id&&s("input",{type:"hidden",name:this.getFactorFieldName(r,a,"id"),value:String(t.id)}),s("span",{class:"s-rating-modal-product-factor-name"},t.name,t.required?s("span",{class:"s-rating-modal-product-factor-required"},"*"):""),s("salla-rating-stars",{size:"medium",name:this.getFactorFieldName(r,a,"rating"),key:`factor-rating-${t.id??a}-${h(t,a)??0}`,value:h(t,a),editable:i.alwaysEditable||"number"==typeof h(t,a),withLabel:!0,labelBeforeStars:!0,tag:!1})))))}handleSendEmail(){const t=`${this.contactSubjectLabel} #${this.order.id}`,a=this.contact_body(salla.config.get("store.name"),this.order.id,this.getCustomerName()),s=`mailto:${salla.config.get("store.contacts.email")}?subject=${encodeURIComponent(t)}&body=${encodeURIComponent(a)}`;window.open(s,"_blank")}handleSendWhatsApp(){const t=this.contact_body(salla.config.get("store.name"),this.order.id,this.getCustomerName()),a=`https://wa.me/${salla.config.get("store.contacts.whatsapp")}?text=${encodeURIComponent(t)}`;window.open(a,"_blank")}resetData(t){t.detail||(this.clearThanksCountdown(),this.modal?.close(),this.editItem=null,this.editItemImages=[],this.editFactorRatings={},this.productMainRatings={},this.productFactorRatings={},this.editMainRating=void 0,this.userFilledFactorKeys={},this.hiddenInputs[1]&&(this.hiddenInputs[1].value=""),this.deleteFeedbackId=null,this.editFeedbackId=null,this.shouldOpenDeleteModal=!1,this.editMode=!1,this.deleteMode=!1,this.defaultMode=!1,this.currentIndex=0,this.submitted=[],this.scheduleWizardSetup=!1,this.loyaltyImageRatingPoints=0)}getDeleteModal(){return s("salla-modal",{ref:t=>this.deleteModal=t,width:"xs",onModalVisibilityChanged:t=>this.resetData(t)},s("div",{class:"s-rating-modal-delete-wrapper",ref:t=>this.body=t},s("h3",null,this.confirmDeletionLabel),s("p",null,this.areYouSureLabel),s("div",{class:"s-rating-modal-delete-actions"},s("salla-button",{loaderPosition:"center",onClick:()=>this.deleteReview()},this.confirmDeleteBtn),s("salla-button",{color:"danger",fill:"outline",onClick:()=>this.deleteModal.close()},this.cancelLabel))))}renderUploadedImagesCount(t){const a=this.editMode?this.editItemImages.length:(this.productImages[t]||[]).length;return s("span",{class:"s-rating-modal-upload-count"},salla.lang.choice("pages.rating.images_count",a,{current:a,total:this.MAX_UPLOAD_LIMIT}))}getEditModal(){return s("salla-modal",{ref:t=>this.editModal=t,width:"md",onModalVisibilityChanged:t=>this.resetData(t)},s("div",{class:"s-rating-modal-edit-wrapper",ref:t=>this.body=t},"store"===this.editType&&this.editItem?s("div",{class:"rating-outer-form s-rating-modal-step-wrap s-rating-modal-step","data-type":"store",ref:t=>this.currentTab=t},s("div",{class:"s-rating-modal-rounded-icon"},s("img",{src:salla.config.get("store.logo","https://assets.salla.sa/cp/assets/images/logo-new.png"),alt:"store name",class:"s-rating-modal-store-logo"})),s("h2",{class:"s-rating-modal-title"},salla.lang.get("pages.rating.rate_the_store")),s("div",{class:"s-rating-modal-stars-company"},s("salla-rating-stars",{withLabel:!0,size:"large",editable:!0,value:this.editItem.stars})),s("textarea",{name:"content",value:this.editItem.content,class:"s-rating-modal-comment",placeholder:salla.lang.get("pages.rating.write_store_rate")}),s("small",{class:"s-rating-modal-validation-msg"})):null,"shipping"===this.editType&&this.editItem?s("div",{class:"rating-outer-form s-rating-modal-step-wrap s-rating-modal-step","data-type":"shipping",ref:t=>this.currentTab=t},this.editItem.shipping.logo?s("div",{class:"s-rating-modal-rounded-icon"},s("img",{src:this.editItem.shipping.logo,class:"s-rating-modal-shipping-logo",alt:this.editItem.shipping.name})):s("span",{class:"s-rating-modal-icon",innerHTML:n}),s("div",{class:"s-rating-modal-title"}," ",`${salla.lang.get("pages.rating.rate_shipping")} ${this.editItem.shipping.name}`),s("div",{class:"s-rating-modal-stars-company"},s("salla-rating-stars",{withLabel:!0,size:"large",editable:!0,value:this.editItem.stars})),s("textarea",{name:"content",class:"s-rating-modal-comment",value:this.editItem.content,placeholder:salla.lang.get("pages.rating.write_shipping_rate")}),s("small",{class:"s-rating-modal-validation-msg"})):null,"product"==this.editType&&this.editItem?s("section",{class:"s-rating-modal-step","data-type":"products",ref:t=>this.currentTab=t},s("div",{class:"s-rating-modal-product"},this.allowAttachImages&&this.loyaltyPointsNote(),s("div",{class:"rating-outer-form","data-stars-error":salla.lang.get("pages.rating.rate_product_stars")},s("div",{class:"s-rating-modal-product-details"},s("div",{class:"s-rating-modal-product-info-row"},s("div",{class:"s-rating-modal-product-img-wrap"},s("img",{src:this.editItem.product.image.url,alt:this.editItem.product.name,class:"s-rating-modal-product-img"})),s("h3",{class:"s-rating-modal-product-title"},this.editItem.product.name)),this.renderProductReviewFactors(this.editItem.product.id,0,{fieldPrefix:"",mainRating:this.editMainRating??Number(this.editItem.stars??this.editItem.rating),factorRatings:this.editFactorRatings,alwaysEditable:!0}),s("input",{type:"hidden",name:"product_id",value:this.editItem.product.id}),s("textarea",{value:this.editItem.content,placeholder:salla.lang.get("pages.rating.write_product_rate"),name:"comment",class:"s-rating-modal-comment"}),s("small",{class:"s-rating-modal-validation-msg"}))),this.allowAttachImages&&s("div",{class:"s-rating-modal-uploader is-opened",ref:t=>this.contentRefs[1]=t},s("salla-file-upload",{name:"images",allowMultiple:!0,maxFilesCount:this.MAX_UPLOAD_LIMIT,imagePreviewHeight:117,filePosterHeight:117,"instant-upload":!0,type:"feedback",files:JSON.stringify(this.editItemImages),payloadName:"files[]",id:`file-${this.editItem.product.id}`,title:this.editItem.product.name,instantUpload:!0,accept:"image/png, image/jpeg, image/jpg",url:salla.url.api("upload"),onUploaded:t=>{this.editItemImages=[...this.editItemImages,t.detail],this.hiddenInputs[1].value=this.editItemImages.map((t=>t.url)).join()},onRemoved:t=>{const a=t.detail;a&&(this.editItemImages=this.editItemImages.filter((t=>t.id!==a)),this.hiddenInputs[1].value=this.editItemImages.map((t=>t.url)).join())},labelIdle:this.getFilepondPlaceholder()}),s("input",{type:"hidden",name:"images",value:this.editItemImages.map((t=>t.url)).join(","),ref:t=>this.hiddenInputs[1]=t}),this.renderUploadedImagesCount(this.editItem.product.id)))):null,s("div",{class:"s-rating-modal-footer s-rating-modal-footer-end"},s("salla-button",{"loader-position":"center",onClick:()=>this.editReview()},this.editReviewLabel))))}render(){return this.deleteMode?s(i,{class:"s-rating-modal"},this.getDeleteModal()):this.editMode?s(i,{class:"s-rating-modal"},this.getEditModal()):this.defaultMode?s(i,{class:"s-rating-modal"},s("salla-modal",{class:"s-rating-modal-wrap",onModalVisibilityChanged:t=>this.resetData(t),isLoading:!0,width:"md",ref:t=>this.modal=t},s("div",{slot:"loading"},s("div",{class:"s-rating-modal-skeleton"},s("salla-skeleton",{type:"circle",height:"80px",width:"80px"}),s("salla-skeleton",{height:"15px",width:"60%"}),s("salla-skeleton",{height:"10px",width:"30%"}),s("div",{class:"s-rating-modal-skeleton-stars"},[...Array(5)].map((t=>s("div",{key:t,innerHTML:r})))),s("salla-skeleton",{height:"100px",width:"100%"}),s("div",{class:"s-rating-modal-skeleton-footer"},s("salla-skeleton",{height:"40px",width:"30%"})))),!this.hasError&&this.order?[s("div",{class:"s-rating-modal-wrapper",ref:t=>this.body=t},this.isTestimonialsEnabled()?s("div",{class:"rating-outer-form s-rating-modal-step-wrap s-rating-modal-step s-rating-modal-hidden","data-type":"store"},s("div",{class:"s-rating-modal-rounded-icon"},s("img",{src:salla.config.get("store.logo","https://assets.salla.sa/cp/assets/images/logo-new.png"),alt:"store name",class:"s-rating-modal-store-logo"})),s("h2",{class:"s-rating-modal-title"},salla.lang.get("pages.rating.rate_the_store")),s("div",{class:"s-rating-modal-stars-company"},s("salla-rating-stars",{withLabel:!0,size:"large"})),s("textarea",{name:"comment",class:"s-rating-modal-comment",placeholder:salla.lang.get("pages.rating.write_store_rate")}),s("small",{class:"s-rating-modal-validation-msg"})):"",this.isProductsEnabled()&&this.getRateableProducts().map(((t,a)=>this.renderProductStep(t,a))),this.isShippingEnabled()&&this.order.shipping?.company?s("div",{class:"rating-outer-form s-rating-modal-step-wrap s-rating-modal-step s-rating-modal-hidden","data-type":"shipping"},s("input",{type:"hidden",name:"shipping_company_id",value:this.order.shipping.company.id}),this.order.shipping.company.logo?s("div",{class:"s-rating-modal-rounded-icon"},s("img",{src:this.order.shipping.company.logo,class:"s-rating-modal-shipping-logo",alt:this.order.shipping.company.name})):s("span",{class:"s-rating-modal-icon",innerHTML:n}),s("div",{class:"s-rating-modal-title"}," ",`${salla.lang.get("pages.rating.rate_shipping")} ${this.order.shipping.company.name}`),s("div",{class:"s-rating-modal-stars-company"},s("salla-rating-stars",{withLabel:!0,size:"large"})),s("textarea",{name:"comment",class:"s-rating-modal-comment",placeholder:salla.lang.get("pages.rating.write_shipping_rate")}),s("small",{class:"s-rating-modal-validation-msg"})):"",s("div",{class:"s-rating-modal-thanks s-rating-modal-hidden",ref:t=>this.thanksTab=t},s("span",{class:"s-rating-modal-icon",innerHTML:o}),s("h3",{class:"s-rating-modal-thanks-title"},salla.lang.get("pages.rating.thanks")),s("div",{class:"s-rating-modal-thanks-msg",innerHTML:this.order.thanks_message}),s("time",{class:"s-rating-modal-thanks-time",ref:t=>this.thanksTime=t}))),this.allowContactSupport&&this.showContactWidget&&(salla.config.get("store.contacts.whatsapp")||salla.config.get("store.contacts.email"))?s("div",{class:"s-rating-modal-contact"},s("p",null,this.contactUsLabel),s("div",{class:"s-rating-modal-contact-icons"},salla.config.get("store.contacts.whatsapp")&&s("span",{onClick:()=>this.handleSendWhatsApp(),innerHTML:h}),salla.config.get("store.contacts.email")&&s("span",{onClick:()=>this.handleSendEmail(),innerHTML:g}))):"",s("div",{class:"s-rating-modal-footer"},s("button",{ref:t=>this.backBtn=t,onClick:()=>this.previousTab(),class:"s-rating-modal-btn s-rating-modal-unvisiable"},salla.lang.get("common.elements.back")),this.stepsCount>1?s("ul",{class:"s-rating-modal-dots"},[...Array(this.stepsCount)].map(((t,a)=>s("li",{key:a,class:"s-rating-modal-bg-gray s-rating-modal-step-dot"})))):"",s("salla-button",{"loader-position":"center",ref:t=>this.nextBtn=t,onClick:()=>this.submit()},salla.lang.get("common.elements.next")))]:s("salla-placeholder",{alignment:"center"}))):void 0}async componentWillLoad(){await salla.onReady(),this.syncStoreSettings()}componentDidRender(){this.scheduleWizardSetup&&this.defaultMode&&this.order&&(this.scheduleWizardSetup=!1,requestAnimationFrame((()=>this.handleWizard())))}disconnectedCallback(){this.clearThanksCountdown()}get host(){return e(this)}};m.style=".s-rating-modal-product-details{padding-bottom:0.5rem}.s-rating-modal-comment{margin-top:0.35rem}.s-rating-modal-product{margin-bottom:1rem}.s-rating-modal-product-img{position:absolute !important;inset:0;display:block;width:100% !important;max-width:100% !important;height:100% !important;object-fit:cover}.s-rating-modal-product-title{font-size:0.95rem;font-weight:600;line-height:1.5;margin:0}.s-rating-modal-stars-product{margin-top:0.5rem}.s-rating-modal-loyalty-points-note-container{display:flex;align-items:center;gap:0.625rem;width:100%;margin-top:1.5rem;margin-bottom:0.75rem;padding:0.75rem;border-radius:0.5rem;background-color:#E6F4EA}.s-rating-modal-loyalty-points-note-icon{display:flex;flex-shrink:0;align-items:center;justify-content:center;width:1.25rem;height:1.25rem;color:#1B7F5C}.s-rating-modal-loyalty-points-note-icon svg{width:1.5rem;height:1.5rem;fill:currentColor}.s-rating-modal-loyalty-points-note-text{flex:1;margin:0;font-size:0.875rem;line-height:1.25rem;color:#1f2937}.s-rating-modal-product-details-main{display:flex;align-items:center;margin-bottom:0.5rem;padding-bottom:0;border-bottom:0}.s-rating-modal-product-info-row{display:flex;align-items:center;gap:0.6rem;margin-bottom:0.5rem;padding-bottom:0;border-bottom:0}.s-rating-modal-product-main-review{width:100%;text-align:right}.s-rating-modal-product-rating-rows{display:grid;gap:0.45rem;margin:0.2rem 0 0.7rem}.s-rating-modal-product-rating-row{display:flex;align-items:center;justify-content:space-between;gap:0.75rem;min-height:2rem}.s-rating-modal-product-rating-row salla-rating-stars{flex-shrink:0}.s-rating-modal-product-rating-row .s-rating-stars-wrapper{align-items:center;min-height:1.75rem}.s-rating-modal-product-rating-row .s-rating-stars-label,.s-rating-modal-product-rating-row .s-rating-stars-label-without-tag{min-width:auto;min-height:1.25rem;line-height:1.25rem;font-size:0.8rem;color:#5b6470;white-space:nowrap;text-align:end;transition:opacity 0.15s ease}.s-rating-modal-product-rating-row .s-rating-stars-label--empty,.s-rating-modal-product-rating-row .s-rating-stars-label-without-tag--empty{opacity:0}.s-rating-modal-product-rating-row-main{margin-bottom:0.35rem;padding:0.5rem 0.6rem;border:1px solid #d1d5db;border-radius:0.45rem;background:transparent}.s-rating-modal-product-factor-name{color:#5b6470;font-size:0.9rem;line-height:1.25}.s-rating-modal-product-rating-row-main .s-rating-modal-product-factor-name{font-size:1rem;color:#5b6470}.s-rating-modal-product-factor-required{color:#f87171;margin-inline-start:0.2rem}.s-rating-modal-product-img-wrap{position:relative;width:5rem !important;min-width:5rem !important;max-width:5rem !important;height:3.5rem !important;flex-shrink:0 !important;overflow:hidden;border-radius:0.375rem;background:#f3f4f6}.s-rating-modal-uploader.is-opened{height:auto !important;opacity:1 !important;overflow:visible !important;pointer-events:auto !important;margin-bottom:1rem}";export{m as salla_rating_modal_v2}
@@ -1,4 +1,4 @@
1
1
  /*!
2
2
  * Crafted with ❤ by Salla
3
3
  */
4
- import{r as t,h as s}from"./p-BEjZOd--.js";import{a as i}from"./p-CgtvEd63.js";import{a as e}from"./p-BedNk7k1.js";import{S as a}from"./p-8Tsmrwno.js";import{S as h}from"./p-0-eTJXSD.js";const l=class{constructor(s){t(this,s),this.defaultEvent="gifting:open",this.selectImageForYourGift=salla.lang.get("blocks.buy_as_gift.select_image_for_your_gift"),this.currentStep=1,this.showCalendar=!1,this.showGiftText=!1,this.currentLang="",this.parentClass="is-current-step-1",this.errors={},this.gift=void 0,this.selectedGiftTextOption=void 0,this.selectedCountryId=void 0,this.selectedCountryCode=void 0,this.loadingCities=!1,this.loadingRegions=!1,this.regions=[],this.selectedRegionId=void 0,this.isKSA=!1,this.selectedCountry=null,this.selectedRegion=null,this.displayedCities=[],this.selectedCity=null,this.searchingCities=!1,this.enableCityAjaxSearch=!1,this.citySearchQuery="",this.step2Animated=!1,this.citySearchTimer=null,this.citySearchCounter=0,this.locationRequestCounter=0,this.showTextArea=!1,this.selectedImage=void 0,this.uploadedImage=void 0,this.selectedText=void 0,this.hasError=!1,this.timeZone=null,this.receiverCountryCode=salla.config.get("store.scope.countries")?.[0]||salla.config.get("store.store_country")||"SA",this.hostId=`salla-gifting-${Math.random().toString(36).slice(2,10)}`,this.disableClass=this.gift?.show_image_upload?"":"pointer-events-none",this.formSelector="form.product-form, form.form--product-options",this.handleCitySearch=t=>{if(this.citySearchQuery=t,!this.enableCityAjaxSearch)return;this.citySearchTimer&&clearTimeout(this.citySearchTimer);const s=++this.citySearchCounter;this.citySearchTimer=setTimeout((async()=>{this.searchingCities=!0;try{const i=await this.fetchCities(t);s===this.citySearchCounter&&(this.displayedCities=i)}catch(t){s===this.citySearchCounter&&(this.displayedCities=[])}finally{s===this.citySearchCounter&&(this.searchingCities=!1)}}),l.CITY_SEARCH_DEBOUNCE_MS)},this.handleCitySelected=t=>{this.selectedCity=t,this.receiverCity=String(t.id),this.clearError("receiver.city_id")},this.handleCityDropdownClosed=()=>{this.citySearchQuery="",this.citySearchTimer&&(clearTimeout(this.citySearchTimer),this.citySearchTimer=null),++this.citySearchCounter,this.displayedCities=this.gift?.cities??[],this.searchingCities=!1},this.handleCountryDropdownClosed=()=>{},this.handleRegionDropdownClosed=()=>{},salla.lang.onLoaded((()=>{this.selectImageOrUpload=salla.lang.get("blocks.buy_as_gift.select_image_or_upload"),this.selectImageForYourGift=salla.lang.get("blocks.buy_as_gift.select_image_for_your_gift"),this.sectionTitle=salla.lang.get("blocks.buy_as_gift.gift_the_one_you_love"),this.sectionSubtitle=salla.lang.get("blocks.buy_as_gift.gift_the_one_you_love_message"),this.sectionBtnText=salla.lang.get("blocks.buy_as_gift.send_as_a_gift"),this.giftDetails=salla.lang.get("blocks.buy_as_gift.gift_details"),this.selectGiftMessage=salla.lang.get("blocks.buy_as_gift.select_gift_message"),this.giftText=salla.lang.get("blocks.buy_as_gift.gift_text"),this.giftCustomText=salla.lang.get("blocks.buy_as_gift.gift_custom_text"),this.textId=salla.lang.get("blocks.buy_as_gift.text_id"),this.incorrectGiftText=salla.lang.get("blocks.buy_as_gift.incorrect_gift_text"),this.nextStep=salla.lang.get("blocks.buy_as_gift.next_step"),this.senderNameLabel=salla.lang.get("blocks.buy_as_gift.sender_name"),this.receiverNameFieldLabel=salla.lang.get("blocks.buy_as_gift.receiver_name"),this.receiverMobileFieldLabel=salla.lang.get("blocks.buy_as_gift.receiver_mobile"),this.receiverCountryFieldLabel=salla.lang.get("blocks.buy_as_gift.receiver_country"),this.ksa=salla.lang.get("pages.checkout.ksa"),this.selectCity=salla.lang.get("pages.checkout.select_city"),this.selectCountry=salla.lang.get("pages.checkout.select_country"),this.selectCityInfo=salla.lang.get("blocks.buy_as_gift.city_info"),this.cityChangeNotice=salla.lang.get("blocks.buy_as_gift.city_change_notice"),this.receiverCityFieldLabel=salla.lang.get("blocks.buy_as_gift.receiver_city"),this.receiverRegionFieldLabel=salla.lang.get("blocks.buy_as_gift.receiver_region")||salla.lang.get("pages.checkout.region"),this.selectRegion=salla.lang.get("pages.checkout.select_region"),this.receiverEmailFieldLabel=salla.lang.get("blocks.buy_as_gift.receiver_email"),this.emailPlaceholder=salla.lang.get("common.elements.email_placeholder"),this.sendLater=salla.lang.get("blocks.buy_as_gift.send_later"),this.selectSendDateAndTime=salla.lang.get("blocks.buy_as_gift.select_send_date_and_time"),this.canNotEditOrderAfterSelectDate=salla.lang.get("blocks.buy_as_gift.can_not_edit_order_after_select_date"),this.sendGift=salla.lang.get("blocks.buy_as_gift.send_gift"),this.donationRequired=salla.lang.get("pages.products.donation_amount_required"),this.currentLang=salla.lang.locale})),salla.event.on(this.defaultEvent,(()=>{this.open()}))}isPhysical(){return this.physicalProducts||this.physical}cityNoticeText(){return this.gift?.recipient_can_change_address?this.gift?.allows_different_shipping_cost?null:this.cityChangeNotice:this.selectCityInfo}componentDidLoad(){salla.event.product.onPriceUpdated((()=>{const t=document.querySelector(".s-quantity-input-input");this.quantity=t?.value}))}getFormDataFromForm(){if(!this.formSelector)return null;const t=document.querySelector(this.formSelector);return t?new FormData(t):null}mergeObjectToFormData(t,s,i){for(let e in t){if(!t.hasOwnProperty(e)||null==t[e])continue;const a=i?`${i}[${e}]`:e;"object"!=typeof t[e]||null===t[e]||t[e]instanceof File?s.set(a,t[e]):this.mergeObjectToFormData(t[e],s,a)}return s}async open(){if(salla.config.isGuest())return salla.api.auth.setAfterLoginEvent(this.defaultEvent),void salla.event.dispatch("login::open",{withoutReload:!0});this.resetStepsAnimation(),this.currentStep=1,this.parentClass="is-current-step-1",this.step2Animated=!1,this.stepsWrapper?.style.removeProperty("height"),await this.modal.open();const t=this.productId?()=>salla.product.getGiftProductDetails(this.productId):()=>salla.cart.getGiftCartDetails();return await salla.api.withoutNotifier(t).then((t=>{this.gift=t.data,this.senderName=this.gift.sender_name,this.disableClass=this.gift?.show_image_upload?"":"pointer-events-none",this.gift.show_texts||(this.selectedGiftTextOption=void 0,this.selectedText=void 0),this.gift.show_images||(this.selectedImage=void 0,this.uploadedImage=void 0),this.skipStep1()&&(this.currentStep=2,this.parentClass="is-current-step-2",this.step2Animated=!0)})).catch((t=>{this.hasError=!0,this.errorMessage=t.response?.data?.error?.message||t.response?.data})).finally((()=>this.modal.stopLoading()))}skipStep1(){return!!this.gift&&!this.gift.show_images&&!this.gift.show_texts}resetStepsAnimation(){[this.step1Elems,this.step2Elems].forEach((t=>{t?.querySelectorAll(".anime-item").forEach((t=>t.removeAttribute("style")))})),this.step1Elems?.removeAttribute("style"),this.step2Elems&&!this.skipStep1()&&(this.step2Elems.style.removeProperty("opacity"),this.step2Elems.style.removeProperty("transform"))}async close(){return this.modal.close()}async setWrapperHeight(t=1,s=250,i=0,e=0){let a=document.querySelector(`#${this.hostId} .gift-step-${t}`);const h=()=>{this.stepsWrapper.style.height=e?`${e}px`:a.offsetHeight+i+"px"};this.step2Animated&&2===t?requestAnimationFrame(h):setTimeout(h,s)}toggleCalendar(){this.showCalendar=!this.showCalendar,this.setWrapperHeight(2,150,0)}toggleGiftText(t){this.textSelect?.classList.remove("s-form-has-error");let s=t.target.children[t.target.selectedIndex].getAttribute("data-id"),i="custom"==s;const e=this.showGiftText!==i;this.showGiftText=i,s?(this.selectedGiftTextOption=s,this.selectedText=i?void 0:t.target.value):(this.textArea.value="",this.selectedText=void 0,this.selectedGiftTextOption=void 0),e&&this.setWrapperHeight(1,150,5)}async goToStep2(t=!0){this.step1Elems&&(t&&!this.validateStep1()||(this.stepsWrapper&&this.step1Elems&&(this.stepsWrapper.style.height=`${this.step1Elems.offsetHeight}px`),this.setWrapperHeight(2,50,0),(new i.timeline).add({targets:this.step1Elems.querySelectorAll(`#${this.hostId} .anime-item`),opacity:[1,0],translateX:[0,50],delay:i.stagger(70),duration:1200}).add({targets:".gift-step-2",translateX:["-110%",0],opacity:[0,1]},"-=1800").add({targets:this.step2Elems.querySelectorAll(`#${this.hostId} .anime-item`),opacity:[0,1],translateX:[-50,0],delay:i.stagger(70),duration:1200,complete:()=>{this.step2Elems.querySelectorAll(`#${this.hostId} .anime-item`).forEach((t=>{t.classList.remove("opacity-0"),t.removeAttribute("style")})),this.step2Animated=!0}},"-=1200"),this.currentStep=2,this.parentClass=`is-current-step-${this.currentStep}`))}validateStep1(){return!(this.gift?.show_texts&&(this.selectedGiftTextOption?"custom"!=this.selectedGiftTextOption||this.selectedText?(this.textSelect?.classList.remove("s-form-has-error"),this.customTextArea?.classList.remove("s-form-has-error"),0):(this.textSelect?.classList.remove("s-form-has-error"),this.customTextArea?.classList.add("s-form-has-error"),1):(this.textSelect?.classList.add("s-form-has-error"),this.customTextArea?.classList.remove("s-form-has-error"),1)))}goToStep1(t){t.preventDefault();let s=new i.timeline({autoplay:!1});s.add({targets:this.step2Elems.querySelectorAll(`#${this.hostId} .anime-item`),opacity:[1,0],translateX:[0,-50],delay:i.stagger(70),duration:1200}).add({targets:".gift-step-1",translateX:["110%",0],opacity:[0,1]},"-=1800").add({targets:this.step1Elems.querySelectorAll(`#${this.hostId} .anime-item`),opacity:[0,1],translateX:[50,0],delay:i.stagger(70),duration:1200,complete:()=>{this.step1Elems.querySelectorAll(`#${this.hostId} .anime-item`).forEach((t=>{t.classList.remove("opacity-0"),t.removeAttribute("style")}))}},"-=1200"),s.play(),this.step2Animated=!1,this.setWrapperHeight(1,600,0),this.currentStep=1,this.parentClass=`is-current-step-${this.currentStep}`}getFilepondPlaceholder(){return`<div class="s-gifting-filepond-placeholder"><span class="s-gifting-filepond-placeholder-icon"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">\n<title>images</title>\n<path d="M22.667 29.333h-13.333c-3.676 0-6.667-2.991-6.667-6.667v-13.333c0-0.737-0.597-1.333-1.333-1.333s-1.333 0.596-1.333 1.333v13.333c0 5.145 4.187 9.333 9.333 9.333h13.333c0.736 0 1.333-0.596 1.333-1.333s-0.597-1.333-1.333-1.333zM22.667 5.333c-2.205 0-4 1.795-4 4s1.795 4 4 4 4-1.795 4-4-1.795-4-4-4zM22.667 10.667c-0.735 0-1.333-0.597-1.333-1.333s0.599-1.333 1.333-1.333 1.333 0.597 1.333 1.333-0.599 1.333-1.333 1.333zM25.333 0h-13.333c-3.676 0-6.667 2.991-6.667 6.667v13.333c0 1.055 0.268 2.040 0.707 2.927 0.039 0.099 0.088 0.188 0.151 0.277 1.137 2.053 3.301 3.463 5.809 3.463h13.333c3.676 0 6.667-2.991 6.667-6.667v-13.333c0-3.676-2.991-6.667-6.667-6.667zM12 24c-1.244 0-2.344-0.583-3.077-1.476l5.721-7.047 6.629 8.523zM29.333 20c0 2.205-1.795 4-4 4h-0.68l-8.933-11.485c-0.251-0.32-0.633-0.511-1.039-0.515h-0.015c-0.401 0-0.781 0.181-1.035 0.492l-5.632 6.935v-12.76c0-2.205 1.795-4 4-4h13.333c2.205 0 4 1.795 4 4z"></path>\n</svg>\n</span><p class="s-gifting-filepond-placeholder-text">${this.selectImageOrUpload&&this.gift.show_image_upload?this.selectImageOrUpload:this.selectImageForYourGift}</p></div>`}setPreview(t){this.uploader?.classList.add("has-bg");var s=document.querySelector(`#${this.hostId}.filepond-bg`)?document.querySelector(`#${this.hostId} .filepond-bg`):document.createElement("div");s.classList.add("filepond-bg"),s.classList.remove("s-hidden"),s.style.backgroundImage="url('"+t.url+"')",this.uploader?.querySelector(".filepond--root")?.appendChild(s),this.uploadedImage=t.url,this.gift&&this.gift.gift_images?.length&&this.setWrapperHeight(1,150,0)}removePreview(){this.uploader.classList.remove("has-bg");let t=document.querySelector(`#${this.hostId} .filepond-bg`);t.removeAttribute("style"),t.classList.add("s-hidden"),this.handleRemoveImage()}handleTextAreaChange(t){this.selectedText=t.target.value,this.customTextArea?.classList.remove("s-form-has-error")}clearError(t){if(this.errors?.[t]){const{[t]:s,...i}=this.errors;this.errors=i}}handleSenderName(t){this.senderName=t.target.value,this.clearError("sender_name")}handleReceiverName(t){this.receiverName=t.target.value,this.clearError("receiver.name")}resetCityState(){this.citySearchTimer&&(clearTimeout(this.citySearchTimer),this.citySearchTimer=null),++this.citySearchCounter,this.gift={...this.gift,cities:[]},this.displayedCities=[],this.receiverCity=void 0,this.selectedCity=null,this.citySearchQuery="",this.searchingCities=!1,this.enableCityAjaxSearch=!1}setInitialCities(t){this.gift={...this.gift,cities:t},this.displayedCities=t,this.enableCityAjaxSearch=t.length>=l.CITY_AJAX_THRESHOLD}async fetchCities(t=""){if(!this.selectedCountryId)return[];if(this.isKSA&&!this.selectedRegionId)return[];const s=["for_branch=0",`country_id=${this.selectedCountryId}`];this.isKSA&&this.selectedRegionId&&s.push(`region_id=${this.selectedRegionId}`),t?.trim()&&s.push(`query=${encodeURIComponent(t.trim())}`);const i=await salla.api.request(`shipping/cities?${s.join("&")}`);return i?.data??[]}async handleCountrySelected(t){const s=t?.id;this.selectedCountry=t??null,this.selectedCountryId=s,this.selectedCountryCode=t?.country_code,this.isKSA="SA"===t?.country_code,this.clearError("receiver.country"),this.regions=[],this.selectedRegionId=void 0,this.selectedRegion=null,this.resetCityState();const i=++this.locationRequestCounter;if(!s)return this.selectedCountryCode=void 0,this.isKSA=!1,void this.setWrapperHeight(2,0,0);if(this.isKSA){this.loadingRegions=!0,this.setWrapperHeight(2,0,0);try{const t=await salla.api.request(`shipping/countries/${s}/regions`);if(i!==this.locationRequestCounter)return;t&&t.data&&(this.regions=t.data)}catch(t){if(i!==this.locationRequestCounter)return;console.error("Error fetching regions:",t)}finally{i===this.locationRequestCounter&&(this.loadingRegions=!1,this.setWrapperHeight(2,0,0))}}else{this.loadingCities=!0,this.setWrapperHeight(2,0,0);try{const t=await this.fetchCities();if(i!==this.locationRequestCounter)return;this.setInitialCities(t)}catch(t){if(i!==this.locationRequestCounter)return;console.error("Error fetching cities:",t)}finally{i===this.locationRequestCounter&&(this.loadingCities=!1)}}}async handleRegionSelected(t){const s=t?.id;this.selectedRegion=t??null,this.selectedRegionId=s,this.clearError("receiver.region"),this.resetCityState();const i=++this.locationRequestCounter;if(s){this.loadingCities=!0;try{const t=await this.fetchCities();if(i!==this.locationRequestCounter)return;this.setInitialCities(t)}catch(t){if(i!==this.locationRequestCounter)return;console.error("Error fetching cities:",t)}finally{i===this.locationRequestCounter&&(this.loadingCities=!1,this.setWrapperHeight(2,0,0))}}}handleUploadImage(t){this.uploadedImage=t,this.gift&&this.gift.gift_images?.length&&this.setWrapperHeight(1,150,0)}handleRemoveImage(){this.uploadedImage="",this.gift&&this.gift.gift_images?.length&&this.setWrapperHeight(1,150,0)}handlePhoneInputChange(t){let s=t.detail;this.receiverMobile=s.number,this.receiverCountryCode=s.country_code,this.clearError("receiver.mobile")}handleDateTimePicker(t){this.deliveryDate=t.detail}getCalendarClasses(){return{"s-form-group":!0,"anime-item":!0,"s-gifting-calendar":!0,shown:this.showCalendar,hide:!this.showCalendar,"s-form-has-error":!!this.errors&&this.errors.deliver_at}}async submitForm(){const t=document.querySelector("#donating-amount")?.value;if(this.calendarFormGroup.classList.remove("s-form-has-error"),this.errors&&(this.errors={},this.setWrapperHeight(2,150,0)),this.showCalendar&&!this.deliveryDate)return void this.calendarFormGroup.classList.add("s-form-has-error");const s=[{key:"sender_name",value:this.senderName,label:this.senderNameLabel},{key:"receiver.name",value:this.receiverName,label:this.receiverNameFieldLabel},{key:"receiver.mobile",value:this.receiverMobile,label:this.receiverMobileFieldLabel},...this.isPhysical()?[{key:"receiver.country",value:this.selectedCountryId,label:this.receiverCountryFieldLabel},...this.isKSA?[{key:"receiver.region",value:this.selectedRegionId,label:this.receiverRegionFieldLabel}]:[],{key:"receiver.city_id",value:this.receiverCity,label:this.receiverCityFieldLabel}]:[]],i={};if(s.forEach((({key:t,value:s,label:e})=>{s||(i[t]=salla.lang.get("common.errors.field_required",{attribute:e}))})),Object.keys(i).length)return this.errors=i,void this.setWrapperHeight(2,150,0);const e="custom"===this.selectedGiftTextOption,a={text:e?this.selectedText:void 0,text_id:!e&&this.selectedGiftTextOption?Number(this.selectedGiftTextOption):void 0,sender_name:this.senderName,quantity:this.quantity,deliver_at:this.showCalendar?this.deliveryDate:null,image_url:this.uploadedImage??this.selectedImage,donation_amount:t||null,receiver:{name:this.receiverName,mobile_country_code:this.receiverCountryCode,mobile:this.receiverMobile,...this.isPhysical()&&this.selectedCountryCode?{country_code:this.selectedCountryCode}:{},...this.isPhysical()&&this.selectedRegionId?{region_id:this.selectedRegionId}:{},...this.receiverCity&&this.isPhysical()?{city_id:this.receiverCity}:{}},has_apple_pay:salla.helpers.hasApplePay()};let h;this.productId&&this.formSelector&&(h=this.getFormDataFromForm()||new FormData,h=this.mergeObjectToFormData(a,h));const l=this.productId?()=>salla.product.addProductGiftToCart(this.productId,h,!0):()=>salla.cart.addCartGiftToCart(a,!0);return await l().then((()=>this.modal.close())).catch((t=>{t.response&&422==t.response.status?this.errors=t.response.data.error.fields:console.log(t),this.setWrapperHeight(2,150,0)}))}step2ItemClass(t=""){const s="anime-item"+(this.step2Animated?"":" opacity-0");return t?`${t} ${s}`:s}generateClass(){return{"s-gifting-widget":!0,"s-gifting-widget-vertical":!!this.vertical,"s-gifting-widget-horizontal":!this.vertical}}async handleGiftButtonClick(){if(this.productId&&this.formSelector){const t=document.querySelector(this.formSelector);if(!t)return void console.error("SallaGifting:: Form not found in the document!");if(!(t instanceof HTMLFormElement))return void console.error("SallaGifting:: The specified selector does not correspond to a form tag!");if(!t.reportValidity())return console.error("SallaGifting:: Form is not valid!"),void salla.error(salla.lang.get("common.messages.required_fields"))}const t=document.querySelector(`salla-product-options[product-id="${this.productId}"]`);!t||await t.reportValidity()?this.open():salla.error(salla.lang.get("common.messages.required_fields"))}render(){return[s("div",{key:"b4d479166a0a7a8b7bf4d66fd39399eef0bbe1d8"},s("salla-list-tile",{key:"a526748e500753bc4e132b6d8cc5fe56d276378c",class:this.generateClass()},s("div",{key:"3756943a7292552172dfe5fe112a987f9dff2128",slot:"title"},this.vertical?s("span",{innerHTML:h}):"",s("h3",{key:"769df65a33828cdb51270438885bd7554a93b18b"},this.widgetTitle?this.widgetTitle:this.sectionTitle)),s("div",{key:"69c51851715c12002d0d70f936852bf6b6a064a4",slot:"subtitle"},s("div",{key:"ee7979030a5756a4ad74c87cebdb595decc12d48"},this.widgetSubtitle?this.widgetSubtitle:this.sectionSubtitle)),s("div",{key:"374d33078ca9e9f4d26bc801abcb50d8271887bf",slot:"action"},s("salla-button",{key:"f5c53ce21a6e058e484f941d356e1c74bf337b5f",color:"primary",fill:"outline",width:"wide",class:"s-gifting-widget-action",onClick:()=>this.handleGiftButtonClick()},s("slot",{key:"2b57632750b91dc720605c181e19a0329c8db3e9",name:"widget-btn-content"},s("div",{key:"1d43f1351bc3323118c8eace681f382b753d009b",class:"s-gifting-widget-action-content"},s("span",{key:"f62808df38d07bf5db9d54f24a64c103dbcca3c2",innerHTML:h}),"  ",s("span",{key:"d22429956200e68c8d588d0daddae201963ba47a"},this.sectionBtnText)))))),s("salla-modal",{key:"0e1614ad210647ac77bbeb7e19104f5b9ce3b6b3",id:this.hostId,isLoading:!0,class:"s-gifting-modal",width:"sm",ref:t=>this.modal=t},s("div",{key:"230c00dd750aa31d20e450086b26c11094305e0f",slot:"loading"},s("div",{key:"cb48aec5cf71db50ba003cb3607c27e7a629e9be",class:"s-gifting-skeleton"},s("div",{key:"e7aa596896cb841628bf35b4b5d8c9d22ed84dae",class:"s-gifting-modal-header"},s("salla-skeleton",{key:"8e6dff5462dc1644bd89e56d51b3a353341b1741",type:"circle",height:"5rem",width:"5rem"}),s("h2",{key:"5bdf4f1266938b319a5d4642773cb0e8fa772f88",class:"s-gifting-modal-title"},s("div",{key:"2e3ea0e2589152059ec71f0e0a0b6537b0d32d8f",class:"s-gifting-modal-badge-wrapper"},s("salla-skeleton",{key:"7cf08110d0535ec7b719251cf54f3a83d940772f",height:"15px",width:"150px"})))),s("div",{key:"3e341993dd31be4bfbcc272877c8167f50233dd0",class:"s-gifting-skeleton-content"},s("salla-skeleton",{key:"74b584687ed715146e84a7107fb69f18ea78f31d",height:"10px",width:"150px"}),s("salla-skeleton",{key:"8acfdd240b397ea8e0d6c93c745786c68eb34f25",height:"230px"}),s("salla-skeleton",{key:"c92cef763f9d2857429919434a56bbc9686d6a3a",height:"10px",width:"150px"}),s("salla-skeleton",{key:"22e6c56dbabf3f90fa608dcd42d11b463ae86a1c",height:"30px"}),s("salla-skeleton",{key:"8093fcbc09362879ac5afb38f1910bdddfd41390",height:"40px"})))),s("slot",{key:"10842023d5a5861fa1562784c77f718c8e257d80",name:"header"}),this.hasError?s("salla-placeholder",{alignment:"center"},s("span",{slot:"title"},this.errorMessage||salla.lang.get("common.errors.empty_results")),s("span",{slot:"description"}," ")):[s("div",{class:"s-gifting-modal-header"},s("span",{class:"s-gifting-modal-icon"},s("span",{innerHTML:h})),s("h2",{class:"s-gifting-modal-title"},s("div",{class:"s-gifting-modal-badge-wrapper"},!this.skipStep1()&&s("div",{class:"s-gifting-modal-badge"},s("span",null,s("span",null,this.currentStep),"/2")),s("span",null,this.giftDetails)))),s("div",{class:"s-gifting-steps-wrapper "+this.parentClass,ref:t=>this.stepsWrapper=t},!this.skipStep1()&&s("div",{class:"s-gifting-step-one gift-step-1",ref:t=>this.step1Elems=t},this.gift&&this.gift.show_images&&s("div",{class:"s-gifting-modal-uploader-title anime-item"},this.selectImageForYourGift),this.gift&&this.gift.show_images&&s("div",{class:"s-gifting-image-section"},s("div",{class:`s-gifting-modal-uploader anime-item ${this.disableClass}`,ref:t=>this.uploader=t},s("span",{class:"s-gifting-remove-preview pointer-events-auto",onClick:()=>this.removePreview(),innerHTML:a}),this.selectImageOrUpload&&this.gift&&s("salla-file-upload",{"instant-upload":!0,name:"image_url",url:salla.url.api(salla.product.api.getUrl("giftImage")),onUploaded:t=>this.handleUploadImage(t.detail),labelIdle:this.getFilepondPlaceholder(),onRemoved:()=>this.handleRemoveImage()})),s("div",{class:"anime-item"},!this.uploadedImage&&this.gift&&this.gift.gift_images&&this.gift.gift_images.length>0?s("salla-slider",{id:"gifting-slider",loop:!1,"controls-outer":!0,class:"s-gifting-slider",type:"carousel"},s("div",{slot:"items"},this.gift&&this.gift.gift_images?this.gift?.gift_images.map((t=>s("a",{class:"s-gifting-clickable s-gifting-image",onClick:()=>this.setPreview(t)},s("img",{src:t.url,alt:`${t.id}`})))):"")):"")),this.gift&&this.gift.show_texts?s("div",{class:"anime-item"},s("div",{class:"s-gifting-modal-uploader-title s-gifting-text-title"},this.giftText),s("div",{class:"s-form-group s-gifting-selectText",ref:t=>this.textSelect=t},s("select",{id:"gift-text-selection",name:"gift-text-selection",class:"s-form-control s-gifting-select",onChange:t=>this.toggleGiftText(t)},s("option",{"data-id":null,selected:!this.selectedGiftTextOption},this.selectGiftMessage),this.gift&&this.gift.gift_texts?this.gift?.gift_texts.map((t=>s("option",{"data-id":t.id,value:t.text,key:t.id,selected:String(this.selectedGiftTextOption)===String(t.id)},t.text))):"",this.gift&&this.gift.show_custom_text?s("option",{"data-id":"custom",selected:"custom"===this.selectedGiftTextOption},this.giftCustomText):null)),s("div",{class:this.showGiftText&&this.gift&&this.gift.show_custom_text?"s-form-group s-gifting-textarea shown":"s-form-group s-gifting-textarea hide",ref:t=>this.customTextArea=t},s("label",{htmlFor:"gift-custom-text",class:"s-form-label"},this.giftCustomText),s("div",{class:"mt-1"},s("textarea",{onInput:t=>this.handleTextAreaChange(t),rows:4,ref:t=>this.textArea=t,name:"gift-custom-text",id:"gift-custom-text",class:"s-form-control"})))):null,s("div",{class:"anime-item"},s("salla-button",{color:"primary",width:"wide",onClick:()=>this.goToStep2(!!this.gift?.show_texts)},s("span",null,this.nextStep)))),s("div",{class:"s-gifting-step-two gift-step-2",style:this.skipStep1()?{opacity:"1",transform:"translateX(0)",position:"relative"}:void 0,ref:t=>this.step2Elems=t},s("div",{class:this.step2ItemClass(this.errors?.sender_name?"s-form-group s-form-has-error":"s-form-group")},s("label",{htmlFor:"sender_name",class:"s-form-label"},this.senderNameLabel),s("input",{type:"text",class:"s-form-control",name:"sender_name",id:"sender_name",value:this.senderName,onInput:t=>this.handleSenderName(t),placeholder:""}),this.errors&&this.errors.sender_name?s("span",{class:"s-gifting-error"},this.errors.sender_name):""),s("div",{class:this.step2ItemClass(this.errors?.["receiver.name"]?"s-form-group s-form-has-error":"s-form-group")},s("label",{htmlFor:"receiver_name",class:"s-form-label"},this.receiverNameFieldLabel),s("input",{type:"text",class:"s-form-control",name:"receiver_name",id:"receiver_name",value:"",onInput:t=>this.handleReceiverName(t),placeholder:""}),this.errors&&this.errors["receiver.name"]?s("span",{class:"s-gifting-error"},this.errors["receiver.name"]):""),s("div",{class:this.step2ItemClass(this.errors?.["receiver.mobile"]?"s-form-group s-form-has-error":"s-form-group")},s("label",{class:"s-form-label"},this.receiverMobileFieldLabel),s("salla-tel-input",{class:"s-gifting-tel-input",phone:this.receiverMobile,countryCode:this.receiverCountryCode,onPhoneEntered:t=>this.handlePhoneInputChange(t)}),this.errors&&this.errors["receiver.mobile"]?s("span",{class:"s-gifting-error"},this.errors["receiver.mobile"]):""),this.isPhysical()&&s("div",{class:this.step2ItemClass(this.errors?.["receiver.country"]?"s-form-group s-form-has-error":"s-form-group")},s("label",{class:"s-form-label",htmlFor:`${this.hostId}-country`},this.receiverCountryFieldLabel),s("salla-searchable-dropdown",{placeholder:this.selectCountry,items:this.gift?.countries??[],selectedItem:this.selectedCountry,disabled:!this.gift?.countries?.length,required:!0,inputId:`${this.hostId}-country`,searchable:!1,keepParentScroll:!0,onItemSelected:t=>this.handleCountrySelected(t.detail),onDropdownClosed:()=>this.handleCountryDropdownClosed()}),this.errors&&this.errors["receiver.country"]?s("span",{class:"s-gifting-error"},this.errors["receiver.country"]):""),this.isPhysical()&&this.isKSA&&s("div",{class:this.step2ItemClass(this.errors?.["receiver.region"]?"s-form-group s-form-has-error":"s-form-group")},s("label",{class:"s-form-label",htmlFor:`${this.hostId}-region`},this.receiverRegionFieldLabel),s("salla-searchable-dropdown",{placeholder:this.selectRegion,items:this.regions??[],selectedItem:this.selectedRegion,loading:this.loadingRegions,disabled:this.loadingRegions||!this.regions?.length,required:!0,inputId:`${this.hostId}-region`,searchable:!1,keepParentScroll:!0,onItemSelected:t=>this.handleRegionSelected(t.detail),onDropdownClosed:()=>this.handleRegionDropdownClosed()}),this.errors&&this.errors["receiver.region"]?s("span",{class:"s-gifting-error"},this.errors["receiver.region"]):""),this.isPhysical()&&s("div",{class:this.step2ItemClass(this.errors?.["receiver.city_id"]?"s-form-group s-form-has-error":"s-form-group")},s("label",{class:"s-form-label",htmlFor:`${this.hostId}-city`},this.receiverCityFieldLabel),s("salla-searchable-dropdown",{placeholder:this.selectCity,items:this.displayedCities,selectedItem:this.selectedCity,loading:this.loadingCities,searching:this.searchingCities,disabled:this.loadingCities||this.isKSA&&!this.selectedRegionId,required:!0,inputId:`${this.hostId}-city`,searchQuery:this.citySearchQuery,clientSearch:!this.enableCityAjaxSearch,dropUp:!0,keepParentScroll:!0,onItemSelected:t=>this.handleCitySelected(t.detail),onSearchInput:t=>this.handleCitySearch(t.detail),onDropdownClosed:()=>this.handleCityDropdownClosed()}),this.errors&&this.errors["receiver.city_id"]?s("span",{class:"s-gifting-error"},this.errors["receiver.city_id"]):""),this.isPhysical()&&this.cityNoticeText()&&s("div",{class:this.step2ItemClass("s-gifting-info")},s("span",{innerHTML:'\x3c!-- Generated by IcoMoon.io --\x3e\n<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">\n<title>alert</title>\n<path d="M16 13.333c-0.736 0-1.333 0.597-1.333 1.333v8c0 0.736 0.597 1.333 1.333 1.333s1.333-0.597 1.333-1.333v-8c0-0.736-0.597-1.333-1.333-1.333zM16 9.327c-0.736 0-1.333 0.604-1.333 1.34s0.597 1.333 1.333 1.333 1.333-0.597 1.333-1.333v-0.013c0-0.736-0.597-1.327-1.333-1.327zM27.313 4.687c-6.237-6.237-16.389-6.239-22.628 0-6.237 6.239-6.237 16.389 0 22.628 3.119 3.119 7.216 4.679 11.313 4.679s8.195-1.559 11.313-4.679c6.24-6.239 6.24-16.391 0.001-22.628zM25.428 25.428c-5.199 5.197-13.657 5.197-18.857 0-5.197-5.199-5.197-13.659 0-18.857 5.199-5.197 13.659-5.197 18.857 0 5.199 5.2 5.199 13.659 0 18.857z"></path>\n</svg>\n'}),s("span",null,this.cityNoticeText())),!this.isPhysical()&&s("div",{class:this.step2ItemClass()},s("label",{class:"s-gifting-schedule s-gifting-clickable",htmlFor:`schedule-${this.hostId}`},s("input",{type:"checkbox",name:"schedule",id:`schedule-${this.hostId}`,onChange:()=>this.toggleCalendar(),class:"s-checkbox"}),s("span",{class:"s-form-label"}," ",this.sendLater," "))),s("div",{class:this.getCalendarClasses(),ref:t=>this.calendarFormGroup=t},s("label",{class:"s-form-label"},this.selectSendDateAndTime),s("salla-datetime-picker",{value:this.deliveryDate,placeholder:this.selectSendDateAndTime,"enable-time":!0,"date-format":"Y-m-d h:i K",onPicked:t=>this.handleDateTimePicker(t)}),s("span",{class:"s-gifting-calendar-hint"},this.canNotEditOrderAfterSelectDate)),s("div",{class:this.step2ItemClass("s-gifting-step-two-footer")},!this.skipStep1()&&s("a",{href:"#!",innerHTML:e,onClick:t=>this.goToStep1(t)}),s("salla-button",{onClick:()=>this.submitForm(),color:"primary",width:"wide"},s("span",null,this.sendGift)))))],s("slot",{key:"ba5b5cc6e2b20d756ed5149757b23239455939f7",name:"footer"})))]}};l.CITY_AJAX_THRESHOLD=400,l.CITY_SEARCH_DEBOUNCE_MS=100,l.style=".s-gifting-steps-wrapper{transition:height 0.8s cubic-bezier(0.55, 0, 0.1, 1) 0s}.s-gifting-select{background-image:url(\"data:image/svg+xml;utf8,<svg version='1.1' fill='gray' xmlns='http://www.w3.org/2000/svg' width='32' height='32' viewBox='0 0 32 32'><title>keyboard_arrow_down</title><path d='M9.875 11.104l6.125 6.125 6.125-6.125 1.875 1.875-8 8-8-8z'></path></svg>\");background-size:24px;background-repeat:no-repeat;background-position:99%;appearance:none}[dir=rtl] .s-gifting-select{background-position:5px}.s-gifting-widget-vertical .s-list-tile-item [slot=title]{display:flex;align-items:center;gap:1.5rem}.s-gifting-widget-vertical .s-list-tile-item-content{width:100%}.s-gifting-modal .s-searchable-dropdown-trigger{border-color:#d1d5db}.s-gifting-modal .s-searchable-dropdown-trigger:hover:not(.s-searchable-dropdown-trigger--disabled){border-color:#d1d5db}.s-gifting-modal .s-searchable-dropdown-trigger--open,.s-gifting-modal .s-searchable-dropdown-trigger:focus{border-color:var(--color-primary, #00897b);box-shadow:0 0 0 1px var(--color-primary, #00897b)}.s-gifting-modal .s-searchable-dropdown-trigger-placeholder{color:#000}.s-gifting-modal .s-gifting-image-section{margin-bottom:1.5rem}.s-gifting-modal .s-gifting-slider{margin-bottom:0.5rem}.s-gifting-modal .s-gifting-image{display:block}.s-gifting-modal .s-gifting-image img{display:block;width:auto;height:100px;object-fit:contain}.s-gifting-modal .s-gifting-image-section+.anime-item .s-gifting-text-title{margin-top:1rem}";export{l as salla_gifting}
4
+ import{r as t,h as s}from"./p-Bt0ajKaf.js";import{a as i}from"./p-CgtvEd63.js";import{a as e}from"./p-BedNk7k1.js";import{S as a}from"./p-8Tsmrwno.js";import{S as h}from"./p-0-eTJXSD.js";const l=class{constructor(s){t(this,s),this.defaultEvent="gifting:open",this.selectImageForYourGift=salla.lang.get("blocks.buy_as_gift.select_image_for_your_gift"),this.currentStep=1,this.showCalendar=!1,this.showGiftText=!1,this.currentLang="",this.parentClass="is-current-step-1",this.errors={},this.gift=void 0,this.selectedGiftTextOption=void 0,this.selectedCountryId=void 0,this.selectedCountryCode=void 0,this.loadingCities=!1,this.loadingRegions=!1,this.regions=[],this.selectedRegionId=void 0,this.isKSA=!1,this.selectedCountry=null,this.selectedRegion=null,this.displayedCities=[],this.selectedCity=null,this.searchingCities=!1,this.enableCityAjaxSearch=!1,this.citySearchQuery="",this.step2Animated=!1,this.citySearchTimer=null,this.citySearchCounter=0,this.locationRequestCounter=0,this.showTextArea=!1,this.selectedImage=void 0,this.uploadedImage=void 0,this.selectedText=void 0,this.hasError=!1,this.timeZone=null,this.receiverCountryCode=salla.config.get("store.scope.countries")?.[0]||salla.config.get("store.store_country")||"SA",this.hostId=`salla-gifting-${Math.random().toString(36).slice(2,10)}`,this.disableClass=this.gift?.show_image_upload?"":"pointer-events-none",this.formSelector="form.product-form, form.form--product-options",this.handleCitySearch=t=>{if(this.citySearchQuery=t,!this.enableCityAjaxSearch)return;this.citySearchTimer&&clearTimeout(this.citySearchTimer);const s=++this.citySearchCounter;this.citySearchTimer=setTimeout((async()=>{this.searchingCities=!0;try{const i=await this.fetchCities(t);s===this.citySearchCounter&&(this.displayedCities=i)}catch(t){s===this.citySearchCounter&&(this.displayedCities=[])}finally{s===this.citySearchCounter&&(this.searchingCities=!1)}}),l.CITY_SEARCH_DEBOUNCE_MS)},this.handleCitySelected=t=>{this.selectedCity=t,this.receiverCity=String(t.id),this.clearError("receiver.city_id")},this.handleCityDropdownClosed=()=>{this.citySearchQuery="",this.citySearchTimer&&(clearTimeout(this.citySearchTimer),this.citySearchTimer=null),++this.citySearchCounter,this.displayedCities=this.gift?.cities??[],this.searchingCities=!1},this.handleCountryDropdownClosed=()=>{},this.handleRegionDropdownClosed=()=>{},salla.lang.onLoaded((()=>{this.selectImageOrUpload=salla.lang.get("blocks.buy_as_gift.select_image_or_upload"),this.selectImageForYourGift=salla.lang.get("blocks.buy_as_gift.select_image_for_your_gift"),this.sectionTitle=salla.lang.get("blocks.buy_as_gift.gift_the_one_you_love"),this.sectionSubtitle=salla.lang.get("blocks.buy_as_gift.gift_the_one_you_love_message"),this.sectionBtnText=salla.lang.get("blocks.buy_as_gift.send_as_a_gift"),this.giftDetails=salla.lang.get("blocks.buy_as_gift.gift_details"),this.selectGiftMessage=salla.lang.get("blocks.buy_as_gift.select_gift_message"),this.giftText=salla.lang.get("blocks.buy_as_gift.gift_text"),this.giftCustomText=salla.lang.get("blocks.buy_as_gift.gift_custom_text"),this.textId=salla.lang.get("blocks.buy_as_gift.text_id"),this.incorrectGiftText=salla.lang.get("blocks.buy_as_gift.incorrect_gift_text"),this.nextStep=salla.lang.get("blocks.buy_as_gift.next_step"),this.senderNameLabel=salla.lang.get("blocks.buy_as_gift.sender_name"),this.receiverNameFieldLabel=salla.lang.get("blocks.buy_as_gift.receiver_name"),this.receiverMobileFieldLabel=salla.lang.get("blocks.buy_as_gift.receiver_mobile"),this.receiverCountryFieldLabel=salla.lang.get("blocks.buy_as_gift.receiver_country"),this.ksa=salla.lang.get("pages.checkout.ksa"),this.selectCity=salla.lang.get("pages.checkout.select_city"),this.selectCountry=salla.lang.get("pages.checkout.select_country"),this.selectCityInfo=salla.lang.get("blocks.buy_as_gift.city_info"),this.cityChangeNotice=salla.lang.get("blocks.buy_as_gift.city_change_notice"),this.receiverCityFieldLabel=salla.lang.get("blocks.buy_as_gift.receiver_city"),this.receiverRegionFieldLabel=salla.lang.get("blocks.buy_as_gift.receiver_region")||salla.lang.get("pages.checkout.region"),this.selectRegion=salla.lang.get("pages.checkout.select_region"),this.receiverEmailFieldLabel=salla.lang.get("blocks.buy_as_gift.receiver_email"),this.emailPlaceholder=salla.lang.get("common.elements.email_placeholder"),this.sendLater=salla.lang.get("blocks.buy_as_gift.send_later"),this.selectSendDateAndTime=salla.lang.get("blocks.buy_as_gift.select_send_date_and_time"),this.canNotEditOrderAfterSelectDate=salla.lang.get("blocks.buy_as_gift.can_not_edit_order_after_select_date"),this.sendGift=salla.lang.get("blocks.buy_as_gift.send_gift"),this.donationRequired=salla.lang.get("pages.products.donation_amount_required"),this.currentLang=salla.lang.locale})),salla.event.on(this.defaultEvent,(()=>{this.open()}))}isPhysical(){return this.physicalProducts||this.physical}cityNoticeText(){return this.gift?.recipient_can_change_address?this.gift?.allows_different_shipping_cost?null:this.cityChangeNotice:this.selectCityInfo}componentDidLoad(){salla.event.product.onPriceUpdated((()=>{const t=document.querySelector(".s-quantity-input-input");this.quantity=t?.value}))}getFormDataFromForm(){if(!this.formSelector)return null;const t=document.querySelector(this.formSelector);return t?new FormData(t):null}mergeObjectToFormData(t,s,i){for(let e in t){if(!t.hasOwnProperty(e)||null==t[e])continue;const a=i?`${i}[${e}]`:e;"object"!=typeof t[e]||null===t[e]||t[e]instanceof File?s.set(a,t[e]):this.mergeObjectToFormData(t[e],s,a)}return s}async open(){if(salla.config.isGuest())return salla.api.auth.setAfterLoginEvent(this.defaultEvent),void salla.event.dispatch("login::open",{withoutReload:!0});this.resetStepsAnimation(),this.currentStep=1,this.parentClass="is-current-step-1",this.step2Animated=!1,this.stepsWrapper?.style.removeProperty("height"),await this.modal.open();const t=this.productId?()=>salla.product.getGiftProductDetails(this.productId):()=>salla.cart.getGiftCartDetails();return await salla.api.withoutNotifier(t).then((t=>{this.gift=t.data,this.senderName=this.gift.sender_name,this.disableClass=this.gift?.show_image_upload?"":"pointer-events-none",this.gift.show_texts||(this.selectedGiftTextOption=void 0,this.selectedText=void 0),this.gift.show_images||(this.selectedImage=void 0,this.uploadedImage=void 0),this.skipStep1()&&(this.currentStep=2,this.parentClass="is-current-step-2",this.step2Animated=!0)})).catch((t=>{this.hasError=!0,this.errorMessage=t.response?.data?.error?.message||t.response?.data})).finally((()=>this.modal.stopLoading()))}skipStep1(){return!!this.gift&&!this.gift.show_images&&!this.gift.show_texts}resetStepsAnimation(){[this.step1Elems,this.step2Elems].forEach((t=>{t?.querySelectorAll(".anime-item").forEach((t=>t.removeAttribute("style")))})),this.step1Elems?.removeAttribute("style"),this.step2Elems&&!this.skipStep1()&&(this.step2Elems.style.removeProperty("opacity"),this.step2Elems.style.removeProperty("transform"))}async close(){return this.modal.close()}async setWrapperHeight(t=1,s=250,i=0,e=0){let a=document.querySelector(`#${this.hostId} .gift-step-${t}`);const h=()=>{this.stepsWrapper.style.height=e?`${e}px`:a.offsetHeight+i+"px"};this.step2Animated&&2===t?requestAnimationFrame(h):setTimeout(h,s)}toggleCalendar(){this.showCalendar=!this.showCalendar,this.setWrapperHeight(2,150,0)}toggleGiftText(t){this.textSelect?.classList.remove("s-form-has-error");let s=t.target.children[t.target.selectedIndex].getAttribute("data-id"),i="custom"==s;const e=this.showGiftText!==i;this.showGiftText=i,s?(this.selectedGiftTextOption=s,this.selectedText=i?void 0:t.target.value):(this.textArea.value="",this.selectedText=void 0,this.selectedGiftTextOption=void 0),e&&this.setWrapperHeight(1,150,5)}async goToStep2(t=!0){this.step1Elems&&(t&&!this.validateStep1()||(this.stepsWrapper&&this.step1Elems&&(this.stepsWrapper.style.height=`${this.step1Elems.offsetHeight}px`),this.setWrapperHeight(2,50,0),(new i.timeline).add({targets:this.step1Elems.querySelectorAll(`#${this.hostId} .anime-item`),opacity:[1,0],translateX:[0,50],delay:i.stagger(70),duration:1200}).add({targets:".gift-step-2",translateX:["-110%",0],opacity:[0,1]},"-=1800").add({targets:this.step2Elems.querySelectorAll(`#${this.hostId} .anime-item`),opacity:[0,1],translateX:[-50,0],delay:i.stagger(70),duration:1200,complete:()=>{this.step2Elems.querySelectorAll(`#${this.hostId} .anime-item`).forEach((t=>{t.classList.remove("opacity-0"),t.removeAttribute("style")})),this.step2Animated=!0}},"-=1200"),this.currentStep=2,this.parentClass=`is-current-step-${this.currentStep}`))}validateStep1(){return!(this.gift?.show_texts&&(this.selectedGiftTextOption?"custom"!=this.selectedGiftTextOption||this.selectedText?(this.textSelect?.classList.remove("s-form-has-error"),this.customTextArea?.classList.remove("s-form-has-error"),0):(this.textSelect?.classList.remove("s-form-has-error"),this.customTextArea?.classList.add("s-form-has-error"),1):(this.textSelect?.classList.add("s-form-has-error"),this.customTextArea?.classList.remove("s-form-has-error"),1)))}goToStep1(t){t.preventDefault();let s=new i.timeline({autoplay:!1});s.add({targets:this.step2Elems.querySelectorAll(`#${this.hostId} .anime-item`),opacity:[1,0],translateX:[0,-50],delay:i.stagger(70),duration:1200}).add({targets:".gift-step-1",translateX:["110%",0],opacity:[0,1]},"-=1800").add({targets:this.step1Elems.querySelectorAll(`#${this.hostId} .anime-item`),opacity:[0,1],translateX:[50,0],delay:i.stagger(70),duration:1200,complete:()=>{this.step1Elems.querySelectorAll(`#${this.hostId} .anime-item`).forEach((t=>{t.classList.remove("opacity-0"),t.removeAttribute("style")}))}},"-=1200"),s.play(),this.step2Animated=!1,this.setWrapperHeight(1,600,0),this.currentStep=1,this.parentClass=`is-current-step-${this.currentStep}`}getFilepondPlaceholder(){return`<div class="s-gifting-filepond-placeholder"><span class="s-gifting-filepond-placeholder-icon"><svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">\n<title>images</title>\n<path d="M22.667 29.333h-13.333c-3.676 0-6.667-2.991-6.667-6.667v-13.333c0-0.737-0.597-1.333-1.333-1.333s-1.333 0.596-1.333 1.333v13.333c0 5.145 4.187 9.333 9.333 9.333h13.333c0.736 0 1.333-0.596 1.333-1.333s-0.597-1.333-1.333-1.333zM22.667 5.333c-2.205 0-4 1.795-4 4s1.795 4 4 4 4-1.795 4-4-1.795-4-4-4zM22.667 10.667c-0.735 0-1.333-0.597-1.333-1.333s0.599-1.333 1.333-1.333 1.333 0.597 1.333 1.333-0.599 1.333-1.333 1.333zM25.333 0h-13.333c-3.676 0-6.667 2.991-6.667 6.667v13.333c0 1.055 0.268 2.040 0.707 2.927 0.039 0.099 0.088 0.188 0.151 0.277 1.137 2.053 3.301 3.463 5.809 3.463h13.333c3.676 0 6.667-2.991 6.667-6.667v-13.333c0-3.676-2.991-6.667-6.667-6.667zM12 24c-1.244 0-2.344-0.583-3.077-1.476l5.721-7.047 6.629 8.523zM29.333 20c0 2.205-1.795 4-4 4h-0.68l-8.933-11.485c-0.251-0.32-0.633-0.511-1.039-0.515h-0.015c-0.401 0-0.781 0.181-1.035 0.492l-5.632 6.935v-12.76c0-2.205 1.795-4 4-4h13.333c2.205 0 4 1.795 4 4z"></path>\n</svg>\n</span><p class="s-gifting-filepond-placeholder-text">${this.selectImageOrUpload&&this.gift.show_image_upload?this.selectImageOrUpload:this.selectImageForYourGift}</p></div>`}setPreview(t){this.uploader?.classList.add("has-bg");var s=document.querySelector(`#${this.hostId}.filepond-bg`)?document.querySelector(`#${this.hostId} .filepond-bg`):document.createElement("div");s.classList.add("filepond-bg"),s.classList.remove("s-hidden"),s.style.backgroundImage="url('"+t.url+"')",this.uploader?.querySelector(".filepond--root")?.appendChild(s),this.uploadedImage=t.url,this.gift&&this.gift.gift_images?.length&&this.setWrapperHeight(1,150,0)}removePreview(){this.uploader.classList.remove("has-bg");let t=document.querySelector(`#${this.hostId} .filepond-bg`);t.removeAttribute("style"),t.classList.add("s-hidden"),this.handleRemoveImage()}handleTextAreaChange(t){this.selectedText=t.target.value,this.customTextArea?.classList.remove("s-form-has-error")}clearError(t){if(this.errors?.[t]){const{[t]:s,...i}=this.errors;this.errors=i}}handleSenderName(t){this.senderName=t.target.value,this.clearError("sender_name")}handleReceiverName(t){this.receiverName=t.target.value,this.clearError("receiver.name")}resetCityState(){this.citySearchTimer&&(clearTimeout(this.citySearchTimer),this.citySearchTimer=null),++this.citySearchCounter,this.gift={...this.gift,cities:[]},this.displayedCities=[],this.receiverCity=void 0,this.selectedCity=null,this.citySearchQuery="",this.searchingCities=!1,this.enableCityAjaxSearch=!1}setInitialCities(t){this.gift={...this.gift,cities:t},this.displayedCities=t,this.enableCityAjaxSearch=t.length>=l.CITY_AJAX_THRESHOLD}async fetchCities(t=""){if(!this.selectedCountryId)return[];if(this.isKSA&&!this.selectedRegionId)return[];const s=["for_branch=0",`country_id=${this.selectedCountryId}`];this.isKSA&&this.selectedRegionId&&s.push(`region_id=${this.selectedRegionId}`),t?.trim()&&s.push(`query=${encodeURIComponent(t.trim())}`);const i=await salla.api.request(`shipping/cities?${s.join("&")}`);return i?.data??[]}async handleCountrySelected(t){const s=t?.id;this.selectedCountry=t??null,this.selectedCountryId=s,this.selectedCountryCode=t?.country_code,this.isKSA="SA"===t?.country_code,this.clearError("receiver.country"),this.regions=[],this.selectedRegionId=void 0,this.selectedRegion=null,this.resetCityState();const i=++this.locationRequestCounter;if(!s)return this.selectedCountryCode=void 0,this.isKSA=!1,void this.setWrapperHeight(2,0,0);if(this.isKSA){this.loadingRegions=!0,this.setWrapperHeight(2,0,0);try{const t=await salla.api.request(`shipping/countries/${s}/regions`);if(i!==this.locationRequestCounter)return;t&&t.data&&(this.regions=t.data)}catch(t){if(i!==this.locationRequestCounter)return;console.error("Error fetching regions:",t)}finally{i===this.locationRequestCounter&&(this.loadingRegions=!1,this.setWrapperHeight(2,0,0))}}else{this.loadingCities=!0,this.setWrapperHeight(2,0,0);try{const t=await this.fetchCities();if(i!==this.locationRequestCounter)return;this.setInitialCities(t)}catch(t){if(i!==this.locationRequestCounter)return;console.error("Error fetching cities:",t)}finally{i===this.locationRequestCounter&&(this.loadingCities=!1)}}}async handleRegionSelected(t){const s=t?.id;this.selectedRegion=t??null,this.selectedRegionId=s,this.clearError("receiver.region"),this.resetCityState();const i=++this.locationRequestCounter;if(s){this.loadingCities=!0;try{const t=await this.fetchCities();if(i!==this.locationRequestCounter)return;this.setInitialCities(t)}catch(t){if(i!==this.locationRequestCounter)return;console.error("Error fetching cities:",t)}finally{i===this.locationRequestCounter&&(this.loadingCities=!1,this.setWrapperHeight(2,0,0))}}}handleUploadImage(t){this.uploadedImage=t,this.gift&&this.gift.gift_images?.length&&this.setWrapperHeight(1,150,0)}handleRemoveImage(){this.uploadedImage="",this.gift&&this.gift.gift_images?.length&&this.setWrapperHeight(1,150,0)}handlePhoneInputChange(t){let s=t.detail;this.receiverMobile=s.number,this.receiverCountryCode=s.country_code,this.clearError("receiver.mobile")}handleDateTimePicker(t){this.deliveryDate=t.detail}getCalendarClasses(){return{"s-form-group":!0,"anime-item":!0,"s-gifting-calendar":!0,shown:this.showCalendar,hide:!this.showCalendar,"s-form-has-error":!!this.errors&&this.errors.deliver_at}}async submitForm(){const t=document.querySelector("#donating-amount")?.value;if(this.calendarFormGroup.classList.remove("s-form-has-error"),this.errors&&(this.errors={},this.setWrapperHeight(2,150,0)),this.showCalendar&&!this.deliveryDate)return void this.calendarFormGroup.classList.add("s-form-has-error");const s=[{key:"sender_name",value:this.senderName,label:this.senderNameLabel},{key:"receiver.name",value:this.receiverName,label:this.receiverNameFieldLabel},{key:"receiver.mobile",value:this.receiverMobile,label:this.receiverMobileFieldLabel},...this.isPhysical()?[{key:"receiver.country",value:this.selectedCountryId,label:this.receiverCountryFieldLabel},...this.isKSA?[{key:"receiver.region",value:this.selectedRegionId,label:this.receiverRegionFieldLabel}]:[],{key:"receiver.city_id",value:this.receiverCity,label:this.receiverCityFieldLabel}]:[]],i={};if(s.forEach((({key:t,value:s,label:e})=>{s||(i[t]=salla.lang.get("common.errors.field_required",{attribute:e}))})),Object.keys(i).length)return this.errors=i,void this.setWrapperHeight(2,150,0);const e="custom"===this.selectedGiftTextOption,a={text:e?this.selectedText:void 0,text_id:!e&&this.selectedGiftTextOption?Number(this.selectedGiftTextOption):void 0,sender_name:this.senderName,quantity:this.quantity,deliver_at:this.showCalendar?this.deliveryDate:null,image_url:this.uploadedImage??this.selectedImage,donation_amount:t||null,receiver:{name:this.receiverName,mobile_country_code:this.receiverCountryCode,mobile:this.receiverMobile,...this.isPhysical()&&this.selectedCountryCode?{country_code:this.selectedCountryCode}:{},...this.isPhysical()&&this.selectedRegionId?{region_id:this.selectedRegionId}:{},...this.receiverCity&&this.isPhysical()?{city_id:this.receiverCity}:{}},has_apple_pay:salla.helpers.hasApplePay()};let h;this.productId&&this.formSelector&&(h=this.getFormDataFromForm()||new FormData,h=this.mergeObjectToFormData(a,h));const l=this.productId?()=>salla.product.addProductGiftToCart(this.productId,h,!0):()=>salla.cart.addCartGiftToCart(a,!0);return await l().then((()=>this.modal.close())).catch((t=>{t.response&&422==t.response.status?this.errors=t.response.data.error.fields:console.log(t),this.setWrapperHeight(2,150,0)}))}step2ItemClass(t=""){const s="anime-item"+(this.step2Animated?"":" opacity-0");return t?`${t} ${s}`:s}generateClass(){return{"s-gifting-widget":!0,"s-gifting-widget-vertical":!!this.vertical,"s-gifting-widget-horizontal":!this.vertical}}async handleGiftButtonClick(){if(this.productId&&this.formSelector){const t=document.querySelector(this.formSelector);if(!t)return void console.error("SallaGifting:: Form not found in the document!");if(!(t instanceof HTMLFormElement))return void console.error("SallaGifting:: The specified selector does not correspond to a form tag!");if(!t.reportValidity())return console.error("SallaGifting:: Form is not valid!"),void salla.error(salla.lang.get("common.messages.required_fields"))}const t=document.querySelector(`salla-product-options[product-id="${this.productId}"]`);!t||await t.reportValidity()?this.open():salla.error(salla.lang.get("common.messages.required_fields"))}render(){return[s("div",{key:"b4d479166a0a7a8b7bf4d66fd39399eef0bbe1d8"},s("salla-list-tile",{key:"a526748e500753bc4e132b6d8cc5fe56d276378c",class:this.generateClass()},s("div",{key:"3756943a7292552172dfe5fe112a987f9dff2128",slot:"title"},this.vertical?s("span",{innerHTML:h}):"",s("h3",{key:"769df65a33828cdb51270438885bd7554a93b18b"},this.widgetTitle?this.widgetTitle:this.sectionTitle)),s("div",{key:"69c51851715c12002d0d70f936852bf6b6a064a4",slot:"subtitle"},s("div",{key:"ee7979030a5756a4ad74c87cebdb595decc12d48"},this.widgetSubtitle?this.widgetSubtitle:this.sectionSubtitle)),s("div",{key:"374d33078ca9e9f4d26bc801abcb50d8271887bf",slot:"action"},s("salla-button",{key:"f5c53ce21a6e058e484f941d356e1c74bf337b5f",color:"primary",fill:"outline",width:"wide",class:"s-gifting-widget-action",onClick:()=>this.handleGiftButtonClick()},s("slot",{key:"2b57632750b91dc720605c181e19a0329c8db3e9",name:"widget-btn-content"},s("div",{key:"1d43f1351bc3323118c8eace681f382b753d009b",class:"s-gifting-widget-action-content"},s("span",{key:"f62808df38d07bf5db9d54f24a64c103dbcca3c2",innerHTML:h}),"  ",s("span",{key:"d22429956200e68c8d588d0daddae201963ba47a"},this.sectionBtnText)))))),s("salla-modal",{key:"0e1614ad210647ac77bbeb7e19104f5b9ce3b6b3",id:this.hostId,isLoading:!0,class:"s-gifting-modal",width:"sm",ref:t=>this.modal=t},s("div",{key:"230c00dd750aa31d20e450086b26c11094305e0f",slot:"loading"},s("div",{key:"cb48aec5cf71db50ba003cb3607c27e7a629e9be",class:"s-gifting-skeleton"},s("div",{key:"e7aa596896cb841628bf35b4b5d8c9d22ed84dae",class:"s-gifting-modal-header"},s("salla-skeleton",{key:"8e6dff5462dc1644bd89e56d51b3a353341b1741",type:"circle",height:"5rem",width:"5rem"}),s("h2",{key:"5bdf4f1266938b319a5d4642773cb0e8fa772f88",class:"s-gifting-modal-title"},s("div",{key:"2e3ea0e2589152059ec71f0e0a0b6537b0d32d8f",class:"s-gifting-modal-badge-wrapper"},s("salla-skeleton",{key:"7cf08110d0535ec7b719251cf54f3a83d940772f",height:"15px",width:"150px"})))),s("div",{key:"3e341993dd31be4bfbcc272877c8167f50233dd0",class:"s-gifting-skeleton-content"},s("salla-skeleton",{key:"74b584687ed715146e84a7107fb69f18ea78f31d",height:"10px",width:"150px"}),s("salla-skeleton",{key:"8acfdd240b397ea8e0d6c93c745786c68eb34f25",height:"230px"}),s("salla-skeleton",{key:"c92cef763f9d2857429919434a56bbc9686d6a3a",height:"10px",width:"150px"}),s("salla-skeleton",{key:"22e6c56dbabf3f90fa608dcd42d11b463ae86a1c",height:"30px"}),s("salla-skeleton",{key:"8093fcbc09362879ac5afb38f1910bdddfd41390",height:"40px"})))),s("slot",{key:"10842023d5a5861fa1562784c77f718c8e257d80",name:"header"}),this.hasError?s("salla-placeholder",{alignment:"center"},s("span",{slot:"title"},this.errorMessage||salla.lang.get("common.errors.empty_results")),s("span",{slot:"description"}," ")):[s("div",{class:"s-gifting-modal-header"},s("span",{class:"s-gifting-modal-icon"},s("span",{innerHTML:h})),s("h2",{class:"s-gifting-modal-title"},s("div",{class:"s-gifting-modal-badge-wrapper"},!this.skipStep1()&&s("div",{class:"s-gifting-modal-badge"},s("span",null,s("span",null,this.currentStep),"/2")),s("span",null,this.giftDetails)))),s("div",{class:"s-gifting-steps-wrapper "+this.parentClass,ref:t=>this.stepsWrapper=t},!this.skipStep1()&&s("div",{class:"s-gifting-step-one gift-step-1",ref:t=>this.step1Elems=t},this.gift&&this.gift.show_images&&s("div",{class:"s-gifting-modal-uploader-title anime-item"},this.selectImageForYourGift),this.gift&&this.gift.show_images&&s("div",{class:"s-gifting-image-section"},s("div",{class:`s-gifting-modal-uploader anime-item ${this.disableClass}`,ref:t=>this.uploader=t},s("span",{class:"s-gifting-remove-preview pointer-events-auto",onClick:()=>this.removePreview(),innerHTML:a}),this.selectImageOrUpload&&this.gift&&s("salla-file-upload",{"instant-upload":!0,name:"image_url",url:salla.url.api(salla.product.api.getUrl("giftImage")),onUploaded:t=>this.handleUploadImage(t.detail),labelIdle:this.getFilepondPlaceholder(),onRemoved:()=>this.handleRemoveImage()})),s("div",{class:"anime-item"},!this.uploadedImage&&this.gift&&this.gift.gift_images&&this.gift.gift_images.length>0?s("salla-slider",{id:"gifting-slider",loop:!1,"controls-outer":!0,class:"s-gifting-slider",type:"carousel"},s("div",{slot:"items"},this.gift&&this.gift.gift_images?this.gift?.gift_images.map((t=>s("a",{class:"s-gifting-clickable s-gifting-image",onClick:()=>this.setPreview(t)},s("img",{src:t.url,alt:`${t.id}`})))):"")):"")),this.gift&&this.gift.show_texts?s("div",{class:"anime-item"},s("div",{class:"s-gifting-modal-uploader-title s-gifting-text-title"},this.giftText),s("div",{class:"s-form-group s-gifting-selectText",ref:t=>this.textSelect=t},s("select",{id:"gift-text-selection",name:"gift-text-selection",class:"s-form-control s-gifting-select",onChange:t=>this.toggleGiftText(t)},s("option",{"data-id":null,selected:!this.selectedGiftTextOption},this.selectGiftMessage),this.gift&&this.gift.gift_texts?this.gift?.gift_texts.map((t=>s("option",{"data-id":t.id,value:t.text,key:t.id,selected:String(this.selectedGiftTextOption)===String(t.id)},t.text))):"",this.gift&&this.gift.show_custom_text?s("option",{"data-id":"custom",selected:"custom"===this.selectedGiftTextOption},this.giftCustomText):null)),s("div",{class:this.showGiftText&&this.gift&&this.gift.show_custom_text?"s-form-group s-gifting-textarea shown":"s-form-group s-gifting-textarea hide",ref:t=>this.customTextArea=t},s("label",{htmlFor:"gift-custom-text",class:"s-form-label"},this.giftCustomText),s("div",{class:"mt-1"},s("textarea",{onInput:t=>this.handleTextAreaChange(t),rows:4,ref:t=>this.textArea=t,name:"gift-custom-text",id:"gift-custom-text",class:"s-form-control"})))):null,s("div",{class:"anime-item"},s("salla-button",{color:"primary",width:"wide",onClick:()=>this.goToStep2(!!this.gift?.show_texts)},s("span",null,this.nextStep)))),s("div",{class:"s-gifting-step-two gift-step-2",style:this.skipStep1()?{opacity:"1",transform:"translateX(0)",position:"relative"}:void 0,ref:t=>this.step2Elems=t},s("div",{class:this.step2ItemClass(this.errors?.sender_name?"s-form-group s-form-has-error":"s-form-group")},s("label",{htmlFor:"sender_name",class:"s-form-label"},this.senderNameLabel),s("input",{type:"text",class:"s-form-control",name:"sender_name",id:"sender_name",value:this.senderName,onInput:t=>this.handleSenderName(t),placeholder:""}),this.errors&&this.errors.sender_name?s("span",{class:"s-gifting-error"},this.errors.sender_name):""),s("div",{class:this.step2ItemClass(this.errors?.["receiver.name"]?"s-form-group s-form-has-error":"s-form-group")},s("label",{htmlFor:"receiver_name",class:"s-form-label"},this.receiverNameFieldLabel),s("input",{type:"text",class:"s-form-control",name:"receiver_name",id:"receiver_name",value:"",onInput:t=>this.handleReceiverName(t),placeholder:""}),this.errors&&this.errors["receiver.name"]?s("span",{class:"s-gifting-error"},this.errors["receiver.name"]):""),s("div",{class:this.step2ItemClass(this.errors?.["receiver.mobile"]?"s-form-group s-form-has-error":"s-form-group")},s("label",{class:"s-form-label"},this.receiverMobileFieldLabel),s("salla-tel-input",{class:"s-gifting-tel-input",phone:this.receiverMobile,countryCode:this.receiverCountryCode,onPhoneEntered:t=>this.handlePhoneInputChange(t)}),this.errors&&this.errors["receiver.mobile"]?s("span",{class:"s-gifting-error"},this.errors["receiver.mobile"]):""),this.isPhysical()&&s("div",{class:this.step2ItemClass(this.errors?.["receiver.country"]?"s-form-group s-form-has-error":"s-form-group")},s("label",{class:"s-form-label",htmlFor:`${this.hostId}-country`},this.receiverCountryFieldLabel),s("salla-searchable-dropdown",{placeholder:this.selectCountry,items:this.gift?.countries??[],selectedItem:this.selectedCountry,disabled:!this.gift?.countries?.length,required:!0,inputId:`${this.hostId}-country`,searchable:!1,keepParentScroll:!0,onItemSelected:t=>this.handleCountrySelected(t.detail),onDropdownClosed:()=>this.handleCountryDropdownClosed()}),this.errors&&this.errors["receiver.country"]?s("span",{class:"s-gifting-error"},this.errors["receiver.country"]):""),this.isPhysical()&&this.isKSA&&s("div",{class:this.step2ItemClass(this.errors?.["receiver.region"]?"s-form-group s-form-has-error":"s-form-group")},s("label",{class:"s-form-label",htmlFor:`${this.hostId}-region`},this.receiverRegionFieldLabel),s("salla-searchable-dropdown",{placeholder:this.selectRegion,items:this.regions??[],selectedItem:this.selectedRegion,loading:this.loadingRegions,disabled:this.loadingRegions||!this.regions?.length,required:!0,inputId:`${this.hostId}-region`,searchable:!1,keepParentScroll:!0,onItemSelected:t=>this.handleRegionSelected(t.detail),onDropdownClosed:()=>this.handleRegionDropdownClosed()}),this.errors&&this.errors["receiver.region"]?s("span",{class:"s-gifting-error"},this.errors["receiver.region"]):""),this.isPhysical()&&s("div",{class:this.step2ItemClass(this.errors?.["receiver.city_id"]?"s-form-group s-form-has-error":"s-form-group")},s("label",{class:"s-form-label",htmlFor:`${this.hostId}-city`},this.receiverCityFieldLabel),s("salla-searchable-dropdown",{placeholder:this.selectCity,items:this.displayedCities,selectedItem:this.selectedCity,loading:this.loadingCities,searching:this.searchingCities,disabled:this.loadingCities||this.isKSA&&!this.selectedRegionId,required:!0,inputId:`${this.hostId}-city`,searchQuery:this.citySearchQuery,clientSearch:!this.enableCityAjaxSearch,dropUp:!0,keepParentScroll:!0,onItemSelected:t=>this.handleCitySelected(t.detail),onSearchInput:t=>this.handleCitySearch(t.detail),onDropdownClosed:()=>this.handleCityDropdownClosed()}),this.errors&&this.errors["receiver.city_id"]?s("span",{class:"s-gifting-error"},this.errors["receiver.city_id"]):""),this.isPhysical()&&this.cityNoticeText()&&s("div",{class:this.step2ItemClass("s-gifting-info")},s("span",{innerHTML:'\x3c!-- Generated by IcoMoon.io --\x3e\n<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">\n<title>alert</title>\n<path d="M16 13.333c-0.736 0-1.333 0.597-1.333 1.333v8c0 0.736 0.597 1.333 1.333 1.333s1.333-0.597 1.333-1.333v-8c0-0.736-0.597-1.333-1.333-1.333zM16 9.327c-0.736 0-1.333 0.604-1.333 1.34s0.597 1.333 1.333 1.333 1.333-0.597 1.333-1.333v-0.013c0-0.736-0.597-1.327-1.333-1.327zM27.313 4.687c-6.237-6.237-16.389-6.239-22.628 0-6.237 6.239-6.237 16.389 0 22.628 3.119 3.119 7.216 4.679 11.313 4.679s8.195-1.559 11.313-4.679c6.24-6.239 6.24-16.391 0.001-22.628zM25.428 25.428c-5.199 5.197-13.657 5.197-18.857 0-5.197-5.199-5.197-13.659 0-18.857 5.199-5.197 13.659-5.197 18.857 0 5.199 5.2 5.199 13.659 0 18.857z"></path>\n</svg>\n'}),s("span",null,this.cityNoticeText())),!this.isPhysical()&&s("div",{class:this.step2ItemClass()},s("label",{class:"s-gifting-schedule s-gifting-clickable",htmlFor:`schedule-${this.hostId}`},s("input",{type:"checkbox",name:"schedule",id:`schedule-${this.hostId}`,onChange:()=>this.toggleCalendar(),class:"s-checkbox"}),s("span",{class:"s-form-label"}," ",this.sendLater," "))),s("div",{class:this.getCalendarClasses(),ref:t=>this.calendarFormGroup=t},s("label",{class:"s-form-label"},this.selectSendDateAndTime),s("salla-datetime-picker",{value:this.deliveryDate,placeholder:this.selectSendDateAndTime,"enable-time":!0,"date-format":"Y-m-d h:i K",onPicked:t=>this.handleDateTimePicker(t)}),s("span",{class:"s-gifting-calendar-hint"},this.canNotEditOrderAfterSelectDate)),s("div",{class:this.step2ItemClass("s-gifting-step-two-footer")},!this.skipStep1()&&s("a",{href:"#!",innerHTML:e,onClick:t=>this.goToStep1(t)}),s("salla-button",{onClick:()=>this.submitForm(),color:"primary",width:"wide"},s("span",null,this.sendGift)))))],s("slot",{key:"ba5b5cc6e2b20d756ed5149757b23239455939f7",name:"footer"})))]}};l.CITY_AJAX_THRESHOLD=400,l.CITY_SEARCH_DEBOUNCE_MS=100,l.style=".s-gifting-steps-wrapper{transition:height 0.8s cubic-bezier(0.55, 0, 0.1, 1) 0s}.s-gifting-select{background-image:url(\"data:image/svg+xml;utf8,<svg version='1.1' fill='gray' xmlns='http://www.w3.org/2000/svg' width='32' height='32' viewBox='0 0 32 32'><title>keyboard_arrow_down</title><path d='M9.875 11.104l6.125 6.125 6.125-6.125 1.875 1.875-8 8-8-8z'></path></svg>\");background-size:24px;background-repeat:no-repeat;background-position:99%;appearance:none}[dir=rtl] .s-gifting-select{background-position:5px}.s-gifting-widget-vertical .s-list-tile-item [slot=title]{display:flex;align-items:center;gap:1.5rem}.s-gifting-widget-vertical .s-list-tile-item-content{width:100%}.s-gifting-modal .s-searchable-dropdown-trigger{border-color:#d1d5db}.s-gifting-modal .s-searchable-dropdown-trigger:hover:not(.s-searchable-dropdown-trigger--disabled){border-color:#d1d5db}.s-gifting-modal .s-searchable-dropdown-trigger--open,.s-gifting-modal .s-searchable-dropdown-trigger:focus{border-color:var(--color-primary, #00897b);box-shadow:0 0 0 1px var(--color-primary, #00897b)}.s-gifting-modal .s-searchable-dropdown-trigger-placeholder{color:#000}.s-gifting-modal .s-gifting-image-section{margin-bottom:1.5rem}.s-gifting-modal .s-gifting-slider{margin-bottom:0.5rem}.s-gifting-modal .s-gifting-image{display:block}.s-gifting-modal .s-gifting-image img{display:block;width:auto;height:100px;object-fit:contain}.s-gifting-modal .s-gifting-image-section+.anime-item .s-gifting-text-title{margin-top:1rem}";export{l as salla_gifting}
@@ -1,4 +1,4 @@
1
1
  /*!
2
2
  * Crafted with ❤ by Salla
3
3
  */
4
- import{r as t,c as s,h as i,H as e,a as r}from"./p-BEjZOd--.js";import{a as o}from"./p-CgtvEd63.js";import{S as a}from"./p-DiKTtDW5.js";import{H as l}from"./p-XnA1YTjA.js";const n=class{constructor(i){t(this,i),this.productsFetched=s(this,"productsFetched"),this.selectionChanged=s(this,"selectionChanged"),this.autoload=!1,this.productCardComponent="custom-salla-product-card",this.selectable=!1,this.page=1,this.placeholderText=salla.lang.get("pages.categories.no_products"),this.endOfText=salla.lang.get("common.elements.end_of_content"),this.failedLoadMore=salla.lang.get("common.elements.failed_to_load_more"),this.currentPage=salla.config.get("page"),this.filtersSnapshot=[],this.selectedProducts=new Map,this.lastViewedProductKey="lastViewedProductId",this.filtersKey="filters",this.infiniteScrollStateKey="infiniteScrollState",this.prevCategoryIdKey="prevCategoryId",this.isProcessing=!1,this.scrollTimeout=null,this.boundScrollToLastViewedProduct=()=>this.scrollToLastViewedProduct(),this.boundHandleScroll=()=>this.handleScroll(),this.specialPagesWithoutIds={"product.index.latest":"latest","product.index.offers":"offers","product.index.search":"search","product.index.sales":"sales"},this.onWishlistItemRemoved=(t,s)=>{if("wishlist"!==this.getSource()||!this.wrapper)return;const i=String(s),e=this.hasCustomComponent?this.productCardComponent:"salla-product-card";for(const t of Array.from(this.wrapper.children)){const s=t,r=t.querySelector(e),o=s.product?.id??r?.product?.id;if(null!=o&&String(o)===i){t.remove();break}}for(const t of Array.from(this.wrapper.children)){if(!t.classList.contains("s-products-list-selectable-item"))continue;const s=t;if(null!=s.product?.id&&String(s.product.id)===i&&!t.querySelector(e)){t.remove();break}}if(this.selectable){for(const t of Array.from(this.selectedProducts.keys()))String(t)===i&&this.selectedProducts.delete(t);this.emitSelection()}},this.onWishlistStorageSynced=()=>l.syncWishlistIcons(this.wrapper,`${this.productCardComponent}, salla-product-card`),this.includes=l.parseJson(this.includes||this.host.getAttribute("includes")),Array.isArray(this.includes)||(this.includes=null),l.setIncludes(this.includes),salla.lang.onLoaded((()=>{this.placeholderText=salla.lang.get("pages.categories.no_products"),this.endOfText=salla.lang.get("common.elements.end_of_content"),this.failedLoadMore=salla.lang.get("common.elements.failed_to_load_more"),this.currentPage=salla.config.get("page")}))}connectedCallback(){"scrollRestoration"in history&&(history.scrollRestoration="manual"),window.addEventListener("DOMContentLoaded",this.boundScrollToLastViewedProduct),salla.event.on("salla-filters::changed",(t=>this.setFilters(t))),salla.event.on("wishlist::removed",this.onWishlistItemRemoved),salla.event.on("wishlist::storage.synced",this.onWishlistStorageSynced)}disconnectedCallback(){window.removeEventListener("DOMContentLoaded",this.boundScrollToLastViewedProduct),window.removeEventListener("scroll",this.boundHandleScroll),salla.event.off("wishlist::removed",this.onWishlistItemRemoved),salla.event.off("wishlist::storage.synced",this.onWishlistStorageSynced)}async setFilters(t){if(t&&JSON.stringify(t)!==JSON.stringify(this.parsedFilters))return window.scrollTo({top:0,behavior:"smooth"}),this.parsedFilters=JSON.parse(JSON.stringify(t)),"product.index"==this.currentPage?.slug&&(this.currentCategoryIdFilter=this.parsedFilters?.category_id?this.toCategoryIdFilter(this.parsedFilters.category_id):null),this.reload()}async reload(){!this.autoload&&this.loadMoreWrapper&&(this.loadMoreWrapper.style.display="none"),this.hasInfiniteScroll&&salla.infiniteScroll.destroy(this.infiniteScroll),await this.buildNextPageUrl(),this.wrapper.innerHTML="",this.hasInfiniteScroll?this.init():this.getInitialData(),this.showPlaceholder&&(this.showPlaceholder=!1,this.placeholderLoader=document.createElement("div"),this.placeholderLoader.classList.add("s-products-list-loading-wrapper"),this.placeholderLoader.style.display="inherit",this.placeholderLoader.innerHTML='<span class="s-button-loader s-button-loader-center s-infinite-scroll-btn-loader"></span>',this.host.insertAdjacentElement("afterend",this.placeholderLoader))}isFilterable(){return salla.config.get("store.settings.product.filters")&&this.filtersResults}getCachedFilters(){return Array.isArray(this.filtersSnapshot)&&this.filtersSnapshot.length?JSON.parse(JSON.stringify(this.filtersSnapshot)):null}emitFilters(t){if(!this.isFilterable())return;if(t.filters)return this.filtersResults=!0,this.filtersSnapshot=JSON.parse(JSON.stringify(t.filters)),void salla.event.emit("filters::fetched",{filters:t.filters});const s=t.cursor?.current>1?this.getCachedFilters():null;if(s)return this.filtersResults=!0,void salla.event.emit("filters::fetched",{filters:s});this.filtersSnapshot=[],salla.event.emit("filters::hidden")}isSourceWithoutValue(){const t=this.getSource();if("wishlist"===t){const t=new URLSearchParams(window.location.search);return!(t.has("source_value")||t.has("source_value[]")||this.sourceValue)}return["offers","latest","sales","top-rated","reorder"].includes(t)}animateItems(){o({targets:"salla-products-list salla-product-card",opacity:[0,1],duration:1200,translateY:[20,0],delay:function(t,s){return 100*s}})}async initBaseNextPageUrl(t){this.nextPage=salla.url.api(`products?source=${t}`),this.includes?.length&&(this.nextPage+=`&includes[]=${this.includes.join("&includes[]=")}`),this.limit&&(this.nextPage+=`&per_page=${this.limit>32?32:this.limit}`),this.sortBy&&(this.nextPage+=`&sort=${this.sortBy}`),"preview"===salla.config.get("theme.mode")&&(this.nextPage+="&use_username_url=1"),this.nextPage+="&filterable=1";for(const[t,s]of Object.entries(this.parsedFilters||{}))if("source_value"!==t&&"source_value[]"!==t)if(["string","number"].includes(typeof s))this.nextPage+=`&filters[${encodeURIComponent(t)}]=${encodeURIComponent(s)}`;else if(Array.isArray(s))s.forEach((s=>this.nextPage+=`&filters[${encodeURIComponent(t)}][]=${encodeURIComponent(s)}`));else if("object"==typeof s)for(const[i,e]of Object.entries(s))this.nextPage+=`&filters[${encodeURIComponent(t)}][${encodeURIComponent(i)}]=${encodeURIComponent(e)}`;this.nextPage=await this.applyBeforeBuildListUrl(this.nextPage)}async buildNextPageUrl(){let t=this.getSource();if("json"===t)return;const s=sessionStorage.getItem(this.infiniteScrollStateKey);if(s){const{nextPage:t}=JSON.parse(s);if(!t)return}if(await this.initBaseNextPageUrl(t),!this.isSourceWithoutValue())if(["search","related","landing-page"].includes(t))this.nextPage+=`&source_value=${this.getSourceValue()}`;else try{this.nextPage+=`&source_value[]=${this.getSourceValue().join("&source_value[]=")}`}catch(s){salla.logger.warn(`source-value prop should be array of ids ex source-value="[1,2,3]" for the source [${t}]`),this.sourceValueIsValid=!1}}loading(t=!0,s=!1){if(t){let t=s&&!this.autoload?this.btnLoader:this.loader;t&&(t.style.display="inherit")}else this.autoload||this.btnLoader&&(this.btnLoader.style.display="none"),this.loader&&(this.loader.style.display="none")}getItemHTML(t){"landing-page"===this.getSource()&&(t.url="");const s=document.createElement(this.hasCustomComponent?this.productCardComponent:"salla-product-card");return s.product=t,this.compactCards&&(s.compact=!0,s.toggleAttribute("compact",!0)),this.applyLandingPageStyles(s),this.applyHorizontalCardStyles(s),s.addEventListener("click",(s=>{s.target.closest("a")&&(l.saveProductSource(this.getSource()),this.hasInfiniteScroll&&(this.takeStateSnapshot(),sessionStorage.setItem(this.lastViewedProductKey,t.id)))})),this.selectable?this.wrapSelectableItem(s,t):s}wrapSelectableItem(t,s){const i=document.createElement("div");i.className="s-products-list-selectable-item",i.product=s;const e=this.selectedProducts.has(s.id);e&&i.classList.add("s-products-list-item-selected");const r=document.createElement("label");r.className="s-products-list-select-control",r.setAttribute("aria-label",salla.lang.get("common.elements.select","تحديد"));const o=document.createElement("input");return o.type="checkbox",o.className="s-products-list-select-checkbox",o.checked=e,o.addEventListener("change",(()=>this.toggleSelection(s,i,o.checked))),r.appendChild(o),i.appendChild(r),i.appendChild(t),i}toggleSelection(t,s,i){i?(this.selectedProducts.set(t.id,t),s?.classList.add("s-products-list-item-selected")):(this.selectedProducts.delete(t.id),s?.classList.remove("s-products-list-item-selected")),this.emitSelection()}emitSelection(){const t=Array.from(this.selectedProducts.values()),s=Array.from(this.selectedProducts.keys()),i={ids:s,products:t,count:s.length};this.selectionChanged.emit(i),salla.event.emit("salla-products-list::selection.changed",i)}appendProductCards(t){this.wrapper&&((Array.isArray(t)?t:[t]).forEach((t=>this.wrapper.append(t))),this.onWishlistStorageSynced())}refreshWishlistIconsAfterHydration(){return salla.wishlist.api.syncStorageFromServer()}onSelectableChanged(t,s){t!==s&&this.isReady&&this.wrapper&&(t||(this.selectedProducts.clear(),this.emitSelection()),this.reload())}applyLandingPageStyles(t){"landing-page"!==this.getSource()||this.hasCustomComponent||(t.toggleAttribute("hide-add-btn",!0),t.classList.add("s-product-card-fit-height"))}applyHorizontalCardStyles(t){this.horizontalCards&&(t.toggleAttribute("horizontal",!0),this.hasCustomComponent||t.toggleAttribute("shadow-on-hover",!0))}waitForResizing(t){let s=null;return new Promise((i=>{const e=new ResizeObserver((()=>{clearTimeout(s),s=setTimeout((()=>{e.disconnect(),i(null)}),160)}));e.observe(t)}))}waitForLayoutStable(t){let s=null,i=null;return new Promise((e=>{let r;const o=()=>{clearTimeout(s),clearTimeout(i),r.disconnect(),e(null)};r=new MutationObserver((()=>{clearTimeout(s),s=setTimeout(o,160)})),r.observe(t,{childList:!0,subtree:!0,attributes:!0}),i=setTimeout(o,1e3)}))}async waitForStableLayout(t){return await Promise.allSettled([this.waitForResizing(t),this.waitForLayoutStable(t)])}scrollToLastViewedProduct(){const t=sessionStorage.getItem(this.lastViewedProductKey);t&&!salla.url.is_page("product.single")&&this.isElementLoaded(`[id*="${t}"]`).then((()=>{const s=this.wrapper?.querySelector(`[id*="${t}"]`);if(!s)return;const i=()=>{const t=()=>{s.scrollIntoView({block:"start",behavior:"instant"});const t=matchMedia("(max-width: 1024px)").matches?"header .inner":"ul.main-menu",i=window?.header_is_sticky?document.querySelector(t)?.getBoundingClientRect()?.height??56:0,e=parseInt(getComputedStyle(this.wrapper).rowGap)??16;scrollBy({top:-1*(i+e),behavior:"instant"})};requestAnimationFrame(t),s.querySelectorAll("img.lazy").forEach((s=>{const i=s,e=()=>{requestAnimationFrame(t),i.onload=i.onerror=null};i.onload=e,i.onerror=e})),this.removeScrollRestorationSession()};this.waitForStableLayout(this.host).then((()=>requestAnimationFrame(i)))}))}isElementLoaded(t){return new Promise((s=>{const i=setInterval((()=>{if(document.querySelector(t))return clearInterval(i),s(document.querySelector(t))}),50)}))}takeStateSnapshot(){const t=[];for(let s=0;s<this.wrapper.children.length;s++){const i=this.wrapper.children?.[s];t.push(i.product)}const s={pageIndex:Math.max((this.infiniteScroll?.pageIndex??1)-1,1),nextPage:this.nextPage,currentPageData:t};if(this.isFilterable()){const t=sessionStorage.getItem(this.filtersKey);sessionStorage.setItem(this.filtersKey,t||JSON.stringify(this.filtersSnapshot))}sessionStorage.setItem(this.infiniteScrollStateKey,JSON.stringify(s));let i=salla.config.get("page.id");const e=Object.keys(this.specialPagesWithoutIds).find((t=>salla.url.is_page(t)));e?i=this.specialPagesWithoutIds[e]:null!==i&&(i=String(i)),sessionStorage.setItem(this.prevCategoryIdKey,i)}removeScrollRestorationSession(){this.isFilterable()||sessionStorage.removeItem(this.filtersKey),sessionStorage.removeItem(this.infiniteScrollStateKey),sessionStorage.removeItem(this.lastViewedProductKey),sessionStorage.removeItem(this.prevCategoryIdKey)}loadStoredScrollState(){const t=sessionStorage.getItem(this.infiniteScrollStateKey),s=sessionStorage.getItem(this.filtersKey),i=sessionStorage.getItem(this.prevCategoryIdKey),e=this.specialPagesWithoutIds[salla.config.get("page.slug")]||null,r=salla.config.get("page.id"),o=salla.url.is_page("index"),a=salla.url.is_page("product.single"),l=e?i!==e:i!==String(r);if(i&&l&&!o&&!a||o&&!this.hasInfiniteScroll)return this.removeScrollRestorationSession(),this.switchToNormalBehavior=!0,!1;if(a)return this.switchToNormalBehavior=!0,!1;if(t)try{const{pageIndex:i,nextPage:e,currentPageData:r}=JSON.parse(t);if(s&&"undefined"!==s){const t=JSON.parse(s);this.filtersSnapshot=JSON.parse(JSON.stringify(t)),salla.event.emit("filters::fetched",{filters:t})}return this.page=i,this.nextPage=e,this.appendProductCards(r.map((t=>this.getItemHTML(t)))),!0}catch(t){console.error("Failed to load stored scroll state:",t),this.removeScrollRestorationSession()}return!1}getSource(){return l.getProductsSource(this.source)}isAuxiliaryProductsListSource(){return["json","selected","related","landing-page","recently"].includes(this.getSource())}toCategoryIdFilter(t){return Array.isArray(t)?t:t&&"object"==typeof t?Object.values(t):[t]}getSourceValue(){if("wishlist"===this.getSource()){const t=new URLSearchParams(window.location.search),s=t.getAll("source_value[]").length?t.getAll("source_value[]"):t.getAll("source_value");if(s.length)return s}return this.currentCategoryIdFilter?this.currentCategoryIdFilter:l.getProductsSourceValue(this.source,this.sourceValue)}logFetchError(t,s,i,e,r){try{const o=r&&"object"==typeof r?r:null,a=this.getSourceValue();salla.analytics?.log("salla::products.list.fetch.error",{errorPhase:t,source:this.getSource(),sourceValue:"string"==typeof a&&a.length>200?`${a.slice(0,200)}…`:Array.isArray(a)?{length:a.length}:a,pageIndex:this.infiniteScroll?.pageIndex,fetchPath:i,httpStatus:e?.status,httpStatusText:e?.statusText,responseUrl:e?.url,...o&&{dataCount:Array.isArray(o.data)?o.data.length:void 0,responseKeys:Object.keys(o).slice(0,15),filtersCount:Array.isArray(o.filters)?o.filters.length:void 0},errorMessage:s instanceof Error?s.message:String(s),..."processing"===t&&s instanceof Error&&s.stack?{errorStack:s.stack.slice(0,500)}:{}})}catch{}}appendDataLayer(t){"object"==typeof dataLayer&&Array.isArray(dataLayer)&&dataLayer.push({event:"impressions",ecommerce:{currencyCode:salla.config.currency().code,impressions:t.map(((t,s)=>({id:t.id,name:t.name,price:t.price,brand:t.brand?.name||"",quantity:t.quantity,categories:[{name:t.category?.name||salla.config.get("page.title"),id:salla.config.get("page.id")}],category:t.category?.name||salla.config.get("page.title"),position:s+1})))}})}initiateInfiniteScroll(){if(!this.hasInfiniteScroll)return;const t=this.autoload&&this.includes&&this.includes.length>0;this.infiniteScroll=salla.infiniteScroll.initiate(this.wrapper,this.wrapper,{path:()=>this.nextPage,history:!1,nextPage:this.nextPage,scrollThreshold:!t&&!!this.autoload&&100,loadOnScroll:!t&&this.autoload},!0),this.infiniteScroll.pageIndex=this.page,this.infiniteScroll?.on("request",(()=>{this.loading(!0,!this.autoload)})),t&&window.addEventListener("scroll",this.boundHandleScroll),this.infiniteScroll?.on("load",(async(t,s,i)=>{if(!this.isProcessing){this.isProcessing=!0;try{if(!t.data?.length&&2===this.infiniteScroll.pageIndex)return this.showPlaceholder=!0,salla.infiniteScroll.destroy(this.infiniteScroll),this.loading(!1),void(this.placeholderLoader&&this.placeholderLoader.remove());this.includes&&await this.injectAndProcessData(t);const s=await this.handleResponse(t);this.infiniteScroll.appendItems(s),this.onWishlistStorageSynced(),2===this.infiniteScroll.pageIndex&&(!this.autoload&&this.nextPage&&(this.loadMoreWrapper.style.display="block"),this.animateItems(),this.refreshInfiniteScrollMeasurements())}catch(e){console.error("Error during load:",e),this.logFetchError("processing",e,"string"==typeof s?s:void 0,i,t)}finally{this.isProcessing=!1}}})),this.infiniteScroll?.on("error",((t,s,i)=>{const e=i;this.status.querySelector(".s-infinite-scroll-error").classList.remove("s-hidden"),this.placeholderLoader&&this.placeholderLoader.remove(),this.loading(!1),this.isProcessing=!1,this.logFetchError("fetch",t,s,e)})),salla.onReady((()=>{sessionStorage.getItem(this.infiniteScrollStateKey)||this.manualLoadNextPage()}))}handleScroll(){this.isProcessing||this.scrollTimeout||(this.scrollTimeout=setTimeout((()=>{this.scrollTimeout=null,requestAnimationFrame((()=>{const t=this.wrapper.getBoundingClientRect(),s=window.innerHeight;t.bottom-s<=200&&!this.isProcessing&&this.nextPage&&this.manualLoadNextPage()}))}),200))}manualLoadNextPage(){this.nextPage&&this.infiniteScroll.loadNextPage()}refreshInfiniteScrollMeasurements(){this.autoload&&this.infiniteScroll?.updateMeasurements&&this.waitForStableLayout(document.body).then((()=>this.infiniteScroll?.updateMeasurements?.()))}async applyBeforeBuildListUrl(t){try{const s={component:this,url:t};return await salla.hooks.call("salla-products-list","beforeBuildListUrl",s),s.url}catch(s){return salla.logger.warn("beforeBuildListUrl hook failed",s?.message),t}}async resolveNextPageFromCursor(t){return t.cursor?t.cursor.next?await this.applyBeforeBuildListUrl(t.cursor.next):t.cursor.next:this.nextPage}async injectAndProcessData(t){try{await l.injectExtraFieldsToResponse(t)}catch(t){console.error("Error injecting data:",t)}}getInitialData(){return this.loading(),salla.api.withoutNotifier((()=>salla.product.api.fetch({source:l.getApiSource(this.getSource()),source_value:this.getSourceValue(),limit:this.limit}).then((async t=>t.data.length?(await l.injectExtraFieldsToResponse(t),this.firstPageResponse?void this.appendProductCards(await this.handleResponse(t)):(this.firstPageResponse=t,void(this.nextPage=await this.resolveNextPageFromCursor(t)))):(this.showPlaceholder=!0,this.placeholderLoader&&this.placeholderLoader.remove(),void this.loading(!1))))))}async loadMore(){this.infiniteScroll?.loadNextPage()}async getSelected(){return{ids:Array.from(this.selectedProducts.keys()),products:Array.from(this.selectedProducts.values())}}async getLoadedProducts(){const t=[];if(!this.wrapper)return t;for(let s=0;s<this.wrapper.children.length;s++){const i=this.wrapper.children[s];i?.product&&t.push(i.product)}return t}async selectAll(){if(this.selectable&&this.wrapper){for(let t=0;t<this.wrapper.children.length;t++){const s=this.wrapper.children[t];if(s?.product){this.selectedProducts.set(s.product.id,s.product),s.classList.add("s-products-list-item-selected");const t=s.querySelector(".s-products-list-select-checkbox");t&&(t.checked=!0)}}this.emitSelection()}}async clearSelection(){this.selectedProducts.clear(),this.wrapper&&(this.wrapper.querySelectorAll(".s-products-list-select-checkbox").forEach((t=>t.checked=!1)),this.wrapper.querySelectorAll(".s-products-list-item-selected").forEach((t=>t.classList.remove("s-products-list-item-selected")))),this.emitSelection()}componentWillLoad(){return salla.onReady().then((async()=>{this.hasCustomComponent=!!customElements.get(this.productCardComponent),this.sourceValueIsValid=!(!this.getSourceValue()&&!this.isSourceWithoutValue()),this.hasInfiniteScroll=!this.isAuxiliaryProductsListSource()&&!this.limit;let t=new URLSearchParams(window.location.search);try{this.sortBy=this.sortBy||t.get("sort")||t.get("by"),this.parsedFilters=l.extractFiltersFromUrl(t),this.parsedFilters&&this.parsedFilters.category_id&&(this.currentCategoryIdFilter=this.toCategoryIdFilter(this.parsedFilters.category_id))}catch(t){salla.logger.warn("failed to get filters from url",t.message)}if(await this.buildNextPageUrl(),this.isReady=!0,!sessionStorage.getItem(this.infiniteScrollStateKey))if(this.sourceValueIsValid){if(!this.hasInfiniteScroll){if("json"===this.getSource())return this.getSourceValue().length?void setTimeout((()=>{this.appendProductCards(this.getSourceValue().map((t=>this.getItemHTML(t))))})):void(this.showPlaceholder=!0);if("selected"!==this.getSource()||this.getSourceValue().length)return this.getInitialData();this.showPlaceholder=!0}}else salla.logger.warn(`source-value prop is required for source [${this.getSource()}]`)}))}async componentDidLoad(){this.hasInfiniteScroll&&this.init(),await Salla.hooks.registerComponent("salla-products-list",this),this.loadStoredScrollState()?(this.autoload?!this.nextPage&&this.loading(!1):this.nextPage?this.loadMoreWrapper&&(this.loadMoreWrapper.style.display="block"):(this.loadMoreWrapper&&(this.loadMoreWrapper.style.display="none"),this.status.querySelector(".s-infinite-scroll-last").classList.remove("s-hidden")),this.scrollToLastViewedProduct(),this.refreshInfiniteScrollMeasurements()):!this.firstPageResponse&&this.switchToNormalBehavior?this.getInitialData().then((async()=>{this.firstPageResponse?(this.appendProductCards(await this.handleResponse(this.firstPageResponse,!1)),setTimeout((()=>{if(!this.autoload&&this.nextPage&&1==this.infiniteScroll.pageIndex){const t=this.host.querySelector(".s-infinite-scroll-wrapper");t&&(t.style.display="block")}}))):console.error("No response received after getInitialData.")})).catch((t=>{console.error("Error during initial data fetch:",t)})):this.firstPageResponse&&this.appendProductCards(await this.handleResponse(this.firstPageResponse,!1)),await this.refreshWishlistIconsAfterHydration()}canRender(){return this.sourceValueIsValid&&this.isReady}render(){return this.canRender()?this.showPlaceholder?i("div",{class:"s-products-list-placeholder"},i("span",{innerHTML:a}),i("p",null,this.placeholderText)):i(e,{class:"s-products-list"},i("div",{class:{"s-products-list-wrapper":!0,"s-products-list-horizontal-cards":this.horizontalCards&&!this.filtersResults,"s-products-list-vertical-cards":!this.horizontalCards&&!this.rowCards&&!this.filtersResults,"s-products-list-row-cards":this.rowCards,"s-products-list-compact-cards":this.compactCards,"s-products-list-filters-results":this.filtersResults},ref:t=>this.wrapper=t}),i("div",{class:"s-infinite-scroll-status",ref:t=>this.status=t},i("p",{class:"s-infinite-scroll-last infinite-scroll-last s-hidden"},this.endOfText),i("p",{class:"s-infinite-scroll-error infinite-scroll-error s-hidden"},this.failedLoadMore)),this.autoload&&i("div",{class:"s-products-list-loading-wrapper",style:{display:"none"},ref:t=>this.loader=t},i("span",{class:"s-button-loader s-button-loader-center s-infinite-scroll-btn-loader"})),this.hasInfiniteScroll&&this.nextPage&&!this.autoload?i("div",{class:"s-infinite-scroll-wrapper",style:{display:"none"},ref:t=>this.loadMoreWrapper=t},i("button",{onClick:()=>this.loadMore(),class:"s-infinite-scroll-btn s-button-btn s-button-primary"},i("span",{class:"s-button-text s-infinite-scroll-btn-text"},this.loadMoreText?this.loadMoreText:salla.lang.get("common.elements.load_more")),i("span",{class:"s-button-loader s-button-loader-center s-infinite-scroll-btn-loader",ref:t=>this.btnLoader=t,style:{display:"none"}}))):""):""}init(){this.initiateInfiniteScroll(),this.loading()}async handleResponse(t,s=!0){if(!t)return[];let i=this.getSource();if(1===t.cursor?.current){if(!this.isAuxiliaryProductsListSource()){let s=l.getPageTitleForSource(i);try{if("search"===this.getSource())s=salla.lang.get("common.elements.search_about",{word:this.getSourceValue()});else if(!s){let i=Object.keys(this.parsedFilters||{}).length?null:this.getSourceValue()[0];s=t.filters?.find((t=>"category_id"===t.key))?.values?.find((t=>t.key==i))?.value??""}s+=(s?" - ":"")+salla.lang.choice("blocks.header.products_count",t.data?.length),15===t.data.length&&(s=s.replace(t.data.length,salla.lang.get("common.elements.more_than")+" "+t.data.length)),t.title=s}catch(t){salla.logger.error("Error::falid to handle response",t)}}l.generateProductSchema(t.data)}this.appendDataLayer(t.data),t.nextPage=this.nextPage,t.source=this.getSource(),t.sourceValue=this.getSourceValue(),salla.event.emit("salla-products-list::products.fetched",t),this.productsFetched.emit(t),this.emitFilters(t),s&&(this.nextPage=await this.resolveNextPageFromCursor(t)),this.loading(!1),this.placeholderLoader&&this.placeholderLoader.remove(),this.hasInfiniteScroll&&!this.nextPage&&(this.infiniteScroll.option({scrollThreshold:!1,loadOnScroll:!1}),this.status.querySelector(".s-infinite-scroll-last").classList.remove("s-hidden"));const e=[];for(let s=0;s<t.data.length;s++)e.push(this.getItemHTML(t.data?.[s]));return e}get host(){return r(this)}static get watchers(){return{selectable:["onSelectableChanged"]}}};n.style='.s-products-list-selectable-item{position:relative;border-radius:0.5rem;transition:box-shadow 0.15s ease-in-out}.s-products-list-item-selected{box-shadow:0 0 0 2px var(--color-primary)}.s-products-list-select-control{position:absolute;top:10px;inset-inline-start:10px;z-index:5;display:inline-flex;align-items:center;justify-content:center;cursor:pointer}.s-products-list-select-checkbox{appearance:none;-webkit-appearance:none;-moz-appearance:none;position:relative;width:22px;height:22px;margin:0;cursor:pointer;color:var(--color-primary);border:1px solid rgba(0, 0, 0, 0.15);border-radius:6px;background-color:#fff;box-shadow:0 1px 3px rgba(0, 0, 0, 0.2);transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out}.s-products-list-select-checkbox:hover{border-color:var(--color-primary)}.s-products-list-select-checkbox:focus,.s-products-list-select-checkbox:focus-visible{outline:none;border-color:var(--color-primary);box-shadow:0 1px 3px rgba(0, 0, 0, 0.2), 0 0 0 3px color-mix(in srgb, var(--color-primary) 30%, transparent)}.s-products-list-select-checkbox:checked,.s-products-list-select-checkbox:checked:hover,.s-products-list-select-checkbox:checked:focus{background-color:var(--color-primary);border-color:var(--color-primary)}.s-products-list-select-checkbox:checked::after{content:"";position:absolute;top:50%;left:50%;width:5px;height:10px;border:solid #fff;border-width:0 2px 2px 0;transform:translate(-50%, -60%) rotate(45deg)}.s-products-list-row-cards .s-products-list-select-control{top:50%;inset-inline-start:14px;transform:translateY(-50%)}.s-products-list-row-cards .s-products-list-selectable-item>:not(.s-products-list-select-control){padding-inline-start:2.75rem}';export{n as salla_products_list}
4
+ import{r as t,c as s,h as i,H as e,a as r}from"./p-Bt0ajKaf.js";import{a as o}from"./p-CgtvEd63.js";import{S as a}from"./p-DiKTtDW5.js";import{H as l}from"./p-XnA1YTjA.js";const n=class{constructor(i){t(this,i),this.productsFetched=s(this,"productsFetched"),this.selectionChanged=s(this,"selectionChanged"),this.autoload=!1,this.productCardComponent="custom-salla-product-card",this.selectable=!1,this.page=1,this.placeholderText=salla.lang.get("pages.categories.no_products"),this.endOfText=salla.lang.get("common.elements.end_of_content"),this.failedLoadMore=salla.lang.get("common.elements.failed_to_load_more"),this.currentPage=salla.config.get("page"),this.filtersSnapshot=[],this.selectedProducts=new Map,this.lastViewedProductKey="lastViewedProductId",this.filtersKey="filters",this.infiniteScrollStateKey="infiniteScrollState",this.prevCategoryIdKey="prevCategoryId",this.isProcessing=!1,this.scrollTimeout=null,this.boundScrollToLastViewedProduct=()=>this.scrollToLastViewedProduct(),this.boundHandleScroll=()=>this.handleScroll(),this.specialPagesWithoutIds={"product.index.latest":"latest","product.index.offers":"offers","product.index.search":"search","product.index.sales":"sales"},this.onWishlistItemRemoved=(t,s)=>{if("wishlist"!==this.getSource()||!this.wrapper)return;const i=String(s),e=this.hasCustomComponent?this.productCardComponent:"salla-product-card";for(const t of Array.from(this.wrapper.children)){const s=t,r=t.querySelector(e),o=s.product?.id??r?.product?.id;if(null!=o&&String(o)===i){t.remove();break}}for(const t of Array.from(this.wrapper.children)){if(!t.classList.contains("s-products-list-selectable-item"))continue;const s=t;if(null!=s.product?.id&&String(s.product.id)===i&&!t.querySelector(e)){t.remove();break}}if(this.selectable){for(const t of Array.from(this.selectedProducts.keys()))String(t)===i&&this.selectedProducts.delete(t);this.emitSelection()}},this.onWishlistStorageSynced=()=>l.syncWishlistIcons(this.wrapper,`${this.productCardComponent}, salla-product-card`),this.includes=l.parseJson(this.includes||this.host.getAttribute("includes")),Array.isArray(this.includes)||(this.includes=null),l.setIncludes(this.includes),salla.lang.onLoaded((()=>{this.placeholderText=salla.lang.get("pages.categories.no_products"),this.endOfText=salla.lang.get("common.elements.end_of_content"),this.failedLoadMore=salla.lang.get("common.elements.failed_to_load_more"),this.currentPage=salla.config.get("page")}))}connectedCallback(){"scrollRestoration"in history&&(history.scrollRestoration="manual"),window.addEventListener("DOMContentLoaded",this.boundScrollToLastViewedProduct),salla.event.on("salla-filters::changed",(t=>this.setFilters(t))),salla.event.on("wishlist::removed",this.onWishlistItemRemoved),salla.event.on("wishlist::storage.synced",this.onWishlistStorageSynced)}disconnectedCallback(){window.removeEventListener("DOMContentLoaded",this.boundScrollToLastViewedProduct),window.removeEventListener("scroll",this.boundHandleScroll),salla.event.off("wishlist::removed",this.onWishlistItemRemoved),salla.event.off("wishlist::storage.synced",this.onWishlistStorageSynced)}async setFilters(t){if(t&&JSON.stringify(t)!==JSON.stringify(this.parsedFilters))return window.scrollTo({top:0,behavior:"smooth"}),this.parsedFilters=JSON.parse(JSON.stringify(t)),"product.index"==this.currentPage?.slug&&(this.currentCategoryIdFilter=this.parsedFilters?.category_id?this.toCategoryIdFilter(this.parsedFilters.category_id):null),this.reload()}async reload(){!this.autoload&&this.loadMoreWrapper&&(this.loadMoreWrapper.style.display="none"),this.hasInfiniteScroll&&salla.infiniteScroll.destroy(this.infiniteScroll),await this.buildNextPageUrl(),this.wrapper.innerHTML="",this.hasInfiniteScroll?this.init():this.getInitialData(),this.showPlaceholder&&(this.showPlaceholder=!1,this.placeholderLoader=document.createElement("div"),this.placeholderLoader.classList.add("s-products-list-loading-wrapper"),this.placeholderLoader.style.display="inherit",this.placeholderLoader.innerHTML='<span class="s-button-loader s-button-loader-center s-infinite-scroll-btn-loader"></span>',this.host.insertAdjacentElement("afterend",this.placeholderLoader))}isFilterable(){return salla.config.get("store.settings.product.filters")&&this.filtersResults}getCachedFilters(){return Array.isArray(this.filtersSnapshot)&&this.filtersSnapshot.length?JSON.parse(JSON.stringify(this.filtersSnapshot)):null}emitFilters(t){if(!this.isFilterable())return;if(t.filters)return this.filtersResults=!0,this.filtersSnapshot=JSON.parse(JSON.stringify(t.filters)),void salla.event.emit("filters::fetched",{filters:t.filters});const s=t.cursor?.current>1?this.getCachedFilters():null;if(s)return this.filtersResults=!0,void salla.event.emit("filters::fetched",{filters:s});this.filtersSnapshot=[],salla.event.emit("filters::hidden")}isSourceWithoutValue(){const t=this.getSource();if("wishlist"===t){const t=new URLSearchParams(window.location.search);return!(t.has("source_value")||t.has("source_value[]")||this.sourceValue)}return["offers","latest","sales","top-rated","reorder"].includes(t)}animateItems(){o({targets:"salla-products-list salla-product-card",opacity:[0,1],duration:1200,translateY:[20,0],delay:function(t,s){return 100*s}})}async initBaseNextPageUrl(t){this.nextPage=salla.url.api(`products?source=${t}`),this.includes?.length&&(this.nextPage+=`&includes[]=${this.includes.join("&includes[]=")}`),this.limit&&(this.nextPage+=`&per_page=${this.limit>32?32:this.limit}`),this.sortBy&&(this.nextPage+=`&sort=${this.sortBy}`),"preview"===salla.config.get("theme.mode")&&(this.nextPage+="&use_username_url=1"),this.nextPage+="&filterable=1";for(const[t,s]of Object.entries(this.parsedFilters||{}))if("source_value"!==t&&"source_value[]"!==t)if(["string","number"].includes(typeof s))this.nextPage+=`&filters[${encodeURIComponent(t)}]=${encodeURIComponent(s)}`;else if(Array.isArray(s))s.forEach((s=>this.nextPage+=`&filters[${encodeURIComponent(t)}][]=${encodeURIComponent(s)}`));else if("object"==typeof s)for(const[i,e]of Object.entries(s))this.nextPage+=`&filters[${encodeURIComponent(t)}][${encodeURIComponent(i)}]=${encodeURIComponent(e)}`;this.nextPage=await this.applyBeforeBuildListUrl(this.nextPage)}async buildNextPageUrl(){let t=this.getSource();if("json"===t)return;const s=sessionStorage.getItem(this.infiniteScrollStateKey);if(s){const{nextPage:t}=JSON.parse(s);if(!t)return}if(await this.initBaseNextPageUrl(t),!this.isSourceWithoutValue())if(["search","related","landing-page"].includes(t))this.nextPage+=`&source_value=${this.getSourceValue()}`;else try{this.nextPage+=`&source_value[]=${this.getSourceValue().join("&source_value[]=")}`}catch(s){salla.logger.warn(`source-value prop should be array of ids ex source-value="[1,2,3]" for the source [${t}]`),this.sourceValueIsValid=!1}}loading(t=!0,s=!1){if(t){let t=s&&!this.autoload?this.btnLoader:this.loader;t&&(t.style.display="inherit")}else this.autoload||this.btnLoader&&(this.btnLoader.style.display="none"),this.loader&&(this.loader.style.display="none")}getItemHTML(t){"landing-page"===this.getSource()&&(t.url="");const s=document.createElement(this.hasCustomComponent?this.productCardComponent:"salla-product-card");return s.product=t,this.compactCards&&(s.compact=!0,s.toggleAttribute("compact",!0)),this.applyLandingPageStyles(s),this.applyHorizontalCardStyles(s),s.addEventListener("click",(s=>{s.target.closest("a")&&(l.saveProductSource(this.getSource()),this.hasInfiniteScroll&&(this.takeStateSnapshot(),sessionStorage.setItem(this.lastViewedProductKey,t.id)))})),this.selectable?this.wrapSelectableItem(s,t):s}wrapSelectableItem(t,s){const i=document.createElement("div");i.className="s-products-list-selectable-item",i.product=s;const e=this.selectedProducts.has(s.id);e&&i.classList.add("s-products-list-item-selected");const r=document.createElement("label");r.className="s-products-list-select-control",r.setAttribute("aria-label",salla.lang.get("common.elements.select","تحديد"));const o=document.createElement("input");return o.type="checkbox",o.className="s-products-list-select-checkbox",o.checked=e,o.addEventListener("change",(()=>this.toggleSelection(s,i,o.checked))),r.appendChild(o),i.appendChild(r),i.appendChild(t),i}toggleSelection(t,s,i){i?(this.selectedProducts.set(t.id,t),s?.classList.add("s-products-list-item-selected")):(this.selectedProducts.delete(t.id),s?.classList.remove("s-products-list-item-selected")),this.emitSelection()}emitSelection(){const t=Array.from(this.selectedProducts.values()),s=Array.from(this.selectedProducts.keys()),i={ids:s,products:t,count:s.length};this.selectionChanged.emit(i),salla.event.emit("salla-products-list::selection.changed",i)}appendProductCards(t){this.wrapper&&((Array.isArray(t)?t:[t]).forEach((t=>this.wrapper.append(t))),this.onWishlistStorageSynced())}refreshWishlistIconsAfterHydration(){return salla.wishlist.api.syncStorageFromServer()}onSelectableChanged(t,s){t!==s&&this.isReady&&this.wrapper&&(t||(this.selectedProducts.clear(),this.emitSelection()),this.reload())}applyLandingPageStyles(t){"landing-page"!==this.getSource()||this.hasCustomComponent||(t.toggleAttribute("hide-add-btn",!0),t.classList.add("s-product-card-fit-height"))}applyHorizontalCardStyles(t){this.horizontalCards&&(t.toggleAttribute("horizontal",!0),this.hasCustomComponent||t.toggleAttribute("shadow-on-hover",!0))}waitForResizing(t){let s=null;return new Promise((i=>{const e=new ResizeObserver((()=>{clearTimeout(s),s=setTimeout((()=>{e.disconnect(),i(null)}),160)}));e.observe(t)}))}waitForLayoutStable(t){let s=null,i=null;return new Promise((e=>{let r;const o=()=>{clearTimeout(s),clearTimeout(i),r.disconnect(),e(null)};r=new MutationObserver((()=>{clearTimeout(s),s=setTimeout(o,160)})),r.observe(t,{childList:!0,subtree:!0,attributes:!0}),i=setTimeout(o,1e3)}))}async waitForStableLayout(t){return await Promise.allSettled([this.waitForResizing(t),this.waitForLayoutStable(t)])}scrollToLastViewedProduct(){const t=sessionStorage.getItem(this.lastViewedProductKey);t&&!salla.url.is_page("product.single")&&this.isElementLoaded(`[id*="${t}"]`).then((()=>{const s=this.wrapper?.querySelector(`[id*="${t}"]`);if(!s)return;const i=()=>{const t=()=>{s.scrollIntoView({block:"start",behavior:"instant"});const t=matchMedia("(max-width: 1024px)").matches?"header .inner":"ul.main-menu",i=window?.header_is_sticky?document.querySelector(t)?.getBoundingClientRect()?.height??56:0,e=parseInt(getComputedStyle(this.wrapper).rowGap)??16;scrollBy({top:-1*(i+e),behavior:"instant"})};requestAnimationFrame(t),s.querySelectorAll("img.lazy").forEach((s=>{const i=s,e=()=>{requestAnimationFrame(t),i.onload=i.onerror=null};i.onload=e,i.onerror=e})),this.removeScrollRestorationSession()};this.waitForStableLayout(this.host).then((()=>requestAnimationFrame(i)))}))}isElementLoaded(t){return new Promise((s=>{const i=setInterval((()=>{if(document.querySelector(t))return clearInterval(i),s(document.querySelector(t))}),50)}))}takeStateSnapshot(){const t=[];for(let s=0;s<this.wrapper.children.length;s++){const i=this.wrapper.children?.[s];t.push(i.product)}const s={pageIndex:Math.max((this.infiniteScroll?.pageIndex??1)-1,1),nextPage:this.nextPage,currentPageData:t};if(this.isFilterable()){const t=sessionStorage.getItem(this.filtersKey);sessionStorage.setItem(this.filtersKey,t||JSON.stringify(this.filtersSnapshot))}sessionStorage.setItem(this.infiniteScrollStateKey,JSON.stringify(s));let i=salla.config.get("page.id");const e=Object.keys(this.specialPagesWithoutIds).find((t=>salla.url.is_page(t)));e?i=this.specialPagesWithoutIds[e]:null!==i&&(i=String(i)),sessionStorage.setItem(this.prevCategoryIdKey,i)}removeScrollRestorationSession(){this.isFilterable()||sessionStorage.removeItem(this.filtersKey),sessionStorage.removeItem(this.infiniteScrollStateKey),sessionStorage.removeItem(this.lastViewedProductKey),sessionStorage.removeItem(this.prevCategoryIdKey)}loadStoredScrollState(){const t=sessionStorage.getItem(this.infiniteScrollStateKey),s=sessionStorage.getItem(this.filtersKey),i=sessionStorage.getItem(this.prevCategoryIdKey),e=this.specialPagesWithoutIds[salla.config.get("page.slug")]||null,r=salla.config.get("page.id"),o=salla.url.is_page("index"),a=salla.url.is_page("product.single"),l=e?i!==e:i!==String(r);if(i&&l&&!o&&!a||o&&!this.hasInfiniteScroll)return this.removeScrollRestorationSession(),this.switchToNormalBehavior=!0,!1;if(a)return this.switchToNormalBehavior=!0,!1;if(t)try{const{pageIndex:i,nextPage:e,currentPageData:r}=JSON.parse(t);if(s&&"undefined"!==s){const t=JSON.parse(s);this.filtersSnapshot=JSON.parse(JSON.stringify(t)),salla.event.emit("filters::fetched",{filters:t})}return this.page=i,this.nextPage=e,this.appendProductCards(r.map((t=>this.getItemHTML(t)))),!0}catch(t){console.error("Failed to load stored scroll state:",t),this.removeScrollRestorationSession()}return!1}getSource(){return l.getProductsSource(this.source)}isAuxiliaryProductsListSource(){return["json","selected","related","landing-page","recently"].includes(this.getSource())}toCategoryIdFilter(t){return Array.isArray(t)?t:t&&"object"==typeof t?Object.values(t):[t]}getSourceValue(){if("wishlist"===this.getSource()){const t=new URLSearchParams(window.location.search),s=t.getAll("source_value[]").length?t.getAll("source_value[]"):t.getAll("source_value");if(s.length)return s}return this.currentCategoryIdFilter?this.currentCategoryIdFilter:l.getProductsSourceValue(this.source,this.sourceValue)}logFetchError(t,s,i,e,r){try{const o=r&&"object"==typeof r?r:null,a=this.getSourceValue();salla.analytics?.log("salla::products.list.fetch.error",{errorPhase:t,source:this.getSource(),sourceValue:"string"==typeof a&&a.length>200?`${a.slice(0,200)}…`:Array.isArray(a)?{length:a.length}:a,pageIndex:this.infiniteScroll?.pageIndex,fetchPath:i,httpStatus:e?.status,httpStatusText:e?.statusText,responseUrl:e?.url,...o&&{dataCount:Array.isArray(o.data)?o.data.length:void 0,responseKeys:Object.keys(o).slice(0,15),filtersCount:Array.isArray(o.filters)?o.filters.length:void 0},errorMessage:s instanceof Error?s.message:String(s),..."processing"===t&&s instanceof Error&&s.stack?{errorStack:s.stack.slice(0,500)}:{}})}catch{}}appendDataLayer(t){"object"==typeof dataLayer&&Array.isArray(dataLayer)&&dataLayer.push({event:"impressions",ecommerce:{currencyCode:salla.config.currency().code,impressions:t.map(((t,s)=>({id:t.id,name:t.name,price:t.price,brand:t.brand?.name||"",quantity:t.quantity,categories:[{name:t.category?.name||salla.config.get("page.title"),id:salla.config.get("page.id")}],category:t.category?.name||salla.config.get("page.title"),position:s+1})))}})}initiateInfiniteScroll(){if(!this.hasInfiniteScroll)return;const t=this.autoload&&this.includes&&this.includes.length>0;this.infiniteScroll=salla.infiniteScroll.initiate(this.wrapper,this.wrapper,{path:()=>this.nextPage,history:!1,nextPage:this.nextPage,scrollThreshold:!t&&!!this.autoload&&100,loadOnScroll:!t&&this.autoload},!0),this.infiniteScroll.pageIndex=this.page,this.infiniteScroll?.on("request",(()=>{this.loading(!0,!this.autoload)})),t&&window.addEventListener("scroll",this.boundHandleScroll),this.infiniteScroll?.on("load",(async(t,s,i)=>{if(!this.isProcessing){this.isProcessing=!0;try{if(!t.data?.length&&2===this.infiniteScroll.pageIndex)return this.showPlaceholder=!0,salla.infiniteScroll.destroy(this.infiniteScroll),this.loading(!1),void(this.placeholderLoader&&this.placeholderLoader.remove());this.includes&&await this.injectAndProcessData(t);const s=await this.handleResponse(t);this.infiniteScroll.appendItems(s),this.onWishlistStorageSynced(),2===this.infiniteScroll.pageIndex&&(!this.autoload&&this.nextPage&&(this.loadMoreWrapper.style.display="block"),this.animateItems(),this.refreshInfiniteScrollMeasurements())}catch(e){console.error("Error during load:",e),this.logFetchError("processing",e,"string"==typeof s?s:void 0,i,t)}finally{this.isProcessing=!1}}})),this.infiniteScroll?.on("error",((t,s,i)=>{const e=i;this.status.querySelector(".s-infinite-scroll-error").classList.remove("s-hidden"),this.placeholderLoader&&this.placeholderLoader.remove(),this.loading(!1),this.isProcessing=!1,this.logFetchError("fetch",t,s,e)})),salla.onReady((()=>{sessionStorage.getItem(this.infiniteScrollStateKey)||this.manualLoadNextPage()}))}handleScroll(){this.isProcessing||this.scrollTimeout||(this.scrollTimeout=setTimeout((()=>{this.scrollTimeout=null,requestAnimationFrame((()=>{const t=this.wrapper.getBoundingClientRect(),s=window.innerHeight;t.bottom-s<=200&&!this.isProcessing&&this.nextPage&&this.manualLoadNextPage()}))}),200))}manualLoadNextPage(){this.nextPage&&this.infiniteScroll.loadNextPage()}refreshInfiniteScrollMeasurements(){this.autoload&&this.infiniteScroll?.updateMeasurements&&this.waitForStableLayout(document.body).then((()=>this.infiniteScroll?.updateMeasurements?.()))}async applyBeforeBuildListUrl(t){try{const s={component:this,url:t};return await salla.hooks.call("salla-products-list","beforeBuildListUrl",s),s.url}catch(s){return salla.logger.warn("beforeBuildListUrl hook failed",s?.message),t}}async resolveNextPageFromCursor(t){return t.cursor?t.cursor.next?await this.applyBeforeBuildListUrl(t.cursor.next):t.cursor.next:this.nextPage}async injectAndProcessData(t){try{await l.injectExtraFieldsToResponse(t)}catch(t){console.error("Error injecting data:",t)}}getInitialData(){return this.loading(),salla.api.withoutNotifier((()=>salla.product.api.fetch({source:l.getApiSource(this.getSource()),source_value:this.getSourceValue(),limit:this.limit}).then((async t=>t.data.length?(await l.injectExtraFieldsToResponse(t),this.firstPageResponse?void this.appendProductCards(await this.handleResponse(t)):(this.firstPageResponse=t,void(this.nextPage=await this.resolveNextPageFromCursor(t)))):(this.showPlaceholder=!0,this.placeholderLoader&&this.placeholderLoader.remove(),void this.loading(!1))))))}async loadMore(){this.infiniteScroll?.loadNextPage()}async getSelected(){return{ids:Array.from(this.selectedProducts.keys()),products:Array.from(this.selectedProducts.values())}}async getLoadedProducts(){const t=[];if(!this.wrapper)return t;for(let s=0;s<this.wrapper.children.length;s++){const i=this.wrapper.children[s];i?.product&&t.push(i.product)}return t}async selectAll(){if(this.selectable&&this.wrapper){for(let t=0;t<this.wrapper.children.length;t++){const s=this.wrapper.children[t];if(s?.product){this.selectedProducts.set(s.product.id,s.product),s.classList.add("s-products-list-item-selected");const t=s.querySelector(".s-products-list-select-checkbox");t&&(t.checked=!0)}}this.emitSelection()}}async clearSelection(){this.selectedProducts.clear(),this.wrapper&&(this.wrapper.querySelectorAll(".s-products-list-select-checkbox").forEach((t=>t.checked=!1)),this.wrapper.querySelectorAll(".s-products-list-item-selected").forEach((t=>t.classList.remove("s-products-list-item-selected")))),this.emitSelection()}componentWillLoad(){return salla.onReady().then((async()=>{this.hasCustomComponent=!!customElements.get(this.productCardComponent),this.sourceValueIsValid=!(!this.getSourceValue()&&!this.isSourceWithoutValue()),this.hasInfiniteScroll=!this.isAuxiliaryProductsListSource()&&!this.limit;let t=new URLSearchParams(window.location.search);try{this.sortBy=this.sortBy||t.get("sort")||t.get("by"),this.parsedFilters=l.extractFiltersFromUrl(t),this.parsedFilters&&this.parsedFilters.category_id&&(this.currentCategoryIdFilter=this.toCategoryIdFilter(this.parsedFilters.category_id))}catch(t){salla.logger.warn("failed to get filters from url",t.message)}if(await this.buildNextPageUrl(),this.isReady=!0,!sessionStorage.getItem(this.infiniteScrollStateKey))if(this.sourceValueIsValid){if(!this.hasInfiniteScroll){if("json"===this.getSource())return this.getSourceValue().length?void setTimeout((()=>{this.appendProductCards(this.getSourceValue().map((t=>this.getItemHTML(t))))})):void(this.showPlaceholder=!0);if("selected"!==this.getSource()||this.getSourceValue().length)return this.getInitialData();this.showPlaceholder=!0}}else salla.logger.warn(`source-value prop is required for source [${this.getSource()}]`)}))}async componentDidLoad(){this.hasInfiniteScroll&&this.init(),await Salla.hooks.registerComponent("salla-products-list",this),this.loadStoredScrollState()?(this.autoload?!this.nextPage&&this.loading(!1):this.nextPage?this.loadMoreWrapper&&(this.loadMoreWrapper.style.display="block"):(this.loadMoreWrapper&&(this.loadMoreWrapper.style.display="none"),this.status.querySelector(".s-infinite-scroll-last").classList.remove("s-hidden")),this.scrollToLastViewedProduct(),this.refreshInfiniteScrollMeasurements()):!this.firstPageResponse&&this.switchToNormalBehavior?this.getInitialData().then((async()=>{this.firstPageResponse?(this.appendProductCards(await this.handleResponse(this.firstPageResponse,!1)),setTimeout((()=>{if(!this.autoload&&this.nextPage&&1==this.infiniteScroll.pageIndex){const t=this.host.querySelector(".s-infinite-scroll-wrapper");t&&(t.style.display="block")}}))):console.error("No response received after getInitialData.")})).catch((t=>{console.error("Error during initial data fetch:",t)})):this.firstPageResponse&&this.appendProductCards(await this.handleResponse(this.firstPageResponse,!1)),await this.refreshWishlistIconsAfterHydration()}canRender(){return this.sourceValueIsValid&&this.isReady}render(){return this.canRender()?this.showPlaceholder?i("div",{class:"s-products-list-placeholder"},i("span",{innerHTML:a}),i("p",null,this.placeholderText)):i(e,{class:"s-products-list"},i("div",{class:{"s-products-list-wrapper":!0,"s-products-list-horizontal-cards":this.horizontalCards&&!this.filtersResults,"s-products-list-vertical-cards":!this.horizontalCards&&!this.rowCards&&!this.filtersResults,"s-products-list-row-cards":this.rowCards,"s-products-list-compact-cards":this.compactCards,"s-products-list-filters-results":this.filtersResults},ref:t=>this.wrapper=t}),i("div",{class:"s-infinite-scroll-status",ref:t=>this.status=t},i("p",{class:"s-infinite-scroll-last infinite-scroll-last s-hidden"},this.endOfText),i("p",{class:"s-infinite-scroll-error infinite-scroll-error s-hidden"},this.failedLoadMore)),this.autoload&&i("div",{class:"s-products-list-loading-wrapper",style:{display:"none"},ref:t=>this.loader=t},i("span",{class:"s-button-loader s-button-loader-center s-infinite-scroll-btn-loader"})),this.hasInfiniteScroll&&this.nextPage&&!this.autoload?i("div",{class:"s-infinite-scroll-wrapper",style:{display:"none"},ref:t=>this.loadMoreWrapper=t},i("button",{onClick:()=>this.loadMore(),class:"s-infinite-scroll-btn s-button-btn s-button-primary"},i("span",{class:"s-button-text s-infinite-scroll-btn-text"},this.loadMoreText?this.loadMoreText:salla.lang.get("common.elements.load_more")),i("span",{class:"s-button-loader s-button-loader-center s-infinite-scroll-btn-loader",ref:t=>this.btnLoader=t,style:{display:"none"}}))):""):""}init(){this.initiateInfiniteScroll(),this.loading()}async handleResponse(t,s=!0){if(!t)return[];let i=this.getSource();if(1===t.cursor?.current){if(!this.isAuxiliaryProductsListSource()){let s=l.getPageTitleForSource(i);try{if("search"===this.getSource())s=salla.lang.get("common.elements.search_about",{word:this.getSourceValue()});else if(!s){let i=Object.keys(this.parsedFilters||{}).length?null:this.getSourceValue()[0];s=t.filters?.find((t=>"category_id"===t.key))?.values?.find((t=>t.key==i))?.value??""}s+=(s?" - ":"")+salla.lang.choice("blocks.header.products_count",t.data?.length),15===t.data.length&&(s=s.replace(t.data.length,salla.lang.get("common.elements.more_than")+" "+t.data.length)),t.title=s}catch(t){salla.logger.error("Error::falid to handle response",t)}}l.generateProductSchema(t.data)}this.appendDataLayer(t.data),t.nextPage=this.nextPage,t.source=this.getSource(),t.sourceValue=this.getSourceValue(),salla.event.emit("salla-products-list::products.fetched",t),this.productsFetched.emit(t),this.emitFilters(t),s&&(this.nextPage=await this.resolveNextPageFromCursor(t)),this.loading(!1),this.placeholderLoader&&this.placeholderLoader.remove(),this.hasInfiniteScroll&&!this.nextPage&&(this.infiniteScroll.option({scrollThreshold:!1,loadOnScroll:!1}),this.status.querySelector(".s-infinite-scroll-last").classList.remove("s-hidden"));let e=await this.applyBeforeAppendItems(t.data);const r=[];for(let t=0;t<e.length;t++)r.push(this.getItemHTML(e[t]));return r}async applyBeforeAppendItems(t){const s={component:this,items:t};try{return await salla.hooks.call("salla-products-list","beforeAppendItems",s),Array.isArray(s.items)?s.items:t}catch{return t}}get host(){return r(this)}static get watchers(){return{selectable:["onSelectableChanged"]}}};n.style='.s-products-list-selectable-item{position:relative;border-radius:0.5rem;transition:box-shadow 0.15s ease-in-out}.s-products-list-item-selected{box-shadow:0 0 0 2px var(--color-primary)}.s-products-list-select-control{position:absolute;top:10px;inset-inline-start:10px;z-index:5;display:inline-flex;align-items:center;justify-content:center;cursor:pointer}.s-products-list-select-checkbox{appearance:none;-webkit-appearance:none;-moz-appearance:none;position:relative;width:22px;height:22px;margin:0;cursor:pointer;color:var(--color-primary);border:1px solid rgba(0, 0, 0, 0.15);border-radius:6px;background-color:#fff;box-shadow:0 1px 3px rgba(0, 0, 0, 0.2);transition:background-color 0.15s ease-in-out, border-color 0.15s ease-in-out}.s-products-list-select-checkbox:hover{border-color:var(--color-primary)}.s-products-list-select-checkbox:focus,.s-products-list-select-checkbox:focus-visible{outline:none;border-color:var(--color-primary);box-shadow:0 1px 3px rgba(0, 0, 0, 0.2), 0 0 0 3px color-mix(in srgb, var(--color-primary) 30%, transparent)}.s-products-list-select-checkbox:checked,.s-products-list-select-checkbox:checked:hover,.s-products-list-select-checkbox:checked:focus{background-color:var(--color-primary);border-color:var(--color-primary)}.s-products-list-select-checkbox:checked::after{content:"";position:absolute;top:50%;left:50%;width:5px;height:10px;border:solid #fff;border-width:0 2px 2px 0;transform:translate(-50%, -60%) rotate(45deg)}.s-products-list-row-cards .s-products-list-select-control{top:50%;inset-inline-start:14px;transform:translateY(-50%)}.s-products-list-row-cards .s-products-list-selectable-item>:not(.s-products-list-select-control){padding-inline-start:2.75rem}';export{n as salla_products_list}