@e-llm-studio/instant-learning 0.1.1-alpha.33 → 0.1.1-alpha.35

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 (48) hide show
  1. package/dist/cjs/features/IL-OTJ/ValueTypeWrappers/TeachMeWrapper.js +1 -1
  2. package/dist/cjs/features/LearningManagement/LearningManagement.js +1 -1
  3. package/dist/cjs/features/LearningManagement/RuleContent/RuleContent.js +1 -1
  4. package/dist/cjs/features/LearningManagement/apis/apiConfig.js +1 -1
  5. package/dist/cjs/features/LearningManagement/apis/scopeApis.js +1 -1
  6. package/dist/cjs/features/LearningManagement/components/InstantLearningModal.js +1 -1
  7. package/dist/cjs/features/LearningManagement/components/StationOnboarding/StationOnboardModal.js +1 -1
  8. package/dist/cjs/features/LearningManagement/store/useLearningTemplateStore.js +1 -1
  9. package/dist/cjs/plugins/ValueTypes/Default/DefaultTeachMeRenderer.js +1 -1
  10. package/dist/features/IL-OTJ/ValueTypeWrappers/TeachMeWrapper.js +1 -1
  11. package/dist/features/LearningManagement/LearningManagement.js +1 -1
  12. package/dist/features/LearningManagement/RuleContent/RuleContent.js +1 -1
  13. package/dist/features/LearningManagement/apis/apiConfig.js +1 -1
  14. package/dist/features/LearningManagement/apis/scopeApis.js +1 -1
  15. package/dist/features/LearningManagement/components/InstantLearningModal.js +1 -1
  16. package/dist/features/LearningManagement/components/StationOnboarding/StationOnboardModal.js +1 -1
  17. package/dist/features/LearningManagement/store/useLearningTemplateStore.js +1 -1
  18. package/dist/plugins/ValueTypes/Default/DefaultTeachMeRenderer.js +1 -1
  19. package/dist/types/src/features/IL-OTJ/ValueTypeWrappers/TeachMeWrapper.d.ts +1 -1
  20. package/dist/types/src/features/IL-OTJ/ValueTypeWrappers/TeachMeWrapper.d.ts.map +1 -1
  21. package/dist/types/src/features/LearningManagement/LearningManagement.d.ts +2 -3
  22. package/dist/types/src/features/LearningManagement/LearningManagement.d.ts.map +1 -1
  23. package/dist/types/src/features/LearningManagement/RuleContent/RuleContent.d.ts.map +1 -1
  24. package/dist/types/src/features/LearningManagement/apis/apiConfig.d.ts +0 -7
  25. package/dist/types/src/features/LearningManagement/apis/apiConfig.d.ts.map +1 -1
  26. package/dist/types/src/features/LearningManagement/apis/scopeApis.d.ts +1 -1
  27. package/dist/types/src/features/LearningManagement/apis/scopeApis.d.ts.map +1 -1
  28. package/dist/types/src/features/LearningManagement/components/InstantLearningModal.d.ts.map +1 -1
  29. package/dist/types/src/features/LearningManagement/components/StationOnboarding/StationOnboardModal.d.ts.map +1 -1
  30. package/dist/types/src/features/LearningManagement/store/useLearningTemplateStore.d.ts +0 -2
  31. package/dist/types/src/features/LearningManagement/store/useLearningTemplateStore.d.ts.map +1 -1
  32. package/package.json +5 -6
  33. package/dist/cjs/features/LearningManagement/assets/Search-result(add new).svg.js +0 -2
  34. package/dist/cjs/features/LearningManagement/assets/Search-result(add new).svg.js.map +0 -1
  35. package/dist/cjs/features/LearningManagement/components/CreateRuleSetLegacyModal.js +0 -2
  36. package/dist/cjs/features/LearningManagement/components/CreateRuleSetLegacyModal.js.map +0 -1
  37. package/dist/cjs/features/LearningManagement/components/StationOnboarding/BackwardStationOnboardModal.js +0 -2
  38. package/dist/cjs/features/LearningManagement/components/StationOnboarding/BackwardStationOnboardModal.js.map +0 -1
  39. package/dist/features/LearningManagement/assets/Search-result(add new).svg.js +0 -2
  40. package/dist/features/LearningManagement/assets/Search-result(add new).svg.js.map +0 -1
  41. package/dist/features/LearningManagement/components/CreateRuleSetLegacyModal.js +0 -2
  42. package/dist/features/LearningManagement/components/CreateRuleSetLegacyModal.js.map +0 -1
  43. package/dist/features/LearningManagement/components/StationOnboarding/BackwardStationOnboardModal.js +0 -2
  44. package/dist/features/LearningManagement/components/StationOnboarding/BackwardStationOnboardModal.js.map +0 -1
  45. package/dist/types/src/features/LearningManagement/components/CreateRuleSetLegacyModal.d.ts +0 -10
  46. package/dist/types/src/features/LearningManagement/components/CreateRuleSetLegacyModal.d.ts.map +0 -1
  47. package/dist/types/src/features/LearningManagement/components/StationOnboarding/BackwardStationOnboardModal.d.ts +0 -12
  48. package/dist/types/src/features/LearningManagement/components/StationOnboarding/BackwardStationOnboardModal.d.ts.map +0 -1
@@ -1,2 +1,2 @@
1
- import{__assign as e,__spreadArray as n,__awaiter as t,__generator as i}from"tslib";import{jsxs as r,jsx as a,Fragment as o}from"react/jsx-runtime";import l,{useState as s,useRef as u,useEffect as d,useCallback as c,useMemo as v}from"react";import{AlertTriangle as _,Loader as p,Check as f}from"lucide-react";import{Toast as g}from"primereact/toast";import{v4 as m}from"uuid";import{saveInstantLearningQuestion as w,publishFeedback as y,updateVariant as h,fetchRulesByQuestionId as b,submitChatFeedback as T}from"../apis/scopeApis.js";import A from"../public/ThinkingBulbIcon.gif.js";import{useLearningTemplateStore as M}from"../store/useLearningTemplateStore.js";import I from"../styles/InstantLearningModal.module.css.js";import k from"../../IL-OTJ/ILOTJ.js";import"../../IL-OTJ/_components/atoms/Textarea/Textarea.js";import"../../IL-OTJ/_components/InputDataReasoningCard.js";import"../../IL-OTJ/_components/TooltipComponent.js";import{TemplateList as S}from"../../IL-OTJ/_components/templates/TemplatesMap/templatesMap.js";import{extractAndParseWithProperty as C,parseValidationData as N,extractAndParseResponse as x,extractVariantIds as E}from"../../IL-OTJ/helpers/utils.js";import{useCitations as O}from"../../IL-OTJ/store/CitationsContext.js";import"@mui/material";import"@mui/material/Tooltip";import"react-markdown";import"rehype-raw";import"axios";import"@e-llm-studio/streaming-response";import"@e-llm-studio/watch-me-work";import"../../IL-OTJ/_components/ChatComponents/ChatHeader.js";import"remark-gfm";import"../../IL-OTJ/_components/MarkdownComponents/MarkdownElements.js";import"../../IL-OTJ/_components/CitationLink.js";import"@e-llm-studio/citation";import"@viswa-test/test-citation";import"./ToolTip.js";import L from"../store/useAuthStore.js";import"date-fns";import"framer-motion";import"@mui/icons-material/Close";import{useConfigStore as R}from"../store/useConfigStore.js";import{IL_CONFIG_CONSTANTS as D}from"../config.js";import"@radix-ui/react-tooltip";import"./StationOnboarding/InputField.js";import"../store/useEnvStore.js";var j=function(){return a("img",{src:A,alt:"Thinking...",width:"20",height:"20"})},V="INITIAL",P="SUCCESS",F="FAILURE",G="IN_PROGRESS",q=function(e){return"string"!=typeof e?"":e.replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g,"").replace(/<!--```json[\s\S]*?```-->/g,"").trim()},U=function(e){if(!e)return!1;var n=e.toLowerCase().trim();return"default"===n||"default_variant"===n},J=function(e){return e.toLowerCase().replace(/ /g,"_").replace(/tier(\d+)/i,"tier_$1")},H=function(A){var H,B,W,K,Y,z,Q=A.isOpen,Z=A.onClose,$=A.initialScope,X=void 0===$?"global":$,ee=A.ruleSet,ne=A.editingRule,te=A.editingTier,ie=A.editingVariants,re=A.focusedVariantIndex,ae=A.setFocusedVariantIndex,oe=A.triggerAddVariant,le=A.triggerFixGaps,se=A.copiedRule,ue=A.copiedSourceTier,de=A.copiedTargetTier,ce=A.initialDraftMessage,ve=A.initialChatMessage,_e=A.applicationIntegrationId;A.modeId;var pe=s({station:X,tiers:["Tier 1"]}),fe=pe[0],ge=pe[1],me=s(V),we=me[0],ye=me[1],he=s(!1),be=he[0],Te=he[1],Ae=s("Thank you teacher for teaching me, your rule has been saved successfully."),Me=Ae[0];Ae[1];var Ie=s(""),ke=Ie[0],Se=Ie[1],Ce=s(!1),Ne=Ce[0],xe=Ce[1],Ee=u(null),Oe=s(!1),Le=Oe[0],Re=Oe[1],De=u(!1),je=M().tiers,Ve=l.useRef(new Set),Pe=s(null);Pe[0];var Fe=Pe[1],Ge=s(null);Ge[0];var qe=Ge[1],Ue=s(null);Ue[0];var Je=Ue[1],He=u(new Map),Be=u(""),We=u(!1),Ke=s(0),Ye=Ke[0],ze=Ke[1],Qe=s(!1),Ze=Qe[0],$e=Qe[1],Xe=u(null),en=u(0),nn=s(null),tn=nn[0],rn=nn[1],an=s([]),on=an[0],ln=an[1],sn=s(null),un=sn[0],dn=sn[1],cn=s(null),vn=cn[0],_n=cn[1],pn=s(!1),fn=pn[0],gn=pn[1],mn=u({}),wn=u([]),yn=u(!1),hn=s(!1),bn=hn[0],Tn=hn[1],An=u(!1),Mn=u(new Set),In=s(null),kn=In[0],Sn=In[1],Cn=s(null),Nn=Cn[0],xn=Cn[1],En=s(null),On=En[0],Ln=En[1],Rn=u(null),Dn=u(null),jn=u(null),Vn=u({}),Pn=u([]),Fn=u([]),Gn=u({}),qn=R(),Un=qn.configuration,Jn=qn.ilLabels;d(function(){kn||xn(null)},[kn]),d(function(){var e;if(Q&&ne){Rn.current=ne.ruleId;var n=null===(e=null==ie?void 0:ie[re||0])||void 0===e?void 0:e.variantId;Ln(n||null)}},[Q,ne,ie,re]),d(function(){Q&&ge(function(n){return e(e({},n),{station:X})})},[Q,X]),d(function(){console.log("triggered",On),console.log(ft,"structuredAIResponse"),gt(function(n){return Array.isArray(n)?n.map(function(n){return e(e({},n),{is_readOnly:n.variant_id!==On&&n.new_variant_id!==On})}):n}),Tt(function(n){return Array.isArray(n)?n.map(function(n){return e(e({},n),{is_readOnly:n.variant_id!==On&&n.new_variant_id!==On})}):n})},[On]),d(function(){var n;if(!Q)return Ar(),void(yn.current=!1);if(!yn.current){var t=ie,i=t&&t.length>0,r=null!=ne;if(i||r){if((null==ne?void 0:ne.ruleTitle)&&nt(ne.ruleTitle),te&&(ge(function(n){return e(e({},n),{tiers:[te]})}),Dn.current=te.toLowerCase().replace(/ /g,"_")),i){var a=te?J(te):"tier_1",o=new Map,l=new Map,s=new Map,u=new Map,d=new Map,c=new Map,v=[];t.forEach(function(e,n){u.set(n,e.description||"");var t=e.whenToApply?e.whenToApply.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,t){return{id:"edit-wta-".concat(n,"-").concat(t),text:e,reasoning:""}}):[];d.set(n,t);var i=e.whenNotToApply?e.whenNotToApply.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,t){return{id:"edit-wnta-".concat(n,"-").concat(t),text:e,reasoning:""}}):[];c.set(n,i),v.push(e.variantId||e.variant_id||"")}),o.set(a,u),l.set(a,d),s.set(a,c);var _=null===(n=null==t?void 0:t[re||0])||void 0===n?void 0:n.variantId,p=t.map(function(e,n){var t,i,r=null===(t=e.configuration)||void 0===t?void 0:t.scheduling_config;return{variant_type:e.variantType||"variant",title:(null==ne?void 0:ne.ruleTitle)||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",scope:[a],scheduling_config:r||{},variant_id:e.variantId,question_id:(null==ne?void 0:ne.ruleId)||"",tier_id:a.replace("tier_",""),is_readOnly:e.variantId!==_,link_id:e.link_id||"",is_enabled:null===(i=e.is_enabled)||void 0===i||i,is_user_accepted_risk:e.is_user_accepted_risk,has_accepted_risk:e.has_accepted_risk,user_accepted_risk_at:e.user_accepted_risk_at,action:"edit"}});gt(p),gt(p),Tt(p),yt(function(e){var n=new Map(e);return n.set(a,JSON.parse(JSON.stringify(p))),n});var f=new Map;t.forEach(function(e,n){var t,i,r,a,o,l,s,u,d,c,v,_,p,g=null===(t=e.configuration)||void 0===t?void 0:t.scheduling_config,m=null!==(a=null!==(i=null==g?void 0:g.order_global_min_separation_seconds)&&void 0!==i?i:null===(r=null==g?void 0:g.order_rules)||void 0===r?void 0:r.global_min_separation_seconds)&&void 0!==a?a:0,w=null!==(s=null!==(o=null==g?void 0:g.advertiser_global_min_separation_seconds)&&void 0!==o?o:null===(l=null==g?void 0:g.advertiser_rules)||void 0===l?void 0:l.global_min_separation_seconds)&&void 0!==s?s:0;f.set(n,{order_rules:{enabled:m>0,global_min_separation_seconds:Math.floor(m/60)},advertiser_rules:{enabled:w>0,global_min_separation_seconds:Math.floor(w/60)},inventory_rules:{respect_inventory_code:null!==(c=null!==(d=null===(u=null==g?void 0:g.inventory_rules)||void 0===u?void 0:u.respect_inventory_code)&&void 0!==d?d:null==g?void 0:g.respect_inventory_code)&&void 0!==c&&c},break_code_rules:{respect_break_code:null!==(p=null!==(_=null===(v=null==g?void 0:g.break_code_rules)||void 0===v?void 0:v.respect_break_code)&&void 0!==_?_:null==g?void 0:g.respect_break_code)&&void 0!==p&&p},is_default_enabled:U(e.variantType||e.variant_type)})}),Kn(new Map([[a,f]])),lt(o),dt(l),_t(s)}else if(r&&ne){var g=ne.ruleDesc;if(g&&lt(new Map([["tier_1",new Map([[0,g]])]])),ne.whenToApply){var m=ne.whenToApply.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,n){return{id:"edit-wta-".concat(n),text:e,reasoning:""}});dt(new Map([["tier_1",new Map([[0,m]])]]))}if(ne.whenNotToApply){var w=ne.whenNotToApply.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,n){return{id:"edit-wnta-".concat(n),text:e,reasoning:""}});_t(new Map([["tier_1",new Map([[0,w]])]]))}}}else if(se&&ue&&de){nt(se.ruleTitle||""),ge(function(n){return e(e({},n),{tiers:[de]})}),Dn.current=J(de);var y=J(ue),h=se.variants||[],b=(o=new Map,l=new Map,s=new Map,new Map),T=new Map,A=new Map;h.forEach(function(e,n){b.set(n,e.description||"");var t=e.whenToApply?e.whenToApply.split(" OR ").map(function(e,t){return{id:"copy-wta-".concat(n,"-").concat(t),text:e.trim(),reasoning:""}}):[];T.set(n,t);var i=e.whenNotToApply?e.whenNotToApply.split(" OR ").map(function(e,t){return{id:"copy-wnta-".concat(n,"-").concat(t),text:e.trim(),reasoning:""}}):[];A.set(n,i)}),o.set(y,b),l.set(y,T),s.set(y,A),lt(o),dt(l),_t(s);var M=h.map(function(e,n){var t,i,r=null===(t=e.configuration)||void 0===t?void 0:t.scheduling_config;return{variant_type:e.variantType||"variant",title:se.ruleTitle||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",scope:[ue],scheduling_config:r||{},variant_id:e.variantId,question_id:se.ruleId||"",tier_id:y.replace("tier_",""),is_readOnly:!0,link_id:e.link_id||"",is_enabled:null===(i=e.is_enabled)||void 0===i||i,is_user_accepted_risk:e.is_user_accepted_risk,has_accepted_risk:e.has_accepted_risk,user_accepted_risk_at:e.user_accepted_risk_at,action:"copy"}});gt(M),Tt(M),yt(function(e){var n=new Map(e);return n.set(y,JSON.parse(JSON.stringify(M))),n});var I=new Map;h.forEach(function(e,n){var t,i,r,a,o,l,s,u,d,c,v,_,p,f=null===(t=e.configuration)||void 0===t?void 0:t.scheduling_config,g=null!==(a=null!==(i=null==f?void 0:f.order_global_min_separation_seconds)&&void 0!==i?i:null===(r=null==f?void 0:f.order_rules)||void 0===r?void 0:r.global_min_separation_seconds)&&void 0!==a?a:0,m=null!==(s=null!==(o=null==f?void 0:f.advertiser_global_min_separation_seconds)&&void 0!==o?o:null===(l=null==f?void 0:f.advertiser_rules)||void 0===l?void 0:l.global_min_separation_seconds)&&void 0!==s?s:0;I.set(n,{order_rules:{enabled:g>0,global_min_separation_seconds:Math.floor(g/60)},advertiser_rules:{enabled:m>0,global_min_separation_seconds:Math.floor(m/60)},inventory_rules:{respect_inventory_code:null!==(c=null!==(d=null===(u=null==f?void 0:f.inventory_rules)||void 0===u?void 0:u.respect_inventory_code)&&void 0!==d?d:null==f?void 0:f.respect_inventory_code)&&void 0!==c&&c},break_code_rules:{respect_break_code:null!==(p=null!==(_=null===(v=null==f?void 0:f.break_code_rules)||void 0===v?void 0:v.respect_break_code)&&void 0!==_?_:null==f?void 0:f.respect_break_code)&&void 0!==p&&p},is_default_enabled:U(e.variantType||e.variant_type)})}),Kn(new Map([[y,I]]))}}},[Q,ne,ie,te,se,ue,de]),d(function(){if(Q){if(console.log("[Accordion Init] editingTier:",te,"focusedVariantIndex:",re),te&&ge(function(n){return e(e({},n),{tiers:[te]})}),fn)return console.log("[Accordion] isAddingNewVariant mode — closing all variant accordions"),void Et(void 0);if(oe){console.log("[Accordion] triggerAddVariant mode — not opening any variant on RHS"),Et(void 0);var n=(te?J(te):"tier_1").replace(/_/g," ");Rt("I want to add a new variant to ".concat(n))}else null!=re?(console.log("[Accordion] Opening SPECIFIC variant index ".concat(re," (from VariantCard)")),Et(re),ni(function(e){return e+1})):(ne||ie&&ie.length>0)&&(console.log("[Accordion] Opening DEFAULT/1st variant (index 0) for RuleHeader edit"),Et(0),ni(function(e){return e+1}))}else Et(void 0)},[Q,te,re,ne,ie,oe,fn]),d(function(){Q&&le&&ne&&null!==re&&Rt("I want to fix the gaps")},[Q,le,ne,re]);var Hn={order_rules:{enabled:!1,global_min_separation_seconds:0},advertiser_rules:{enabled:!1,global_min_separation_seconds:0},inventory_rules:{respect_inventory_code:!1},break_code_rules:{respect_break_code:!1},is_default_enabled:!1},Bn=s(new Map([["tier_1",new Map([[0,Hn]])],["tier_2",new Map([[0,Hn]])]])),Wn=Bn[0],Kn=Bn[1],Yn=s(new Set([])),zn=Yn[0],Qn=Yn[1],Zn=s("");Zn[0];var $n=Zn[1],Xn=s(""),et=Xn[0],nt=Xn[1],tt=s(new Map([["tier_1",new Map],["tier_2",new Map]])),it=tt[0],rt=tt[1],at=s(new Map([["tier_1",new Map],["tier_2",new Map]])),ot=at[0],lt=at[1],st=s(new Map([["tier_1",new Map],["tier_2",new Map]])),ut=st[0],dt=st[1],ct=s(new Map([["tier_1",new Map],["tier_2",new Map]])),vt=ct[0],_t=ct[1],pt=s([]),ft=pt[0],gt=pt[1],mt=s(new Map),wt=mt[0],yt=mt[1],ht=s([]),bt=ht[0],Tt=ht[1],At=s(!1),Mt=At[0],It=At[1],kt=s([]),St=kt[0],Ct=kt[1],Nt=s(void 0),xt=Nt[0],Et=Nt[1],Ot=s(""),Lt=Ot[0],Rt=Ot[1],Dt=s(null),jt=Dt[0],Vt=Dt[1],Pt=s([]),Ft=Pt[0],Gt=Pt[1],qt=s([]),Ut=qt[0],Jt=qt[1],Ht=s({}),Bt=Ht[0],Wt=Ht[1],Kt=s(new Map),Yt=Kt[0],zt=Kt[1],Qt=s(new Set),Zt=Qt[0],$t=Qt[1],Xt=s(0),ei=Xt[0],ni=Xt[1],ti=s({ruleTitle:"",ruleDescription:"",scopeData:"",whenToApply:"",whenNotToApply:"",configData:""}),ii=ti[0],ri=ti[1],ai=s([]),oi=ai[0],li=ai[1],si=s(""),ui=si[0],di=si[1],ci=s({}),vi=ci[0],_i=ci[1],pi=s(!1),fi=pi[0],gi=pi[1],mi=u(null),wi=u(null),yi=u(-1),hi=u(null);d(function(){Fn.current=ft},[ft]),d(function(){var n=new Set,t=console.warn;return console.warn=function(){for(var i,o=[],l=0;l<arguments.length;l++)o[l]=arguments[l];t.apply(void 0,o);var s=o[0];if("string"==typeof s&&s.includes("Failed to parse JSON for property=")){var u=s.match(/warnId="([^"]+)"/),d=null==u?void 0:u[1];if(d&&n.has(d))return;d&&n.add(d),null===(i=hi.current)||void 0===i||i.show({severity:"warn",sticky:!1,life:5e3,className:I.toastWarning,content:r("div",e({className:I.toastContent},{children:[r("div",e({className:I.toastHeaderLeft},{children:[a(_,{className:I.iconWarning}),a("span",e({className:"".concat(I.toastTitle," ").concat(I.toastTitleWarning)},{children:"Parsing Issue"}))]})),a("p",e({className:"".concat(I.toastMessage," ").concat(I.toastMessageWarning)},{children:"The AI response couldn't be parsed correctly. Please try rephrasing your input or retry."}))]}))})}},function(){console.warn=t}},[]);var bi=s(!1),Ti=bi[0],Ai=bi[1],Mi=s(!1),Ii=Mi[0],ki=Mi[1],Si=s({}),Ci=Si[0],Ni=Si[1],xi=s(""),Ei=xi[0],Oi=xi[1],Li=s(!0),Ri=Li[0],Di=Li[1],ji=s(!1),Vi=ji[0],Pi=ji[1],Fi=s(!1),Gi=Fi[0],qi=Fi[1],Ui=s(""),Ji=Ui[0],Hi=Ui[1],Bi=s(""),Wi=Bi[0],Ki=Bi[1],Yi=s(""),zi=Yi[0],Qi=Yi[1],Zi=s(null),$i=Zi[0],Xi=Zi[1],er=s(null),nr=er[0],tr=er[1],ir=s(null),rr=ir[0],ar=ir[1],or=L.getState().user,lr=O(),sr=lr.dispatch,ur=lr.getLatestReasoning;d(function(){console.log("Structured AI Response updated:",ft)},[ft]),d(function(){console.log("isCloseModal AI Response updated:",Ri)},[Ri]),d(function(){!1===fi?(ki(!1),Hi(""),Ki("")):(xe(!1),Se(""))},[fi]),d(function(){null!=xt&&ie&&!ie[xt]&&Xi(null)},[xt,ie]),d(function(){if(Le&&!De.current){De.current=!0,console.log("UseEffect triggered: Sending save message to chat agent");Rt("Save this Learning"),Re(!1),setTimeout(function(){De.current=!1,Rt("")},2e3)}},[Le]);var dr=c(function(e,n){on.some(function(n){return n.id===e})?(qi(!0),dn(e),_n(n),setTimeout(function(){_n(null),dn(null)},6e3)):console.warn("Variant ID ".concat(e," not found in comparison variants."))},[on]),cr=v(function(){var e=Gi&&Ye>0;return console.log("[Loader Debug] showComparison: ".concat(Gi,", activeRequests: ").concat(Ye,", Result: ").concat(e)),e},[Gi,Ye]),vr=c(function(n,t,i){var r,a=void 0!==(null===(r=null==i?void 0:i.target)||void 0===r?void 0:r.value)?i.target.value:i;lt(function(e){var i=new Map(e),r=new Map(i.get(n));return r.set(t,a),i.set(n,r),i}),Ni(function(i){if(i["ruleDescription-".concat(n,"-").concat(t)]){var r=e({},i);return delete r["ruleDescription-".concat(n,"-").concat(t)],r}return i})},[]),_r=c(function(t,i){dt(function(e){var r=new Map(e),a=new Map(r.get(t)),o=a.get(i)||[];return a.set(i,n(n([],o,!0),[{id:Date.now(),text:"",reasoning:""}],!1)),r.set(t,a),r}),Ni(function(n){if(n["whenToApply-".concat(t,"-").concat(i)]){var r=e({},n);return delete r["whenToApply-".concat(t,"-").concat(i)],r}return n})},[]),pr=c(function(e,n,t){dt(function(i){var r=new Map(i),a=new Map(r.get(e)),o=a.get(n)||[];return a.set(n,o.filter(function(e){return e.id!==t})),r.set(e,a),r})},[]),fr=c(function(n,t,i,r){dt(function(a){var o=new Map(a),l=new Map(o.get(n)),s=l.get(t)||[];return l.set(t,s.map(function(n){return String(n.id)===String(i)?e(e({},n),{text:r}):n})),o.set(n,l),o}),Ni(function(i){if(i["whenToApply-".concat(n,"-").concat(t)]){var r=e({},i);return delete r["whenToApply-".concat(n,"-").concat(t)],r}return i})},[]),gr=c(function(e,t){_t(function(i){var r=new Map(i),a=new Map(r.get(e)),o=a.get(t)||[];return a.set(t,n(n([],o,!0),[{id:Date.now(),text:"",reasoning:""}],!1)),r.set(e,a),r})},[]),mr=c(function(e,n,t){_t(function(i){var r=new Map(i),a=new Map(r.get(e)),o=a.get(n)||[];return a.set(n,o.filter(function(e){return e.id!==t})),r.set(e,a),r})},[]),wr=c(function(n,t,i,r){_t(function(a){var o=new Map(a),l=new Map(o.get(n)),s=l.get(t)||[];return l.set(t,s.map(function(n){return String(n.id)===String(i)?e(e({},n),{text:r}):n})),o.set(n,l),o})},[]),yr=c(function(e){var n=e.replace(/_/g," ");gn(!0),null==ae||ae(null),Et(void 0),Rt("I want to add a new variant to ".concat(n))},[]),hr=function(n,t,i){var r="".concat(n,"_").concat(t);console.log("Highlighting ".concat(i," at ").concat(r)),zt(function(n){var t,a=new Map(n),o=a.get(r)||{};return a.set(r,e(e({},o),((t={})[i]=!0,t))),a}),setTimeout(function(){zt(function(n){var t,a=new Map(n),o=a.get(r)||{};return a.set(r,e(e({},o),((t={})[i]=!1,t))),a})},1500)},br=c(function(n,t){ge(function(i){var r;return e(e({},i),((r={})[n]=t,r))}),Ni(function(t){if(t[n]){var i=e({},t);return delete i[n],i}return t})},[]),Tr=c(function(n,t,i,r){rt(function(e){var r=new Map(e),a=new Map(r.get(n)||new Map),o=a.get(t)||new Set;return o.add(i),a.set(t,o),r.set(n,a),r}),Kn(function(a){var o,l,s,u=new Map(a),d=new Map(u.get(n)||new Map),c=d.get(t)||Hn;switch(i){case"order_rules":case"advertiser_rules":s="boolean"==typeof r?e(e({},c),((o={})[i]=e(e({},c[i]),{enabled:r}),o)):"object"==typeof r&&null!==r?e(e({},c),((l={})[i]={enabled:r.enabled,global_min_separation_seconds:r.global_min_separation_seconds},l)):c;break;case"inventory_rules":s=e(e({},c),{inventory_rules:{respect_inventory_code:"boolean"==typeof r?r:r.respect_inventory_code}});break;case"break_code_rules":s=e(e({},c),{break_code_rules:{respect_break_code:"boolean"==typeof r?r:r.respect_break_code}});break;case"is_default_enabled":s=e(e({},c),{is_default_enabled:"boolean"==typeof r?r:!!r});break;default:s=c}return d.set(t,s),u.set(n,d),u})},[]);d(function(){fi&&(qi(!1),_n(null),dn(null))},[fi]);var Ar=c(function(n){var t;if(void 0===n&&(n=!1),n||(sr({type:"RESET"}),mi.current=null,gt([]),Ct([]),li([]),_i({}),qi(!1),Ve.current.clear()),nt(""),Gt([]),gn(!1),Be.current="",Qi(""),tr(null),Jt([]),ge({station:"",tiers:[]}),ze(0),$e(!1),ar(null),lt(new Map([["tier_1",new Map],["tier_2",new Map]])),dt(new Map([["tier_1",new Map],["tier_2",new Map]])),_t(new Map([["tier_1",new Map],["tier_2",new Map]])),Kn(new Map([["tier_1",new Map([[0,Hn]])],["tier_2",new Map([[0,Hn]])]])),rt(new Map([["tier_1",new Map],["tier_2",new Map]])),$n(""),Et(0),ni(0),ge({station:X,tiers:["Tier 1"]}),n||Wt({}),rt(new Map([["tier_1",new Map],["tier_2",new Map]])),Rt(""),ri({ruleTitle:"",ruleDescription:"",scopeData:"",whenToApply:"",whenNotToApply:"",configData:""}),Ni({}),Oi(""),Di(!0),Fe(null),qe(null),yt(new Map),Tt([]),Tn(!1),Je(null),wi.current=null,We.current=!1,mn.current={},Mn.current.clear(),Rn.current=null,Dn.current=null,Ln(null),Se(""),ye(V),Te(!1),xe(!1),Re(!1),rn(null),ln([]),dn(null),_n(null),Sn(null),It(!1),Vt(null),Hi(""),Ki(""),ki(!1),Qn(new Set),De.current=!1,He.current.clear(),en.current=0,Xe.current=null,jn.current=null,yi.current=-1,An.current=!1,yn.current=!1,ne){ne.ruleTitle&&nt(ne.ruleTitle),te&&(ge(function(n){return e(e({},n),{tiers:[te]})}),Dn.current=te.toLowerCase().replace(/ /g,"_")),Rn.current=ne.ruleId;var i=null===(t=null==ie?void 0:ie[re||0])||void 0===t?void 0:t.variantId;if(Ln(i||null),ie&&ie.length>0){var r=te?J(te):"tier_1",a=new Map,o=new Map,l=new Map,s=new Map,u=new Map,d=new Map;ie.forEach(function(e,n){s.set(n,e.description||"");var t=e.whenToApply?e.whenToApply.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,t){return{id:"edit-wta-".concat(n,"-").concat(t),text:e,reasoning:""}}):[];u.set(n,t);var i=e.whenNotToApply?e.whenNotToApply.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,t){return{id:"edit-wnta-".concat(n,"-").concat(t),text:e,reasoning:""}}):[];d.set(n,i)}),a.set(r,s),o.set(r,u),l.set(r,d),lt(a),dt(o),_t(l);var c=ie.map(function(e){var n,t,a=null===(n=e.configuration)||void 0===n?void 0:n.scheduling_config;return{variant_type:e.variantType||"variant",title:ne.ruleTitle||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",scope:[r],scheduling_config:a||{},variant_id:e.variantId,question_id:ne.ruleId||"",tier_id:r.replace("tier_",""),is_readOnly:e.variantId!==i,link_id:e.link_id||"",is_enabled:null===(t=e.is_enabled)||void 0===t||t,is_user_accepted_risk:e.is_user_accepted_risk,has_accepted_risk:e.has_accepted_risk,user_accepted_risk_at:e.user_accepted_risk_at,action:"edit"}});gt(c),Tt(c),yt(function(e){var n=new Map(e);return n.set(r,JSON.parse(JSON.stringify(c))),n});var v=new Map;ie.forEach(function(e,n){var t,i,r,a,o,l,s,u,d,c,_,p,f,g=null===(t=e.configuration)||void 0===t?void 0:t.scheduling_config,m=null!==(a=null!==(i=null==g?void 0:g.order_global_min_separation_seconds)&&void 0!==i?i:null===(r=null==g?void 0:g.order_rules)||void 0===r?void 0:r.global_min_separation_seconds)&&void 0!==a?a:0,w=null!==(s=null!==(o=null==g?void 0:g.advertiser_global_min_separation_seconds)&&void 0!==o?o:null===(l=null==g?void 0:g.advertiser_rules)||void 0===l?void 0:l.global_min_separation_seconds)&&void 0!==s?s:0;v.set(n,{order_rules:{enabled:m>0,global_min_separation_seconds:Math.floor(m/60)},advertiser_rules:{enabled:w>0,global_min_separation_seconds:Math.floor(w/60)},inventory_rules:{respect_inventory_code:null!==(c=null!==(d=null===(u=null==g?void 0:g.inventory_rules)||void 0===u?void 0:u.respect_inventory_code)&&void 0!==d?d:null==g?void 0:g.respect_inventory_code)&&void 0!==c&&c},break_code_rules:{respect_break_code:null!==(f=null!==(p=null===(_=null==g?void 0:g.break_code_rules)||void 0===_?void 0:_.respect_break_code)&&void 0!==p?p:null==g?void 0:g.respect_break_code)&&void 0!==f&&f},is_default_enabled:U(e.variantType||e.variant_type)})}),Kn(new Map([[r,v]])),Et(null!=re?re:0)}}},[sr,X,ne,te,ie,re]),Mr=function(e){if(!e||0===e.length)return"variant 1";var n=e.filter(function(e){var n=e.variant_type||e.variantType||"";return""!==n&&null!==n});return"variant ".concat(n.length+1)},Ir=c(function(){console.log("variantIds",Ft),qi(!0)},[Ft]),kr={"Let me connect the dots for you...":function(e){if("string"==typeof e){var n=e.match(/<!--\s*(\{[^}]*"variant_index"[^}]*\})\s*-->/);if(n)try{var t=JSON.parse(n[1]),i=parseInt(t.variant_index,10);if(!isNaN(i)&&i>0){var r=i-1;yi.current!==r&&(console.log("Opening variant accordion: AI index ".concat(i," → 0-based index ").concat(r)),Et(r),yi.current=r)}}catch(e){console.error("Failed to parse variant_index from HTML comment:",e)}}},"Crafted Instant Learning with C.A.R.E.":function(t){var i,r=C(t),a=C(t,"general_details");console.log("--- [CARE] Staging Initial Structure ---",r);var o=C(t,"critical_gaps");if(console.log("isCriticalGap",o),$e(!!o),r){if(r.variant_type&&!("is_variant"in r)){var l=null===(i=Cr(r.variant_type||"").toLowerCase().match(/^(default_variant|default|variant)/i))||void 0===i?void 0:i[0];r.variant_type=U(l)?"Default":"variant",r.isDefault=U(l),console.log("parsed.variant_type",r.variant_type)}var s=r.scope&&r.scope.length>0?String(r.scope[0]):null,u=s?Cr(s).toLowerCase().trim().replace(/ /g,"_"):null,d=Boolean(u&&Dn.current!==u);if(d&&u){var c=Dn.current;console.log("[Tier Switch Detected]",Dn.current,"→",u),Dn.current=u,Rn.current=null;var v=(Fn.current||[]).findIndex(function(e){return!0===(null==e?void 0:e.is_new_variant)});-1===v&&void 0!==xt&&(v=xt),c&&-1!==v&&(console.log("[Tier Switch] Stripping draft variant at index ".concat(v," from ").concat(c)),lt(function(e){var n=new Map(e),t=new Map(n.get(c)||new Map);return t.delete(v),n.set(c,t),n}),dt(function(e){var n=new Map(e),t=new Map(n.get(c)||new Map);return t.delete(v),n.set(c,t),n}),_t(function(e){var n=new Map(e),t=new Map(n.get(c)||new Map);return t.delete(v),n.set(c,t),n}),Kn(function(e){var n=new Map(e),t=new Map(n.get(c)||new Map);return t.delete(v),n.set(c,t),n}),gt(function(t){if(!Array.isArray(t))return t;var i=n([],t,!0);return i[v]&&(i[v]=e(e({},i[v]),{scope:[u],tier_id:u.replace("tier_","")})),Fn.current=i,i})),yi.current=-1;var _=u.replace(/_/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()});ge(function(n){return e(e({},n),{tiers:[_]})})}Vt(r),Fe({Updated_Fields_Response:r,General_Response:a}),(null==a?void 0:a.variant_id)&&"new_variant_id"===(null==a?void 0:a.variant_id)&&(a.variant_id=null),(null==a?void 0:a.is_interpretation_ready)&&(null==a?void 0:a.question_id)&&aa(a,r,d),(null==a?void 0:a.is_interpretation_ready)&&(null==a?void 0:a.question_id)&&Rn.current&&On?gt(function(n){if(!Array.isArray(n))return n;var t=n.map(function(n){return(null==n?void 0:n.variant_id)&&n.variant_id===On?e(e({},n),r):n}),i=n.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===On});return console.log(i,"targetIndexif"),-1!==i&&setTimeout(function(){console.log("targetIndex",i),Et(i),ni(function(e){return e+1}),yi.current=i},0),t}):(null==a?void 0:a.is_interpretation_ready)&&(null==a?void 0:a.question_id)&&Rn.current&&!On?gt(function(t){var i;if(Array.isArray(t)){var a=t.findIndex(function(e){return!0===e.is_new_variant});if(-1!==a)setTimeout(function(){Et(a),ni(function(e){return e+1}),yi.current=a},0),i=t.map(function(n,t){return t===a?e(e(e({},n),r),{is_new_variant:!0,is_variant:!0}):n});else{var o=t.length;setTimeout(function(){Et(o),ni(function(e){return e+1}),yi.current=o},0),i=n(n([],t,!0),[e(e({},r),{is_new_variant:!0})],!1)}}else setTimeout(function(){Et(0),ni(function(e){return e+1}),yi.current=0},0),i=[e(e({},r),{is_new_variant:!0})];return Fn.current=i,i}):(null==a?void 0:a.is_interpretation_ready)&&(gt([r]),setTimeout(function(){Et(0),ni(function(e){return e+1}),yi.current=0},0)),void 0!==r.is_user_accepted_risk&&gt(function(t){var i=!(!ne&&!ie),a=Array.isArray(t)?n([],t,!0):[];if(i&&0===a.length&&ie&&ie.length>0&&(a=ie.map(function(e,n){var t;return{variant_type:e.variantType||"variant ".concat(n+1),title:(null==ne?void 0:ne.ruleTitle)||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",is_valid:!0,is_readOnly:e.variantId!==On,variant_id:e.variantId,tier_id:(null===(t=e.tier)||void 0===t?void 0:t.tier_id)||"1",is_user_accepted_risk:e.is_user_accepted_risk||!1}})),i){var o=$i||nr,l=a.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===o||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===o||(null==e?void 0:e.id)&&e.id===o});if(-1===l&&void 0!==xt&&(l=xt),-1!==l)return a[l]=e(e({},a[l]),{is_user_accepted_risk:!!r.is_user_accepted_risk}),a}return t})}},"RHS Validation Agent Response":function(t){var i,r,a,o=t;if("string"==typeof t)try{o=JSON.parse(t)}catch(e){o=N(t)}if(qe(o),console.log("--- [RHS] Updating Staged Logic ---"),console.log("parsed data from RHS Validation",o),o){Vt(function(n){var t=n;if(!t){console.log("⚠️ No staged response found! Constructing fallback from current UI state...");var i=null;if(Array.isArray(ft)){var r=$i||nr,a=-1;!(!ne&&!ie)&&r&&(a=ft.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===r||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===r||(null==e?void 0:e.id)&&e.id===r})),-1===a&&void 0!==xt&&(a=xt),-1!==a&&(i=ft[a])}t=i?e({},i):{wta:"",wnta:""}}return e(e({},t),{wta:t.wta,wnta:t.wnta,is_valid:o.is_valid,conflictingConditions:o.conflictingConditions||[],conflictMarkdown:{},conflict_view:o.conflict_view||{}})});var l=(te||"Tier 1").toLowerCase().replace(/ /g,"_"),s=function(){var e,n=Fn.current;if(Array.isArray(n)&&n.length>0){var t,i=n.findIndex(function(e){return!0===(null==e?void 0:e.is_new_variant)});if(-1!==i)return console.log("[RHS] Resolved via is_new_variant flag:",i),i;if(On)if(-1!==(t=n.findIndex(function(e){return(null==e?void 0:e.variant_id)===On||(null==e?void 0:e.new_variant_id)===On})))return t;if($i)if(-1!==(t=n.findIndex(function(e){return(null==e?void 0:e.variant_id)===$i||(null==e?void 0:e.new_variant_id)===$i})))return t;var r=null!==(e=null==ie?void 0:ie.length)&&void 0!==e?e:0;if(n.length>r){var a=n.length-1;return console.log("[RHS] Resolved via length diff (new variant appended):",a),a}}var o=void 0!==xt?xt:0;return console.log("[RHS] Fallback index used:",o),o}();if(console.log("Resolved variant index for conflict injection:",s),!1===o.is_valid)((null===(i=o.conflictingConditions)||void 0===i?void 0:i.length)||0)>0&&(Ni(function(n){var t=e({},n);return o.conflictingConditions.forEach(function(e){e.condition_wnta&&!e.condition_wta?t["whenNotToApply-".concat(l,"-").concat(s)]=e.reason:t["whenToApply-".concat(l,"-").concat(s)]=e.reason}),t}),Oi("")),o.conflict_view&&((null===(r=o.conflict_view.wta)||void 0===r?void 0:r.length)>0&&dt(function(t){var i=new Map(t),r=new Map(i.get(l)||new Map),a=n([],r.get(s)||[],!0);return o.conflict_view.wta.forEach(function(n){var t=a.findIndex(function(e){return e.text.trim()===n.value});-1!==t?a[t]=e(e({},a[t]),{conflict:n}):a.push({id:"conflict-wta-".concat(Date.now(),"-").concat(Math.random()),text:n.value,conflict:n})}),r.set(s,a),i.set(l,r),i}),(null===(a=o.conflict_view.wnta)||void 0===a?void 0:a.length)>0&&_t(function(t){var i=new Map(t),r=new Map(i.get(l)||new Map),a=n([],r.get(s)||[],!0);return o.conflict_view.wnta.forEach(function(n){var t=a.findIndex(function(e){return e.text.trim()===n.value});-1!==t?a[t]=e(e({},a[t]),{conflict:n}):a.push({id:"conflict-wnta-".concat(Date.now(),"-").concat(Math.random()),text:n.value,conflict:n})}),r.set(s,a),i.set(l,r),i}));else!0===o.is_valid&&(Ni({}),Oi(""),dt(function(n){var t=new Map(n),i=new Map(t.get(l)||new Map),r=i.get(s)||[];return i.set(s,r.map(function(n){return e(e({},n),{conflict:void 0})})),t.set(l,i),t}),_t(function(n){var t=new Map(n),i=new Map(t.get(l)||new Map),r=i.get(s)||[];return i.set(s,r.map(function(n){return e(e({},n),{conflict:void 0})})),t.set(l,i),t}))}},"User Action Execution":function(e){console.log("--- [User Action] Execution ---",e);var n=x(e);(console.log("parsedaction",n),"load"===(null==n?void 0:n.action)&&(null==n?void 0:n.question_id)&&aa(n,null),"save"===(null==n?void 0:n.action)&&(null==n?void 0:n.is_save)&&(Di(!0),Pi(!0)),"discard_rule"===(null==n?void 0:n.action))&&(gt([{variant_id:void 0,rule_description:"",wta:"",wnta:"",variant_type:"variant"}]),Tt([]),Ln(null),Et(0),ni(0),Sn(null),Tn(!1),gn(!1),Gt([]),Rn.current=null,nt(""),ar(null),Kn(new Map([["tier_1",new Map([[0,Hn]])],["tier_2",new Map([[0,Hn]])]])),lt(new Map([["tier_1",new Map],["tier_2",new Map]])),dt(new Map([["tier_1",new Map],["tier_2",new Map]])),_t(new Map([["tier_1",new Map],["tier_2",new Map]])))},"Validation Agent Response":function(t){var i,r;if(console.log("--- [Validation Agent] Committing Staged Data to UI ---"),console.log("raw data from Validation Agent",t,typeof t),"string"==typeof t){var a=t.match(/<!--\s*```json\s+property="rule_validation_card"\s+([\s\S]*?)```\s*-->/i);if(a&&a[1])try{var o=JSON.parse(a[1].trim()),l=null===(r=null===(i=null==o?void 0:o.validated_rules)||void 0===i?void 0:i[0])||void 0===r?void 0:r.rule_id;l&&(console.log("Setting default comparison ID:",l),dn(l))}catch(e){console.error("Failed to parse rule_validation_card JSON",e)}}var s=C(t,"critical_gaps");console.log("isCriticalGap",s),$e(!!s);var u="string"==typeof t?x(t):t;console.log("parsed data from Validation Agent",u);var d=E(t);Je(u);var c=!!(null==u?void 0:u.is_variant),v=void 0===(null==u?void 0:u.close_modal)||!!(null==u?void 0:u.close_modal),_=void 0!==(null==u?void 0:u.is_save)&&!!(null==u?void 0:u.is_save);Di(v),Pi(_);var p=null==u?void 0:u.action,f="string"==typeof(null==u?void 0:u.edit_variant_id)&&u.edit_variant_id.trim()?u.edit_variant_id:"string"==typeof(null==u?void 0:u.set_variant_id)&&u.set_variant_id.trim()?u.set_variant_id:null,g="variant"===p&&c;if((null==u?void 0:u.edit_variant_id)&&!g&&Xi(u.edit_variant_id),"edit"!==p&&"edit_current_rule"!==p||!f||tr(f),g&&(Xi(null),tr(null)),"discard"===p)return console.log("Action 'discard' received: Resetting UI state but preserving chat."),yn.current=!0,Ar(!0),gt([]),mi.current=null,void(wi.current=null);Qi(p);var m=null==u?void 0:u.new_variant_id,w="edit"===(null==u?void 0:u.action)&&(null==u?void 0:u.set_variant_id)&&!ie;(null==u?void 0:u.is_valid)?(Ni({}),Vt(function(t){var i,r,a,o,l,s,d,c,v,_,p,g;if(console.log("⏮️ PREVIOUS Staged Response:",t),!t)return console.warn("⚠️ No previous staged response found"),t;var m=function(e,n){return Object.prototype.hasOwnProperty.call(e||{},n)},w=e(e({},t),u);Array.isArray(null===(i=null==u?void 0:u.condition_result)||void 0===i?void 0:i.when_to_apply)?w.wta=u.condition_result.when_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join(" OR "):m(u,"wta")&&void 0!==(null==u?void 0:u.wta)&&(w.wta=null!==(r=null==u?void 0:u.wta)&&void 0!==r?r:""),Array.isArray(null===(a=null==u?void 0:u.condition_result)||void 0===a?void 0:a.when_not_to_apply)?w.wnta=u.condition_result.when_not_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join(" OR "):m(u,"wnta")&&void 0!==(null==u?void 0:u.wnta)&&(w.wnta=null!==(o=null==u?void 0:u.wnta)&&void 0!==o?o:""),console.log("finalData",w),console.log("checking parsed here :",u);var y,h=f;if(Array.isArray(ft)&&h&&(y=h,ft.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===y||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===y||(null==e?void 0:e.id)&&e.id===y})),"edit"!==(null==u?void 0:u.action)||!ne&&!ie)return w;console.log("inside edit flow merge");var b=ie||[],T=f,A=T?b.findIndex(function(e){return e.variantId===T||e.variant_id&&e.variant_id===T||e.id&&e.id===T}):-1;if(-1===A&&(null==u?void 0:u.set_variant_id)&&(A=b.findIndex(function(e){return e.variantId===u.set_variant_id||e.variant_id&&e.variant_id===u.set_variant_id||e.id&&e.id===u.set_variant_id})),-1===A&&T&&Array.isArray(ft)&&(A=ft.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===T||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===T||(null==e?void 0:e.id)&&e.id===T})),-1!==A){var M,I,k,S=b[A]||(null==ft?void 0:ft[A]),C=(null==S?void 0:S.tier_id)||(null==S?void 0:S.tierId)||"1",N=(null==te?void 0:te.toLowerCase().replace(/ /g,"_"))||"tier_".concat(C);if(yi.current!==A&&(Et(A),yi.current=A),Array.isArray(null===(l=u.condition_result)||void 0===l?void 0:l.when_to_apply)?M=u.condition_result.when_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join("\n"):m(u,"wta")&&void 0!==(null==u?void 0:u.wta)?M=null!==(s=null==u?void 0:u.wta)&&void 0!==s?s:"":m(t,"wta")&&void 0!==(null==t?void 0:t.wta)&&(M=null!==(d=null==t?void 0:t.wta)&&void 0!==d?d:""),Array.isArray(null===(c=u.condition_result)||void 0===c?void 0:c.when_not_to_apply)?I=u.condition_result.when_not_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join("\n"):m(u,"wnta")&&void 0!==(null==u?void 0:u.wnta)?I=null!==(v=null==u?void 0:u.wnta)&&void 0!==v?v:"":m(t,"wnta")&&void 0!==(null==t?void 0:t.wnta)&&(I=null!==(_=null==t?void 0:t.wnta)&&void 0!==_?_:""),void 0!==M){var x=Cr(M);Nr(N,A,M,x,ut,dt,null==u?void 0:u.conflict_view),hr(N,A,"wta")}if(void 0!==I){var E=Cr(I);Nr(N,A,I,E,vt,_t,null==u?void 0:u.conflict_view),hr(N,A,"wnta")}if(m(u,"rule_description")&&void 0!==(null==u?void 0:u.rule_description)?k=null!==(p=null==u?void 0:u.rule_description)&&void 0!==p?p:"":m(t,"rule_description")&&void 0!==(null==t?void 0:t.rule_description)&&(k=null!==(g=null==t?void 0:t.rule_description)&&void 0!==g?g:""),void 0!==k){var O=Cr(k);lt(function(e){var n=new Map(e),t=new Map(n.get(N)||new Map);return t.set(A,O),n.set(N,t),n}),hr(N,A,"ruleDescription")}var L=void 0;m(u,"scheduling_config")&&void 0!==(null==u?void 0:u.scheduling_config)?L=null==u?void 0:u.scheduling_config:m(t,"scheduling_config")&&void 0!==(null==t?void 0:t.scheduling_config)&&(L=null==t?void 0:t.scheduling_config),L&&(Kn(function(e){var n,i,r,a,o,l,s=new Map(e),u=new Map(s.get(N)||new Map);return u.set(A,{order_rules:{enabled:!!(null===(n=L.order_rules)||void 0===n?void 0:n.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(i=L.order_rules)||void 0===i?void 0:i.global_min_separation_seconds)||0)/60)},advertiser_rules:{enabled:!!(null===(r=L.advertiser_rules)||void 0===r?void 0:r.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(a=L.advertiser_rules)||void 0===a?void 0:a.global_min_separation_seconds)||0)/60)},inventory_rules:{respect_inventory_code:!!(null===(o=L.inventory_rules)||void 0===o?void 0:o.respect_inventory_code)},break_code_rules:{respect_break_code:!!(null===(l=L.break_code_rules)||void 0===l?void 0:l.respect_break_code)},is_default_enabled:"Default"===(null==t?void 0:t.variant_type)||"default_variant"===(null==t?void 0:t.variant_type)||"default"===(null==t?void 0:t.variant_type)}),s.set(N,u),s}),hr(N,A,"order_enabled"),hr(N,A,"advertiser_enabled"),hr(N,A,"respect_inventory_code"),hr(N,A,"respect_break_code")),gt(function(t){if(!Array.isArray(t)||A<0||!t[A])return t;var i=n([],t,!0),r=e({},i[A]);return void 0!==M&&(r.wta=M),void 0!==I&&(r.wnta=I),void 0!==k&&(r.rule_description=Cr(k)),L&&(r.scheduling_config=L),console.log("updated variantxxx",r),i[A]=r,i});var R=null==t?void 0:t.variant_type;R&&gt(function(t){var i=Array.isArray(t)?n([],t,!0):[],r=i.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===T||(null==e?void 0:e.variant_id)&&e.variant_id===(null==u?void 0:u.set_variant_id)||(null==e?void 0:e.variantId)===T});return-1!==r?i[r]=e(e({},i[r]),{variant_type:R}):i[A]=e(e({},i[A]||{}),{variant_type:R,variant_id:T||(null==u?void 0:u.set_variant_id)}),i})}})):console.warn("⚠️ parsed.is_valid is false, not committing to structuredAIResponse"),w||(c?(It(!0),m&&m!==wi.current?(console.log("🚀 New Variant detected (".concat(m,"). Triggering loader.")),ki(!0),Hi("Loading a variant"),console.log("reaching here in new variant flow"),Ki("This may take a moment as we update the rule with the new variant."),wi.current=m):m||console.log("ℹ️ Variant flow detected without specific ID.")):(It(!1),wi.current=null),d&&Gt(d))},"Rule comparison results":function(e){try{var n=e;if("string"==typeof e)try{n=JSON.parse(e)}catch(t){n=x(e)||[]}if(!Array.isArray(n)){if(!n||"object"!=typeof n)return void console.error("[Rule comparison results] Data is not an array:",e);n=[n]}var t=n.map(function(e,n){var t,i,r,a,o=null,l=null;if((Array.isArray(e)?e:[e]).forEach(function(e){e&&(e.intent_output&&(o=e.intent_output),e.behaviour_output&&(l=e.behaviour_output))}),"string"==typeof o)try{o=JSON.parse(o)}catch(e){console.error("Failed to parse intent_output",e)}if("string"==typeof l)try{l=JSON.parse(l)}catch(e){console.error("Failed to parse behaviour_output",e)}var s="existing_variant",u="fallback-id-".concat(Math.random()),d=(null==o?void 0:o.documents)||(null==l?void 0:l.documents);if(d){var c=Object.keys(d).find(function(e){return"reference"===d[e].role});c&&(s=c,u="".concat(c,"-").concat(n))}var v="";if((null==o?void 0:o.nodes)&&o.nodes.title){var _=o.nodes.title;(null===(i=null===(t=null==_?void 0:_.comparison_inputs)||void 0===t?void 0:t[s])||void 0===i?void 0:i.content)&&(v=_.comparison_inputs[s].content)}var p="Score";(null==l?void 0:l.final_score)&&(p=l.final_score);var f="Unknown Tier",g=(null===(r=null==d?void 0:d[s])||void 0===r?void 0:r.title)||(null===(a=null==d?void 0:d.existing_variant)||void 0===a?void 0:a.title);return g&&g.includes("|")&&(f=g.split("|")[1].trim()),console.log("Extracted for carousel:",{uniqueId:u,extractedTitle:v,extractedScore:p,extractedScope:f}),{id:u,title:v,similarityScoreText:p,scope:f,intentTreeData:o,behaviorTreeData:l,isLoading:!1}});ln(t)}catch(e){console.error("[Rule comparison results] Critical Handler Error:",e)}}},Sr=function(e){var n=Array.isArray(e)?e.join(" "):String(e||""),t=null==n?void 0:n.match(/<ai_reasoning>([\s\S]*?)<\/ai_reasoning>/);return t?t[1]:null},Cr=function(e){return"string"!=typeof e?"":e.replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g,"").replace(/<!--```json[\s\S]*?```-->/g,"").trim()},Nr=function(t,i,r,a,o,l,s){var u;if(void 0!==r){var d=(o.get(t)||new Map).get(i)||[],c=d.map(function(e){return e.text}).join("\n"),v=(null===(u=d[(null==d?void 0:d.length)-1])||void 0===u?void 0:u.reasoning)||"",_=Sr(r)||"";if(""===r&&d.length>0||a.trim()!==c.trim()||_!==v){var p=""===r?{updatedItems:[],newIds:[]}:function(t,i,r){if(!t.trim())return{updatedItems:n([],i,!0),newIds:[]};var a=t.match(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g)||[],o=t.replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g,"").replace(/<!--```json[\s\S]*?```-->/g,""),l=[],s=o.replace(/<conflicting>[\s\S]*?<\/conflicting>/g,function(e){return l.push(e),"__CONFLICT_BLOCK_".concat((null==l?void 0:l.length)-1,"__")}).split(/\s*(?:\r?\n|\\+n)\s*/).map(function(e){return e.trim().replace(/^-\s*/,"")}).filter(Boolean),u=new Map(i.map(function(e){return[e.text,e]})),d=[],c=[],v=Array.isArray(null==r?void 0:r.wta)&&t.includes("wta")?r.wta:Array.isArray(null==r?void 0:r.wnta)?r.wnta:[];return s.forEach(function(n,t){var i=n;i.includes("__CONFLICT_BLOCK_")&&(i=i.replace(/__CONFLICT_BLOCK_(\d+)__/g,function(e,n){return l[parseInt(n)]}));var r=a[t]||"",o=i.replace(/<conflicting>[\s\S]*?<\/conflicting>/g,"").trim(),s=null==v?void 0:v.find(function(e){return e.value===o}),_=u.get(i);if(_)c.push(e(e({},_),{reasoning:r||_.reasoning,conflict:s||_.conflict}));else{var p="new-".concat(Date.now(),"-").concat(t);d.push(p),c.push({id:p,text:i,reasoning:r,conflict:s})}}),{updatedItems:c,newIds:d}}(r,d,s),f=p.updatedItems,g=p.newIds;l(function(e){var n=new Map(e),r=new Map(n.get(t)||new Map);return r.set(i,f),n.set(t,r),n}),(null==g?void 0:g.length)>0&&($t(function(e){return new Set(n(n([],Array.from(e),!0),g,!0))}),setTimeout(function(){$t(function(e){var n=new Set(e);return g.forEach(function(e){return n.delete(e)}),n})},1500))}}},xr=function(e){return(Array.isArray(e)?e:e?[e]:[]).map(function(e){return String(e).replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/,"").trim().replace(/_/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()})})};d(function(){Lt&&!De.current&&"save this learning"!==Lt.toLowerCase()&&(xe(!1),Se(""),yi.current=null!=xt?xt:-1)},[Lt]),d(function(){var t,i,r,a,o,l,s,u,d;if(Pn.current=oi,Array.isArray(ft)&&ft.length>0){var c=ui||"local-".concat(Date.now()),v=["ruleTitle","ruleDescription","whenToApply","whenNotToApply","scopeData","configData"],_={},p=mi.current||[];ft.forEach(function(t,i){var r,a;if(t){t.is_readOnly||(en.current=i);var o=i;if((null==t?void 0:t.variant_id)&&ie)-1!==(l=ie.findIndex(function(e){return e.variantId===t.variant_id}))&&(o=l);else if($i&&ie&&1===ft.length){var l;-1!==(l=ie.findIndex(function(e){return e.variantId===$i}))&&(o=l)}var s=null!==(r=p[o])&&void 0!==r?r:p[i],u=null!==(a=t.scope)&&void 0!==a?a:null==s?void 0:s.scope,d=xr(u).map(function(e){return e.toLowerCase().replace(/ /g,"_")}),c=d.length>0?d:wn.current.length>0?wn.current:["tier_1"];c.length>0&&(wn.current=c),console.log("prevTierRef.current",wn.current,"targetTiers",c);var f=Cr(t.title);f&&f!==Cr(null==s?void 0:s.title)&&!t.is_readOnly&&function(e,n,t,i,r,a){var o=Cr(i);o&&o!==r&&(hr(e,n,t),a(o))}("global",0,"ruleTitle",t.title,et,nt),c.forEach(function(r){var a,l,s,u,d,c=null!==(a=p[o])&&void 0!==a?a:p[i],f=!c,g=void 0!==t.rule_description&&null!==t.rule_description,m=Cr(t.rule_description),w=(null===(l=ot.get(r))||void 0===l?void 0:l.get(o))||"",y=Cr(w);g&&(m!==y||""===m&&""!==w)&&(lt(function(e){var n=new Map(e),i=new Map(n.get(r)||new Map);return i.set(o,t.rule_description),n.set(r,i),n}),hr(r,o,"ruleDescription"));var h=!1===(null==jt?void 0:jt.is_valid),b=Cr(t.wta),T=Cr(null==c?void 0:c.wta),A=(null===(s=ut.get(r))||void 0===s?void 0:s.get(o))||[];!(h&&""===b&&A.length>0)&&void 0!==t.wta&&null!==t.wta&&(b!==T||""===b&&A.length>0||0===A.length&&""!==b)&&(Nr(r,o,t.wta,b,ut,dt,null==jt?void 0:jt.conflict_view),hr(r,o,"wta"));var M=Cr(t.wnta),I=Cr(null==c?void 0:c.wnta),k=(null===(u=vt.get(r))||void 0===u?void 0:u.get(o))||[];if(!(h&&""===M&&k.length>0)&&void 0!==t.wnta&&null!==t.wnta&&(M!==I||""===M&&k.length>0||0===k.length&&""!==M)&&(Nr(r,o,t.wnta,M,vt,_t,null==jt?void 0:jt.conflict_view),hr(r,o,"wnta")),t.scheduling_config||f||t.variant_type||t.variantType){var S=t.scheduling_config||{order_rules:{enabled:!1,global_min_separation_seconds:0},advertiser_rules:{enabled:!1,global_min_separation_seconds:0},inventory_rules:{respect_inventory_code:!1},break_code_rules:{respect_break_code:!1}},C=null==c?void 0:c.scheduling_config,N=null===(d=Wn.get(r))||void 0===d?void 0:d.get(o),x=t.variant_type||t.variantType,E=x?U(x):void 0,O=JSON.stringify(S)!==JSON.stringify(C),L=void 0!==E&&E!==(null==N?void 0:N.is_default_enabled),R=function(n,t){if(!n)return t;if(!t)return n;var i=e({},n);for(var r in t)t[r]&&"object"==typeof t[r]&&!Array.isArray(t[r])?i[r]=e(e({},i[r]||{}),t[r]):i[r]=t[r];return i};if(Wt(function(e){return R(e,S)}),O||L){Wt(function(e){return R(e,S)});var D=function(e,n,t,i){var r,a,o,l,s=[],u=(i.get(e)||new Map).get(n)||{order_rules:{enabled:!1,global_min_separation_seconds:0},advertiser_rules:{enabled:!1,global_min_separation_seconds:0},inventory_rules:{respect_inventory_code:!1},break_code_rules:{respect_break_code:!1}};return Math.floor(((null===(r=t.order_rules)||void 0===r?void 0:r.global_min_separation_seconds)||0)/60)!==u.order_rules.global_min_separation_seconds&&s.push("config_order_rules"),Math.floor(((null===(a=t.advertiser_rules)||void 0===a?void 0:a.global_min_separation_seconds)||0)/60)!==u.advertiser_rules.global_min_separation_seconds&&s.push("config_advertiser_rules"),!!(null===(o=t.inventory_rules)||void 0===o?void 0:o.respect_inventory_code)!==u.inventory_rules.respect_inventory_code&&s.push("config_inventory_rules"),!!(null===(l=t.break_code_rules)||void 0===l?void 0:l.respect_break_code)!==u.break_code_rules.respect_break_code&&s.push("config_break_code_rules"),!!t.is_default_enabled!=!!u.is_default_enabled&&s.push("config_is_default_enabled"),s}(r,o,S,Wn);D.forEach(function(e){return hr(r,o,e)}),Qn(function(e){return new Set(e).add("config")}),Kn(function(n){var t,i,a,l,s,u,d=new Map(n),c=new Map(d.get(r)||new Map),v=c.get(o)||Hn;return c.set(o,e(e(e(e(e(e({},v),S.order_rules&&{order_rules:{enabled:!!(null===(t=S.order_rules)||void 0===t?void 0:t.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(i=S.order_rules)||void 0===i?void 0:i.global_min_separation_seconds)||0)/60)}}),S.advertiser_rules&&{advertiser_rules:{enabled:!!(null===(a=S.advertiser_rules)||void 0===a?void 0:a.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(l=S.advertiser_rules)||void 0===l?void 0:l.global_min_separation_seconds)||0)/60)}}),S.inventory_rules&&{inventory_rules:{respect_inventory_code:!!(null===(s=S.inventory_rules)||void 0===s?void 0:s.respect_inventory_code)}}),S.break_code_rules&&{break_code_rules:{respect_break_code:!!(null===(u=S.break_code_rules)||void 0===u?void 0:u.respect_break_code)}}),void 0!==E&&{is_default_enabled:E})),d.set(r,c),d}),rt(function(e){var n=new Map(e),t=new Map(n.get(r)||new Map),i=t.get(o)||new Set;return S.order_rules&&i.add("order_rules"),S.advertiser_rules&&i.add("advertiser_rules"),S.inventory_rules&&i.add("inventory_rules"),S.break_code_rules&&i.add("break_code_rules"),void 0!==E&&i.add("is_default_enabled"),t.set(o,i),n.set(r,t),n})}}var j={ruleTitle:t.title,ruleDescription:t.rule_description,whenToApply:t.wta,whenNotToApply:t.wnta,scopeData:t.scope,configData:t.action};t.is_readOnly||v.forEach(function(e){var n=Sr(j[e]),t="ruleTitle"===e||"scopeData"===e?e:"".concat(e,"_").concat(r);n&&(n!==Vn.current[t]&&(Vn.current[t]=n,Gn.current[t]=!0,_[t]={reasoning:n,associatedCitations:[],tier:r,variantIndex:o}))}),t.conflictingConditions&&(Ni(function(n){var i=e({},n);return t.conflictingConditions.forEach(function(e){e.condition_wta&&(i["whenToApply-".concat(r,"-").concat(o)]=e.reason),e.condition_wnta&&(i["whenNotToApply-".concat(r,"-").concat(o)]=e.reason)}),i}),Qn(function(e){return new Set(n(n([],Array.from(e),!0),["conditions"],!1))}))})}});var f=-1,g=!(!ne&&!ie),m="edit"===zi||"edit_current_rule"===zi,w=function(e,n){return(null==e?void 0:e.variant_id)&&e.variant_id===n||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===n||(null==e?void 0:e.id)&&e.id===n},y=function(e,n){if(!n)return-1;var t=e.find(function(e){return w(e,n)});if(!t)return-1;var i=String((null==t?void 0:t.tier_id)||"");if(!i)return e.findIndex(function(e){return w(e,n)});var r=e.filter(function(e){return String((null==e?void 0:e.tier_id)||"")===i}).findIndex(function(e){return w(e,n)});return-1!==r?r:e.findIndex(function(e){return w(e,n)})};if(g)if(wi.current&&Mt)-1!==(f=ft.findIndex(function(e){return(null==e?void 0:e.new_variant_id)&&e.new_variant_id===wi.current||(null==e?void 0:e.variant_id)&&e.variant_id===wi.current||(null==e?void 0:e.id)&&e.id===wi.current}))&&(wi.current=null);else if($i||nr){var h;(h=$i||nr)&&(f=y(ft,h))}else if(oe&&Array.isArray(ft)&&ft.length>0){for(b=ft.length-1;b>=0;b--)if(ft[b]&&!(null===(i=ft[b])||void 0===i?void 0:i.is_readOnly)){f=b;break}}else null==re||mi.current&&0!==mi.current.length||(f=re);else if((h=$i||nr||wi.current)&&m&&(f=y(ft,h)),!m&&-1===f&&Array.isArray(ft)&&ft.length>0){for(var b=ft.length-1;b>=0;b--)if(ft[b]&&!(null===(t=ft[b])||void 0===t?void 0:t.is_readOnly)){f=b;break}-1===f&&(f=ft.length-1)}-1!==f&&xt!==f&&(yi.current===f||We.current&&!m||(console.log("🎯 Setting active variant accordion to index ".concat(f," (").concat(g?"EDIT":"CREATE"," mode)")),Et(f),yi.current=f));var T=ft[0];if(T){if(T.scope&&JSON.stringify(T.scope)!==JSON.stringify(null===(r=p[0])||void 0===r?void 0:r.scope)&&"copy"!==T.action&&(l=T.scope,s=null===(a=p[0])||void 0===a?void 0:a.scope,u=xr(l),d=s?xr(s):[],ge(function(n){return e(e({},n),{tiers:u})}),u.forEach(function(e){var n=e.trim();d.includes(e)||hr("global",0,"scope_".concat(n))})),T.scope_rule_set&&T.scope_rule_set!==(null===(o=p[0])||void 0===o?void 0:o.scope_rule_set)){var A=T.scope_rule_set.toLowerCase().trim();["global","genre","custom"].includes(A)&&(ge(function(n){return e(e({},n),{station:A})}),hr("global",0,"scope_station"))}T.wtl&&$n(T.wtl)}mi.current=ft.map(function(e){return e?(n=e,"function"==typeof(t=null===globalThis||void 0===globalThis?void 0:globalThis.structuredClone)?t(n):JSON.parse(JSON.stringify(n))):e;var n,t}),Object.keys(_).length>0&&(sr({type:"SAVE_CITATIONS",requestId:c,reasoningMap:_,rawCitations:oi}),function(e){var n=e.requestId,t=e.keys,i=e.newReasoningMap,r=e.getLatestReasoning,a=e.currentCitations;console.group("%c Citation Audit: ".concat(n," "),"background: #5928ed; color: #fff; font-weight: bold;");var o={};t.forEach(function(e){var n=r(e),t=!!i[e],l=t?a:(null==n?void 0:n.associatedCitations)||[];o[e]={Status:t?"NEW ✅":n?"FALLBACK 🔄":"EMPTY ❌",Source:t?"Current Msg":n?"History":"N/A","Reasoning Preview":t?i[e].reasoning:(null==n?void 0:n.reasoning)||"None","Full Citations":l}}),console.table(o),console.groupEnd()}({requestId:c,keys:Object.keys(_),newReasoningMap:_,getLatestReasoning:ur,currentCitations:oi}),ri(function(n){var t=e({},n),i=!1;return Object.keys(_).forEach(function(e){var n=_[e];n.reasoning&&t[e]!==n.reasoning&&(t[e]=n.reasoning,i=!0),n.associatedCitations}),i?t:n}))}},[ft,oi,ui]),d(function(){var t=Object.keys(Gn.current);if(0!==t.length){var i={};t.forEach(function(e){i[e]=n([],oi,!0)}),Gn.current={},_i(function(n){return e(e({},n),i)})}},[oi]);var Er=function(e){return e.map(function(e){var n;return null===(n=e.match(/\d+/))||void 0===n||n[0],e.replace(/\s+/g,"-"),{name:"Custom",parentScopeId:null,scopeRowId:(null==ee?void 0:ee.ruleSetId)||"",value:{scopeName:(null==ee?void 0:ee.ruleSetName)||"",scopeId:"Audacy_"+m(),customScopeGroupName:(null==Un?void 0:Un.CUSTOM_SCOPE_GROUP_NAME)||"",description:(null==ee?void 0:ee.ruleSetDesc)||""}}})},Or=function(e){var n={};return Object.entries(e).forEach(function(e){var t,i=e[0],r=e[1];if("custom_sep_time_for_entities"===i&&r)n.custom_sep_time_for_entities=r;else if("max_priority_override"===i&&r&&void 0!==r.override_priority_code)n.override_priority_code=r.override_priority_code;else if(r&&"object"==typeof r&&(null===(t=Object.keys(r))||void 0===t?void 0:t.length)>0){var a=i.replace(/_rules$/,""),o=["global_min_separation_seconds","respect_inventory_code","respect_break_code","exemption_advertiser_list","exemption_break_code_list","exemption_priority_code_list"];Object.entries(r).forEach(function(e){var t=e[0],r=e[1];if(o.includes(t)&&("product_rules"!==i||"global_min_separation_seconds"!==t)){var l="respect_inventory_code"===t||"respect_break_code"===t?t:"".concat(a,"_").concat(t);n[l]=r}})}else if(void 0!==r&&"object"!=typeof r){if("station_guid"===i||"is_default_enabled"===i)return;n[i]=r}}),{config_structure:{scheduling_config:{advertiser_exemption_advertiser_list:"array",advertiser_exemption_break_code_list:"array",advertiser_exemption_priority_code_list:"array",advertiser_exemption_product_code_list:"array",advertiser_global_min_separation_seconds:"int",break_code_exemption_advertiser_list:"array",break_code_exemption_break_code_list:"array",break_code_exemption_priority_code_list:"array",break_code_exemption_product_code_list:"array",custom_sep_time_for_entities:"object",inventory_exemption_advertiser_list:"array",inventory_exemption_break_code_list:"array",inventory_exemption_priority_code_list:"array",inventory_exemption_product_code_list:"array",order_exemption_advertiser_list:"array",order_exemption_break_code_list:"array",order_exemption_priority_code_list:"array",order_exemption_product_code_list:"array",order_global_min_separation_seconds:"int",override_priority_code:"str",product_exemption_advertiser_list:"array",product_exemption_break_code_list:"array",product_exemption_priority_code_list:"array",product_exemption_product_code_list:"array",max_priority_override_priority_code_list:"array",max_priority_override_exemption_advertiser_list:"array",max_priority_override_exemption_break_code_list:"array",max_priority_override_exemption_priority_code_list:"array",max_priority_override_exemption_product_code_list:"array",first_in_break_exemption_advertiser_list:"array",first_in_break_exemption_break_code_list:"array",first_in_break_exemption_priority_code_list:"array",first_in_break_exemption_product_code_list:"array",first_in_break_condition_advertiser_list:"array",first_in_break_condition_break_code_list:"array",first_in_break_condition_priority_code_list:"array",first_in_break_condition_product_code_list:"array",advertiser_pair_break_constraint:"array",respect_break_code:"bool",respect_inventory_code:"bool"}},config_data:{scheduling_config:n}}},Lr=function(n,t,i,r){void 0===r&&(r=0);var a=e({},t||{});return n.forEach(function(n,o){var l=n.get(r);l&&l.forEach(function(n){var l,s=t[n]||{},u=i.get(o),d=null==u?void 0:u.get(r),c=null==d?void 0:d[n];if("order_rules"===n||"advertiser_rules"===n){var v=null!==(l=null==c?void 0:c.enabled)&&void 0!==l&&l?60*((null==c?void 0:c.global_min_separation_seconds)||0):0;a[n]=e(e({},s),{global_min_separation_seconds:v})}else a[n]="inventory_rules"===n?e(e({},s),{respect_inventory_code:null==c?void 0:c.respect_inventory_code}):"break_code_rules"===n?e(e({},s),{respect_break_code:null==c?void 0:c.respect_break_code}):"is_default_enabled"===n?null!=c&&c:s})}),a},Rr=function(e,n,t){void 0===t&&(t="variantType");var i=null==e?void 0:e[n];if(!i)return{label:Mr(e),isDefault:!1};var r=i[t]||"",a=U(r);return{label:"variant ".concat(n+1),isDefault:a}},Dr=function(e,n){var t=U(e);return{label:"variant ".concat(n+1),isDefault:t}},jr=function(e,n,t){var i;void 0===t&&(t="");var r=null===(i=Wn.get(e))||void 0===i?void 0:i.get(n);return r?r.is_default_enabled?"Default":"Variant":U(t)?"Default":"Variant"},Vr=function(n,o){return void 0===o&&(o=!1),t(void 0,void 0,void 0,function(){var t,l,s,u,d,c,v,p,g,w,h,b,T,A,k,S,C;return i(this,function(i){switch(i.label){case 0:t=Er(fe.tiers),l=M.getState().backwardCompatibility,s=en.current,u=Lr(it,Bt,Wn,s),i.label=1;case 1:return i.trys.push([1,3,,4]),ye(G),Se(""),d=Or(u),c=m(),v=[],p=[],g=(ft||[])[s]||{},console.log("originalItem check :",g,s),fe.tiers.forEach(function(i){var r,a,o,u,_,f,w,h,b,T,A,M,I,k,S,C=i.toLowerCase().replace(/ /g,"_");p.push(C);var N=(null===(r=ot.get(C))||void 0===r?void 0:r.get(s))||"",x=(null===(a=ut.get(C))||void 0===a?void 0:a.get(s))||[],E=(null===(o=vt.get(C))||void 0===o?void 0:o.get(s))||[];if(!1===l){var O=[e(e({},d&&{config:e({master_name:Un.CONFIG_MASTER_NAME},d)}),{datasource:{type:"link",ref:"www.something.com",tag:"something"},tierLinkId:c,variant:Cr(N),conditions_whentoapply:x.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),conditions_whennottoapply:E.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),isDefault:null===(f=null===(_=null===(u=Wn.get(C))||void 0===u?void 0:u.get(s))||void 0===_?void 0:_.is_default_enabled)||void 0===f||f,tier_id:(null===(w=je.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===C||e.tier_name.toLowerCase()===C.replace(/_/g,"")}))||void 0===w?void 0:w.tier_id)||"",topic_id:null,scope_id:(null==ee?void 0:ee.ruleSetId)||"",question_title:et,variantType:jr(C,s,g.variant_type||g.variantType),instantLearningType:Un.INSTANT_LEARNING_TYPE,is_user_accepted_risk:!1,propagation:!1,applicationMappingId:_e,modeId:"019e1e39-2030-7775-8312-0ad525700588"})];v.push(y(O,Un.ASSISTANT_NAME))}else{O={status:"approved",metadata:e(e({userName:null!==(h=null==or?void 0:or.firstname)&&void 0!==h?h:"",userEmailId:null!==(b=null==or?void 0:or.email)&&void 0!==b?b:"",llm:D.MODEL,isVariantFlow:!0},d&&{config:e({master_name:D.CONFIG_MASTER_NAME},d)}),{datasource:{type:"link",ref:"www.something.com",tag:"something"},variant:{tierLinkId:c,variant:Cr(N),conditions_whentoapply:x.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),conditions_whennottoapply:E.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),referenceVariantID:null,referenceVariantIDVersion:null,scope:t[0]||{name:D.SCOPE_NAME,parentScopeId:null,scopeRowId:(null==ee?void 0:ee.ruleSetId)||"",value:{scopeName:(null==ee?void 0:ee.ruleSetName)||"",scopeId:"Audacy_"+m(),customScopeGroupName:D.CUSTOM_SCOPE_GROUP_NAME,description:(null==ee?void 0:ee.ruleSetDesc)||""}},overriden:!1,isDefault:null===(M=null===(A=null===(T=Wn.get(C))||void 0===T?void 0:T.get(s))||void 0===A?void 0:A.is_default_enabled)||void 0===M||M,tier:{name:i.split(" ").join("").toLowerCase(),tierGroupName:D.CUSTOM_SCOPE_GROUP_NAME,tierPriority:parseInt(i.split(" ")[1]||"1"),tier_id:(null===(I=je.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===C||e.tier_name.toLowerCase()===C.replace(/_/g,"")}))||void 0===I?void 0:I.tier_id)||""},topic:{id:null,value:"".concat(fe.station||X,"RuleSet"),description:null},categories:[{id:null,value:D.CATEGORY,description:D.CATEGORY}],originalQuestion:et,questionId:n.get(C)||null,variantType:jr(C,s,g.variant_type||g.variantType),parameterizedQuestion:null,created_at:(new Date).toISOString(),created_by:null!==(k=null==or?void 0:or.email)&&void 0!==k?k:"",instantLearningType:D.INSTANT_LEARNING_TYPE,appliedTagsIL:[],tagMappingInfoIL:{},is_user_accepted_risk:!!(null!==(S=null==g?void 0:g.is_user_accepted_risk)&&void 0!==S?S:null==jt?void 0:jt.is_user_accepted_risk)},isAgentsFeedback:!0})};v.push(y(O,Un.ASSISTANT_NAME))}}),[4,Promise.all(v)];case 2:return w=i.sent(),Re(!1),console.log("✅ All feedback published:",w),ye(P),Te(!0),h=new Map,w.forEach(function(e,n){var t,i,r=p[n],a=(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.id)||(null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.variant_id)&&e.data.variant_id||(null==e?void 0:e.id)||(null==e?void 0:e.variant_id)&&e.variant_id;if(a||"string"!=typeof(null==e?void 0:e.data)||(a=e.data),a&&"string"==typeof a){var o=h.get(r)||[];o.push({id:a,action:"new"}),h.set(r,o)}}),M.getState().setCreatedVariantInfo(Array.from(h.entries()).map(function(e){return{tierName:e[0],variants:e[1]}})),null===(k=hi.current)||void 0===k||k.show({severity:"success",sticky:!1,life:6e3,className:I.toastSuccess,content:r("div",e({className:I.toastContent},{children:[r("div",e({className:I.toastHeaderLeft},{children:[a(f,{className:I.iconSuccess}),a("span",e({className:"".concat(I.toastTitle," ").concat(I.toastTitleSuccess)},{children:"Success"}))]})),a("p",e({className:"".concat(I.toastMessage," ").concat(I.toastMessageSuccess)},{children:"Learning saved successfully!"}))]}))}),Ee.current=setTimeout(function(){Ri||o?(console.log("Closing modal after save success",{isCloseModal:Ri,forceClose:o}),ia()):Ar(!0)},3e3),[3,4];case 3:return b=i.sent(),console.error("❌ Error publishing feedback:",b),Re(!1),ye(F),xe(!0),T=(null===(S=null==b?void 0:b.response)||void 0===S?void 0:S.data)||{},console.log("errorData: ",T),(A="Variant already exists"===(null==T?void 0:T.message))||409===(null==b?void 0:b.status)?Se('Looks like a similar rule already exists with the same conditions. You can update the description or conditions to make it unique, or discard this learning. <br/> How would you like to proceed?\n <br/><button class="clickable-button" data-value="Discard learning">Discard learning</button>\n <br/><button class="clickable-button" data-value="Continue editing learning">Continue editing learning</button>\n <br/><button class="clickable-button" id="typeYourAnswer">Or, type your response</button>'):Se(((null==T?void 0:T.message)||(null==T?void 0:T.detail)||"Error Occurred while saving the rule.")+'Please try again.<br/><button class="clickable-button" data-value="Save this Learning">Retry</button>'),null===(C=hi.current)||void 0===C||C.show({severity:"error",sticky:!1,className:I.toastError,content:r("div",e({className:I.toastContent},{children:[r("div",e({className:I.toastHeaderLeft},{children:[a(_,{className:I.iconError}),a("span",e({className:"".concat(I.toastTitle," ").concat(I.toastTitleError)},{children:"Error"}))]})),a("p",e({className:"".concat(I.toastMessage," ").concat(I.toastMessageError)},{children:A||409===(null==b?void 0:b.status)?"Similar rule already exists. Please update and try again.":(null==T?void 0:T.message)||(null==T?void 0:T.detail)||"Something went wrong while saving the learning!"}))]}))}),[3,4];case 4:return[2]}})})},Pr=function(){return t(void 0,void 0,void 0,function(){var t,o,l,s,u,d,c,v,p,g,w,b,T,A,k,S,C,N,x,E,O,L,R,D,j,V;return i(this,function(i){switch(i.label){case 0:t=M.getState().tiers,o=Lr(it,Bt,Wn),l=Or(o),s=en.current,u=(ft||[])[s]||{},d=(null==jt?void 0:jt.variant_type)||u.variant_type||"",i.label=1;case 1:for(i.trys.push([1,3,,4]),ye(G),Se(""),v=(c=ie||[]).length>0?null===(O=c.find(function(e){return(null==e?void 0:e.link_id)&&""!==e.link_id.trim()}))||void 0===O?void 0:O.link_id:null,p=(null===(L=fe.tiers[0])||void 0===L?void 0:L.toLowerCase().replace(/ /g,"_"))||"tier_1",g=(null===(R=ot.get(p))||void 0===R?void 0:R.size)||c.length,w=n([],c,!0),b=c.length;b<g;b++)w.push({isNewVariant:!0,variantId:m()});return T=[],A=[],k=Er(fe.tiers),fe.tiers.forEach(function(n){var i=n.toLowerCase().replace(/ /g,"_"),r=t.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===i||e.tier_name.toLowerCase()===i.replace(/_/g,"")}),a=ot.get(i),o=ut.get(i),s=vt.get(i);w.forEach(function(t,c){var _,p,f,g,w,b,M,I,S,C,N,x,E,O,L,R,D,j,V,P,F,G,J,H,B,W,K,Y,z=(null==a?void 0:a.get(c))||t.description||"",Q=(null==o?void 0:o.get(c))||[],Z=(null==s?void 0:s.get(c))||[];if(t.isNewVariant){A.push({tierKey:i,payloadType:"new"});var $=Lr(it,Bt,Wn,c),X=Or($);console.log("variant in save edit add part :",t,u);var te={status:"approved",metadata:e(e({userName:null!==(_=null==or?void 0:or.firstname)&&void 0!==_?_:"",userEmailId:null!==(p=null==or?void 0:or.email)&&void 0!==p?p:"",llm:Un.MODEL,isVariantFlow:!0},X&&{config:e({master_name:Un.CONFIG_MASTER_NAME},X)}),{datasource:{type:"link",ref:"www.something.com",tag:"something"},variant:{tierLinkId:v||m(),variant:Cr(z),conditions_whentoapply:Q.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),conditions_whennottoapply:Z.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),referenceVariantID:null,referenceVariantIDVersion:null,scope:k[0]||{name:Un.SCOPE_NAME,parentScopeId:null,scopeRowId:(null==ee?void 0:ee.ruleSetId)||"",value:{scopeName:(null==ee?void 0:ee.ruleSetName)||"",scopeId:"Audacy_"+m(),customScopeGroupName:Un.CUSTOM_SCOPE_GROUP_NAME,description:(null==ee?void 0:ee.ruleSetDesc)||""}},overriden:!1,isDefault:null!==(w=null===(g=null===(f=Wn.get(i))||void 0===f?void 0:f.get(c))||void 0===g?void 0:g.is_default_enabled)&&void 0!==w?w:U(t.variantType||t.variant_type||(0===c?"Default":"variant")),tier:{name:n.split(" ").join("").toLowerCase(),tierGroupName:Un.CUSTOM_SCOPE_GROUP_NAME,tierPriority:parseInt(n.split(" ")[1]||"1")},topic:{id:null,value:"".concat(fe.station,"RuleSet"),description:null},categories:[{id:null,value:Un.CATEGORY,description:Un.CATEGORY}],originalQuestion:et,questionId:null==ne?void 0:ne.ruleId,variantType:jr(i,c,u.variant_type||""),parameterizedQuestion:null,created_at:(new Date).toISOString(),created_by:null!==(b=null==or?void 0:or.email)&&void 0!==b?b:"",instantLearningType:Un.INSTANT_LEARNING_TYPE,appliedTagsIL:[],tagMappingInfoIL:{},is_user_accepted_risk:!!(null!==(I=null===(M=(ft||[])[c])||void 0===M?void 0:M.is_user_accepted_risk)&&void 0!==I?I:null==jt?void 0:jt.is_user_accepted_risk)},isAgentsFeedback:!0})};console.log("payload (publish new variant)",te),T.push(y(te,Un.ASSISTANT_NAME))}else{A.push({tierKey:i,payloadType:"existing",existingId:t.variantId});var ie=t.variantId===$i,re=jr(i,c,ie?d||t.variantType||"":t.variantType||"");console.log("isThisVariantBeingEdited variantTypeToUse :",re,ie,t,$i);var ae={variantId:t.variantId,ruleDesc:(null==ee?void 0:ee.ruleSetDesc)||"",whenToApply:Q.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),whenNotToApply:Z.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),isDefault:null!==(N=null===(C=null===(S=Wn.get(i))||void 0===S?void 0:S.get(c))||void 0===C?void 0:C.is_default_enabled)&&void 0!==N?N:U(t.variantType||t.variant_type||(0===c?"Default":"variant")),tier:{tier_id:(null==r?void 0:r.tier_id)||"",tier_name:(null==r?void 0:r.tier_name)||n,tier_priority:null!==(x=null==r?void 0:r.tier_priority)&&void 0!==x?x:null},scope_id:(null==ee?void 0:ee.ruleSetId)||"",description:Cr(z)||"",topic:"".concat(fe.station,"RuleSet"),configuration:(null==l?void 0:l.config_data)||{},tierLinkId:null!=v?v:null,variantType:re,is_user_accepted_risk:!!(null!==(O=null===(E=(ft||[])[c])||void 0===E?void 0:E.is_user_accepted_risk)&&void 0!==O?O:null==t?void 0:t.is_user_accepted_risk),is_enabled:t.is_enabled},oe=(wt.get(i)||[]).find(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===t.variantId}),le=!0;if(oe){var se=function(e){var n=(e||"").trim();return(n=q(n)).replace(/\s+/g," ").replace(/(\s*OR\s*)/g," OR ")},ue=se(et)===se(oe.title),de=se(z)===se(oe.rule_description),ce=se(ae.whenToApply)===se(oe.wta),ve=se(ae.whenNotToApply)===se(oe.wnta),_e=!!ae.isDefault===U(oe.variant_type),pe=oe.scheduling_config||{},ge=null!==(D=null!==(L=pe.order_global_min_separation_seconds)&&void 0!==L?L:null===(R=pe.order_rules)||void 0===R?void 0:R.global_min_separation_seconds)&&void 0!==D?D:0,me=null!==(P=null!==(j=pe.advertiser_global_min_separation_seconds)&&void 0!==j?j:null===(V=pe.advertiser_rules)||void 0===V?void 0:V.global_min_separation_seconds)&&void 0!==P?P:0,we=null!==(J=null!==(G=null===(F=pe.inventory_rules)||void 0===F?void 0:F.respect_inventory_code)&&void 0!==G?G:pe.respect_inventory_code)&&void 0!==J&&J,ye=null!==(W=null!==(B=null===(H=pe.break_code_rules)||void 0===H?void 0:H.respect_break_code)&&void 0!==B?B:pe.respect_break_code)&&void 0!==W&&W,he=(null===(K=Wn.get(i))||void 0===K?void 0:K.get(c))||Hn,be=he.order_rules.enabled===ge>0&&he.order_rules.global_min_separation_seconds===Math.floor(ge/60)&&he.advertiser_rules.enabled===me>0&&he.advertiser_rules.global_min_separation_seconds===Math.floor(me/60)&&he.inventory_rules.respect_inventory_code===we&&he.break_code_rules.respect_break_code===ye;ue&&de&&ce&&ve&&_e&&be&&(le=!1)}le?(console.log("payloadv (update existing variant)",ae),T.push(h(ae,null!==(Y=null==or?void 0:or.email)&&void 0!==Y?Y:""))):(console.log("[saveEditedVariant] No changes for variant ".concat(t.variantId,", skipping API call")),T.push(Promise.resolve({data:{id:t.variantId},skipped:!0})))}})}),[4,Promise.all(T)];case 2:return S=i.sent(),console.log("✅ All variants updated:",S),ye(P),Te(!0),Re(!1),C=new Map,S.forEach(function(e,n){var t,i;if(!(null==e?void 0:e.skipped)){var r=A[n],a=(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.id)||(null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.variant_id)||(null==e?void 0:e.id)||(null==e?void 0:e.variant_id);a||"string"!=typeof(null==e?void 0:e.data)||(a=e.data);var o="existing"===r.payloadType?r.existingId:a;if(o&&"string"==typeof o){var l=C.get(r.tierKey)||[];l.push({id:o,action:r.payloadType}),C.set(r.tierKey,l)}}}),M.getState().setCreatedVariantInfo(Array.from(C.entries()).map(function(e){return{tierName:e[0],variants:e[1]}})),null===(D=hi.current)||void 0===D||D.show({severity:"success",sticky:!1,life:3e3,className:I.toastSuccess,content:r("div",e({className:I.toastContent},{children:[r("div",e({className:I.toastHeaderLeft},{children:[a(f,{className:I.iconSuccess}),a("span",e({className:"".concat(I.toastTitle," ").concat(I.toastTitleSuccess)},{children:"Success"}))]})),a("p",e({className:"".concat(I.toastMessage," ").concat(I.toastMessageSuccess)},{children:"Changes saved successfully!"}))]}))}),Ee.current=setTimeout(function(){ia()},3e3),[3,4];case 3:return N=i.sent(),console.error("❌ Error updating variant:",N),ye(F),xe(!0),Re(!1),x=(null===(j=null==N?void 0:N.response)||void 0===j?void 0:j.data)||{},console.log("errorData: ",x),(E="Variant already exists"===(null==x?void 0:x.message))||409===(null==N?void 0:N.status)?Se('Looks like a similar rule already exists with the same conditions. You can update the description or conditions to make it unique, or discard this learning. <br/> How would you like to proceed?\n <br/><button class="clickable-button" data-value="Discard learning">Discard learning</button>\n <br/><button class="clickable-button" data-value="Continue editing learning">Continue editing learning</button>\n <br/><button class="clickable-button" id="typeYourAnswer">Or, type your response</button>'):Se(((null==x?void 0:x.message)||(null==x?void 0:x.detail)||"Error Occurred while saving the rule.")+'Please try again.<br/><button class="clickable-button" data-value="Save this Learning">Retry</button>'),null===(V=hi.current)||void 0===V||V.show({severity:"error",sticky:!1,className:I.toastError,content:r("div",e({className:I.toastContent},{children:[r("div",e({className:I.toastHeaderLeft},{children:[a(_,{className:I.iconError}),a("span",e({className:"".concat(I.toastTitle," ").concat(I.toastTitleError)},{children:"Error"}))]})),a("p",e({className:"".concat(I.toastMessage," ").concat(I.toastMessageError)},{children:E||409===(null==N?void 0:N.status)?"Similar rule already exists. Please update and try again.":(null==x?void 0:x.message)||(null==x?void 0:x.detail)||"Something went wrong while saving the learning!"}))]}))}),[3,4];case 4:return[2]}})})},Fr=function(){return t(void 0,void 0,void 0,function(){var n,t,o,l,s,u,d,c,v,p,g,w,b,T,A,k,S,C,N,x,E,O,L,R,D,j,V;return i(this,function(i){switch(i.label){case 0:n=M.getState().tiers,t=Lr(it,Bt,Wn),o=Or(t),i.label=1;case 1:return i.trys.push([1,9,,10]),ye(G),Se(""),0===(l=Array.isArray(ft)?ft:[]).length?(console.warn("No variants found to save."),ye(F),[2]):(s=l.filter(function(e){return e.is_new_variant}),u=l.filter(function(e){return!e.is_new_variant&&(null==e?void 0:e.variant_id)}),console.log("[saveLoadAndEditVariant] New: ".concat(s.length,", Existing: ").concat(u.length)),d=u.length>0?null===(R=u.find(function(e){return(null==e?void 0:e.link_id)&&""!==e.link_id.trim()}))||void 0===R?void 0:R.link_id:null,c=[],v=[],p=[],g=[],w=Er(fe.tiers),fe.tiers.forEach(function(t){var i=t.toLowerCase().replace(/ /g,"_"),r=n.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===i||e.tier_name.toLowerCase()===i.replace(/_/g,"")}),a=ot.get(i),s=ut.get(i),u=vt.get(i);l.forEach(function(n,l){var _,f,y,b,T,A,M,I,k,S,C,N,x,E,O,L,R,D,j,V,P,F,G,J,H,B,W,K=(null==a?void 0:a.get(l))||n.rule_description||n.description||"",Y=(null==s?void 0:s.get(l))||[],z=(null==u?void 0:u.get(l))||[];if(n.is_new_variant){var Q=Lr(it,Bt,Wn,l),Z=Or(Q),$=jr(i,l,n.variant_type||n.variantType||""),ne={status:"approved",metadata:e(e({userName:null!==(_=null==or?void 0:or.firstname)&&void 0!==_?_:"",userEmailId:null!==(f=null==or?void 0:or.email)&&void 0!==f?f:"",llm:Un.MODEL,isVariantFlow:!0},Z&&{config:e({master_name:Un.CONFIG_MASTER_NAME},Z)}),{datasource:{type:"link",ref:"www.something.com",tag:"something"},variant:{tierLinkId:d||m(),variant:Cr(K),conditions_whentoapply:Y.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),conditions_whennottoapply:z.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),referenceVariantID:null,referenceVariantIDVersion:null,scope:w[0]||{name:Un.SCOPE_NAME,parentScopeId:null,scopeRowId:(null==ee?void 0:ee.ruleSetId)||"",value:{scopeName:(null==ee?void 0:ee.ruleSetName)||"",scopeId:"Audacy_"+m(),customScopeGroupName:Un.CUSTOM_SCOPE_GROUP_NAME,description:(null==ee?void 0:ee.ruleSetDesc)||""}},overriden:!1,isDefault:null!==(T=null===(b=null===(y=Wn.get(i))||void 0===y?void 0:y.get(l))||void 0===b?void 0:b.is_default_enabled)&&void 0!==T?T:U(n.variantType||n.variant_type||(0===l?"Default":"variant")),tier:{name:t.split(" ").join("").toLowerCase(),tierGroupName:Un.CUSTOM_SCOPE_GROUP_NAME,tierPriority:parseInt(t.split(" ")[1]||"1"),tier_id:(null==r?void 0:r.tier_id)||""},topic:{id:null,value:"".concat(fe.station||X,"RuleSet"),description:null},categories:[{id:null,value:Un.CATEGORY,description:Un.CATEGORY}],originalQuestion:et,questionId:Rn.current||null,variantType:$,parameterizedQuestion:null,created_at:(new Date).toISOString(),created_by:null!==(A=null==or?void 0:or.email)&&void 0!==A?A:"",instantLearningType:Un.INSTANT_LEARNING_TYPE,appliedTagsIL:[],tagMappingInfoIL:{},is_user_accepted_risk:!!(null!==(M=null==n?void 0:n.is_user_accepted_risk)&&void 0!==M?M:null==jt?void 0:jt.is_user_accepted_risk)},isAgentsFeedback:!0})};console.log("[saveLoadAndEditVariant] publish payload (new variant)",ne),v.push({payload:ne,tierKey:i}),g.push({tierKey:i})}else if(null==n?void 0:n.variant_id){p.push({tierKey:i,existingId:n.variant_id});var te=(null==n?void 0:n.variant_id)&&n.variant_id===rr?(null==jt?void 0:jt.variant_type)||n.variant_type||n.variantType||"":n.variant_type||n.variantType||"",ie=($=jr(i,l,te),{variantId:n.variant_id,ruleDesc:(null==ee?void 0:ee.ruleSetDesc)||"",whenToApply:Y.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),whenNotToApply:z.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),isDefault:null!==(S=null===(k=null===(I=Wn.get(i))||void 0===I?void 0:I.get(l))||void 0===k?void 0:k.is_default_enabled)&&void 0!==S?S:U(n.variantType||n.variant_type||(0===l?"Default":"variant")),tier:{tier_id:(null==r?void 0:r.tier_id)||"",tier_name:(null==r?void 0:r.tier_name)||t,tier_priority:null!==(C=null==r?void 0:r.tier_priority)&&void 0!==C?C:null},scope_id:(null==ee?void 0:ee.ruleSetId)||"",description:Cr(K)||"",topic:"".concat(fe.station,"RuleSet"),configuration:(null==o?void 0:o.config_data)||{},tierLinkId:null!=d?d:null,variantType:$,is_user_accepted_risk:!!(null!==(N=null==n?void 0:n.is_user_accepted_risk)&&void 0!==N?N:null===(x=(ft||[])[l])||void 0===x?void 0:x.is_user_accepted_risk),is_enabled:n.is_enabled}),re=(wt.get(i)||[]).find(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===(null==n?void 0:n.variant_id)}),ae=!0;if(re){var oe=function(e){var n=(e||"").trim();return(n=q(n)).replace(/\s+/g," ").replace(/(\s*OR\s*)/g," OR ")},le=oe(et)===oe(re.title),se=oe(K)===oe(re.rule_description),ue=oe(ie.whenToApply)===oe(re.wta),de=oe(ie.whenNotToApply)===oe(re.wnta),ce=!!ie.isDefault===U(re.variant_type),ve=re.scheduling_config||{},_e=null!==(L=null!==(E=ve.order_global_min_separation_seconds)&&void 0!==E?E:null===(O=ve.order_rules)||void 0===O?void 0:O.global_min_separation_seconds)&&void 0!==L?L:0,pe=null!==(j=null!==(R=ve.advertiser_global_min_separation_seconds)&&void 0!==R?R:null===(D=ve.advertiser_rules)||void 0===D?void 0:D.global_min_separation_seconds)&&void 0!==j?j:0,ge=null!==(F=null!==(P=null===(V=ve.inventory_rules)||void 0===V?void 0:V.respect_inventory_code)&&void 0!==P?P:ve.respect_inventory_code)&&void 0!==F&&F,me=null!==(H=null!==(J=null===(G=ve.break_code_rules)||void 0===G?void 0:G.respect_break_code)&&void 0!==J?J:ve.respect_break_code)&&void 0!==H&&H,we=(null===(B=Wn.get(i))||void 0===B?void 0:B.get(l))||Hn,ye=we.order_rules.enabled===_e>0&&we.order_rules.global_min_separation_seconds===Math.floor(_e/60)&&we.advertiser_rules.enabled===pe>0&&we.advertiser_rules.global_min_separation_seconds===Math.floor(pe/60)&&we.inventory_rules.respect_inventory_code===ge&&we.break_code_rules.respect_break_code===me;le&&se&&ue&&de&&ce&&ye&&(ae=!1)}ae?(console.log("[saveLoadAndEditVariant] update payload (existing variant)",ie),c.push(h(ie,null!==(W=null==or?void 0:or.email)&&void 0!==W?W:""))):(console.log("[saveLoadAndEditVariant] No changes for variant ".concat(n.variant_id,", skipping API call")),c.push(Promise.resolve({data:{id:n.variant_id},skipped:!0})))}})}),[4,Promise.all(c)]);case 2:b=i.sent(),console.log("✅ All existing variants updated:",b),T=[],A=0,k=v,i.label=3;case 3:if(!(A<k.length))return[3,8];S=k[A],i.label=4;case 4:return i.trys.push([4,6,,7]),[4,y(S.payload,Un.ASSISTANT_NAME)];case 5:return C=i.sent(),T.push(C),[3,7];case 6:throw N=i.sent(),console.error("❌ Error publishing new variant:",N),N;case 7:return A++,[3,3];case 8:return console.log("✅ All new variants published:",T),x=new Map,b.forEach(function(e,n){var t,i;if(!(null==e?void 0:e.skipped)){var r=p[n],a=(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.id)||(null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.variant_id)&&e.data.variant_id||(null==e?void 0:e.id)||(null==e?void 0:e.variant_id)&&e.variant_id;a||"string"!=typeof(null==e?void 0:e.data)||(a=e.data);var o=r.existingId||a;if(o&&"string"==typeof o){var l=x.get(r.tierKey)||[];l.push({id:o,action:"existing"}),x.set(r.tierKey,l)}}}),T.forEach(function(e,n){var t,i,r=g[n],a=(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.id)||(null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.variant_id)&&e.data.variant_id||(null==e?void 0:e.id)||(null==e?void 0:e.variant_id)&&e.variant_id;if(a||"string"!=typeof(null==e?void 0:e.data)||(a=e.data),a&&"string"==typeof a){var o=x.get(r.tierKey)||[];o.push({id:a,action:"new"}),x.set(r.tierKey,o)}}),M.getState().setCreatedVariantInfo(Array.from(x.entries()).map(function(e){return{tierName:e[0],variants:e[1]}})),ye(P),Te(!0),Re(!1),We.current=!1,null===(D=hi.current)||void 0===D||D.show({severity:"success",sticky:!1,life:3e3,className:I.toastSuccess,content:r("div",e({className:I.toastContent},{children:[r("div",e({className:I.toastHeaderLeft},{children:[a(f,{className:I.iconSuccess}),a("span",e({className:"".concat(I.toastTitle," ").concat(I.toastTitleSuccess)},{children:"Success"}))]})),a("p",e({className:"".concat(I.toastMessage," ").concat(I.toastMessageSuccess)},{children:"Changes saved successfully!"}))]}))}),Ee.current=setTimeout(function(){ia()},3e3),[3,10];case 9:return E=i.sent(),console.error("❌ Error updating variant:",E),ye(F),xe(!0),Re(!1),O=(null===(j=null==E?void 0:E.response)||void 0===j?void 0:j.data)||{},console.log("errorData: ",O),(L="Variant already exists"===(null==O?void 0:O.message))||409===(null==E?void 0:E.status)?Se('Looks like a similar rule already exists with the same conditions. You can update the description or conditions to make it unique, or discard this learning. <br/> How would you like to proceed?\n <br/><button class="clickable-button" data-value="Discard learning">Discard learning</button>\n <br/><button class="clickable-button" data-value="Continue editing learning">Continue editing learning</button>\n <br/><button class="clickable-button" id="typeYourAnswer">Or, type your response</button>'):Se(((null==O?void 0:O.message)||(null==O?void 0:O.detail)||"Error Occurred while saving the rule.")+'Please try again.<br/><button class="clickable-button" data-value="Save this Learning">Retry</button>'),null===(V=hi.current)||void 0===V||V.show({severity:"error",sticky:!1,className:I.toastError,content:r("div",e({className:I.toastContent},{children:[r("div",e({className:I.toastHeaderLeft},{children:[a(_,{className:I.iconError}),a("span",e({className:"".concat(I.toastTitle," ").concat(I.toastTitleError)},{children:"Error"}))]})),a("p",e({className:"".concat(I.toastMessage," ").concat(I.toastMessageError)},{children:L||409===(null==E?void 0:E.status)?"Similar rule already exists. Please update and try again.":(null==O?void 0:O.message)||(null==O?void 0:O.detail)||"Something went wrong while saving the learning!"}))]}))}),[3,10];case 10:return[2]}})})},Gr=function(e){return"string"!=typeof e?e:e.replace(/<conflicting_text>[\s\S]*?<\/conflicting_text>/g,"").replace(/<decision_strength>[\s\S]*?<\/decision_strength>/g,"").replace(/<conflicting_reasoning>[\s\S]*?<\/conflicting_reasoning>/g,"").replace(/<conflicting_gap>[\s\S]*?<\/conflicting_gap>/g,"").replace(/<\/?conflicting>/g,"").trim()};d(function(){Vi&&!fi&&(console.log("isSaveRule received from agent — calling publish APIs directly."),Pi(!1),ne||ie?Pr():!0===We.current?Fr():t(void 0,void 0,void 0,function(){var e,n,t,r,a,o,l,s;return i(this,function(u){switch(u.label){case 0:u.trys.push([0,5,,6]),ye(G),e=new Map,n=function(n){var t,r,a,o,l,u;return i(this,function(i){switch(i.label){case 0:if(t=n.toLowerCase().replace(/ /g,"_"),r=je.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===t||e.tier_name.toLowerCase()===t.replace(/_/g,"")}),!(a=null==r?void 0:r.tier_id))return e.set(t,null),[2,"continue"];o={question:et,orgName:Un.ORGANIZATION_NAME,scope_id:(null==ee?void 0:ee.ruleSetId)||"",tier_id:a},i.label=1;case 1:return i.trys.push([1,3,,4]),[4,w(o)];case 2:return l=i.sent(),e.set(t,(null===(s=null==l?void 0:l.data)||void 0===s?void 0:s.id)||null),console.log("✅ Question saved for ".concat(n,":"),l),[3,4];case 3:return u=i.sent(),console.error("❌ Error saving question for ".concat(n,":"),u),e.set(t,null),[3,4];case 4:return[2]}})},t=0,r=fe.tiers,u.label=1;case 1:return t<r.length?(a=r[t],[5,n(a)]):[3,4];case 2:u.sent(),u.label=3;case 3:return t++,[3,1];case 4:return Vr(e),[3,6];case 5:return o=u.sent(),l=new Map,fe.tiers.forEach(function(e){l.set(e.toLowerCase().replace(/ /g,"_"),null)}),Vr(l),console.error("❌ Error saving Instant Learning Question:",o),[3,6];case 6:return[2]}})}))},[Vi,fi]);var qr=(null===(B=(null===(H=null==fe?void 0:fe.tiers)||void 0===H?void 0:H[0])||te||"Tier 1")||void 0===B?void 0:B.toLowerCase().replace(/ /g,"_"))||"tier_1",Ur=null!==(W=null!=xt?xt:re)&&void 0!==W?W:0,Jr=null!=xt,Hr=Jr?null==ft?void 0:ft[Ur]:null,Br=ft&&(null==ft?void 0:ft.find(function(e){return e&&!e.is_readOnly&&((null==e?void 0:e.new_variant_id)&&Ut.includes(e.new_variant_id)||(null==e?void 0:e.variant_id)&&Ft.includes(e.variant_id))})),Wr=(null==Hr?void 0:Hr.new_variant_id)&&Ut.includes(Hr.new_variant_id)?Hr.new_variant_id:(null==Br?void 0:Br.new_variant_id)&&Ut.includes(Br.new_variant_id)?Br.new_variant_id:"",Kr=!(!ne&&!ie),Yr=function(n){var t={},i=fe.tiers.map(function(e){return null==e?void 0:e.toLowerCase().replace(/ /g,"_")}),r=(null==fe?void 0:fe.station)+"RuleSet",a=i.map(function(e){var n=je.find(function(n){return n.tier_name.toLowerCase().replace(/ /g,"_")===e||n.tier_name.toLowerCase()===e.replace(/_/g,"")});return(null==n?void 0:n.tier_id)||""}).filter(Boolean);return n.forEach(function(n,o){var l,s,u,d,c,v,_=(null==n?void 0:n.variant_id)&&n.variant_id||Ft[o]||"new_variant_".concat(o),p=(null===(l=n.scope)||void 0===l?void 0:l[0])||qr,f=ot.get(p),g=ut.get(p),m=vt.get(p),w=(null==f?void 0:f.get(o))||n.rule_description||"",y=(null==g?void 0:g.get(o))||[],h=y.length>0?y.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" \\n "):n.wta||"",b=(null==m?void 0:m.get(o))||[],T=b.length>0?b.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" \\n "):n.wnta||"",A=Wn.get(p),M=null==A?void 0:A.get(o),I={};M&&Object.keys(M).length>0?I=e(e({},M),{order_rules:e(e({},M.order_rules),{global_min_separation_seconds:60*((null===(s=M.order_rules)||void 0===s?void 0:s.global_min_separation_seconds)||0)}),advertiser_rules:e(e({},M.advertiser_rules),{global_min_separation_seconds:60*((null===(u=M.advertiser_rules)||void 0===u?void 0:u.global_min_separation_seconds)||0)})}):n.scheduling_config&&(I=n.scheduling_config),t[_]={rule_title:et,variant_description:w,wta:h,ruleset_id:(null==ee?void 0:ee.ruleSetId)||"",tier_id:a,wnta:T,scope:i,scope_rule_set:r,scheduling_config:I,is_user_accepted_risk:!(null===(v=null!==(d=null==n?void 0:n.is_user_accepted_risk)&&void 0!==d?d:null===(c=(ft||[])[o])||void 0===c?void 0:c.is_user_accepted_risk)||void 0===v||!v)}}),t};bn&&console.log("customMetaData.ui_state for addvariant flow",Yr(bt));var zr={send_metadata_to_orchestrator:!1,default:["scope"],app_mapping_id:_e,ui_state:Kr?{variants:function(){var n={},t=Wn.get(qr);if(!t)return n;var i=ot.get(qr),r=ut.get(qr),a=vt.get(qr),o=fe.tiers.map(function(e){return null==e?void 0:e.toLowerCase().replace(/ /g,"_")}),l=(null==fe?void 0:fe.station)+"RuleSet",s=o.map(function(e){var n=je.find(function(n){return n.tier_name.toLowerCase().replace(/ /g,"_")===e||n.tier_name.toLowerCase()===e.replace(/_/g,"")});return(null==n?void 0:n.tier_id)||""}).filter(Boolean);return t.forEach(function(u,d){var c,v,_,p,f,g,m=null===(c=null==ie?void 0:ie[d])||void 0===c?void 0:c.variantId,w=(ft||[])[d],y=(null==w?void 0:w.new_variant_id)||"",h=m||y||Ft[d]||"variant_".concat(d),b=(null==i?void 0:i.get(d))||"",T=((null==r?void 0:r.get(d))||[]).map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" \\n ")||"",A=((null==a?void 0:a.get(d))||[]).map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" \\n ")||"",M=t.get(d),I={};M&&Object.keys(M).length>0&&(I=e(e({},M),{order_rules:e(e({},M.order_rules),{global_min_separation_seconds:60*((null===(v=M.order_rules)||void 0===v?void 0:v.global_min_separation_seconds)||0)}),advertiser_rules:e(e({},M.advertiser_rules),{global_min_separation_seconds:60*((null===(_=M.advertiser_rules)||void 0===_?void 0:_.global_min_separation_seconds)||0)})})),n[h]={rule_title:et,variant_description:b,wta:T,ruleset_id:(null==ee?void 0:ee.ruleSetId)||"",tier_id:s,wnta:A,scope:o,scope_rule_set:l,scheduling_config:I,is_user_accepted_risk:!(null===(g=null!==(p=null==w?void 0:w.is_user_accepted_risk)&&void 0!==p?p:null===(f=null==ie?void 0:ie[d])||void 0===f?void 0:f.is_user_accepted_risk)||void 0===g||!g)}}),n}()}:function(){var n,t,i,r,a,o,l=(ft||[]).findIndex(function(e){return!0===e.is_new_variant}),s=-1;return-1!==l?s=l:fn?s=-1:bn||(s=Ur),{new_current_variant:-1!==s?{rule_title:et,rule_description:(null===(n=ot.get(qr))||void 0===n?void 0:n.get(s))||"",wta:(null===(i=null===(t=ut.get(qr))||void 0===t?void 0:t.get(s))||void 0===i?void 0:i.map(function(e){return Gr(e.text)}).filter(function(e){return""!==e}).join(" \\n "))||"",wnta:(null===(a=null===(r=vt.get(qr))||void 0===r?void 0:r.get(s))||void 0===a?void 0:a.map(function(e){return Gr(e.text)}).filter(function(e){return""!==e}).join(" \\n "))||"",scope:fe.tiers.map(function(e){return null==e?void 0:e.toLowerCase().replace(/ /g,"_")}),scope_rule_set:(null==fe?void 0:fe.station)+"RuleSet",scheduling_config:function(){var n,t,i,r=null===(n=Wn.get(qr))||void 0===n?void 0:n.get(s);return r&&0!==Object.keys(r).length?e(e({},r),{order_rules:e(e({},r.order_rules),{global_min_separation_seconds:60*((null===(t=r.order_rules)||void 0===t?void 0:t.global_min_separation_seconds)||0)}),advertiser_rules:e(e({},r.advertiser_rules),{global_min_separation_seconds:60*((null===(i=r.advertiser_rules)||void 0===i?void 0:i.global_min_separation_seconds)||0)})}):{}}(),is_user_accepted_risk:!!(null===(o=(ft||[])[s])||void 0===o?void 0:o.is_user_accepted_risk)}:{rule_title:"",rule_description:"",wta:"",wnta:"",scope:[],scope_rule_set:"",scheduling_config:{},is_user_accepted_risk:!1},variants:bn?Yr(bt):{}}}(),rule_id_in_current_session:St,new_variant_id:function(){var e;return Jr&&ne?(null===(e=null==ie?void 0:ie[Ur])||void 0===e?void 0:e.variantId)?null:Wr:null}(),edit_variant_id:On,rule_id:Rn.current,ruleset_id:(null==ee?void 0:ee.ruleSetId)||"",current_variants_length:ne?Array.isArray(ft)&&ft.length>0?Math.max((null===(K=null==ne?void 0:ne.variants)||void 0===K?void 0:K.length)||0,ft.length):null===(Y=null==ne?void 0:ne.variants)||void 0===Y?void 0:Y.length:void 0,tiers:je,authToken:(null==or?void 0:or.accessToken)||""},Qr=Mr(bt),Zr={ruleTitle:et,scopeData:fe,variantsByTier:Array.from(Wn.keys()).reduce(function(n,t){var i=Wn.get(t)||new Map,r=ot.get(t)||new Map,a=ut.get(t)||new Map,o=vt.get(t)||new Map;return console.log("tier config map",i),n[t]=Array.from(i.keys()).map(function(n,l){var s,u,d=(ft||[])[n]||{};console.log("Original item for tier",t,"index",n,":",d);var c={label:"",isDefault:!1};if(d.is_variant&&!U(d.variant_type))c={label:"",isDefault:!1};else if(ie&&ie.length>0){c=Rr(ie,n,"variantType"),console.log("Found matching variant at index",n,":",c);var v=ie[n];if(v){if(!c.label){var _=v.variantType||"",p=U(_);c={label:"variant ".concat(n+1),isDefault:p}}if(v.variantId===$i)(g=d.variant_type||(null==jt?void 0:jt.variant_type))&&(c=Dr(g,n),console.log("[templateState] editingVariants[".concat(n,']: using CARE variant_type "').concat(g,'" → label "').concat(c.label,'"')));console.log("Computed variant type at index",n,":",c)}else c={label:Mr(ie),isDefault:!1},console.log("No match found, using getNextVariantType:",c)}else if(bt&&bt.length>0){if(c=Rr(bt,n,"variant_type"),console.log("Found matching variant at index",n,":",c),We.current){var f=bt[n];if((null==f?void 0:f.variant_id)===rr||(null==f?void 0:f.variantId)===rr)(g=d.variant_type||(null==jt?void 0:jt.variant_type))&&(c=Dr(g,n),console.log("[templateState] existingVariants[".concat(n,']: load-and-edit using CARE variant_type "').concat(g,'" → label "').concat(c.label,'"')))}}else{var g=d.variant_type||"";c={label:Qr,isDefault:U(g)}}console.log("Computed variant data for tier",t,"index",n,":",c);var m=null!==(u=null===(s=i.get(n))||void 0===s?void 0:s.is_default_enabled)&&void 0!==u?u:c.isDefault;console.log("live is default :",m);var w="variant ".concat(l+1),y=r.get(n)||"";return{variantId:Ft[n]||d.variant_id||d.variantId,variantType:w,isDefault:m,isModified:d.is_modified,tier:t,index:n,ruleDescription:y.replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g,""),whenToApplyConditions:(a.get(n)||[]).flatMap(function(n){var t,i=(null===(t=null==n?void 0:n.text)||void 0===t?void 0:t.split(/\s+OR\s+/))||[];return i.length>1?i.map(function(t,i){return e(e({},n),{id:"split-".concat(n.id,"-").concat(i),text:t.trim()})}):[n]}),whenNotToApplyConditions:(o.get(n)||[]).flatMap(function(n){var t,i=(null===(t=null==n?void 0:n.text)||void 0===t?void 0:t.split(/\s+OR\s+/))||[];return i.length>1?i.map(function(t,i){return e(e({},n),{id:"split-".concat(n.id,"-").concat(i),text:t.trim()})}):[n]}),configData:i.get(n)||Hn,isReadOnly:d.is_readOnly||!1,is_variant:d.is_variant||!1,reasoning:{ruleDescription:Sr(y),whenToApply:Sr(d.wta),whenNotToApply:Sr(d.wnta),configData:Sr(d.action)}}}),n},{}),citation:ii,fieldCitations:vi,citations:oi};console.log("templateState",Zr);var $r={setRuleTitle:function(n){var t,i=void 0!==(null===(t=null==n?void 0:n.target)||void 0===t?void 0:t.value)?n.target.value:n;nt(i),Ni(function(n){if(n.ruleTitle){var t=e({},n);return delete t.ruleTitle,t}return n})},setRuleDescription:function(e,n,t){return vr(e,n,t)},addWhenToApply:function(e,n){return _r(e,n)},removeWhenToApply:function(e,n,t){return pr(e,n,t)},editWhenToApply:function(e,n,t,i){return fr(e,n,t,i)},addWhenNotToApply:function(e,n){return gr(e,n)},removeWhenNotToApply:function(e,n,t){return mr(e,n,t)},editWhenNotToApply:function(e,n,t,i){return wr(e,n,t,i)},addNewVariant:function(e){return yr(e)},onScopeChange:br,onConfigChange:function(e,n,t,i){return Tr(e,n,t,i)}},Xr={},ea={};Wn.forEach(function(n,t){Xr[t]=new Map,ea[t]=new Map,n.forEach(function(n,i){Xr[t].set(i,[e({key:"order_rules",label:"Order"},n.order_rules),e({key:"advertiser_rules",label:"Advertiser"},n.advertiser_rules)]),ea[t].set(i,[{key:"inventory_rules",label:"Inventory code",enabled:n.inventory_rules.respect_inventory_code},{key:"break_code_rules",label:"Break Code",enabled:n.break_code_rules.respect_break_code},{key:"is_default_enabled",label:"Default Variant",enabled:n.is_default_enabled}])})});var na=v(function(){if(te){if(1===fe.tiers.length)return 0;var e=fe.tiers.findIndex(function(e){return e.toLowerCase()===te.toLowerCase()});return e>=0?e:0}},[te,fe.tiers]),ta=e(e({defaultOpen:!0,tierOptions:["Tier 1","Tier 2"],stationOptions:[{label:"Global Scope",value:"global"},{label:"Genre Scope",value:"genre"},{label:"Custom Scope",value:"custom"}],separationItemsByTier:Xr,togglesByTier:ea,highlights:Yt,highlightedIds:Zt,openSections:zn,setOpenSections:Qn,setSendMessageInChat:Rt,isAiStreaming:fi,defaultTierOpen:na,defaultVariantOpen:fn?void 0:xt,autoScrollVariantIndex:fn?void 0:xt,activeVariantAccordionIndex:fn?void 0:xt,setActiveVariantAccordionIndex:function(e){Et(e),null!=e&&setTimeout(function(){gn(!1)},100)},validationErrors:Ci,activeEditId:kn,setActiveEditId:Sn,pendingEditId:Nn,setPendingEditId:xn,conflictReason:Ei,usedFor:ne||ie?"Edit":"Create"},Jn),{scrollTrigger:ei});console.log(xt,"editVariantIndex checking"),d(function(){},[Q]),d(function(){if(!fi&&Mt&&!!(!ne&&!ie)){var e=n([],ft,!0).reverse().findIndex(function(e){return"variant"===e.action||e.is_variant});-1===e||ft.length,-1!==e&&(console.log("Post-stream: Focusing new variant at index",e),Et(e))}},[fi,Mt]);var ia=function(){Ee.current&&(clearTimeout(Ee.current),Ee.current=null),We.current=!1,Z(),Ar()},ra=function(){var e={};et.trim()||(e.ruleTitle="Rule Title is required"),fe.station||(e.station="Station Rule Set is required"),fe.tiers&&0!==fe.tiers.length||(e.tiers="At least one tier must be selected");return fe.tiers.map(function(e){return e.toLowerCase().replace(/ /g,"_")}).forEach(function(n){var t=ot.get(n),i=ut.get(n),r=Wn.get(n);r&&Array.from(r.keys()).forEach(function(r){var a=null==t?void 0:t.get(r);a&&a.trim()||(e["ruleDescription-".concat(n,"-").concat(r)]="Rule Description is required");var o=null==i?void 0:i.get(r);o&&o.some(function(e){return""!==e.text.trim()})||(e["whenToApply-".concat(n,"-").concat(r)]='At least one "When to apply" condition is required')})}),e};function aa(r,a,o){var l,s,u,d,c,v;return void 0===o&&(o=!1),t(this,void 0,void 0,function(){var t,_,p,f,g,m,w,y,h,T,A,M,I,k,S,C,N,x,E,O,L,R,D,j;return i(this,function(i){switch(i.label){case 0:if(t=r.question_id,_=(null==r?void 0:r.variant_id)||null,An.current&&jn.current===t)return console.log("[handleAILoadAction] Already fetching question ID, skipping duplicate request:",t),[2];if(Rn.current===t&&!o)return console.log("[handleAILoadAction] Question ID unchanged, updating variant focus only:",_),Ln(_),_?(-1!==(p=(ft||[]).findIndex(function(e){return e.is_new_variant}))&&(ki(!0),Hi("Removing new variant..."),Ki("Please wait while we remove new variant.")),gt(function(e){if(!Array.isArray(e))return e;var n=e.filter(function(e){return!e.is_new_variant}),t=n.findIndex(function(e){return e.variant_id===_});return-1!==t&&setTimeout(function(){Et(t),ni(function(e){return e+1}),yi.current=t},0),n}),-1!==p&&((f=function(e){e(function(e){var n=new Map;return e.forEach(function(e,t){var i=new Map(e);i.delete(p);var r=new Map,a=0;i.forEach(function(e){r.set(a,e),a++}),n.set(t,r)}),n})})(Kn),f(lt),f(dt),f(_t),Gt(function(e){var t=n([],e,!0);return t.length>p&&t.splice(p,1),t})),!1===An.current&&(An.current=!0,-1!==p&&(null===(l=hi.current)||void 0===l||l.show({severity:"success",summary:"Success",detail:"New variant removed successfully because you selected to edit an existing variant",life:4e3}))),gn(!1)):(console.log("lastLoadedQuestionIdRef.current in else",Rn.current),null===Rn.current&&(ki(!0),Hi("Adding new variant..."),Ki("Please wait while we add new variant."))),[2];console.log("User Action: fetching fresh variant info for question",t),Mn.current.clear(),Mn.current.add(t),ki(!0),Hi("Loading variants..."),console.log("reaching here in load and edit"),Ki("Please wait while we fetch the latest variant data."),An.current=!0,jn.current=t,i.label=1;case 1:return i.trys.push([1,5,6,10]),g=Date.now(),[4,b(t,(null==ee?void 0:ee.ruleSetId)||"")];case 2:return m=i.sent(),(w=Date.now()-g)<3e3?[4,new Promise(function(e){return setTimeout(e,3e3-w)})]:[3,4];case 3:i.sent(),i.label=4;case 4:return 0===(y=(null===(s=null==m?void 0:m.data)||void 0===s?void 0:s.variants)||[]).length?(console.warn("No variants found for question_id",t),ki(!1),Hi(""),null===(u=hi.current)||void 0===u||u.show({severity:"error",summary:"Error",detail:"No variants found for this question.",life:3e3}),[2]):(We.current=!0,An.current=!0,h=(null===(d=null==m?void 0:m.data)||void 0===d?void 0:d.ruleTitle)||"",nt(h),T=null===(c=null==m?void 0:m.data)||void 0===c?void 0:c.tier,A="tier_1",M="Tier 1",I="1",T&&((k=String(T).match(/(\d+)/))?(S=k[1],I=S,A="tier_".concat(S),M="Tier ".concat(S)):(A=String(T).toLowerCase().trim().replace(/ /g,"_"),M=A.replace(/_/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()}),I=A.includes("2")?"2":"1")),console.log("[handleAILoadAction] Detected Tier: ".concat(M," (ID: ").concat(I,", Key: ").concat(A,")")),ge({station:X||"global",tiers:[M]}),C=function(e,n,t,i,r,a){var o=e.map(function(e){var o,l,s=[t];return{variant_type:e.variantType||"variant",title:n,rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",scope:s,scheduling_config:(null===(o=e.configuration)||void 0===o?void 0:o.scheduling_config)||{},variant_id:e.variantId,question_id:r,tier_id:i,is_readOnly:e.variantId!==a,link_id:e.link_id||"",is_enabled:null===(l=e.is_enabled)||void 0===l||l,is_user_accepted_risk:e.is_user_accepted_risk,has_accepted_risk:e.has_accepted_risk,user_accepted_risk_at:e.user_accepted_risk_at,action:"edit"}}),l=new Map,s=new Map,u=new Map,d=new Map;return o.forEach(function(e,n){var t,i,r,a,o,c,v=e.scheduling_config||{};l.set(n,{order_rules:{enabled:!!v.order_global_min_separation_seconds||!!(null===(t=v.order_rules)||void 0===t?void 0:t.global_min_separation_seconds),global_min_separation_seconds:Math.floor((v.order_global_min_separation_seconds||(null===(i=v.order_rules)||void 0===i?void 0:i.global_min_separation_seconds)||0)/60)},advertiser_rules:{enabled:!!v.advertiser_global_min_separation_seconds||!!(null===(r=v.advertiser_rules)||void 0===r?void 0:r.global_min_separation_seconds),global_min_separation_seconds:Math.floor((v.advertiser_global_min_separation_seconds||(null===(a=v.advertiser_rules)||void 0===a?void 0:a.global_min_separation_seconds)||0)/60)},inventory_rules:{respect_inventory_code:!!v.respect_inventory_code||!!(null===(o=v.inventory_rules)||void 0===o?void 0:o.respect_inventory_code)},break_code_rules:{respect_break_code:!!v.respect_break_code||!!(null===(c=v.break_code_rules)||void 0===c?void 0:c.respect_break_code)},is_default_enabled:U(e.variantType||e.variant_type)}),s.set(n,q(e.rule_description||""));var _=e.wta?e.wta.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,t){return{id:"edit-wta-".concat(n,"-").concat(t),text:e,reasoning:""}}):[];u.set(n,_);var p=e.wnta?e.wnta.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,t){return{id:"edit-wnta-".concat(n,"-").concat(t),text:e,reasoning:""}}):[];d.set(n,p)}),{transformedVariants:o,tierConfigMap:l,tierDescMap:s,tierWtaMap:u,tierWntaMap:d}}(y,h,A,I,t,_),N=C.transformedVariants,x=C.tierConfigMap,E=C.tierDescMap,O=C.tierWtaMap,L=C.tierWntaMap,yt(function(e){var n=new Map(e);return n.set(A,JSON.parse(JSON.stringify(N))),n}),gt(function(e){var t=(Array.isArray(e)?e:[]).filter(function(e){return"copy"===e.action||e.tier_id&&e.tier_id!==I});return n(n([],t,!0),N,!0)}),Tt(function(e){var t=(Array.isArray(e)?e:[]).filter(function(e){return"copy"===e.action||e.tier_id&&e.tier_id!==I});return n(n([],t,!0),N,!0)}),Tn(!0),Rn.current=t,Ln(_),R=0,_&&-1!==(D=N.findIndex(function(e){return e.variant_id===_}))&&(R=D),Et(R),ni(function(e){return e+1}),yi.current=R,gn(!1),Kn(function(e){var n=new Map(e);return n.set(A,x),n}),lt(function(e){var n=new Map(e);return n.set(A,E),n}),dt(function(e){var n=new Map(e);return n.set(A,O),n}),_t(function(e){var n=new Map(e);return n.set(A,L),n}),Ni({}),[3,10]);case 5:return j=i.sent(),console.error("Failed to fetch variants by question ID:",j),null===(v=hi.current)||void 0===v||v.show({severity:"error",summary:"Error",detail:"Failed to fetch variants. Please try again.",life:3e3}),[3,10];case 6:return An.current=!1,ki(!1),Hi(""),Ki(""),(null==r?void 0:r.is_interpretation_ready)&&(null==r?void 0:r.question_id)&&Rn.current&&On?(console.log("inside edit variant flow",Rn.current,On),gt(function(n){if(!Array.isArray(n))return n;var t=n.map(function(n){return(null==n?void 0:n.variant_id)===On?e(e({},n),a):n}),i=n.findIndex(function(e){return(null==e?void 0:e.variant_id)===On});return console.log(i,"targetIndexif"),-1!==i&&setTimeout(function(){console.log("targetIndex",i),Et(i),ni(function(e){return e+1}),yi.current=i},0),t}),[3,9]):[3,7];case 7:return(null==r?void 0:r.is_interpretation_ready)&&(null==r?void 0:r.question_id)&&Rn.current&&!On?(console.log("inside add new variant flow",Rn.current,On),ki(!0),Hi("Adding new variant..."),Ki("Please wait while we add new variant."),[4,new Promise(function(e){return setTimeout(e,3e3)})]):[3,9];case 8:i.sent(),ki(!1),Hi(""),Ki(""),gt(function(t){var i;if(Array.isArray(t)){var r=t.findIndex(function(e){return!0===e.is_new_variant});if(-1!==r)setTimeout(function(){Et(r),ni(function(e){return e+1}),yi.current=r},0),i=t.map(function(n,t){return t===r?e(e(e({},n),a),{is_new_variant:!0,is_variant:!0}):n});else{var o=t.length;setTimeout(function(){Et(o),ni(function(e){return e+1}),yi.current=o},0),i=n(n([],t,!0),[e(e({},a),{is_new_variant:!0,is_variant:!0})],!1)}}else setTimeout(function(){Et(0),ni(0),yi.current=0},0),i=[e(e({},a),{is_new_variant:!0})];return Fn.current=i,i}),i.label=9;case 9:return[7];case 10:return[2]}})})}var oa;return console.log("RuleSet in render",ee),r(o,{children:[a(g,{ref:hi}),a(k,{open:Q,chatAssistantName:Un.ASSISTANT_NAME,organizationName:Un.ORGANIZATION_NAME,baseUrl:Un.BASE_URL,baseWebsocketUrl:Un.BASE_WEBSOCKET_URL,closeFunction:ia,ThinkingBulbIconComponent:a(j,{}),customSections:a(o,{}),customMetaData:zr,chatTitle:ne?Un.CHAT_TITLE_EDIT.replace("<scope>",(null==ee?void 0:ee.ruleSetName)||""):Un.CHAT_TITLE.replace("<scope>",(null==ee?void 0:ee.ruleSetName)||""),formTitle:Un.FORM_TITLE,showSavedMessage:!1,savedMessage:Me,isError:Ne,errorMessage:ke,isSaving:Le,onSave:function(e){console.log("Save this Learning",e);var n=ra();if(Object.keys(n).length>0)return console.log("validation errors",n),void Ni(n);Re(!0),xe(!1),Se("")},showSaveWithoutValidation:!1,onSaveWithoutValidation:function(){return t(void 0,void 0,void 0,function(){var e,n,t,r,a,o,l,s,u;return i(this,function(d){switch(d.label){case 0:return e=ra(),Object.keys(e).length>0?(Ni(e),[2]):(console.log("✅ Bypass Save: Initiated"),ne||ie?[4,Pr()]:[3,2]);case 1:return d.sent(),[3,11];case 2:return!0!==We.current?[3,4]:[4,Fr()];case 3:return d.sent(),[3,11];case 4:d.trys.push([4,10,,11]),ye(G),n=new Map,t=function(e){var t,r,a,o,l,s;return i(this,function(i){switch(i.label){case 0:if(t=e.toLowerCase().replace(/ /g,"_"),r=je.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===t||e.tier_name.toLowerCase()===t.replace(/_/g,"")}),!(a=null==r?void 0:r.tier_id))return n.set(t,null),[2,"continue"];o={question:et,orgName:Un.ORGANIZATION_NAME,scope_id:(null==ee?void 0:ee.ruleSetId)||"",tier_id:a},i.label=1;case 1:return i.trys.push([1,3,,4]),[4,w(o)];case 2:return l=i.sent(),n.set(t,(null===(u=null==l?void 0:l.data)||void 0===u?void 0:u.id)||null),[3,4];case 3:return s=i.sent(),console.error("❌ Bypass Save: Error saving question for ".concat(e,":"),s),n.set(t,null),[3,4];case 4:return[2]}})},r=0,a=fe.tiers,d.label=5;case 5:return r<a.length?(o=a[r],[5,t(o)]):[3,8];case 6:d.sent(),d.label=7;case 7:return r++,[3,5];case 8:return[4,Vr(n,!0)];case 9:return d.sent(),[3,11];case 10:return l=d.sent(),ye(F),s=new Map,fe.tiers.forEach(function(e){s.set(e.toLowerCase().replace(/ /g,"_"),null)}),Vr(s,!0),console.error("❌ Bypass Save: Error",l),[3,11];case 11:return[2]}})})},headerMessageHandlers:kr,aiResponse:ft,setAIResponse:gt,width:"90vw",height:"90vh",sendMessageInChat:Lt,template:S.CreateRule,isLoading:we===G,templateProps:{state:Zr,handlers:$r,uiState:ta},setSendMessageInChat:Rt,onResetChat:function(){Ar()},onResetRequest:function(){Ai(!0)},isFormDirty:function(){return""!==et.trim()||""!==fe.station||fe.tiers.length>0||Array.from(ot.values()).some(function(e){return Array.from(e.values()).some(function(e){return""!==e.trim()})})||Array.from(ut.values()).some(function(e){return Array.from(e.values()).some(function(e){return e.length>0})})||Array.from(vt.values()).some(function(e){return Array.from(e.values()).some(function(e){return e.length>0})})||Wn.size>0||it.size>0},initialChatMessage:ne?(oa=ne.ruleTitle||"this rule",null===(z=null==ie?void 0:ie[null!=re?re:0])||void 0===z||z.is_user_accepted_risk,'<p><span>Welcome back! 👋</span>\n <span>I see you want to edit <strong>"'.concat(oa,'."</strong></span>\n <span> <strong>What would you like to update? </strong> </span>\n <span>Describe the change you want to make, and I’ll help you edit it.</span>\n </p>')):null!=ve?ve:Un.INITIAL_CHAT_MESSAGE,validateCustom:function(){if(we===P||be)return!1;if(!et||""===et.trim())return!1;if(null!==kn)return!1;if(!fe.station||""===fe.station.trim())return!1;var e=fe.tiers&&fe.tiers.filter(function(e){return e&&""!==e.trim()});if(!e||0===(null==e?void 0:e.length))return!1;for(var n,t=0,i=e.map(function(e){return e.toLowerCase().replace(/ /g,"_")});t<i.length;t++){var r=i[t],a=ot.get(r),o=ut.get(r),l=Wn.get(r);if(!l||0===l.size)return!1;for(var s=0,u=Array.from(l.keys());s<u.length;s++){var d=u[s],c=null==a?void 0:a.get(d);if(!c||""===c.trim())return!1;var v=null==o?void 0:o.get(d);if(!(null==v?void 0:v.some(function(e){return e.text&&""!==e.text.trim()})))return!1}}return!(!Wn||0===Wn.size)&&(!(n=function(e){return Array.from(e.values()).some(function(e){return Array.from(e.values()).some(function(e){return e.some(function(e){return!!e.conflict})})})})(ut)&&!n(vt)&&!Ze)},setCitations:li,isLocked:!0,textareaPlaceholder:"Tell me more about this learning..",saveButtonConfig:{label:ne?"Save Changes":"Save Learning",loadingLabel:r("span",e({style:{display:"flex",gap:"5px",alignItems:"center"}},{children:[a(p,{size:20,color:"white",className:"animate-spin"}),a("span",{children:" Saving Changes..."})]}))},setCurrentRequestId:di,isAiStreaming:fi,setIsAiStreaming:gi,showConfirmReset:Ti,setShowConfirmReset:Ai,confirmReset:function(){Ar(),Ai(!1),ia()},isLoadingVariants:Ii,mainText:Ji,subText:Wi,proposedRule:tn,isFetchingComparison:cr,handleOpenComparison:Ir,showComparison:Gi,setShowComparison:qi,variants:on,onComparisonLinkClick:dr,targetComparisonVariantId:un,highlightedComparisonField:vn,onAddAsVariant:function(){qi(!1)},isCopyEnabled:!0,onSubmitFeedback:function(n){return t(void 0,void 0,void 0,function(){var t,r,a,o,l;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),t=e({user_id:null!==(a=null==or?void 0:or._id)&&void 0!==a?a:"",user_name:null!==(o=null==or?void 0:or.firstname)&&void 0!==o?o:"",user_email:null!==(l=null==or?void 0:or.email)&&void 0!==l?l:"",assistant_name:Un.ASSISTANT_NAME},n),[4,T(t)];case 1:return i.sent(),[3,3];case 2:throw r=i.sent(),console.error("Failed to submit chat feedback",r),r;case 3:return[2]}})})},handleGlobalClickCapture:function(e){null!==kn&&(e.target.closest('[data-edit-id="'.concat(kn,'"]'))||(e.preventDefault(),e.stopPropagation(),xn(kn)))},isGlobalEditActive:null!==kn,initialDraftMessage:se?ce:"",socketTimeOutInMilliSeconds:Un.SOCKET_TIMEOUT})]})};export{H as default,q as filterAgentText};
1
+ import{__assign as e,__spreadArray as n,__awaiter as t,__generator as i}from"tslib";import{jsxs as r,jsx as a,Fragment as o}from"react/jsx-runtime";import l,{useState as s,useRef as u,useEffect as d,useCallback as c,useMemo as v}from"react";import{AlertTriangle as _,Loader as p,Check as f}from"lucide-react";import{Toast as g}from"primereact/toast";import{v4 as m}from"uuid";import{saveInstantLearningQuestion as w,publishFeedback as y,updateVariant as h,fetchRulesByQuestionId as b,submitChatFeedback as T}from"../apis/scopeApis.js";import M from"../public/ThinkingBulbIcon.gif.js";import{useLearningTemplateStore as A}from"../store/useLearningTemplateStore.js";import k from"../styles/InstantLearningModal.module.css.js";import I from"../../IL-OTJ/ILOTJ.js";import"../../IL-OTJ/_components/atoms/Textarea/Textarea.js";import"../../IL-OTJ/_components/InputDataReasoningCard.js";import"../../IL-OTJ/_components/TooltipComponent.js";import{TemplateList as S}from"../../IL-OTJ/_components/templates/TemplatesMap/templatesMap.js";import{extractAndParseWithProperty as C,parseValidationData as x,extractAndParseResponse as N,extractVariantIds as E}from"../../IL-OTJ/helpers/utils.js";import{useCitations as O}from"../../IL-OTJ/store/CitationsContext.js";import"@mui/material";import"@mui/material/Tooltip";import"react-markdown";import"rehype-raw";import"axios";import"@e-llm-studio/streaming-response";import"@e-llm-studio/watch-me-work";import"../../IL-OTJ/_components/ChatComponents/ChatHeader.js";import"remark-gfm";import"../../IL-OTJ/_components/MarkdownComponents/MarkdownElements.js";import"../../IL-OTJ/_components/CitationLink.js";import"@e-llm-studio/citation";import"@viswa-test/test-citation";import"./ToolTip.js";import L from"../store/useAuthStore.js";import"date-fns";import"framer-motion";import"@mui/icons-material/Close";import{useConfigStore as R}from"../store/useConfigStore.js";import"@radix-ui/react-tooltip";import"./StationOnboarding/InputField.js";import"../store/useEnvStore.js";var D=function(){return a("img",{src:M,alt:"Thinking...",width:"20",height:"20"})},j="INITIAL",V="SUCCESS",P="FAILURE",q="IN_PROGRESS",F=function(e){return"string"!=typeof e?"":e.replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g,"").replace(/<!--```json[\s\S]*?```-->/g,"").trim()},G=function(e){if(!e)return!1;var n=e.toLowerCase().trim();return"default"===n||"default_variant"===n},J=function(M){var J,U,H,B,W,K,Y=M.isOpen,z=M.onClose,Q=M.initialScope,Z=void 0===Q?"global":Q,$=M.ruleSet,X=M.editingRule,ee=M.editingTier,ne=M.editingVariants,te=M.focusedVariantIndex,ie=M.setFocusedVariantIndex,re=M.triggerAddVariant,ae=M.triggerFixGaps,oe=M.copiedRule,le=M.copiedSourceTier,se=M.copiedTargetTier,ue=M.initialDraftMessage,de=M.initialChatMessage,ce=M.applicationIntegrationId;M.modeId;var ve=s({station:Z,tiers:["Tier 1"]}),_e=ve[0],pe=ve[1],fe=s(j),ge=fe[0],me=fe[1],we=s(!1),ye=we[0],he=we[1],be=s("Thank you teacher for teaching me, your rule has been saved successfully."),Te=be[0];be[1];var Me=s(""),Ae=Me[0],ke=Me[1],Ie=s(!1),Se=Ie[0],Ce=Ie[1],xe=u(null),Ne=s(!1),Ee=Ne[0],Oe=Ne[1],Le=u(!1),Re=A().tiers,De=l.useRef(new Set),je=s(null);je[0];var Ve=je[1],Pe=s(null);Pe[0];var qe=Pe[1],Fe=s(null);Fe[0];var Ge=Fe[1],Je=u(new Map),Ue=u(""),He=u(!1),Be=s(0),We=Be[0],Ke=Be[1],Ye=s(!1),ze=Ye[0],Qe=Ye[1],Ze=u(null),$e=u(0),Xe=s(null),en=Xe[0],nn=Xe[1],tn=s([]),rn=tn[0],an=tn[1],on=s(null),ln=on[0],sn=on[1],un=s(null),dn=un[0],cn=un[1],vn=s(!1),_n=vn[0],pn=vn[1],fn=u({}),gn=u([]),mn=u(!1),wn=s(!1),yn=wn[0],hn=wn[1],bn=u(!1),Tn=u(new Set),Mn=s(null),An=Mn[0],kn=Mn[1],In=s(null),Sn=In[0],Cn=In[1],xn=s(null),Nn=xn[0],En=xn[1],On=u(null),Ln=u(null),Rn=u(null),Dn=u({}),jn=u([]),Vn=u([]),Pn=u({}),qn=R(),Fn=qn.configuration,Gn=qn.ilLabels;d(function(){An||Cn(null)},[An]),d(function(){var e;if(Y&&X){On.current=X.ruleId;var n=null===(e=null==ne?void 0:ne[te||0])||void 0===e?void 0:e.variantId;En(n||null)}},[Y,X,ne,te]),d(function(){Y&&pe(function(n){return e(e({},n),{station:Z})})},[Y,Z]),d(function(){console.log("triggered",Nn),console.log(_t,"structuredAIResponse"),pt(function(n){return Array.isArray(n)?n.map(function(n){return e(e({},n),{is_readOnly:n.variant_id!==Nn&&n.new_variant_id!==Nn})}):n}),ht(function(n){return Array.isArray(n)?n.map(function(n){return e(e({},n),{is_readOnly:n.variant_id!==Nn&&n.new_variant_id!==Nn})}):n})},[Nn]),d(function(){var n;if(!Y)return br(),void(mn.current=!1);if(!mn.current){var t=ne,i=t&&t.length>0,r=null!=X;if(i||r){if((null==X?void 0:X.ruleTitle)&&Xn(X.ruleTitle),ee&&(pe(function(n){return e(e({},n),{tiers:[ee]})}),Ln.current=ee.toLowerCase().replace(/ /g,"_")),i){var a=(null==ee?void 0:ee.toLowerCase().replace(/ /g,"_"))||"tier_1",o=new Map,l=new Map,s=new Map,u=new Map,d=new Map,c=new Map,v=[];t.forEach(function(e,n){u.set(n,e.description||"");var t=e.whenToApply?e.whenToApply.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,t){return{id:"edit-wta-".concat(n,"-").concat(t),text:e,reasoning:""}}):[];d.set(n,t);var i=e.whenNotToApply?e.whenNotToApply.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,t){return{id:"edit-wnta-".concat(n,"-").concat(t),text:e,reasoning:""}}):[];c.set(n,i),v.push(e.variantId||e.variant_id||"")}),o.set(a,u),l.set(a,d),s.set(a,c);var _=null===(n=null==t?void 0:t[te||0])||void 0===n?void 0:n.variantId,p=t.map(function(e,n){var t,i,r=null===(t=e.configuration)||void 0===t?void 0:t.scheduling_config;return{variant_type:e.variantType||"variant",title:(null==X?void 0:X.ruleTitle)||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",scope:[a],scheduling_config:r||{},variant_id:e.variantId,question_id:(null==X?void 0:X.ruleId)||"",tier_id:a.replace("tier_",""),is_readOnly:e.variantId!==_,link_id:e.link_id||"",is_enabled:null===(i=e.is_enabled)||void 0===i||i,is_user_accepted_risk:e.is_user_accepted_risk,has_accepted_risk:e.has_accepted_risk,user_accepted_risk_at:e.user_accepted_risk_at,action:"edit"}});pt(p),pt(p),ht(p),mt(function(e){var n=new Map(e);return n.set(a,JSON.parse(JSON.stringify(p))),n});var f=new Map;t.forEach(function(e,n){var t,i,r,a,o,l,s,u,d,c,v,_,p,g=null===(t=e.configuration)||void 0===t?void 0:t.scheduling_config,m=null!==(a=null!==(i=null==g?void 0:g.order_global_min_separation_seconds)&&void 0!==i?i:null===(r=null==g?void 0:g.order_rules)||void 0===r?void 0:r.global_min_separation_seconds)&&void 0!==a?a:0,w=null!==(s=null!==(o=null==g?void 0:g.advertiser_global_min_separation_seconds)&&void 0!==o?o:null===(l=null==g?void 0:g.advertiser_rules)||void 0===l?void 0:l.global_min_separation_seconds)&&void 0!==s?s:0;f.set(n,{order_rules:{enabled:m>0,global_min_separation_seconds:Math.floor(m/60)},advertiser_rules:{enabled:w>0,global_min_separation_seconds:Math.floor(w/60)},inventory_rules:{respect_inventory_code:null!==(c=null!==(d=null===(u=null==g?void 0:g.inventory_rules)||void 0===u?void 0:u.respect_inventory_code)&&void 0!==d?d:null==g?void 0:g.respect_inventory_code)&&void 0!==c&&c},break_code_rules:{respect_break_code:null!==(p=null!==(_=null===(v=null==g?void 0:g.break_code_rules)||void 0===v?void 0:v.respect_break_code)&&void 0!==_?_:null==g?void 0:g.respect_break_code)&&void 0!==p&&p},is_default_enabled:G(e.variantType||e.variant_type)})}),Bn(new Map([[a,f]])),at(o),st(l),ct(s)}else if(r&&X){var g=X.ruleDesc;if(g&&at(new Map([["tier_1",new Map([[0,g]])]])),X.whenToApply){var m=X.whenToApply.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,n){return{id:"edit-wta-".concat(n),text:e,reasoning:""}});st(new Map([["tier_1",new Map([[0,m]])]]))}if(X.whenNotToApply){var w=X.whenNotToApply.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,n){return{id:"edit-wnta-".concat(n),text:e,reasoning:""}});ct(new Map([["tier_1",new Map([[0,w]])]]))}}}else if(oe&&le&&se){Xn(oe.ruleTitle||""),pe(function(n){return e(e({},n),{tiers:[se]})}),Ln.current=se.toLowerCase().replace(/ /g,"_");var y=le.toLowerCase().replace(/ /g,"_"),h=oe.variants||[],b=(o=new Map,l=new Map,s=new Map,new Map),T=new Map,M=new Map;h.forEach(function(e,n){b.set(n,e.description||"");var t=e.whenToApply?e.whenToApply.split(" OR ").map(function(e,t){return{id:"copy-wta-".concat(n,"-").concat(t),text:e.trim(),reasoning:""}}):[];T.set(n,t);var i=e.whenNotToApply?e.whenNotToApply.split(" OR ").map(function(e,t){return{id:"copy-wnta-".concat(n,"-").concat(t),text:e.trim(),reasoning:""}}):[];M.set(n,i)}),o.set(y,b),l.set(y,T),s.set(y,M),at(o),st(l),ct(s);var A=h.map(function(e,n){var t,i,r=null===(t=e.configuration)||void 0===t?void 0:t.scheduling_config;return{variant_type:e.variantType||"variant",title:oe.ruleTitle||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",scope:[le],scheduling_config:r||{},variant_id:e.variantId,question_id:oe.ruleId||"",tier_id:y.replace("tier_",""),is_readOnly:!0,link_id:e.link_id||"",is_enabled:null===(i=e.is_enabled)||void 0===i||i,is_user_accepted_risk:e.is_user_accepted_risk,has_accepted_risk:e.has_accepted_risk,user_accepted_risk_at:e.user_accepted_risk_at,action:"copy"}});pt(A),ht(A),mt(function(e){var n=new Map(e);return n.set(y,JSON.parse(JSON.stringify(A))),n});var k=new Map;h.forEach(function(e,n){var t,i,r,a,o,l,s,u,d,c,v,_,p,f=null===(t=e.configuration)||void 0===t?void 0:t.scheduling_config,g=null!==(a=null!==(i=null==f?void 0:f.order_global_min_separation_seconds)&&void 0!==i?i:null===(r=null==f?void 0:f.order_rules)||void 0===r?void 0:r.global_min_separation_seconds)&&void 0!==a?a:0,m=null!==(s=null!==(o=null==f?void 0:f.advertiser_global_min_separation_seconds)&&void 0!==o?o:null===(l=null==f?void 0:f.advertiser_rules)||void 0===l?void 0:l.global_min_separation_seconds)&&void 0!==s?s:0;k.set(n,{order_rules:{enabled:g>0,global_min_separation_seconds:Math.floor(g/60)},advertiser_rules:{enabled:m>0,global_min_separation_seconds:Math.floor(m/60)},inventory_rules:{respect_inventory_code:null!==(c=null!==(d=null===(u=null==f?void 0:f.inventory_rules)||void 0===u?void 0:u.respect_inventory_code)&&void 0!==d?d:null==f?void 0:f.respect_inventory_code)&&void 0!==c&&c},break_code_rules:{respect_break_code:null!==(p=null!==(_=null===(v=null==f?void 0:f.break_code_rules)||void 0===v?void 0:v.respect_break_code)&&void 0!==_?_:null==f?void 0:f.respect_break_code)&&void 0!==p&&p},is_default_enabled:G(e.variantType||e.variant_type)})}),Bn(new Map([[y,k]]))}}},[Y,X,ne,ee,oe,le,se]),d(function(){if(Y){if(console.log("[Accordion Init] editingTier:",ee,"focusedVariantIndex:",te),ee&&pe(function(n){return e(e({},n),{tiers:[ee]})}),_n)return console.log("[Accordion] isAddingNewVariant mode — closing all variant accordions"),void xt(void 0);if(re){console.log("[Accordion] triggerAddVariant mode — not opening any variant on RHS"),xt(void 0);var n=((null==ee?void 0:ee.toLowerCase().replace(/ /g,"_"))||"tier_1").replace(/_/g," ");Ot("I want to add a new variant to ".concat(n))}else null!=te?(console.log("[Accordion] Opening SPECIFIC variant index ".concat(te," (from VariantCard)")),xt(te),Xt(function(e){return e+1})):(X||ne&&ne.length>0)&&(console.log("[Accordion] Opening DEFAULT/1st variant (index 0) for RuleHeader edit"),xt(0),Xt(function(e){return e+1}))}else xt(void 0)},[Y,ee,te,X,ne,re,_n]),d(function(){Y&&ae&&X&&null!==te&&Ot("I want to fix the gaps")},[Y,ae,X,te]);var Jn={order_rules:{enabled:!1,global_min_separation_seconds:0},advertiser_rules:{enabled:!1,global_min_separation_seconds:0},inventory_rules:{respect_inventory_code:!1},break_code_rules:{respect_break_code:!1},is_default_enabled:!1},Un=s(new Map([["tier_1",new Map([[0,Jn]])],["tier_2",new Map([[0,Jn]])]])),Hn=Un[0],Bn=Un[1],Wn=s(new Set([])),Kn=Wn[0],Yn=Wn[1],zn=s("");zn[0];var Qn=zn[1],Zn=s(""),$n=Zn[0],Xn=Zn[1],et=s(new Map([["tier_1",new Map],["tier_2",new Map]])),nt=et[0],tt=et[1],it=s(new Map([["tier_1",new Map],["tier_2",new Map]])),rt=it[0],at=it[1],ot=s(new Map([["tier_1",new Map],["tier_2",new Map]])),lt=ot[0],st=ot[1],ut=s(new Map([["tier_1",new Map],["tier_2",new Map]])),dt=ut[0],ct=ut[1],vt=s([]),_t=vt[0],pt=vt[1],ft=s(new Map),gt=ft[0],mt=ft[1],wt=s([]),yt=wt[0],ht=wt[1],bt=s(!1),Tt=bt[0],Mt=bt[1],At=s([]),kt=At[0],It=At[1],St=s(void 0),Ct=St[0],xt=St[1],Nt=s(""),Et=Nt[0],Ot=Nt[1],Lt=s(null),Rt=Lt[0],Dt=Lt[1],jt=s([]),Vt=jt[0],Pt=jt[1],qt=s([]),Ft=qt[0],Gt=qt[1],Jt=s({}),Ut=Jt[0],Ht=Jt[1],Bt=s(new Map),Wt=Bt[0],Kt=Bt[1],Yt=s(new Set),zt=Yt[0],Qt=Yt[1],Zt=s(0),$t=Zt[0],Xt=Zt[1],ei=s({ruleTitle:"",ruleDescription:"",scopeData:"",whenToApply:"",whenNotToApply:"",configData:""}),ni=ei[0],ti=ei[1],ii=s([]),ri=ii[0],ai=ii[1],oi=s(""),li=oi[0],si=oi[1],ui=s({}),di=ui[0],ci=ui[1],vi=s(!1),_i=vi[0],pi=vi[1],fi=u(null),gi=u(null),mi=u(-1),wi=u(null);d(function(){Vn.current=_t},[_t]),d(function(){var n=new Set,t=console.warn;return console.warn=function(){for(var i,o=[],l=0;l<arguments.length;l++)o[l]=arguments[l];t.apply(void 0,o);var s=o[0];if("string"==typeof s&&s.includes("Failed to parse JSON for property=")){var u=s.match(/warnId="([^"]+)"/),d=null==u?void 0:u[1];if(d&&n.has(d))return;d&&n.add(d),null===(i=wi.current)||void 0===i||i.show({severity:"warn",sticky:!1,life:5e3,className:k.toastWarning,content:r("div",e({className:k.toastContent},{children:[r("div",e({className:k.toastHeaderLeft},{children:[a(_,{className:k.iconWarning}),a("span",e({className:"".concat(k.toastTitle," ").concat(k.toastTitleWarning)},{children:"Parsing Issue"}))]})),a("p",e({className:"".concat(k.toastMessage," ").concat(k.toastMessageWarning)},{children:"The AI response couldn't be parsed correctly. Please try rephrasing your input or retry."}))]}))})}},function(){console.warn=t}},[]);var yi=s(!1),hi=yi[0],bi=yi[1],Ti=s(!1),Mi=Ti[0],Ai=Ti[1],ki=s({}),Ii=ki[0],Si=ki[1],Ci=s(""),xi=Ci[0],Ni=Ci[1],Ei=s(!0),Oi=Ei[0],Li=Ei[1],Ri=s(!1),Di=Ri[0],ji=Ri[1],Vi=s(!1),Pi=Vi[0],qi=Vi[1],Fi=s(""),Gi=Fi[0],Ji=Fi[1],Ui=s(""),Hi=Ui[0],Bi=Ui[1],Wi=s(""),Ki=Wi[0],Yi=Wi[1],zi=s(null),Qi=zi[0],Zi=zi[1],$i=s(null),Xi=$i[0],er=$i[1],nr=s(null),tr=nr[0],ir=nr[1],rr=L.getState().user,ar=O(),or=ar.dispatch,lr=ar.getLatestReasoning;d(function(){console.log("Structured AI Response updated:",_t)},[_t]),d(function(){console.log("isCloseModal AI Response updated:",Oi)},[Oi]),d(function(){!1===_i?(Ai(!1),Ji(""),Bi("")):(Ce(!1),ke(""))},[_i]),d(function(){null!=Ct&&ne&&!ne[Ct]&&Zi(null)},[Ct,ne]),d(function(){if(Ee&&!Le.current){Le.current=!0,console.log("UseEffect triggered: Sending save message to chat agent");Ot("Save this Learning"),Oe(!1),setTimeout(function(){Le.current=!1,Ot("")},2e3)}},[Ee]);var sr=c(function(e,n){rn.some(function(n){return n.id===e})?(qi(!0),sn(e),cn(n),setTimeout(function(){cn(null),sn(null)},6e3)):console.warn("Variant ID ".concat(e," not found in comparison variants."))},[rn]),ur=v(function(){var e=Pi&&We>0;return console.log("[Loader Debug] showComparison: ".concat(Pi,", activeRequests: ").concat(We,", Result: ").concat(e)),e},[Pi,We]),dr=c(function(n,t,i){var r,a=void 0!==(null===(r=null==i?void 0:i.target)||void 0===r?void 0:r.value)?i.target.value:i;at(function(e){var i=new Map(e),r=new Map(i.get(n));return r.set(t,a),i.set(n,r),i}),Si(function(i){if(i["ruleDescription-".concat(n,"-").concat(t)]){var r=e({},i);return delete r["ruleDescription-".concat(n,"-").concat(t)],r}return i})},[]),cr=c(function(t,i){st(function(e){var r=new Map(e),a=new Map(r.get(t)),o=a.get(i)||[];return a.set(i,n(n([],o,!0),[{id:Date.now(),text:"",reasoning:""}],!1)),r.set(t,a),r}),Si(function(n){if(n["whenToApply-".concat(t,"-").concat(i)]){var r=e({},n);return delete r["whenToApply-".concat(t,"-").concat(i)],r}return n})},[]),vr=c(function(e,n,t){st(function(i){var r=new Map(i),a=new Map(r.get(e)),o=a.get(n)||[];return a.set(n,o.filter(function(e){return e.id!==t})),r.set(e,a),r})},[]),_r=c(function(n,t,i,r){st(function(a){var o=new Map(a),l=new Map(o.get(n)),s=l.get(t)||[];return l.set(t,s.map(function(n){return String(n.id)===String(i)?e(e({},n),{text:r}):n})),o.set(n,l),o}),Si(function(i){if(i["whenToApply-".concat(n,"-").concat(t)]){var r=e({},i);return delete r["whenToApply-".concat(n,"-").concat(t)],r}return i})},[]),pr=c(function(e,t){ct(function(i){var r=new Map(i),a=new Map(r.get(e)),o=a.get(t)||[];return a.set(t,n(n([],o,!0),[{id:Date.now(),text:"",reasoning:""}],!1)),r.set(e,a),r})},[]),fr=c(function(e,n,t){ct(function(i){var r=new Map(i),a=new Map(r.get(e)),o=a.get(n)||[];return a.set(n,o.filter(function(e){return e.id!==t})),r.set(e,a),r})},[]),gr=c(function(n,t,i,r){ct(function(a){var o=new Map(a),l=new Map(o.get(n)),s=l.get(t)||[];return l.set(t,s.map(function(n){return String(n.id)===String(i)?e(e({},n),{text:r}):n})),o.set(n,l),o})},[]),mr=c(function(e){var n=e.replace(/_/g," ");pn(!0),null==ie||ie(null),xt(void 0),Ot("I want to add a new variant to ".concat(n))},[]),wr=function(n,t,i){var r="".concat(n,"_").concat(t);console.log("Highlighting ".concat(i," at ").concat(r)),Kt(function(n){var t,a=new Map(n),o=a.get(r)||{};return a.set(r,e(e({},o),((t={})[i]=!0,t))),a}),setTimeout(function(){Kt(function(n){var t,a=new Map(n),o=a.get(r)||{};return a.set(r,e(e({},o),((t={})[i]=!1,t))),a})},1500)},yr=c(function(n,t){pe(function(i){var r;return e(e({},i),((r={})[n]=t,r))}),Si(function(t){if(t[n]){var i=e({},t);return delete i[n],i}return t})},[]),hr=c(function(n,t,i,r){tt(function(e){var r=new Map(e),a=new Map(r.get(n)||new Map),o=a.get(t)||new Set;return o.add(i),a.set(t,o),r.set(n,a),r}),Bn(function(a){var o,l,s,u=new Map(a),d=new Map(u.get(n)||new Map),c=d.get(t)||Jn;switch(i){case"order_rules":case"advertiser_rules":s="boolean"==typeof r?e(e({},c),((o={})[i]=e(e({},c[i]),{enabled:r}),o)):"object"==typeof r&&null!==r?e(e({},c),((l={})[i]={enabled:r.enabled,global_min_separation_seconds:r.global_min_separation_seconds},l)):c;break;case"inventory_rules":s=e(e({},c),{inventory_rules:{respect_inventory_code:"boolean"==typeof r?r:r.respect_inventory_code}});break;case"break_code_rules":s=e(e({},c),{break_code_rules:{respect_break_code:"boolean"==typeof r?r:r.respect_break_code}});break;case"is_default_enabled":s=e(e({},c),{is_default_enabled:"boolean"==typeof r?r:!!r});break;default:s=c}return d.set(t,s),u.set(n,d),u})},[]);d(function(){_i&&(qi(!1),cn(null),sn(null))},[_i]);var br=c(function(n){var t;if(void 0===n&&(n=!1),n||(or({type:"RESET"}),fi.current=null,pt([]),It([]),ai([]),ci({}),qi(!1),De.current.clear()),Xn(""),Pt([]),pn(!1),Ue.current="",Yi(""),er(null),Gt([]),pe({station:"",tiers:[]}),Ke(0),Qe(!1),ir(null),at(new Map([["tier_1",new Map],["tier_2",new Map]])),st(new Map([["tier_1",new Map],["tier_2",new Map]])),ct(new Map([["tier_1",new Map],["tier_2",new Map]])),Bn(new Map([["tier_1",new Map([[0,Jn]])],["tier_2",new Map([[0,Jn]])]])),tt(new Map([["tier_1",new Map],["tier_2",new Map]])),Qn(""),xt(0),Xt(0),pe({station:Z,tiers:["Tier 1"]}),n||Ht({}),tt(new Map([["tier_1",new Map],["tier_2",new Map]])),Ot(""),ti({ruleTitle:"",ruleDescription:"",scopeData:"",whenToApply:"",whenNotToApply:"",configData:""}),Si({}),Ni(""),Li(!0),Ve(null),qe(null),mt(new Map),ht([]),hn(!1),Ge(null),gi.current=null,He.current=!1,fn.current={},Tn.current.clear(),On.current=null,Ln.current=null,En(null),ke(""),me(j),he(!1),Ce(!1),Oe(!1),nn(null),an([]),sn(null),cn(null),kn(null),Mt(!1),Dt(null),Ji(""),Bi(""),Ai(!1),Yn(new Set),Le.current=!1,Je.current.clear(),$e.current=0,Ze.current=null,Rn.current=null,mi.current=-1,bn.current=!1,mn.current=!1,X){X.ruleTitle&&Xn(X.ruleTitle),ee&&(pe(function(n){return e(e({},n),{tiers:[ee]})}),Ln.current=ee.toLowerCase().replace(/ /g,"_")),On.current=X.ruleId;var i=null===(t=null==ne?void 0:ne[te||0])||void 0===t?void 0:t.variantId;if(En(i||null),ne&&ne.length>0){var r=(null==ee?void 0:ee.toLowerCase().replace(/ /g,"_"))||"tier_1",a=new Map,o=new Map,l=new Map,s=new Map,u=new Map,d=new Map;ne.forEach(function(e,n){s.set(n,e.description||"");var t=e.whenToApply?e.whenToApply.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,t){return{id:"edit-wta-".concat(n,"-").concat(t),text:e,reasoning:""}}):[];u.set(n,t);var i=e.whenNotToApply?e.whenNotToApply.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,t){return{id:"edit-wnta-".concat(n,"-").concat(t),text:e,reasoning:""}}):[];d.set(n,i)}),a.set(r,s),o.set(r,u),l.set(r,d),at(a),st(o),ct(l);var c=ne.map(function(e){var n,t,a=null===(n=e.configuration)||void 0===n?void 0:n.scheduling_config;return{variant_type:e.variantType||"variant",title:X.ruleTitle||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",scope:[r],scheduling_config:a||{},variant_id:e.variantId,question_id:X.ruleId||"",tier_id:r.replace("tier_",""),is_readOnly:e.variantId!==i,link_id:e.link_id||"",is_enabled:null===(t=e.is_enabled)||void 0===t||t,is_user_accepted_risk:e.is_user_accepted_risk,has_accepted_risk:e.has_accepted_risk,user_accepted_risk_at:e.user_accepted_risk_at,action:"edit"}});pt(c),ht(c),mt(function(e){var n=new Map(e);return n.set(r,JSON.parse(JSON.stringify(c))),n});var v=new Map;ne.forEach(function(e,n){var t,i,r,a,o,l,s,u,d,c,_,p,f,g=null===(t=e.configuration)||void 0===t?void 0:t.scheduling_config,m=null!==(a=null!==(i=null==g?void 0:g.order_global_min_separation_seconds)&&void 0!==i?i:null===(r=null==g?void 0:g.order_rules)||void 0===r?void 0:r.global_min_separation_seconds)&&void 0!==a?a:0,w=null!==(s=null!==(o=null==g?void 0:g.advertiser_global_min_separation_seconds)&&void 0!==o?o:null===(l=null==g?void 0:g.advertiser_rules)||void 0===l?void 0:l.global_min_separation_seconds)&&void 0!==s?s:0;v.set(n,{order_rules:{enabled:m>0,global_min_separation_seconds:Math.floor(m/60)},advertiser_rules:{enabled:w>0,global_min_separation_seconds:Math.floor(w/60)},inventory_rules:{respect_inventory_code:null!==(c=null!==(d=null===(u=null==g?void 0:g.inventory_rules)||void 0===u?void 0:u.respect_inventory_code)&&void 0!==d?d:null==g?void 0:g.respect_inventory_code)&&void 0!==c&&c},break_code_rules:{respect_break_code:null!==(f=null!==(p=null===(_=null==g?void 0:g.break_code_rules)||void 0===_?void 0:_.respect_break_code)&&void 0!==p?p:null==g?void 0:g.respect_break_code)&&void 0!==f&&f},is_default_enabled:G(e.variantType||e.variant_type)})}),Bn(new Map([[r,v]])),xt(null!=te?te:0)}}},[or,Z,X,ee,ne,te]),Tr=function(e){if(!e||0===e.length)return"variant 1";var n=e.filter(function(e){var n=e.variant_type||e.variantType||"";return""!==n&&null!==n});return"variant ".concat(n.length+1)},Mr=c(function(){console.log("variantIds",Vt),qi(!0)},[Vt]),Ar={"Let me connect the dots for you...":function(e){if("string"==typeof e){var n=e.match(/<!--\s*(\{[^}]*"variant_index"[^}]*\})\s*-->/);if(n)try{var t=JSON.parse(n[1]),i=parseInt(t.variant_index,10);if(!isNaN(i)&&i>0){var r=i-1;mi.current!==r&&(console.log("Opening variant accordion: AI index ".concat(i," → 0-based index ").concat(r)),xt(r),mi.current=r)}}catch(e){console.error("Failed to parse variant_index from HTML comment:",e)}}},"Crafted Instant Learning with C.A.R.E.":function(t){var i,r=C(t),a=C(t,"general_details");console.log("--- [CARE] Staging Initial Structure ---",r);var o=C(t,"critical_gaps");if(console.log("isCriticalGap",o),Qe(!!o),r){if(r.variant_type&&!("is_variant"in r)){var l=null===(i=Ir(r.variant_type||"").toLowerCase().match(/^(default_variant|default|variant)/i))||void 0===i?void 0:i[0];r.variant_type=G(l)?"Default":"variant",r.isDefault=G(l),console.log("parsed.variant_type",r.variant_type)}var s=r.scope&&r.scope.length>0?String(r.scope[0]):null,u=s?Ir(s).toLowerCase().trim().replace(/ /g,"_"):null,d=Boolean(u&&Ln.current!==u);if(d&&u){var c=Ln.current;console.log("[Tier Switch Detected]",Ln.current,"→",u),Ln.current=u,On.current=null;var v=(Vn.current||[]).findIndex(function(e){return!0===(null==e?void 0:e.is_new_variant)});-1===v&&void 0!==Ct&&(v=Ct),c&&-1!==v&&(console.log("[Tier Switch] Stripping draft variant at index ".concat(v," from ").concat(c)),at(function(e){var n=new Map(e),t=new Map(n.get(c)||new Map);return t.delete(v),n.set(c,t),n}),st(function(e){var n=new Map(e),t=new Map(n.get(c)||new Map);return t.delete(v),n.set(c,t),n}),ct(function(e){var n=new Map(e),t=new Map(n.get(c)||new Map);return t.delete(v),n.set(c,t),n}),Bn(function(e){var n=new Map(e),t=new Map(n.get(c)||new Map);return t.delete(v),n.set(c,t),n}),pt(function(t){if(!Array.isArray(t))return t;var i=n([],t,!0);return i[v]&&(i[v]=e(e({},i[v]),{scope:[u],tier_id:u.replace("tier_","")})),Vn.current=i,i})),mi.current=-1;var _=u.replace(/_/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()});pe(function(n){return e(e({},n),{tiers:[_]})})}Dt(r),Ve({Updated_Fields_Response:r,General_Response:a}),(null==a?void 0:a.variant_id)&&"new_variant_id"===(null==a?void 0:a.variant_id)&&(a.variant_id=null),(null==a?void 0:a.is_interpretation_ready)&&(null==a?void 0:a.question_id)&&ra(a,r,d),(null==a?void 0:a.is_interpretation_ready)&&(null==a?void 0:a.question_id)&&On.current&&Nn?pt(function(n){if(!Array.isArray(n))return n;var t=n.map(function(n){return(null==n?void 0:n.variant_id)&&n.variant_id===Nn?e(e({},n),r):n}),i=n.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===Nn});return console.log(i,"targetIndexif"),-1!==i&&setTimeout(function(){console.log("targetIndex",i),xt(i),Xt(function(e){return e+1}),mi.current=i},0),t}):(null==a?void 0:a.is_interpretation_ready)&&(null==a?void 0:a.question_id)&&On.current&&!Nn?pt(function(t){var i;if(Array.isArray(t)){var a=t.findIndex(function(e){return!0===e.is_new_variant});if(-1!==a)setTimeout(function(){xt(a),Xt(function(e){return e+1}),mi.current=a},0),i=t.map(function(n,t){return t===a?e(e(e({},n),r),{is_new_variant:!0,is_variant:!0}):n});else{var o=t.length;setTimeout(function(){xt(o),Xt(function(e){return e+1}),mi.current=o},0),i=n(n([],t,!0),[e(e({},r),{is_new_variant:!0})],!1)}}else setTimeout(function(){xt(0),Xt(function(e){return e+1}),mi.current=0},0),i=[e(e({},r),{is_new_variant:!0})];return Vn.current=i,i}):(null==a?void 0:a.is_interpretation_ready)&&(pt([r]),setTimeout(function(){xt(0),Xt(function(e){return e+1}),mi.current=0},0)),void 0!==r.is_user_accepted_risk&&pt(function(t){var i=!(!X&&!ne),a=Array.isArray(t)?n([],t,!0):[];if(i&&0===a.length&&ne&&ne.length>0&&(a=ne.map(function(e,n){var t;return{variant_type:e.variantType||"variant ".concat(n+1),title:(null==X?void 0:X.ruleTitle)||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",is_valid:!0,is_readOnly:e.variantId!==Nn,variant_id:e.variantId,tier_id:(null===(t=e.tier)||void 0===t?void 0:t.tier_id)||"1",is_user_accepted_risk:e.is_user_accepted_risk||!1}})),i){var o=Qi||Xi,l=a.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===o||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===o||(null==e?void 0:e.id)&&e.id===o});if(-1===l&&void 0!==Ct&&(l=Ct),-1!==l)return a[l]=e(e({},a[l]),{is_user_accepted_risk:!!r.is_user_accepted_risk}),a}return t})}},"RHS Validation Agent Response":function(t){var i,r,a,o=t;if("string"==typeof t)try{o=JSON.parse(t)}catch(e){o=x(t)}if(qe(o),console.log("--- [RHS] Updating Staged Logic ---"),console.log("parsed data from RHS Validation",o),o){Dt(function(n){var t=n;if(!t){console.log("⚠️ No staged response found! Constructing fallback from current UI state...");var i=null;if(Array.isArray(_t)){var r=Qi||Xi,a=-1;!(!X&&!ne)&&r&&(a=_t.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===r||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===r||(null==e?void 0:e.id)&&e.id===r})),-1===a&&void 0!==Ct&&(a=Ct),-1!==a&&(i=_t[a])}t=i?e({},i):{wta:"",wnta:""}}return e(e({},t),{wta:t.wta,wnta:t.wnta,is_valid:o.is_valid,conflictingConditions:o.conflictingConditions||[],conflictMarkdown:{},conflict_view:o.conflict_view||{}})});var l=(ee||"Tier 1").toLowerCase().replace(/ /g,"_"),s=function(){var e,n=Vn.current;if(Array.isArray(n)&&n.length>0){var t,i=n.findIndex(function(e){return!0===(null==e?void 0:e.is_new_variant)});if(-1!==i)return console.log("[RHS] Resolved via is_new_variant flag:",i),i;if(Nn)if(-1!==(t=n.findIndex(function(e){return(null==e?void 0:e.variant_id)===Nn||(null==e?void 0:e.new_variant_id)===Nn})))return t;if(Qi)if(-1!==(t=n.findIndex(function(e){return(null==e?void 0:e.variant_id)===Qi||(null==e?void 0:e.new_variant_id)===Qi})))return t;var r=null!==(e=null==ne?void 0:ne.length)&&void 0!==e?e:0;if(n.length>r){var a=n.length-1;return console.log("[RHS] Resolved via length diff (new variant appended):",a),a}}var o=void 0!==Ct?Ct:0;return console.log("[RHS] Fallback index used:",o),o}();if(console.log("Resolved variant index for conflict injection:",s),!1===o.is_valid)((null===(i=o.conflictingConditions)||void 0===i?void 0:i.length)||0)>0&&(Si(function(n){var t=e({},n);return o.conflictingConditions.forEach(function(e){e.condition_wnta&&!e.condition_wta?t["whenNotToApply-".concat(l,"-").concat(s)]=e.reason:t["whenToApply-".concat(l,"-").concat(s)]=e.reason}),t}),Ni("")),o.conflict_view&&((null===(r=o.conflict_view.wta)||void 0===r?void 0:r.length)>0&&st(function(t){var i=new Map(t),r=new Map(i.get(l)||new Map),a=n([],r.get(s)||[],!0);return o.conflict_view.wta.forEach(function(n){var t=a.findIndex(function(e){return e.text.trim()===n.value});-1!==t?a[t]=e(e({},a[t]),{conflict:n}):a.push({id:"conflict-wta-".concat(Date.now(),"-").concat(Math.random()),text:n.value,conflict:n})}),r.set(s,a),i.set(l,r),i}),(null===(a=o.conflict_view.wnta)||void 0===a?void 0:a.length)>0&&ct(function(t){var i=new Map(t),r=new Map(i.get(l)||new Map),a=n([],r.get(s)||[],!0);return o.conflict_view.wnta.forEach(function(n){var t=a.findIndex(function(e){return e.text.trim()===n.value});-1!==t?a[t]=e(e({},a[t]),{conflict:n}):a.push({id:"conflict-wnta-".concat(Date.now(),"-").concat(Math.random()),text:n.value,conflict:n})}),r.set(s,a),i.set(l,r),i}));else!0===o.is_valid&&(Si({}),Ni(""),st(function(n){var t=new Map(n),i=new Map(t.get(l)||new Map),r=i.get(s)||[];return i.set(s,r.map(function(n){return e(e({},n),{conflict:void 0})})),t.set(l,i),t}),ct(function(n){var t=new Map(n),i=new Map(t.get(l)||new Map),r=i.get(s)||[];return i.set(s,r.map(function(n){return e(e({},n),{conflict:void 0})})),t.set(l,i),t}))}},"User Action Execution":function(e){console.log("--- [User Action] Execution ---",e);var n=N(e);(console.log("parsedaction",n),"load"===(null==n?void 0:n.action)&&(null==n?void 0:n.question_id)&&ra(n,null),"save"===(null==n?void 0:n.action)&&(null==n?void 0:n.is_save)&&(Li(!0),ji(!0)),"discard_rule"===(null==n?void 0:n.action))&&(pt([{variant_id:void 0,rule_description:"",wta:"",wnta:"",variant_type:"variant"}]),ht([]),En(null),xt(0),Xt(0),kn(null),hn(!1),pn(!1),Pt([]),On.current=null,Xn(""),ir(null),Bn(new Map([["tier_1",new Map([[0,Jn]])],["tier_2",new Map([[0,Jn]])]])),at(new Map([["tier_1",new Map],["tier_2",new Map]])),st(new Map([["tier_1",new Map],["tier_2",new Map]])),ct(new Map([["tier_1",new Map],["tier_2",new Map]])))},"Validation Agent Response":function(t){var i,r;if(console.log("--- [Validation Agent] Committing Staged Data to UI ---"),console.log("raw data from Validation Agent",t,typeof t),"string"==typeof t){var a=t.match(/<!--\s*```json\s+property="rule_validation_card"\s+([\s\S]*?)```\s*-->/i);if(a&&a[1])try{var o=JSON.parse(a[1].trim()),l=null===(r=null===(i=null==o?void 0:o.validated_rules)||void 0===i?void 0:i[0])||void 0===r?void 0:r.rule_id;l&&(console.log("Setting default comparison ID:",l),sn(l))}catch(e){console.error("Failed to parse rule_validation_card JSON",e)}}var s=C(t,"critical_gaps");console.log("isCriticalGap",s),Qe(!!s);var u="string"==typeof t?N(t):t;console.log("parsed data from Validation Agent",u);var d=E(t);Ge(u);var c=!!(null==u?void 0:u.is_variant),v=void 0===(null==u?void 0:u.close_modal)||!!(null==u?void 0:u.close_modal),_=void 0!==(null==u?void 0:u.is_save)&&!!(null==u?void 0:u.is_save);Li(v),ji(_);var p=null==u?void 0:u.action,f="string"==typeof(null==u?void 0:u.edit_variant_id)&&u.edit_variant_id.trim()?u.edit_variant_id:"string"==typeof(null==u?void 0:u.set_variant_id)&&u.set_variant_id.trim()?u.set_variant_id:null,g="variant"===p&&c;if((null==u?void 0:u.edit_variant_id)&&!g&&Zi(u.edit_variant_id),"edit"!==p&&"edit_current_rule"!==p||!f||er(f),g&&(Zi(null),er(null)),"discard"===p)return console.log("Action 'discard' received: Resetting UI state but preserving chat."),mn.current=!0,br(!0),pt([]),fi.current=null,void(gi.current=null);Yi(p);var m=null==u?void 0:u.new_variant_id,w="edit"===(null==u?void 0:u.action)&&(null==u?void 0:u.set_variant_id)&&!ne;(null==u?void 0:u.is_valid)?(Si({}),Dt(function(t){var i,r,a,o,l,s,d,c,v,_,p,g;if(console.log("⏮️ PREVIOUS Staged Response:",t),!t)return console.warn("⚠️ No previous staged response found"),t;var m=function(e,n){return Object.prototype.hasOwnProperty.call(e||{},n)},w=e(e({},t),u);Array.isArray(null===(i=null==u?void 0:u.condition_result)||void 0===i?void 0:i.when_to_apply)?w.wta=u.condition_result.when_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join(" OR "):m(u,"wta")&&void 0!==(null==u?void 0:u.wta)&&(w.wta=null!==(r=null==u?void 0:u.wta)&&void 0!==r?r:""),Array.isArray(null===(a=null==u?void 0:u.condition_result)||void 0===a?void 0:a.when_not_to_apply)?w.wnta=u.condition_result.when_not_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join(" OR "):m(u,"wnta")&&void 0!==(null==u?void 0:u.wnta)&&(w.wnta=null!==(o=null==u?void 0:u.wnta)&&void 0!==o?o:""),console.log("finalData",w),console.log("checking parsed here :",u);var y,h=f;if(Array.isArray(_t)&&h&&(y=h,_t.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===y||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===y||(null==e?void 0:e.id)&&e.id===y})),"edit"!==(null==u?void 0:u.action)||!X&&!ne)return w;console.log("inside edit flow merge");var b=ne||[],T=f,M=T?b.findIndex(function(e){return e.variantId===T||e.variant_id&&e.variant_id===T||e.id&&e.id===T}):-1;if(-1===M&&(null==u?void 0:u.set_variant_id)&&(M=b.findIndex(function(e){return e.variantId===u.set_variant_id||e.variant_id&&e.variant_id===u.set_variant_id||e.id&&e.id===u.set_variant_id})),-1===M&&T&&Array.isArray(_t)&&(M=_t.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===T||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===T||(null==e?void 0:e.id)&&e.id===T})),-1!==M){var A,k,I,S=b[M]||(null==_t?void 0:_t[M]),C=(null==S?void 0:S.tier_id)||(null==S?void 0:S.tierId)||"1",x=(null==ee?void 0:ee.toLowerCase().replace(/ /g,"_"))||"tier_".concat(C);if(mi.current!==M&&(xt(M),mi.current=M),Array.isArray(null===(l=u.condition_result)||void 0===l?void 0:l.when_to_apply)?A=u.condition_result.when_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join("\n"):m(u,"wta")&&void 0!==(null==u?void 0:u.wta)?A=null!==(s=null==u?void 0:u.wta)&&void 0!==s?s:"":m(t,"wta")&&void 0!==(null==t?void 0:t.wta)&&(A=null!==(d=null==t?void 0:t.wta)&&void 0!==d?d:""),Array.isArray(null===(c=u.condition_result)||void 0===c?void 0:c.when_not_to_apply)?k=u.condition_result.when_not_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join("\n"):m(u,"wnta")&&void 0!==(null==u?void 0:u.wnta)?k=null!==(v=null==u?void 0:u.wnta)&&void 0!==v?v:"":m(t,"wnta")&&void 0!==(null==t?void 0:t.wnta)&&(k=null!==(_=null==t?void 0:t.wnta)&&void 0!==_?_:""),void 0!==A){var N=Ir(A);Sr(x,M,A,N,lt,st,null==u?void 0:u.conflict_view),wr(x,M,"wta")}if(void 0!==k){var E=Ir(k);Sr(x,M,k,E,dt,ct,null==u?void 0:u.conflict_view),wr(x,M,"wnta")}if(m(u,"rule_description")&&void 0!==(null==u?void 0:u.rule_description)?I=null!==(p=null==u?void 0:u.rule_description)&&void 0!==p?p:"":m(t,"rule_description")&&void 0!==(null==t?void 0:t.rule_description)&&(I=null!==(g=null==t?void 0:t.rule_description)&&void 0!==g?g:""),void 0!==I){var O=Ir(I);at(function(e){var n=new Map(e),t=new Map(n.get(x)||new Map);return t.set(M,O),n.set(x,t),n}),wr(x,M,"ruleDescription")}var L=void 0;m(u,"scheduling_config")&&void 0!==(null==u?void 0:u.scheduling_config)?L=null==u?void 0:u.scheduling_config:m(t,"scheduling_config")&&void 0!==(null==t?void 0:t.scheduling_config)&&(L=null==t?void 0:t.scheduling_config),L&&(Bn(function(e){var n,i,r,a,o,l,s=new Map(e),u=new Map(s.get(x)||new Map);return u.set(M,{order_rules:{enabled:!!(null===(n=L.order_rules)||void 0===n?void 0:n.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(i=L.order_rules)||void 0===i?void 0:i.global_min_separation_seconds)||0)/60)},advertiser_rules:{enabled:!!(null===(r=L.advertiser_rules)||void 0===r?void 0:r.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(a=L.advertiser_rules)||void 0===a?void 0:a.global_min_separation_seconds)||0)/60)},inventory_rules:{respect_inventory_code:!!(null===(o=L.inventory_rules)||void 0===o?void 0:o.respect_inventory_code)},break_code_rules:{respect_break_code:!!(null===(l=L.break_code_rules)||void 0===l?void 0:l.respect_break_code)},is_default_enabled:"Default"===(null==t?void 0:t.variant_type)||"default_variant"===(null==t?void 0:t.variant_type)||"default"===(null==t?void 0:t.variant_type)}),s.set(x,u),s}),wr(x,M,"order_enabled"),wr(x,M,"advertiser_enabled"),wr(x,M,"respect_inventory_code"),wr(x,M,"respect_break_code")),pt(function(t){if(!Array.isArray(t)||M<0||!t[M])return t;var i=n([],t,!0),r=e({},i[M]);return void 0!==A&&(r.wta=A),void 0!==k&&(r.wnta=k),void 0!==I&&(r.rule_description=Ir(I)),L&&(r.scheduling_config=L),console.log("updated variantxxx",r),i[M]=r,i});var R=null==t?void 0:t.variant_type;R&&pt(function(t){var i=Array.isArray(t)?n([],t,!0):[],r=i.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===T||(null==e?void 0:e.variant_id)&&e.variant_id===(null==u?void 0:u.set_variant_id)||(null==e?void 0:e.variantId)===T});return-1!==r?i[r]=e(e({},i[r]),{variant_type:R}):i[M]=e(e({},i[M]||{}),{variant_type:R,variant_id:T||(null==u?void 0:u.set_variant_id)}),i})}})):console.warn("⚠️ parsed.is_valid is false, not committing to structuredAIResponse"),w||(c?(Mt(!0),m&&m!==gi.current?(console.log("🚀 New Variant detected (".concat(m,"). Triggering loader.")),Ai(!0),Ji("Loading a variant"),console.log("reaching here in new variant flow"),Bi("This may take a moment as we update the rule with the new variant."),gi.current=m):m||console.log("ℹ️ Variant flow detected without specific ID.")):(Mt(!1),gi.current=null),d&&Pt(d))},"Rule comparison results":function(e){try{var n=e;if("string"==typeof e)try{n=JSON.parse(e)}catch(t){n=N(e)||[]}if(!Array.isArray(n)){if(!n||"object"!=typeof n)return void console.error("[Rule comparison results] Data is not an array:",e);n=[n]}var t=n.map(function(e,n){var t,i,r,a,o=null,l=null;if((Array.isArray(e)?e:[e]).forEach(function(e){e&&(e.intent_output&&(o=e.intent_output),e.behaviour_output&&(l=e.behaviour_output))}),"string"==typeof o)try{o=JSON.parse(o)}catch(e){console.error("Failed to parse intent_output",e)}if("string"==typeof l)try{l=JSON.parse(l)}catch(e){console.error("Failed to parse behaviour_output",e)}var s="existing_variant",u="fallback-id-".concat(Math.random()),d=(null==o?void 0:o.documents)||(null==l?void 0:l.documents);if(d){var c=Object.keys(d).find(function(e){return"reference"===d[e].role});c&&(s=c,u="".concat(c,"-").concat(n))}var v="";if((null==o?void 0:o.nodes)&&o.nodes.title){var _=o.nodes.title;(null===(i=null===(t=null==_?void 0:_.comparison_inputs)||void 0===t?void 0:t[s])||void 0===i?void 0:i.content)&&(v=_.comparison_inputs[s].content)}var p="Score";(null==l?void 0:l.final_score)&&(p=l.final_score);var f="Unknown Tier",g=(null===(r=null==d?void 0:d[s])||void 0===r?void 0:r.title)||(null===(a=null==d?void 0:d.existing_variant)||void 0===a?void 0:a.title);return g&&g.includes("|")&&(f=g.split("|")[1].trim()),console.log("Extracted for carousel:",{uniqueId:u,extractedTitle:v,extractedScore:p,extractedScope:f}),{id:u,title:v,similarityScoreText:p,scope:f,intentTreeData:o,behaviorTreeData:l,isLoading:!1}});an(t)}catch(e){console.error("[Rule comparison results] Critical Handler Error:",e)}}},kr=function(e){var n=Array.isArray(e)?e.join(" "):String(e||""),t=null==n?void 0:n.match(/<ai_reasoning>([\s\S]*?)<\/ai_reasoning>/);return t?t[1]:null},Ir=function(e){return"string"!=typeof e?"":e.replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g,"").replace(/<!--```json[\s\S]*?```-->/g,"").trim()},Sr=function(t,i,r,a,o,l,s){var u;if(void 0!==r){var d=(o.get(t)||new Map).get(i)||[],c=d.map(function(e){return e.text}).join("\n"),v=(null===(u=d[(null==d?void 0:d.length)-1])||void 0===u?void 0:u.reasoning)||"",_=kr(r)||"";if(""===r&&d.length>0||a.trim()!==c.trim()||_!==v){var p=""===r?{updatedItems:[],newIds:[]}:function(t,i,r){if(!t.trim())return{updatedItems:n([],i,!0),newIds:[]};var a=t.match(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g)||[],o=t.replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g,"").replace(/<!--```json[\s\S]*?```-->/g,""),l=[],s=o.replace(/<conflicting>[\s\S]*?<\/conflicting>/g,function(e){return l.push(e),"__CONFLICT_BLOCK_".concat((null==l?void 0:l.length)-1,"__")}).split(/\s*(?:\r?\n|\\+n)\s*/).map(function(e){return e.trim().replace(/^-\s*/,"")}).filter(Boolean),u=new Map(i.map(function(e){return[e.text,e]})),d=[],c=[],v=Array.isArray(null==r?void 0:r.wta)&&t.includes("wta")?r.wta:Array.isArray(null==r?void 0:r.wnta)?r.wnta:[];return s.forEach(function(n,t){var i=n;i.includes("__CONFLICT_BLOCK_")&&(i=i.replace(/__CONFLICT_BLOCK_(\d+)__/g,function(e,n){return l[parseInt(n)]}));var r=a[t]||"",o=i.replace(/<conflicting>[\s\S]*?<\/conflicting>/g,"").trim(),s=null==v?void 0:v.find(function(e){return e.value===o}),_=u.get(i);if(_)c.push(e(e({},_),{reasoning:r||_.reasoning,conflict:s||_.conflict}));else{var p="new-".concat(Date.now(),"-").concat(t);d.push(p),c.push({id:p,text:i,reasoning:r,conflict:s})}}),{updatedItems:c,newIds:d}}(r,d,s),f=p.updatedItems,g=p.newIds;l(function(e){var n=new Map(e),r=new Map(n.get(t)||new Map);return r.set(i,f),n.set(t,r),n}),(null==g?void 0:g.length)>0&&(Qt(function(e){return new Set(n(n([],Array.from(e),!0),g,!0))}),setTimeout(function(){Qt(function(e){var n=new Set(e);return g.forEach(function(e){return n.delete(e)}),n})},1500))}}},Cr=function(e){return(Array.isArray(e)?e:e?[e]:[]).map(function(e){return String(e).replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/,"").trim().replace(/_/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()})})};d(function(){Et&&!Le.current&&"save this learning"!==Et.toLowerCase()&&(Ce(!1),ke(""),mi.current=null!=Ct?Ct:-1)},[Et]),d(function(){var t,i,r,a,o,l,s,u,d;if(jn.current=ri,Array.isArray(_t)&&_t.length>0){var c=li||"local-".concat(Date.now()),v=["ruleTitle","ruleDescription","whenToApply","whenNotToApply","scopeData","configData"],_={},p=fi.current||[];_t.forEach(function(t,i){var r,a;if(t){t.is_readOnly||($e.current=i);var o=i;if((null==t?void 0:t.variant_id)&&ne)-1!==(l=ne.findIndex(function(e){return e.variantId===t.variant_id}))&&(o=l);else if(Qi&&ne&&1===_t.length){var l;-1!==(l=ne.findIndex(function(e){return e.variantId===Qi}))&&(o=l)}var s=null!==(r=p[o])&&void 0!==r?r:p[i],u=null!==(a=t.scope)&&void 0!==a?a:null==s?void 0:s.scope,d=Cr(u).map(function(e){return e.toLowerCase().replace(/ /g,"_")}),c=d.length>0?d:gn.current.length>0?gn.current:["tier_1"];c.length>0&&(gn.current=c),console.log("prevTierRef.current",gn.current,"targetTiers",c);var f=Ir(t.title);f&&f!==Ir(null==s?void 0:s.title)&&!t.is_readOnly&&function(e,n,t,i,r,a){var o=Ir(i);o&&o!==r&&(wr(e,n,t),a(o))}("global",0,"ruleTitle",t.title,$n,Xn),c.forEach(function(r){var a,l,s,u,d,c=null!==(a=p[o])&&void 0!==a?a:p[i],f=!c,g=void 0!==t.rule_description&&null!==t.rule_description,m=Ir(t.rule_description),w=(null===(l=rt.get(r))||void 0===l?void 0:l.get(o))||"",y=Ir(w);g&&(m!==y||""===m&&""!==w)&&(at(function(e){var n=new Map(e),i=new Map(n.get(r)||new Map);return i.set(o,t.rule_description),n.set(r,i),n}),wr(r,o,"ruleDescription"));var h=!1===(null==Rt?void 0:Rt.is_valid),b=Ir(t.wta),T=Ir(null==c?void 0:c.wta),M=(null===(s=lt.get(r))||void 0===s?void 0:s.get(o))||[];!(h&&""===b&&M.length>0)&&void 0!==t.wta&&null!==t.wta&&(b!==T||""===b&&M.length>0||0===M.length&&""!==b)&&(Sr(r,o,t.wta,b,lt,st,null==Rt?void 0:Rt.conflict_view),wr(r,o,"wta"));var A=Ir(t.wnta),k=Ir(null==c?void 0:c.wnta),I=(null===(u=dt.get(r))||void 0===u?void 0:u.get(o))||[];if(!(h&&""===A&&I.length>0)&&void 0!==t.wnta&&null!==t.wnta&&(A!==k||""===A&&I.length>0||0===I.length&&""!==A)&&(Sr(r,o,t.wnta,A,dt,ct,null==Rt?void 0:Rt.conflict_view),wr(r,o,"wnta")),t.scheduling_config||f||t.variant_type||t.variantType){var S=t.scheduling_config||{order_rules:{enabled:!1,global_min_separation_seconds:0},advertiser_rules:{enabled:!1,global_min_separation_seconds:0},inventory_rules:{respect_inventory_code:!1},break_code_rules:{respect_break_code:!1}},C=null==c?void 0:c.scheduling_config,x=null===(d=Hn.get(r))||void 0===d?void 0:d.get(o),N=t.variant_type||t.variantType,E=N?G(N):void 0,O=JSON.stringify(S)!==JSON.stringify(C),L=void 0!==E&&E!==(null==x?void 0:x.is_default_enabled),R=function(n,t){if(!n)return t;if(!t)return n;var i=e({},n);for(var r in t)t[r]&&"object"==typeof t[r]&&!Array.isArray(t[r])?i[r]=e(e({},i[r]||{}),t[r]):i[r]=t[r];return i};if(Ht(function(e){return R(e,S)}),O||L){Ht(function(e){return R(e,S)});var D=function(e,n,t,i){var r,a,o,l,s=[],u=(i.get(e)||new Map).get(n)||{order_rules:{enabled:!1,global_min_separation_seconds:0},advertiser_rules:{enabled:!1,global_min_separation_seconds:0},inventory_rules:{respect_inventory_code:!1},break_code_rules:{respect_break_code:!1}};return Math.floor(((null===(r=t.order_rules)||void 0===r?void 0:r.global_min_separation_seconds)||0)/60)!==u.order_rules.global_min_separation_seconds&&s.push("config_order_rules"),Math.floor(((null===(a=t.advertiser_rules)||void 0===a?void 0:a.global_min_separation_seconds)||0)/60)!==u.advertiser_rules.global_min_separation_seconds&&s.push("config_advertiser_rules"),!!(null===(o=t.inventory_rules)||void 0===o?void 0:o.respect_inventory_code)!==u.inventory_rules.respect_inventory_code&&s.push("config_inventory_rules"),!!(null===(l=t.break_code_rules)||void 0===l?void 0:l.respect_break_code)!==u.break_code_rules.respect_break_code&&s.push("config_break_code_rules"),!!t.is_default_enabled!=!!u.is_default_enabled&&s.push("config_is_default_enabled"),s}(r,o,S,Hn);D.forEach(function(e){return wr(r,o,e)}),Yn(function(e){return new Set(e).add("config")}),Bn(function(n){var t,i,a,l,s,u,d=new Map(n),c=new Map(d.get(r)||new Map),v=c.get(o)||Jn;return c.set(o,e(e(e(e(e(e({},v),S.order_rules&&{order_rules:{enabled:!!(null===(t=S.order_rules)||void 0===t?void 0:t.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(i=S.order_rules)||void 0===i?void 0:i.global_min_separation_seconds)||0)/60)}}),S.advertiser_rules&&{advertiser_rules:{enabled:!!(null===(a=S.advertiser_rules)||void 0===a?void 0:a.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(l=S.advertiser_rules)||void 0===l?void 0:l.global_min_separation_seconds)||0)/60)}}),S.inventory_rules&&{inventory_rules:{respect_inventory_code:!!(null===(s=S.inventory_rules)||void 0===s?void 0:s.respect_inventory_code)}}),S.break_code_rules&&{break_code_rules:{respect_break_code:!!(null===(u=S.break_code_rules)||void 0===u?void 0:u.respect_break_code)}}),void 0!==E&&{is_default_enabled:E})),d.set(r,c),d}),tt(function(e){var n=new Map(e),t=new Map(n.get(r)||new Map),i=t.get(o)||new Set;return S.order_rules&&i.add("order_rules"),S.advertiser_rules&&i.add("advertiser_rules"),S.inventory_rules&&i.add("inventory_rules"),S.break_code_rules&&i.add("break_code_rules"),void 0!==E&&i.add("is_default_enabled"),t.set(o,i),n.set(r,t),n})}}var j={ruleTitle:t.title,ruleDescription:t.rule_description,whenToApply:t.wta,whenNotToApply:t.wnta,scopeData:t.scope,configData:t.action};t.is_readOnly||v.forEach(function(e){var n=kr(j[e]),t="ruleTitle"===e||"scopeData"===e?e:"".concat(e,"_").concat(r);n&&(n!==Dn.current[t]&&(Dn.current[t]=n,Pn.current[t]=!0,_[t]={reasoning:n,associatedCitations:[],tier:r,variantIndex:o}))}),t.conflictingConditions&&(Si(function(n){var i=e({},n);return t.conflictingConditions.forEach(function(e){e.condition_wta&&(i["whenToApply-".concat(r,"-").concat(o)]=e.reason),e.condition_wnta&&(i["whenNotToApply-".concat(r,"-").concat(o)]=e.reason)}),i}),Yn(function(e){return new Set(n(n([],Array.from(e),!0),["conditions"],!1))}))})}});var f=-1,g=!(!X&&!ne),m="edit"===Ki||"edit_current_rule"===Ki,w=function(e,n){return(null==e?void 0:e.variant_id)&&e.variant_id===n||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===n||(null==e?void 0:e.id)&&e.id===n},y=function(e,n){if(!n)return-1;var t=e.find(function(e){return w(e,n)});if(!t)return-1;var i=String((null==t?void 0:t.tier_id)||"");if(!i)return e.findIndex(function(e){return w(e,n)});var r=e.filter(function(e){return String((null==e?void 0:e.tier_id)||"")===i}).findIndex(function(e){return w(e,n)});return-1!==r?r:e.findIndex(function(e){return w(e,n)})};if(g)if(gi.current&&Tt)-1!==(f=_t.findIndex(function(e){return(null==e?void 0:e.new_variant_id)&&e.new_variant_id===gi.current||(null==e?void 0:e.variant_id)&&e.variant_id===gi.current||(null==e?void 0:e.id)&&e.id===gi.current}))&&(gi.current=null);else if(Qi||Xi){var h;(h=Qi||Xi)&&(f=y(_t,h))}else if(re&&Array.isArray(_t)&&_t.length>0){for(b=_t.length-1;b>=0;b--)if(_t[b]&&!(null===(i=_t[b])||void 0===i?void 0:i.is_readOnly)){f=b;break}}else null==te||fi.current&&0!==fi.current.length||(f=te);else if((h=Qi||Xi||gi.current)&&m&&(f=y(_t,h)),!m&&-1===f&&Array.isArray(_t)&&_t.length>0){for(var b=_t.length-1;b>=0;b--)if(_t[b]&&!(null===(t=_t[b])||void 0===t?void 0:t.is_readOnly)){f=b;break}-1===f&&(f=_t.length-1)}-1!==f&&Ct!==f&&(mi.current===f||He.current&&!m||(console.log("🎯 Setting active variant accordion to index ".concat(f," (").concat(g?"EDIT":"CREATE"," mode)")),xt(f),mi.current=f));var T=_t[0];if(T){if(T.scope&&JSON.stringify(T.scope)!==JSON.stringify(null===(r=p[0])||void 0===r?void 0:r.scope)&&"copy"!==T.action&&(l=T.scope,s=null===(a=p[0])||void 0===a?void 0:a.scope,u=Cr(l),d=s?Cr(s):[],pe(function(n){return e(e({},n),{tiers:u})}),u.forEach(function(e){var n=e.trim();d.includes(e)||wr("global",0,"scope_".concat(n))})),T.scope_rule_set&&T.scope_rule_set!==(null===(o=p[0])||void 0===o?void 0:o.scope_rule_set)){var M=T.scope_rule_set.toLowerCase().trim();["global","genre","custom"].includes(M)&&(pe(function(n){return e(e({},n),{station:M})}),wr("global",0,"scope_station"))}T.wtl&&Qn(T.wtl)}fi.current=_t.map(function(e){return e?(n=e,"function"==typeof(t=null===globalThis||void 0===globalThis?void 0:globalThis.structuredClone)?t(n):JSON.parse(JSON.stringify(n))):e;var n,t}),Object.keys(_).length>0&&(or({type:"SAVE_CITATIONS",requestId:c,reasoningMap:_,rawCitations:ri}),function(e){var n=e.requestId,t=e.keys,i=e.newReasoningMap,r=e.getLatestReasoning,a=e.currentCitations;console.group("%c Citation Audit: ".concat(n," "),"background: #5928ed; color: #fff; font-weight: bold;");var o={};t.forEach(function(e){var n=r(e),t=!!i[e],l=t?a:(null==n?void 0:n.associatedCitations)||[];o[e]={Status:t?"NEW ✅":n?"FALLBACK 🔄":"EMPTY ❌",Source:t?"Current Msg":n?"History":"N/A","Reasoning Preview":t?i[e].reasoning:(null==n?void 0:n.reasoning)||"None","Full Citations":l}}),console.table(o),console.groupEnd()}({requestId:c,keys:Object.keys(_),newReasoningMap:_,getLatestReasoning:lr,currentCitations:ri}),ti(function(n){var t=e({},n),i=!1;return Object.keys(_).forEach(function(e){var n=_[e];n.reasoning&&t[e]!==n.reasoning&&(t[e]=n.reasoning,i=!0),n.associatedCitations}),i?t:n}))}},[_t,ri,li]),d(function(){var t=Object.keys(Pn.current);if(0!==t.length){var i={};t.forEach(function(e){i[e]=n([],ri,!0)}),Pn.current={},ci(function(n){return e(e({},n),i)})}},[ri]);var xr=function(e){return e.map(function(e){var n;return null===(n=e.match(/\d+/))||void 0===n||n[0],e.replace(/\s+/g,"-"),{name:"Custom",parentScopeId:null,scopeRowId:(null==$?void 0:$.ruleSetId)||"",value:{scopeName:(null==$?void 0:$.ruleSetName)||"",scopeId:"Audacy_"+m(),customScopeGroupName:(null==Fn?void 0:Fn.CUSTOM_SCOPE_GROUP_NAME)||"",description:(null==$?void 0:$.ruleSetDesc)||""}}})},Nr=function(e){var n={};return Object.entries(e).forEach(function(e){var t,i=e[0],r=e[1];if("custom_sep_time_for_entities"===i&&r)n.custom_sep_time_for_entities=r;else if("max_priority_override"===i&&r&&void 0!==r.override_priority_code)n.override_priority_code=r.override_priority_code;else if("advertiser_pair_break_constraint"===i&&r)n.advertiser_pair_break_constraint=r.advertiser_pair_list;else if(r&&"object"==typeof r&&(null===(t=Object.keys(r))||void 0===t?void 0:t.length)>0){var a=i.replace(/_rules$/,""),o=["global_min_separation_seconds","respect_inventory_code","respect_break_code","exemption_advertiser_list","exemption_break_code_list","exemption_priority_code_list","priority_code_list","exemption_product_code_list","condition_advertiser_list","condition_break_code_list","condition_priority_code_list","condition_product_code_list"];Object.entries(r).forEach(function(e){var t=e[0],r=e[1];if(o.includes(t)&&("product_rules"!==i||"global_min_separation_seconds"!==t)){var l="respect_inventory_code"===t||"respect_break_code"===t?t:"".concat(a,"_").concat(t);n[l]=r}})}else if(void 0!==r&&"object"!=typeof r){if("station_guid"===i||"is_default_enabled"===i)return;n[i]=r}}),{config_structure:{scheduling_config:{advertiser_exemption_advertiser_list:"array",advertiser_exemption_break_code_list:"array",advertiser_exemption_priority_code_list:"array",advertiser_exemption_product_code_list:"array",advertiser_global_min_separation_seconds:"int",break_code_exemption_advertiser_list:"array",break_code_exemption_break_code_list:"array",break_code_exemption_priority_code_list:"array",break_code_exemption_product_code_list:"array",custom_sep_time_for_entities:"object",inventory_exemption_advertiser_list:"array",inventory_exemption_break_code_list:"array",inventory_exemption_priority_code_list:"array",inventory_exemption_product_code_list:"array",order_exemption_advertiser_list:"array",order_exemption_break_code_list:"array",order_exemption_priority_code_list:"array",order_exemption_product_code_list:"array",order_global_min_separation_seconds:"int",override_priority_code:"str",product_exemption_advertiser_list:"array",product_exemption_break_code_list:"array",product_exemption_priority_code_list:"array",product_exemption_product_code_list:"array",max_priority_override_priority_code_list:"array",max_priority_override_exemption_advertiser_list:"array",max_priority_override_exemption_break_code_list:"array",max_priority_override_exemption_priority_code_list:"array",max_priority_override_exemption_product_code_list:"array",first_in_break_exemption_advertiser_list:"array",first_in_break_exemption_break_code_list:"array",first_in_break_exemption_priority_code_list:"array",first_in_break_exemption_product_code_list:"array",first_in_break_condition_advertiser_list:"array",first_in_break_condition_break_code_list:"array",first_in_break_condition_priority_code_list:"array",first_in_break_condition_product_code_list:"array",advertiser_pair_break_constraint:"array",respect_break_code:"bool",respect_inventory_code:"bool"}},config_data:{scheduling_config:n}}},Er=function(n,t,i,r){void 0===r&&(r=0);var a=e({},t||{});return n.forEach(function(n,o){var l=n.get(r);l&&l.forEach(function(n){var l,s=t[n]||{},u=i.get(o),d=null==u?void 0:u.get(r),c=null==d?void 0:d[n];if("order_rules"===n||"advertiser_rules"===n){var v=null!==(l=null==c?void 0:c.enabled)&&void 0!==l&&l?60*((null==c?void 0:c.global_min_separation_seconds)||0):0;a[n]=e(e({},s),{global_min_separation_seconds:v})}else a[n]="inventory_rules"===n?e(e({},s),{respect_inventory_code:null==c?void 0:c.respect_inventory_code}):"break_code_rules"===n?e(e({},s),{respect_break_code:null==c?void 0:c.respect_break_code}):"is_default_enabled"===n?null!=c&&c:s})}),a},Or=function(e,n,t){void 0===t&&(t="variantType");var i=null==e?void 0:e[n];if(!i)return{label:Tr(e),isDefault:!1};var r=i[t]||"",a=G(r);return{label:"variant ".concat(n+1),isDefault:a}},Lr=function(e,n){var t=G(e);return{label:"variant ".concat(n+1),isDefault:t}},Rr=function(e,n,t){var i;void 0===t&&(t="");var r=null===(i=Hn.get(e))||void 0===i?void 0:i.get(n);return r?r.is_default_enabled?"Default":"Variant":G(t)?"Default":"Variant"},Dr=function(n,o){return void 0===o&&(o=!1),t(void 0,void 0,void 0,function(){var n,t,l,s,u,d,c,v,p,g,w,h,b,T,M;return i(this,function(i){switch(i.label){case 0:xr(_e.tiers),n=$e.current,t=Er(nt,Ut,Hn,n),i.label=1;case 1:return i.trys.push([1,3,,4]),me(q),ke(""),l=Nr(t),s=m(),u=[],d=[],c=(_t||[])[n]||{},console.log("originalItem check :",c,n),_e.tiers.forEach(function(t){var i,r,a,o,v,_,p,f=t.toLowerCase().replace(/ /g,"_");d.push(f);var g=(null===(i=rt.get(f))||void 0===i?void 0:i.get(n))||"",m=(null===(r=lt.get(f))||void 0===r?void 0:r.get(n))||[],w=(null===(a=dt.get(f))||void 0===a?void 0:a.get(n))||[],h=[e(e({},l&&{config:e({master_name:Fn.CONFIG_MASTER_NAME},l)}),{datasource:{type:"link",ref:"www.something.com",tag:"something"},tierLinkId:s,variant:Ir(g),conditions_whentoapply:m.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),conditions_whennottoapply:w.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),isDefault:null===(_=null===(v=null===(o=Hn.get(f))||void 0===o?void 0:o.get(n))||void 0===v?void 0:v.is_default_enabled)||void 0===_||_,tier_id:(null===(p=Re.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===f||e.tier_name.toLowerCase()===f.replace(/_/g,"")}))||void 0===p?void 0:p.tier_id)||"",topic_id:null,scope_id:(null==$?void 0:$.ruleSetId)||"",question_title:$n,variantType:Rr(f,n,c.variant_type||c.variantType),instantLearningType:Fn.INSTANT_LEARNING_TYPE,is_user_accepted_risk:!1,propagation:!1,applicationMappingId:ce,modeId:"019e1e39-2030-7775-8312-0ad525700588"})];u.push(y(h,Fn.ASSISTANT_NAME))}),[4,Promise.all(u)];case 2:return v=i.sent(),Oe(!1),console.log("✅ All feedback published:",v),me(V),he(!0),p=new Map,v.forEach(function(e,n){var t,i,r=d[n],a=(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.id)||(null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.variant_id)&&e.data.variant_id||(null==e?void 0:e.id)||(null==e?void 0:e.variant_id)&&e.variant_id;if(a||"string"!=typeof(null==e?void 0:e.data)||(a=e.data),a&&"string"==typeof a){var o=p.get(r)||[];o.push({id:a,action:"new"}),p.set(r,o)}}),A.getState().setCreatedVariantInfo(Array.from(p.entries()).map(function(e){return{tierName:e[0],variants:e[1]}})),null===(b=wi.current)||void 0===b||b.show({severity:"success",sticky:!1,life:6e3,className:k.toastSuccess,content:r("div",e({className:k.toastContent},{children:[r("div",e({className:k.toastHeaderLeft},{children:[a(f,{className:k.iconSuccess}),a("span",e({className:"".concat(k.toastTitle," ").concat(k.toastTitleSuccess)},{children:"Success"}))]})),a("p",e({className:"".concat(k.toastMessage," ").concat(k.toastMessageSuccess)},{children:"Learning saved successfully!"}))]}))}),xe.current=setTimeout(function(){Oi||o?(console.log("Closing modal after save success",{isCloseModal:Oi,forceClose:o}),ta()):br(!0)},3e3),[3,4];case 3:return g=i.sent(),console.error("❌ Error publishing feedback:",g),Oe(!1),me(P),Ce(!0),w=(null===(T=null==g?void 0:g.response)||void 0===T?void 0:T.data)||{},console.log("errorData: ",w),(h="Variant already exists"===(null==w?void 0:w.message))||409===(null==g?void 0:g.status)?ke('Looks like a similar rule already exists with the same conditions. You can update the description or conditions to make it unique, or discard this learning. <br/> How would you like to proceed?\n <br/><button class="clickable-button" data-value="Discard learning">Discard learning</button>\n <br/><button class="clickable-button" data-value="Continue editing learning">Continue editing learning</button>\n <br/><button class="clickable-button" id="typeYourAnswer">Or, type your response</button>'):ke(((null==w?void 0:w.message)||(null==w?void 0:w.detail)||"Error Occurred while saving the rule.")+'Please try again.<br/><button class="clickable-button" data-value="Save this Learning">Retry</button>'),null===(M=wi.current)||void 0===M||M.show({severity:"error",sticky:!1,className:k.toastError,content:r("div",e({className:k.toastContent},{children:[r("div",e({className:k.toastHeaderLeft},{children:[a(_,{className:k.iconError}),a("span",e({className:"".concat(k.toastTitle," ").concat(k.toastTitleError)},{children:"Error"}))]})),a("p",e({className:"".concat(k.toastMessage," ").concat(k.toastMessageError)},{children:h||409===(null==g?void 0:g.status)?"Similar rule already exists. Please update and try again.":(null==w?void 0:w.message)||(null==w?void 0:w.detail)||"Something went wrong while saving the learning!"}))]}))}),[3,4];case 4:return[2]}})})},jr=function(){return t(void 0,void 0,void 0,function(){var t,o,l,s,u,d,c,v,p,g,w,b,T,M,I,S,C,x,N,E,O,L,R,D,j,J;return i(this,function(i){switch(i.label){case 0:t=A.getState().tiers,o=Er(nt,Ut,Hn),l=Nr(o),s=$e.current,u=(_t||[])[s]||{},d=(null==Rt?void 0:Rt.variant_type)||u.variant_type||"",i.label=1;case 1:for(i.trys.push([1,3,,4]),me(q),ke(""),v=(c=ne||[]).length>0?null===(O=c.find(function(e){return(null==e?void 0:e.link_id)&&""!==e.link_id.trim()}))||void 0===O?void 0:O.link_id:null,p=(null===(L=_e.tiers[0])||void 0===L?void 0:L.toLowerCase().replace(/ /g,"_"))||"tier_1",g=(null===(R=rt.get(p))||void 0===R?void 0:R.size)||c.length,w=n([],c,!0),b=c.length;b<g;b++)w.push({isNewVariant:!0,variantId:m()});return T=[],M=[],I=xr(_e.tiers),_e.tiers.forEach(function(n){var i=n.toLowerCase().replace(/ /g,"_"),r=t.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===i||e.tier_name.toLowerCase()===i.replace(/_/g,"")}),a=rt.get(i),o=lt.get(i),s=dt.get(i);w.forEach(function(t,c){var _,p,f,g,w,b,A,k,S,C,x,N,E,O,L,R,D,j,V,P,q,J,U,H,B,W,K,Y,z=(null==a?void 0:a.get(c))||t.description||"",Q=(null==o?void 0:o.get(c))||[],Z=(null==s?void 0:s.get(c))||[];if(t.isNewVariant){M.push({tierKey:i,payloadType:"new"});var ee=Er(nt,Ut,Hn,c),ne=Nr(ee);console.log("variant in save edit add part :",t,u);var te={status:"approved",metadata:e(e({userName:null!==(_=null==rr?void 0:rr.firstname)&&void 0!==_?_:"",userEmailId:null!==(p=null==rr?void 0:rr.email)&&void 0!==p?p:"",llm:Fn.MODEL,isVariantFlow:!0},ne&&{config:e({master_name:Fn.CONFIG_MASTER_NAME},ne)}),{datasource:{type:"link",ref:"www.something.com",tag:"something"},variant:{tierLinkId:v||m(),variant:Ir(z),conditions_whentoapply:Q.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),conditions_whennottoapply:Z.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),referenceVariantID:null,referenceVariantIDVersion:null,scope:I[0]||{name:Fn.SCOPE_NAME,parentScopeId:null,scopeRowId:(null==$?void 0:$.ruleSetId)||"",value:{scopeName:(null==$?void 0:$.ruleSetName)||"",scopeId:"Audacy_"+m(),customScopeGroupName:Fn.CUSTOM_SCOPE_GROUP_NAME,description:(null==$?void 0:$.ruleSetDesc)||""}},overriden:!1,isDefault:null!==(w=null===(g=null===(f=Hn.get(i))||void 0===f?void 0:f.get(c))||void 0===g?void 0:g.is_default_enabled)&&void 0!==w?w:G(t.variantType||t.variant_type||(0===c?"Default":"variant")),tier:{name:n.split(" ").join("").toLowerCase(),tierGroupName:Fn.CUSTOM_SCOPE_GROUP_NAME,tierPriority:parseInt(n.split(" ")[1]||"1")},topic:{id:null,value:"".concat(_e.station,"RuleSet"),description:null},categories:[{id:null,value:Fn.CATEGORY,description:Fn.CATEGORY}],originalQuestion:$n,questionId:null==X?void 0:X.ruleId,variantType:Rr(i,c,u.variant_type||""),parameterizedQuestion:null,created_at:(new Date).toISOString(),created_by:null!==(b=null==rr?void 0:rr.email)&&void 0!==b?b:"",instantLearningType:Fn.INSTANT_LEARNING_TYPE,appliedTagsIL:[],tagMappingInfoIL:{},is_user_accepted_risk:!!(null!==(k=null===(A=(_t||[])[c])||void 0===A?void 0:A.is_user_accepted_risk)&&void 0!==k?k:null==Rt?void 0:Rt.is_user_accepted_risk)},isAgentsFeedback:!0})};console.log("payload (publish new variant)",te),T.push(y(te,Fn.ASSISTANT_NAME))}else{M.push({tierKey:i,payloadType:"existing",existingId:t.variantId});var ie=t.variantId===Qi,re=Rr(i,c,ie?d||t.variantType||"":t.variantType||"");console.log("isThisVariantBeingEdited variantTypeToUse :",re,ie,t,Qi);var ae={variantId:t.variantId,ruleDesc:(null==$?void 0:$.ruleSetDesc)||"",whenToApply:Q.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),whenNotToApply:Z.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),isDefault:null!==(x=null===(C=null===(S=Hn.get(i))||void 0===S?void 0:S.get(c))||void 0===C?void 0:C.is_default_enabled)&&void 0!==x?x:G(t.variantType||t.variant_type||(0===c?"Default":"variant")),tier:{tier_id:(null==r?void 0:r.tier_id)||"",tier_name:(null==r?void 0:r.tier_name)||n,tier_priority:null!==(N=null==r?void 0:r.tier_priority)&&void 0!==N?N:null},scope_id:(null==$?void 0:$.ruleSetId)||"",description:Ir(z)||"",topic:"".concat(_e.station,"RuleSet"),configuration:(null==l?void 0:l.config_data)||{},tierLinkId:null!=v?v:null,variantType:re,is_user_accepted_risk:!!(null!==(O=null===(E=(_t||[])[c])||void 0===E?void 0:E.is_user_accepted_risk)&&void 0!==O?O:null==t?void 0:t.is_user_accepted_risk),is_enabled:t.is_enabled},oe=(gt.get(i)||[]).find(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===t.variantId}),le=!0;if(oe){var se=function(e){var n=(e||"").trim();return(n=F(n)).replace(/\s+/g," ").replace(/(\s*OR\s*)/g," OR ")},ue=se($n)===se(oe.title),de=se(z)===se(oe.rule_description),ce=se(ae.whenToApply)===se(oe.wta),ve=se(ae.whenNotToApply)===se(oe.wnta),pe=!!ae.isDefault===G(oe.variant_type),fe=oe.scheduling_config||{},ge=null!==(D=null!==(L=fe.order_global_min_separation_seconds)&&void 0!==L?L:null===(R=fe.order_rules)||void 0===R?void 0:R.global_min_separation_seconds)&&void 0!==D?D:0,me=null!==(P=null!==(j=fe.advertiser_global_min_separation_seconds)&&void 0!==j?j:null===(V=fe.advertiser_rules)||void 0===V?void 0:V.global_min_separation_seconds)&&void 0!==P?P:0,we=null!==(U=null!==(J=null===(q=fe.inventory_rules)||void 0===q?void 0:q.respect_inventory_code)&&void 0!==J?J:fe.respect_inventory_code)&&void 0!==U&&U,ye=null!==(W=null!==(B=null===(H=fe.break_code_rules)||void 0===H?void 0:H.respect_break_code)&&void 0!==B?B:fe.respect_break_code)&&void 0!==W&&W,he=(null===(K=Hn.get(i))||void 0===K?void 0:K.get(c))||Jn,be=he.order_rules.enabled===ge>0&&he.order_rules.global_min_separation_seconds===Math.floor(ge/60)&&he.advertiser_rules.enabled===me>0&&he.advertiser_rules.global_min_separation_seconds===Math.floor(me/60)&&he.inventory_rules.respect_inventory_code===we&&he.break_code_rules.respect_break_code===ye;ue&&de&&ce&&ve&&pe&&be&&(le=!1)}le?(console.log("payloadv (update existing variant)",ae),T.push(h(ae,null!==(Y=null==rr?void 0:rr.email)&&void 0!==Y?Y:""))):(console.log("[saveEditedVariant] No changes for variant ".concat(t.variantId,", skipping API call")),T.push(Promise.resolve({data:{id:t.variantId},skipped:!0})))}})}),[4,Promise.all(T)];case 2:return S=i.sent(),console.log("✅ All variants updated:",S),me(V),he(!0),Oe(!1),C=new Map,S.forEach(function(e,n){var t,i;if(!(null==e?void 0:e.skipped)){var r=M[n],a=(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.id)||(null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.variant_id)||(null==e?void 0:e.id)||(null==e?void 0:e.variant_id);a||"string"!=typeof(null==e?void 0:e.data)||(a=e.data);var o="existing"===r.payloadType?r.existingId:a;if(o&&"string"==typeof o){var l=C.get(r.tierKey)||[];l.push({id:o,action:r.payloadType}),C.set(r.tierKey,l)}}}),A.getState().setCreatedVariantInfo(Array.from(C.entries()).map(function(e){return{tierName:e[0],variants:e[1]}})),null===(D=wi.current)||void 0===D||D.show({severity:"success",sticky:!1,life:3e3,className:k.toastSuccess,content:r("div",e({className:k.toastContent},{children:[r("div",e({className:k.toastHeaderLeft},{children:[a(f,{className:k.iconSuccess}),a("span",e({className:"".concat(k.toastTitle," ").concat(k.toastTitleSuccess)},{children:"Success"}))]})),a("p",e({className:"".concat(k.toastMessage," ").concat(k.toastMessageSuccess)},{children:"Changes saved successfully!"}))]}))}),xe.current=setTimeout(function(){ta()},3e3),[3,4];case 3:return x=i.sent(),console.error("❌ Error updating variant:",x),me(P),Ce(!0),Oe(!1),N=(null===(j=null==x?void 0:x.response)||void 0===j?void 0:j.data)||{},console.log("errorData: ",N),(E="Variant already exists"===(null==N?void 0:N.message))||409===(null==x?void 0:x.status)?ke('Looks like a similar rule already exists with the same conditions. You can update the description or conditions to make it unique, or discard this learning. <br/> How would you like to proceed?\n <br/><button class="clickable-button" data-value="Discard learning">Discard learning</button>\n <br/><button class="clickable-button" data-value="Continue editing learning">Continue editing learning</button>\n <br/><button class="clickable-button" id="typeYourAnswer">Or, type your response</button>'):ke(((null==N?void 0:N.message)||(null==N?void 0:N.detail)||"Error Occurred while saving the rule.")+'Please try again.<br/><button class="clickable-button" data-value="Save this Learning">Retry</button>'),null===(J=wi.current)||void 0===J||J.show({severity:"error",sticky:!1,className:k.toastError,content:r("div",e({className:k.toastContent},{children:[r("div",e({className:k.toastHeaderLeft},{children:[a(_,{className:k.iconError}),a("span",e({className:"".concat(k.toastTitle," ").concat(k.toastTitleError)},{children:"Error"}))]})),a("p",e({className:"".concat(k.toastMessage," ").concat(k.toastMessageError)},{children:E||409===(null==x?void 0:x.status)?"Similar rule already exists. Please update and try again.":(null==N?void 0:N.message)||(null==N?void 0:N.detail)||"Something went wrong while saving the learning!"}))]}))}),[3,4];case 4:return[2]}})})},Vr=function(){return t(void 0,void 0,void 0,function(){var n,t,o,l,s,u,d,c,v,p,g,w,b,T,M,I,S,C,x,N,E,O,L,R,D,j,J;return i(this,function(i){switch(i.label){case 0:n=A.getState().tiers,t=Er(nt,Ut,Hn),o=Nr(t),i.label=1;case 1:return i.trys.push([1,9,,10]),me(q),ke(""),0===(l=Array.isArray(_t)?_t:[]).length?(console.warn("No variants found to save."),me(P),[2]):(s=l.filter(function(e){return e.is_new_variant}),u=l.filter(function(e){return!e.is_new_variant&&(null==e?void 0:e.variant_id)}),console.log("[saveLoadAndEditVariant] New: ".concat(s.length,", Existing: ").concat(u.length)),d=u.length>0?null===(R=u.find(function(e){return(null==e?void 0:e.link_id)&&""!==e.link_id.trim()}))||void 0===R?void 0:R.link_id:null,c=[],v=[],p=[],g=[],w=xr(_e.tiers),_e.tiers.forEach(function(t){var i=t.toLowerCase().replace(/ /g,"_"),r=n.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===i||e.tier_name.toLowerCase()===i.replace(/_/g,"")}),a=rt.get(i),s=lt.get(i),u=dt.get(i);l.forEach(function(n,l){var _,f,y,b,T,M,A,k,I,S,C,x,N,E,O,L,R,D,j,V,P,q,J,U,H,B,W,K=(null==a?void 0:a.get(l))||n.rule_description||n.description||"",Y=(null==s?void 0:s.get(l))||[],z=(null==u?void 0:u.get(l))||[];if(n.is_new_variant){var Q=Er(nt,Ut,Hn,l),X=Nr(Q),ee=Rr(i,l,n.variant_type||n.variantType||""),ne={status:"approved",metadata:e(e({userName:null!==(_=null==rr?void 0:rr.firstname)&&void 0!==_?_:"",userEmailId:null!==(f=null==rr?void 0:rr.email)&&void 0!==f?f:"",llm:Fn.MODEL,isVariantFlow:!0},X&&{config:e({master_name:Fn.CONFIG_MASTER_NAME},X)}),{datasource:{type:"link",ref:"www.something.com",tag:"something"},variant:{tierLinkId:d||m(),variant:Ir(K),conditions_whentoapply:Y.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),conditions_whennottoapply:z.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),referenceVariantID:null,referenceVariantIDVersion:null,scope:w[0]||{name:Fn.SCOPE_NAME,parentScopeId:null,scopeRowId:(null==$?void 0:$.ruleSetId)||"",value:{scopeName:(null==$?void 0:$.ruleSetName)||"",scopeId:"Audacy_"+m(),customScopeGroupName:Fn.CUSTOM_SCOPE_GROUP_NAME,description:(null==$?void 0:$.ruleSetDesc)||""}},overriden:!1,isDefault:null!==(T=null===(b=null===(y=Hn.get(i))||void 0===y?void 0:y.get(l))||void 0===b?void 0:b.is_default_enabled)&&void 0!==T?T:G(n.variantType||n.variant_type||(0===l?"Default":"variant")),tier:{name:t.split(" ").join("").toLowerCase(),tierGroupName:Fn.CUSTOM_SCOPE_GROUP_NAME,tierPriority:parseInt(t.split(" ")[1]||"1"),tier_id:(null==r?void 0:r.tier_id)||""},topic:{id:null,value:"".concat(_e.station||Z,"RuleSet"),description:null},categories:[{id:null,value:Fn.CATEGORY,description:Fn.CATEGORY}],originalQuestion:$n,questionId:On.current||null,variantType:ee,parameterizedQuestion:null,created_at:(new Date).toISOString(),created_by:null!==(M=null==rr?void 0:rr.email)&&void 0!==M?M:"",instantLearningType:Fn.INSTANT_LEARNING_TYPE,appliedTagsIL:[],tagMappingInfoIL:{},is_user_accepted_risk:!!(null!==(A=null==n?void 0:n.is_user_accepted_risk)&&void 0!==A?A:null==Rt?void 0:Rt.is_user_accepted_risk)},isAgentsFeedback:!0})};console.log("[saveLoadAndEditVariant] publish payload (new variant)",ne),v.push({payload:ne,tierKey:i}),g.push({tierKey:i})}else if(null==n?void 0:n.variant_id){p.push({tierKey:i,existingId:n.variant_id});var te=(null==n?void 0:n.variant_id)&&n.variant_id===tr?(null==Rt?void 0:Rt.variant_type)||n.variant_type||n.variantType||"":n.variant_type||n.variantType||"",ie=(ee=Rr(i,l,te),{variantId:n.variant_id,ruleDesc:(null==$?void 0:$.ruleSetDesc)||"",whenToApply:Y.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),whenNotToApply:z.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),isDefault:null!==(S=null===(I=null===(k=Hn.get(i))||void 0===k?void 0:k.get(l))||void 0===I?void 0:I.is_default_enabled)&&void 0!==S?S:G(n.variantType||n.variant_type||(0===l?"Default":"variant")),tier:{tier_id:(null==r?void 0:r.tier_id)||"",tier_name:(null==r?void 0:r.tier_name)||t,tier_priority:null!==(C=null==r?void 0:r.tier_priority)&&void 0!==C?C:null},scope_id:(null==$?void 0:$.ruleSetId)||"",description:Ir(K)||"",topic:"".concat(_e.station,"RuleSet"),configuration:(null==o?void 0:o.config_data)||{},tierLinkId:null!=d?d:null,variantType:ee,is_user_accepted_risk:!!(null!==(x=null==n?void 0:n.is_user_accepted_risk)&&void 0!==x?x:null===(N=(_t||[])[l])||void 0===N?void 0:N.is_user_accepted_risk),is_enabled:n.is_enabled}),re=(gt.get(i)||[]).find(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===(null==n?void 0:n.variant_id)}),ae=!0;if(re){var oe=function(e){var n=(e||"").trim();return(n=F(n)).replace(/\s+/g," ").replace(/(\s*OR\s*)/g," OR ")},le=oe($n)===oe(re.title),se=oe(K)===oe(re.rule_description),ue=oe(ie.whenToApply)===oe(re.wta),de=oe(ie.whenNotToApply)===oe(re.wnta),ce=!!ie.isDefault===G(re.variant_type),ve=re.scheduling_config||{},pe=null!==(L=null!==(E=ve.order_global_min_separation_seconds)&&void 0!==E?E:null===(O=ve.order_rules)||void 0===O?void 0:O.global_min_separation_seconds)&&void 0!==L?L:0,fe=null!==(j=null!==(R=ve.advertiser_global_min_separation_seconds)&&void 0!==R?R:null===(D=ve.advertiser_rules)||void 0===D?void 0:D.global_min_separation_seconds)&&void 0!==j?j:0,ge=null!==(q=null!==(P=null===(V=ve.inventory_rules)||void 0===V?void 0:V.respect_inventory_code)&&void 0!==P?P:ve.respect_inventory_code)&&void 0!==q&&q,me=null!==(H=null!==(U=null===(J=ve.break_code_rules)||void 0===J?void 0:J.respect_break_code)&&void 0!==U?U:ve.respect_break_code)&&void 0!==H&&H,we=(null===(B=Hn.get(i))||void 0===B?void 0:B.get(l))||Jn,ye=we.order_rules.enabled===pe>0&&we.order_rules.global_min_separation_seconds===Math.floor(pe/60)&&we.advertiser_rules.enabled===fe>0&&we.advertiser_rules.global_min_separation_seconds===Math.floor(fe/60)&&we.inventory_rules.respect_inventory_code===ge&&we.break_code_rules.respect_break_code===me;le&&se&&ue&&de&&ce&&ye&&(ae=!1)}ae?(console.log("[saveLoadAndEditVariant] update payload (existing variant)",ie),c.push(h(ie,null!==(W=null==rr?void 0:rr.email)&&void 0!==W?W:""))):(console.log("[saveLoadAndEditVariant] No changes for variant ".concat(n.variant_id,", skipping API call")),c.push(Promise.resolve({data:{id:n.variant_id},skipped:!0})))}})}),[4,Promise.all(c)]);case 2:b=i.sent(),console.log("✅ All existing variants updated:",b),T=[],M=0,I=v,i.label=3;case 3:if(!(M<I.length))return[3,8];S=I[M],i.label=4;case 4:return i.trys.push([4,6,,7]),[4,y(S.payload,Fn.ASSISTANT_NAME)];case 5:return C=i.sent(),T.push(C),[3,7];case 6:throw x=i.sent(),console.error("❌ Error publishing new variant:",x),x;case 7:return M++,[3,3];case 8:return console.log("✅ All new variants published:",T),N=new Map,b.forEach(function(e,n){var t,i;if(!(null==e?void 0:e.skipped)){var r=p[n],a=(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.id)||(null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.variant_id)&&e.data.variant_id||(null==e?void 0:e.id)||(null==e?void 0:e.variant_id)&&e.variant_id;a||"string"!=typeof(null==e?void 0:e.data)||(a=e.data);var o=r.existingId||a;if(o&&"string"==typeof o){var l=N.get(r.tierKey)||[];l.push({id:o,action:"existing"}),N.set(r.tierKey,l)}}}),T.forEach(function(e,n){var t,i,r=g[n],a=(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.id)||(null===(i=null==e?void 0:e.data)||void 0===i?void 0:i.variant_id)&&e.data.variant_id||(null==e?void 0:e.id)||(null==e?void 0:e.variant_id)&&e.variant_id;if(a||"string"!=typeof(null==e?void 0:e.data)||(a=e.data),a&&"string"==typeof a){var o=N.get(r.tierKey)||[];o.push({id:a,action:"new"}),N.set(r.tierKey,o)}}),A.getState().setCreatedVariantInfo(Array.from(N.entries()).map(function(e){return{tierName:e[0],variants:e[1]}})),me(V),he(!0),Oe(!1),He.current=!1,null===(D=wi.current)||void 0===D||D.show({severity:"success",sticky:!1,life:3e3,className:k.toastSuccess,content:r("div",e({className:k.toastContent},{children:[r("div",e({className:k.toastHeaderLeft},{children:[a(f,{className:k.iconSuccess}),a("span",e({className:"".concat(k.toastTitle," ").concat(k.toastTitleSuccess)},{children:"Success"}))]})),a("p",e({className:"".concat(k.toastMessage," ").concat(k.toastMessageSuccess)},{children:"Changes saved successfully!"}))]}))}),xe.current=setTimeout(function(){ta()},3e3),[3,10];case 9:return E=i.sent(),console.error("❌ Error updating variant:",E),me(P),Ce(!0),Oe(!1),O=(null===(j=null==E?void 0:E.response)||void 0===j?void 0:j.data)||{},console.log("errorData: ",O),(L="Variant already exists"===(null==O?void 0:O.message))||409===(null==E?void 0:E.status)?ke('Looks like a similar rule already exists with the same conditions. You can update the description or conditions to make it unique, or discard this learning. <br/> How would you like to proceed?\n <br/><button class="clickable-button" data-value="Discard learning">Discard learning</button>\n <br/><button class="clickable-button" data-value="Continue editing learning">Continue editing learning</button>\n <br/><button class="clickable-button" id="typeYourAnswer">Or, type your response</button>'):ke(((null==O?void 0:O.message)||(null==O?void 0:O.detail)||"Error Occurred while saving the rule.")+'Please try again.<br/><button class="clickable-button" data-value="Save this Learning">Retry</button>'),null===(J=wi.current)||void 0===J||J.show({severity:"error",sticky:!1,className:k.toastError,content:r("div",e({className:k.toastContent},{children:[r("div",e({className:k.toastHeaderLeft},{children:[a(_,{className:k.iconError}),a("span",e({className:"".concat(k.toastTitle," ").concat(k.toastTitleError)},{children:"Error"}))]})),a("p",e({className:"".concat(k.toastMessage," ").concat(k.toastMessageError)},{children:L||409===(null==E?void 0:E.status)?"Similar rule already exists. Please update and try again.":(null==O?void 0:O.message)||(null==O?void 0:O.detail)||"Something went wrong while saving the learning!"}))]}))}),[3,10];case 10:return[2]}})})},Pr=function(e){return"string"!=typeof e?e:e.replace(/<conflicting_text>[\s\S]*?<\/conflicting_text>/g,"").replace(/<decision_strength>[\s\S]*?<\/decision_strength>/g,"").replace(/<conflicting_reasoning>[\s\S]*?<\/conflicting_reasoning>/g,"").replace(/<conflicting_gap>[\s\S]*?<\/conflicting_gap>/g,"").replace(/<\/?conflicting>/g,"").trim()};d(function(){Di&&!_i&&(console.log("isSaveRule received from agent — calling publish APIs directly."),ji(!1),X||ne?jr():!0===He.current?Vr():t(void 0,void 0,void 0,function(){var e,n,t,r,a,o,l,s;return i(this,function(u){switch(u.label){case 0:u.trys.push([0,5,,6]),me(q),e=new Map,n=function(n){var t,r,a,o,l,u;return i(this,function(i){switch(i.label){case 0:if(t=n.toLowerCase().replace(/ /g,"_"),r=Re.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===t||e.tier_name.toLowerCase()===t.replace(/_/g,"")}),!(a=null==r?void 0:r.tier_id))return e.set(t,null),[2,"continue"];o={question:$n,orgName:Fn.ORGANIZATION_NAME,scope_id:(null==$?void 0:$.ruleSetId)||"",tier_id:a},i.label=1;case 1:return i.trys.push([1,3,,4]),[4,w(o)];case 2:return l=i.sent(),e.set(t,(null===(s=null==l?void 0:l.data)||void 0===s?void 0:s.id)||null),console.log("✅ Question saved for ".concat(n,":"),l),[3,4];case 3:return u=i.sent(),console.error("❌ Error saving question for ".concat(n,":"),u),e.set(t,null),[3,4];case 4:return[2]}})},t=0,r=_e.tiers,u.label=1;case 1:return t<r.length?(a=r[t],[5,n(a)]):[3,4];case 2:u.sent(),u.label=3;case 3:return t++,[3,1];case 4:return Dr(),[3,6];case 5:return o=u.sent(),l=new Map,_e.tiers.forEach(function(e){l.set(e.toLowerCase().replace(/ /g,"_"),null)}),Dr(),console.error("❌ Error saving Instant Learning Question:",o),[3,6];case 6:return[2]}})}))},[Di,_i]);var qr=(null===(U=(null===(J=null==_e?void 0:_e.tiers)||void 0===J?void 0:J[0])||ee||"Tier 1")||void 0===U?void 0:U.toLowerCase().replace(/ /g,"_"))||"tier_1",Fr=null!==(H=null!=Ct?Ct:te)&&void 0!==H?H:0,Gr=null!=Ct,Jr=Gr?null==_t?void 0:_t[Fr]:null,Ur=_t&&(null==_t?void 0:_t.find(function(e){return e&&!e.is_readOnly&&((null==e?void 0:e.new_variant_id)&&Ft.includes(e.new_variant_id)||(null==e?void 0:e.variant_id)&&Vt.includes(e.variant_id))})),Hr=(null==Jr?void 0:Jr.new_variant_id)&&Ft.includes(Jr.new_variant_id)?Jr.new_variant_id:(null==Ur?void 0:Ur.new_variant_id)&&Ft.includes(Ur.new_variant_id)?Ur.new_variant_id:"",Br=!(!X&&!ne),Wr=function(n){var t={},i=_e.tiers.map(function(e){return null==e?void 0:e.toLowerCase().replace(/ /g,"_")}),r=(null==_e?void 0:_e.station)+"RuleSet",a=i.map(function(e){var n=Re.find(function(n){return n.tier_name.toLowerCase().replace(/ /g,"_")===e||n.tier_name.toLowerCase()===e.replace(/_/g,"")});return(null==n?void 0:n.tier_id)||""}).filter(Boolean);return n.forEach(function(n,o){var l,s,u,d,c,v,_=(null==n?void 0:n.variant_id)&&n.variant_id||Vt[o]||"new_variant_".concat(o),p=(null===(l=n.scope)||void 0===l?void 0:l[0])||qr,f=rt.get(p),g=lt.get(p),m=dt.get(p),w=(null==f?void 0:f.get(o))||n.rule_description||"",y=(null==g?void 0:g.get(o))||[],h=y.length>0?y.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" \\n "):n.wta||"",b=(null==m?void 0:m.get(o))||[],T=b.length>0?b.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" \\n "):n.wnta||"",M=Hn.get(p),A=null==M?void 0:M.get(o),k={};A&&Object.keys(A).length>0?k=e(e({},A),{order_rules:e(e({},A.order_rules),{global_min_separation_seconds:60*((null===(s=A.order_rules)||void 0===s?void 0:s.global_min_separation_seconds)||0)}),advertiser_rules:e(e({},A.advertiser_rules),{global_min_separation_seconds:60*((null===(u=A.advertiser_rules)||void 0===u?void 0:u.global_min_separation_seconds)||0)})}):n.scheduling_config&&(k=n.scheduling_config),t[_]={rule_title:$n,variant_description:w,wta:h,ruleset_id:(null==$?void 0:$.ruleSetId)||"",tier_id:a,wnta:T,scope:i,scope_rule_set:r,scheduling_config:k,is_user_accepted_risk:!(null===(v=null!==(d=null==n?void 0:n.is_user_accepted_risk)&&void 0!==d?d:null===(c=(_t||[])[o])||void 0===c?void 0:c.is_user_accepted_risk)||void 0===v||!v)}}),t};yn&&console.log("customMetaData.ui_state for addvariant flow",Wr(yt));var Kr=A(function(e){return e.selectedRuleSetId}),Yr={send_metadata_to_orchestrator:!1,default:["scope"],app_mapping_id:ce,ui_state:Br?{variants:function(){var n={},t=Hn.get(qr);if(!t)return n;var i=rt.get(qr),r=lt.get(qr),a=dt.get(qr),o=_e.tiers.map(function(e){return null==e?void 0:e.toLowerCase().replace(/ /g,"_")}),l=(null==_e?void 0:_e.station)+"RuleSet",s=o.map(function(e){var n=Re.find(function(n){return n.tier_name.toLowerCase().replace(/ /g,"_")===e||n.tier_name.toLowerCase()===e.replace(/_/g,"")});return(null==n?void 0:n.tier_id)||""}).filter(Boolean);return t.forEach(function(u,d){var c,v,_,p,f,g,m=null===(c=null==ne?void 0:ne[d])||void 0===c?void 0:c.variantId,w=(_t||[])[d],y=(null==w?void 0:w.new_variant_id)||"",h=m||y||Vt[d]||"variant_".concat(d),b=(null==i?void 0:i.get(d))||"",T=((null==r?void 0:r.get(d))||[]).map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" \\n ")||"",M=((null==a?void 0:a.get(d))||[]).map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" \\n ")||"",A=t.get(d),k={};A&&Object.keys(A).length>0&&(k=e(e({},A),{order_rules:e(e({},A.order_rules),{global_min_separation_seconds:60*((null===(v=A.order_rules)||void 0===v?void 0:v.global_min_separation_seconds)||0)}),advertiser_rules:e(e({},A.advertiser_rules),{global_min_separation_seconds:60*((null===(_=A.advertiser_rules)||void 0===_?void 0:_.global_min_separation_seconds)||0)})})),n[h]={rule_title:$n,variant_description:b,wta:T,ruleset_id:(null==$?void 0:$.ruleSetId)||"",tier_id:s,wnta:M,scope:o,scope_rule_set:l,scheduling_config:k,is_user_accepted_risk:!(null===(g=null!==(p=null==w?void 0:w.is_user_accepted_risk)&&void 0!==p?p:null===(f=null==ne?void 0:ne[d])||void 0===f?void 0:f.is_user_accepted_risk)||void 0===g||!g)}}),n}()}:function(){var n,t,i,r,a,o,l=(_t||[]).findIndex(function(e){return!0===e.is_new_variant}),s=-1;return-1!==l?s=l:_n?s=-1:yn||(s=Fr),{new_current_variant:-1!==s?{rule_title:$n,rule_description:(null===(n=rt.get(qr))||void 0===n?void 0:n.get(s))||"",wta:(null===(i=null===(t=lt.get(qr))||void 0===t?void 0:t.get(s))||void 0===i?void 0:i.map(function(e){return Pr(e.text)}).filter(function(e){return""!==e}).join(" \\n "))||"",wnta:(null===(a=null===(r=dt.get(qr))||void 0===r?void 0:r.get(s))||void 0===a?void 0:a.map(function(e){return Pr(e.text)}).filter(function(e){return""!==e}).join(" \\n "))||"",scope:_e.tiers.map(function(e){return null==e?void 0:e.toLowerCase().replace(/ /g,"_")}),scope_rule_set:(null==_e?void 0:_e.station)+"RuleSet",scheduling_config:function(){var n,t,i,r=null===(n=Hn.get(qr))||void 0===n?void 0:n.get(s);return r&&0!==Object.keys(r).length?e(e({},r),{order_rules:e(e({},r.order_rules),{global_min_separation_seconds:60*((null===(t=r.order_rules)||void 0===t?void 0:t.global_min_separation_seconds)||0)}),advertiser_rules:e(e({},r.advertiser_rules),{global_min_separation_seconds:60*((null===(i=r.advertiser_rules)||void 0===i?void 0:i.global_min_separation_seconds)||0)})}):{}}(),is_user_accepted_risk:!!(null===(o=(_t||[])[s])||void 0===o?void 0:o.is_user_accepted_risk)}:{rule_title:"",rule_description:"",wta:"",wnta:"",scope:[],scope_rule_set:"",scheduling_config:{},is_user_accepted_risk:!1},variants:yn?Wr(yt):{}}}(),rule_id_in_current_session:kt,new_variant_id:function(){var e;return Gr&&X?(null===(e=null==ne?void 0:ne[Fr])||void 0===e?void 0:e.variantId)?null:Hr:null}(),edit_variant_id:Nn,rule_id:On.current,ruleset_id:Kr,current_variants_length:X?Array.isArray(_t)&&_t.length>0?Math.max((null===(B=null==X?void 0:X.variants)||void 0===B?void 0:B.length)||0,_t.length):null===(W=null==X?void 0:X.variants)||void 0===W?void 0:W.length:void 0,tiers:Re,authToken:(null==rr?void 0:rr.accessToken)||""},zr=Tr(yt),Qr={ruleTitle:$n,scopeData:_e,variantsByTier:Array.from(Hn.keys()).reduce(function(n,t){var i=Hn.get(t)||new Map,r=rt.get(t)||new Map,a=lt.get(t)||new Map,o=dt.get(t)||new Map;return console.log("tier config map",i),n[t]=Array.from(i.keys()).map(function(n,l){var s,u,d=(_t||[])[n]||{};console.log("Original item for tier",t,"index",n,":",d);var c={label:"",isDefault:!1};if(d.is_variant&&!G(d.variant_type))c={label:"",isDefault:!1};else if(ne&&ne.length>0){c=Or(ne,n,"variantType"),console.log("Found matching variant at index",n,":",c);var v=ne[n];if(v){if(!c.label){var _=v.variantType||"",p=G(_);c={label:"variant ".concat(n+1),isDefault:p}}if(v.variantId===Qi)(g=d.variant_type||(null==Rt?void 0:Rt.variant_type))&&(c=Lr(g,n),console.log("[templateState] editingVariants[".concat(n,']: using CARE variant_type "').concat(g,'" → label "').concat(c.label,'"')));console.log("Computed variant type at index",n,":",c)}else c={label:Tr(ne),isDefault:!1},console.log("No match found, using getNextVariantType:",c)}else if(yt&&yt.length>0){if(c=Or(yt,n,"variant_type"),console.log("Found matching variant at index",n,":",c),He.current){var f=yt[n];if((null==f?void 0:f.variant_id)===tr||(null==f?void 0:f.variantId)===tr)(g=d.variant_type||(null==Rt?void 0:Rt.variant_type))&&(c=Lr(g,n),console.log("[templateState] existingVariants[".concat(n,']: load-and-edit using CARE variant_type "').concat(g,'" → label "').concat(c.label,'"')))}}else{var g=d.variant_type||"";c={label:zr,isDefault:G(g)}}console.log("Computed variant data for tier",t,"index",n,":",c);var m=null!==(u=null===(s=i.get(n))||void 0===s?void 0:s.is_default_enabled)&&void 0!==u?u:c.isDefault;console.log("live is default :",m);var w="variant ".concat(l+1),y=r.get(n)||"";return{variantId:Vt[n]||d.variant_id||d.variantId,variantType:w,isDefault:m,isModified:d.is_modified,tier:t,index:n,ruleDescription:y.replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g,""),whenToApplyConditions:(a.get(n)||[]).flatMap(function(n){var t,i=(null===(t=null==n?void 0:n.text)||void 0===t?void 0:t.split(/\s+OR\s+/))||[];return i.length>1?i.map(function(t,i){return e(e({},n),{id:"split-".concat(n.id,"-").concat(i),text:t.trim()})}):[n]}),whenNotToApplyConditions:(o.get(n)||[]).flatMap(function(n){var t,i=(null===(t=null==n?void 0:n.text)||void 0===t?void 0:t.split(/\s+OR\s+/))||[];return i.length>1?i.map(function(t,i){return e(e({},n),{id:"split-".concat(n.id,"-").concat(i),text:t.trim()})}):[n]}),configData:i.get(n)||Jn,isReadOnly:d.is_readOnly||!1,is_variant:d.is_variant||!1,reasoning:{ruleDescription:kr(y),whenToApply:kr(d.wta),whenNotToApply:kr(d.wnta),configData:kr(d.action)}}}),n},{}),citation:ni,fieldCitations:di,citations:ri};console.log("templateState",Qr);var Zr={setRuleTitle:function(n){var t,i=void 0!==(null===(t=null==n?void 0:n.target)||void 0===t?void 0:t.value)?n.target.value:n;Xn(i),Si(function(n){if(n.ruleTitle){var t=e({},n);return delete t.ruleTitle,t}return n})},setRuleDescription:function(e,n,t){return dr(e,n,t)},addWhenToApply:function(e,n){return cr(e,n)},removeWhenToApply:function(e,n,t){return vr(e,n,t)},editWhenToApply:function(e,n,t,i){return _r(e,n,t,i)},addWhenNotToApply:function(e,n){return pr(e,n)},removeWhenNotToApply:function(e,n,t){return fr(e,n,t)},editWhenNotToApply:function(e,n,t,i){return gr(e,n,t,i)},addNewVariant:function(e){return mr(e)},onScopeChange:yr,onConfigChange:function(e,n,t,i){return hr(e,n,t,i)}},$r={},Xr={};Hn.forEach(function(n,t){$r[t]=new Map,Xr[t]=new Map,n.forEach(function(n,i){$r[t].set(i,[e({key:"order_rules",label:"Order"},n.order_rules),e({key:"advertiser_rules",label:"Advertiser"},n.advertiser_rules)]),Xr[t].set(i,[{key:"inventory_rules",label:"Inventory code",enabled:n.inventory_rules.respect_inventory_code},{key:"break_code_rules",label:"Break Code",enabled:n.break_code_rules.respect_break_code},{key:"is_default_enabled",label:"Default Variant",enabled:n.is_default_enabled}])})});var ea=v(function(){if(ee){if(1===_e.tiers.length)return 0;var e=_e.tiers.findIndex(function(e){return e.toLowerCase()===ee.toLowerCase()});return e>=0?e:0}},[ee,_e.tiers]),na=e(e({defaultOpen:!0,tierOptions:["Tier 1","Tier 2"],stationOptions:[{label:"Global Scope",value:"global"},{label:"Genre Scope",value:"genre"},{label:"Custom Scope",value:"custom"}],separationItemsByTier:$r,togglesByTier:Xr,highlights:Wt,highlightedIds:zt,openSections:Kn,setOpenSections:Yn,setSendMessageInChat:Ot,isAiStreaming:_i,defaultTierOpen:ea,defaultVariantOpen:_n?void 0:Ct,autoScrollVariantIndex:_n?void 0:Ct,activeVariantAccordionIndex:_n?void 0:Ct,setActiveVariantAccordionIndex:function(e){xt(e),null!=e&&setTimeout(function(){pn(!1)},100)},validationErrors:Ii,activeEditId:An,setActiveEditId:kn,pendingEditId:Sn,setPendingEditId:Cn,conflictReason:xi,usedFor:X||ne?"Edit":"Create"},Gn),{scrollTrigger:$t});console.log(Ct,"editVariantIndex checking"),d(function(){},[Y]),d(function(){if(!_i&&Tt&&!!(!X&&!ne)){var e=n([],_t,!0).reverse().findIndex(function(e){return"variant"===e.action||e.is_variant});-1===e||_t.length,-1!==e&&(console.log("Post-stream: Focusing new variant at index",e),xt(e))}},[_i,Tt]);var ta=function(){xe.current&&(clearTimeout(xe.current),xe.current=null),He.current=!1,z(),br()},ia=function(){var e={};$n.trim()||(e.ruleTitle="Rule Title is required"),_e.station||(e.station="Station Rule Set is required"),_e.tiers&&0!==_e.tiers.length||(e.tiers="At least one tier must be selected");return _e.tiers.map(function(e){return e.toLowerCase().replace(/ /g,"_")}).forEach(function(n){var t=rt.get(n),i=lt.get(n),r=Hn.get(n);r&&Array.from(r.keys()).forEach(function(r){var a=null==t?void 0:t.get(r);a&&a.trim()||(e["ruleDescription-".concat(n,"-").concat(r)]="Rule Description is required");var o=null==i?void 0:i.get(r);o&&o.some(function(e){return""!==e.text.trim()})||(e["whenToApply-".concat(n,"-").concat(r)]='At least one "When to apply" condition is required')})}),e};function ra(r,a,o){var l,s,u,d,c,v;return void 0===o&&(o=!1),t(this,void 0,void 0,function(){var t,_,p,f,g,m,w,y,h,T,M,A,k,I,S,C,x,N,E,O,L,R,D,j;return i(this,function(i){switch(i.label){case 0:if(t=r.question_id,_=(null==r?void 0:r.variant_id)||null,bn.current&&Rn.current===t)return console.log("[handleAILoadAction] Already fetching question ID, skipping duplicate request:",t),[2];if(On.current===t&&!o)return console.log("[handleAILoadAction] Question ID unchanged, updating variant focus only:",_),En(_),_?(-1!==(p=(_t||[]).findIndex(function(e){return e.is_new_variant}))&&(Ai(!0),Ji("Removing new variant..."),Bi("Please wait while we remove new variant.")),pt(function(e){if(!Array.isArray(e))return e;var n=e.filter(function(e){return!e.is_new_variant}),t=n.findIndex(function(e){return e.variant_id===_});return-1!==t&&setTimeout(function(){xt(t),Xt(function(e){return e+1}),mi.current=t},0),n}),-1!==p&&((f=function(e){e(function(e){var n=new Map;return e.forEach(function(e,t){var i=new Map(e);i.delete(p);var r=new Map,a=0;i.forEach(function(e){r.set(a,e),a++}),n.set(t,r)}),n})})(Bn),f(at),f(st),f(ct),Pt(function(e){var t=n([],e,!0);return t.length>p&&t.splice(p,1),t})),!1===bn.current&&(bn.current=!0,-1!==p&&(null===(l=wi.current)||void 0===l||l.show({severity:"success",summary:"Success",detail:"New variant removed successfully because you selected to edit an existing variant",life:4e3}))),pn(!1)):(console.log("lastLoadedQuestionIdRef.current in else",On.current),null===On.current&&(Ai(!0),Ji("Adding new variant..."),Bi("Please wait while we add new variant."))),[2];console.log("User Action: fetching fresh variant info for question",t),Tn.current.clear(),Tn.current.add(t),Ai(!0),Ji("Loading variants..."),console.log("reaching here in load and edit"),Bi("Please wait while we fetch the latest variant data."),bn.current=!0,Rn.current=t,i.label=1;case 1:return i.trys.push([1,5,6,10]),g=Date.now(),[4,b(t,(null==$?void 0:$.ruleSetId)||"")];case 2:return m=i.sent(),(w=Date.now()-g)<3e3?[4,new Promise(function(e){return setTimeout(e,3e3-w)})]:[3,4];case 3:i.sent(),i.label=4;case 4:return 0===(y=(null===(s=null==m?void 0:m.data)||void 0===s?void 0:s.variants)||[]).length?(console.warn("No variants found for question_id",t),Ai(!1),Ji(""),null===(u=wi.current)||void 0===u||u.show({severity:"error",summary:"Error",detail:"No variants found for this question.",life:3e3}),[2]):(He.current=!0,bn.current=!0,h=(null===(d=null==m?void 0:m.data)||void 0===d?void 0:d.ruleTitle)||"",Xn(h),T=null===(c=null==m?void 0:m.data)||void 0===c?void 0:c.tier,M="tier_1",A="Tier 1",k="1",T&&((I=String(T).match(/(\d+)/))?(S=I[1],k=S,M="tier_".concat(S),A="Tier ".concat(S)):(M=String(T).toLowerCase().trim().replace(/ /g,"_"),A=M.replace(/_/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()}),k=M.includes("2")?"2":"1")),console.log("[handleAILoadAction] Detected Tier: ".concat(A," (ID: ").concat(k,", Key: ").concat(M,")")),pe({station:Z||"global",tiers:[A]}),C=function(e,n,t,i,r,a){var o=e.map(function(e){var o,l,s=[t];return{variant_type:e.variantType||"variant",title:n,rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",scope:s,scheduling_config:(null===(o=e.configuration)||void 0===o?void 0:o.scheduling_config)||{},variant_id:e.variantId,question_id:r,tier_id:i,is_readOnly:e.variantId!==a,link_id:e.link_id||"",is_enabled:null===(l=e.is_enabled)||void 0===l||l,is_user_accepted_risk:e.is_user_accepted_risk,has_accepted_risk:e.has_accepted_risk,user_accepted_risk_at:e.user_accepted_risk_at,action:"edit"}}),l=new Map,s=new Map,u=new Map,d=new Map;return o.forEach(function(e,n){var t,i,r,a,o,c,v=e.scheduling_config||{};l.set(n,{order_rules:{enabled:!!v.order_global_min_separation_seconds||!!(null===(t=v.order_rules)||void 0===t?void 0:t.global_min_separation_seconds),global_min_separation_seconds:Math.floor((v.order_global_min_separation_seconds||(null===(i=v.order_rules)||void 0===i?void 0:i.global_min_separation_seconds)||0)/60)},advertiser_rules:{enabled:!!v.advertiser_global_min_separation_seconds||!!(null===(r=v.advertiser_rules)||void 0===r?void 0:r.global_min_separation_seconds),global_min_separation_seconds:Math.floor((v.advertiser_global_min_separation_seconds||(null===(a=v.advertiser_rules)||void 0===a?void 0:a.global_min_separation_seconds)||0)/60)},inventory_rules:{respect_inventory_code:!!v.respect_inventory_code||!!(null===(o=v.inventory_rules)||void 0===o?void 0:o.respect_inventory_code)},break_code_rules:{respect_break_code:!!v.respect_break_code||!!(null===(c=v.break_code_rules)||void 0===c?void 0:c.respect_break_code)},is_default_enabled:G(e.variantType||e.variant_type)}),s.set(n,F(e.rule_description||""));var _=e.wta?e.wta.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,t){return{id:"edit-wta-".concat(n,"-").concat(t),text:e,reasoning:""}}):[];u.set(n,_);var p=e.wnta?e.wnta.split(" OR ").map(function(e){return e.trim()}).filter(function(e){return""!==e}).map(function(e,t){return{id:"edit-wnta-".concat(n,"-").concat(t),text:e,reasoning:""}}):[];d.set(n,p)}),{transformedVariants:o,tierConfigMap:l,tierDescMap:s,tierWtaMap:u,tierWntaMap:d}}(y,h,M,k,t,_),x=C.transformedVariants,N=C.tierConfigMap,E=C.tierDescMap,O=C.tierWtaMap,L=C.tierWntaMap,mt(function(e){var n=new Map(e);return n.set(M,JSON.parse(JSON.stringify(x))),n}),pt(function(e){var t=(Array.isArray(e)?e:[]).filter(function(e){return"copy"===e.action||e.tier_id&&e.tier_id!==k});return n(n([],t,!0),x,!0)}),ht(function(e){var t=(Array.isArray(e)?e:[]).filter(function(e){return"copy"===e.action||e.tier_id&&e.tier_id!==k});return n(n([],t,!0),x,!0)}),hn(!0),On.current=t,En(_),R=0,_&&-1!==(D=x.findIndex(function(e){return e.variant_id===_}))&&(R=D),xt(R),Xt(function(e){return e+1}),mi.current=R,pn(!1),Bn(function(e){var n=new Map(e);return n.set(M,N),n}),at(function(e){var n=new Map(e);return n.set(M,E),n}),st(function(e){var n=new Map(e);return n.set(M,O),n}),ct(function(e){var n=new Map(e);return n.set(M,L),n}),Si({}),[3,10]);case 5:return j=i.sent(),console.error("Failed to fetch variants by question ID:",j),null===(v=wi.current)||void 0===v||v.show({severity:"error",summary:"Error",detail:"Failed to fetch variants. Please try again.",life:3e3}),[3,10];case 6:return bn.current=!1,Ai(!1),Ji(""),Bi(""),(null==r?void 0:r.is_interpretation_ready)&&(null==r?void 0:r.question_id)&&On.current&&Nn?(console.log("inside edit variant flow",On.current,Nn),pt(function(n){if(!Array.isArray(n))return n;var t=n.map(function(n){return(null==n?void 0:n.variant_id)===Nn?e(e({},n),a):n}),i=n.findIndex(function(e){return(null==e?void 0:e.variant_id)===Nn});return console.log(i,"targetIndexif"),-1!==i&&setTimeout(function(){console.log("targetIndex",i),xt(i),Xt(function(e){return e+1}),mi.current=i},0),t}),[3,9]):[3,7];case 7:return(null==r?void 0:r.is_interpretation_ready)&&(null==r?void 0:r.question_id)&&On.current&&!Nn?(console.log("inside add new variant flow",On.current,Nn),Ai(!0),Ji("Adding new variant..."),Bi("Please wait while we add new variant."),[4,new Promise(function(e){return setTimeout(e,3e3)})]):[3,9];case 8:i.sent(),Ai(!1),Ji(""),Bi(""),pt(function(t){var i;if(Array.isArray(t)){var r=t.findIndex(function(e){return!0===e.is_new_variant});if(-1!==r)setTimeout(function(){xt(r),Xt(function(e){return e+1}),mi.current=r},0),i=t.map(function(n,t){return t===r?e(e(e({},n),a),{is_new_variant:!0,is_variant:!0}):n});else{var o=t.length;setTimeout(function(){xt(o),Xt(function(e){return e+1}),mi.current=o},0),i=n(n([],t,!0),[e(e({},a),{is_new_variant:!0,is_variant:!0})],!1)}}else setTimeout(function(){xt(0),Xt(0),mi.current=0},0),i=[e(e({},a),{is_new_variant:!0})];return Vn.current=i,i}),i.label=9;case 9:return[7];case 10:return[2]}})})}var aa;return console.log("RuleSet in render",$),r(o,{children:[a(g,{ref:wi}),a(I,{open:Y,chatAssistantName:Fn.ASSISTANT_NAME,organizationName:Fn.ORGANIZATION_NAME,baseUrl:Fn.BASE_URL,baseWebsocketUrl:Fn.BASE_WEBSOCKET_URL,closeFunction:ta,ThinkingBulbIconComponent:a(D,{}),customSections:a(o,{}),customMetaData:Yr,chatTitle:X?Fn.CHAT_TITLE_EDIT.replace("<scope>",(null==$?void 0:$.ruleSetName)||""):Fn.CHAT_TITLE.replace("<scope>",(null==$?void 0:$.ruleSetName)||""),formTitle:Fn.FORM_TITLE,showSavedMessage:!1,savedMessage:Te,isError:Se,errorMessage:Ae,isSaving:Ee,onSave:function(e){console.log("Save this Learning",e);var n=ia();if(Object.keys(n).length>0)return console.log("validation errors",n),void Si(n);Oe(!0),Ce(!1),ke("")},showSaveWithoutValidation:!1,onSaveWithoutValidation:function(){return t(void 0,void 0,void 0,function(){var e,n,t,r,a,o,l,s,u;return i(this,function(d){switch(d.label){case 0:return e=ia(),Object.keys(e).length>0?(Si(e),[2]):(console.log("✅ Bypass Save: Initiated"),X||ne?[4,jr()]:[3,2]);case 1:return d.sent(),[3,11];case 2:return!0!==He.current?[3,4]:[4,Vr()];case 3:return d.sent(),[3,11];case 4:d.trys.push([4,10,,11]),me(q),n=new Map,t=function(e){var t,r,a,o,l,s;return i(this,function(i){switch(i.label){case 0:if(t=e.toLowerCase().replace(/ /g,"_"),r=Re.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===t||e.tier_name.toLowerCase()===t.replace(/_/g,"")}),!(a=null==r?void 0:r.tier_id))return n.set(t,null),[2,"continue"];o={question:$n,orgName:Fn.ORGANIZATION_NAME,scope_id:(null==$?void 0:$.ruleSetId)||"",tier_id:a},i.label=1;case 1:return i.trys.push([1,3,,4]),[4,w(o)];case 2:return l=i.sent(),n.set(t,(null===(u=null==l?void 0:l.data)||void 0===u?void 0:u.id)||null),[3,4];case 3:return s=i.sent(),console.error("❌ Bypass Save: Error saving question for ".concat(e,":"),s),n.set(t,null),[3,4];case 4:return[2]}})},r=0,a=_e.tiers,d.label=5;case 5:return r<a.length?(o=a[r],[5,t(o)]):[3,8];case 6:d.sent(),d.label=7;case 7:return r++,[3,5];case 8:return[4,Dr(n,!0)];case 9:return d.sent(),[3,11];case 10:return l=d.sent(),me(P),s=new Map,_e.tiers.forEach(function(e){s.set(e.toLowerCase().replace(/ /g,"_"),null)}),Dr(s,!0),console.error("❌ Bypass Save: Error",l),[3,11];case 11:return[2]}})})},headerMessageHandlers:Ar,aiResponse:_t,setAIResponse:pt,width:"90vw",height:"90vh",sendMessageInChat:Et,template:S.CreateRule,isLoading:ge===q,templateProps:{state:Qr,handlers:Zr,uiState:na},setSendMessageInChat:Ot,onResetChat:function(){br()},onResetRequest:function(){bi(!0)},isFormDirty:function(){return""!==$n.trim()||""!==_e.station||_e.tiers.length>0||Array.from(rt.values()).some(function(e){return Array.from(e.values()).some(function(e){return""!==e.trim()})})||Array.from(lt.values()).some(function(e){return Array.from(e.values()).some(function(e){return e.length>0})})||Array.from(dt.values()).some(function(e){return Array.from(e.values()).some(function(e){return e.length>0})})||Hn.size>0||nt.size>0},initialChatMessage:X?(aa=X.ruleTitle||"this rule",null===(K=null==ne?void 0:ne[null!=te?te:0])||void 0===K||K.is_user_accepted_risk,'<p><span>Welcome back! 👋</span>\n <span>I see you want to edit <strong>"'.concat(aa,'."</strong></span>\n <span> <strong>What would you like to update? </strong> </span>\n <span>Describe the change you want to make, and I’ll help you edit it.</span>\n </p>')):null!=de?de:Fn.INITIAL_CHAT_MESSAGE,validateCustom:function(){if(ge===V||ye)return!1;if(!$n||""===$n.trim())return!1;if(null!==An)return!1;if(!_e.station||""===_e.station.trim())return!1;var e=_e.tiers&&_e.tiers.filter(function(e){return e&&""!==e.trim()});if(!e||0===(null==e?void 0:e.length))return!1;for(var n,t=0,i=e.map(function(e){return e.toLowerCase().replace(/ /g,"_")});t<i.length;t++){var r=i[t],a=rt.get(r),o=lt.get(r),l=Hn.get(r);if(!l||0===l.size)return!1;for(var s=0,u=Array.from(l.keys());s<u.length;s++){var d=u[s],c=null==a?void 0:a.get(d);if(!c||""===c.trim())return!1;var v=null==o?void 0:o.get(d);if(!(null==v?void 0:v.some(function(e){return e.text&&""!==e.text.trim()})))return!1}}return!(!Hn||0===Hn.size)&&(!(n=function(e){return Array.from(e.values()).some(function(e){return Array.from(e.values()).some(function(e){return e.some(function(e){return!!e.conflict})})})})(lt)&&!n(dt)&&!ze)},setCitations:ai,isLocked:!0,textareaPlaceholder:"Tell me more about this learning..",saveButtonConfig:{label:X?"Save Changes":"Save Learning",loadingLabel:r("span",e({style:{display:"flex",gap:"5px",alignItems:"center"}},{children:[a(p,{size:20,color:"white",className:"animate-spin"}),a("span",{children:" Saving Changes..."})]}))},setCurrentRequestId:si,isAiStreaming:_i,setIsAiStreaming:pi,showConfirmReset:hi,setShowConfirmReset:bi,confirmReset:function(){br(),bi(!1),ta()},isLoadingVariants:Mi,mainText:Gi,subText:Hi,proposedRule:en,isFetchingComparison:ur,handleOpenComparison:Mr,showComparison:Pi,setShowComparison:qi,variants:rn,onComparisonLinkClick:sr,targetComparisonVariantId:ln,highlightedComparisonField:dn,onAddAsVariant:function(){qi(!1)},isCopyEnabled:!0,onSubmitFeedback:function(n){return t(void 0,void 0,void 0,function(){var t,r,a,o,l;return i(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),t=e({user_id:null!==(a=null==rr?void 0:rr._id)&&void 0!==a?a:"",user_name:null!==(o=null==rr?void 0:rr.firstname)&&void 0!==o?o:"",user_email:null!==(l=null==rr?void 0:rr.email)&&void 0!==l?l:"",assistant_name:Fn.ASSISTANT_NAME},n),[4,T(t)];case 1:return i.sent(),[3,3];case 2:throw r=i.sent(),console.error("Failed to submit chat feedback",r),r;case 3:return[2]}})})},handleGlobalClickCapture:function(e){null!==An&&(e.target.closest('[data-edit-id="'.concat(An,'"]'))||(e.preventDefault(),e.stopPropagation(),Cn(An)))},isGlobalEditActive:null!==An,initialDraftMessage:oe?ue:"",socketTimeOutInMilliSeconds:Fn.SOCKET_TIMEOUT})]})};export{J as default,F as filterAgentText};
2
2
  //# sourceMappingURL=InstantLearningModal.js.map