@e-llm-studio/instant-learning 0.1.1-alpha.36 → 0.1.1-alpha.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/features/IL-OTJ/ValueTypeWrappers/TeachMeWrapper.js +1 -1
- package/dist/cjs/features/LearningManagement/LearningManagement.js +1 -1
- package/dist/cjs/features/LearningManagement/RuleContent/RuleContent.js +1 -1
- package/dist/cjs/features/LearningManagement/apis/apiConfig.js +1 -1
- package/dist/cjs/features/LearningManagement/apis/scopeApis.js +1 -1
- package/dist/cjs/features/LearningManagement/components/InstantLearningModal.js +1 -1
- package/dist/cjs/features/LearningManagement/components/ScopeTree/TreeNode.js +1 -1
- package/dist/cjs/features/LearningManagement/components/ScopeTree/TreeSidebar.js +1 -1
- package/dist/cjs/features/LearningManagement/components/StationOnboarding/StationOnboardModal.js +1 -1
- package/dist/cjs/features/LearningManagement/store/useLearningTemplateStore.js +1 -1
- package/dist/cjs/features/LearningManagement/styles/ScopeTree.module.css.js +1 -1
- package/dist/cjs/plugins/ValueTypes/Default/DefaultTeachMeRenderer.js +1 -1
- package/dist/features/IL-OTJ/ValueTypeWrappers/TeachMeWrapper.js +1 -1
- package/dist/features/LearningManagement/LearningManagement.js +1 -1
- package/dist/features/LearningManagement/RuleContent/RuleContent.js +1 -1
- package/dist/features/LearningManagement/apis/apiConfig.js +1 -1
- package/dist/features/LearningManagement/apis/scopeApis.js +1 -1
- package/dist/features/LearningManagement/components/InstantLearningModal.js +1 -1
- package/dist/features/LearningManagement/components/ScopeTree/TreeNode.js +1 -1
- package/dist/features/LearningManagement/components/ScopeTree/TreeSidebar.js +1 -1
- package/dist/features/LearningManagement/components/StationOnboarding/StationOnboardModal.js +1 -1
- package/dist/features/LearningManagement/store/useLearningTemplateStore.js +1 -1
- package/dist/features/LearningManagement/styles/ScopeTree.module.css.js +1 -1
- package/dist/plugins/ValueTypes/Default/DefaultTeachMeRenderer.js +1 -1
- package/dist/types/src/features/IL-OTJ/ValueTypeWrappers/TeachMeWrapper.d.ts +1 -1
- package/dist/types/src/features/IL-OTJ/ValueTypeWrappers/TeachMeWrapper.d.ts.map +1 -1
- package/dist/types/src/features/LearningManagement/LearningManagement.d.ts +2 -3
- package/dist/types/src/features/LearningManagement/LearningManagement.d.ts.map +1 -1
- package/dist/types/src/features/LearningManagement/LearningManagementTest.d.ts.map +1 -1
- package/dist/types/src/features/LearningManagement/RuleContent/RuleContent.d.ts.map +1 -1
- package/dist/types/src/features/LearningManagement/apis/apiConfig.d.ts +0 -8
- package/dist/types/src/features/LearningManagement/apis/apiConfig.d.ts.map +1 -1
- package/dist/types/src/features/LearningManagement/apis/scopeApis.d.ts +1 -25
- package/dist/types/src/features/LearningManagement/apis/scopeApis.d.ts.map +1 -1
- package/dist/types/src/features/LearningManagement/components/InstantLearningModal.d.ts.map +1 -1
- package/dist/types/src/features/LearningManagement/components/ScopeTree/TreeNode.d.ts.map +1 -1
- package/dist/types/src/features/LearningManagement/components/ScopeTree/TreeSidebar.d.ts.map +1 -1
- package/dist/types/src/features/LearningManagement/components/StationOnboarding/StationOnboardModal.d.ts.map +1 -1
- package/dist/types/src/features/LearningManagement/store/useLearningTemplateStore.d.ts +0 -2
- package/dist/types/src/features/LearningManagement/store/useLearningTemplateStore.d.ts.map +1 -1
- package/package.json +3 -6
- package/dist/ThinkingBulbIcon-3OP7E5JZ.gif +0 -0
- package/dist/cjs/features/LearningManagement/components/CreateRuleSetLegacyModal.js +0 -2
- package/dist/cjs/features/LearningManagement/components/CreateRuleSetLegacyModal.js.map +0 -1
- package/dist/cjs/plugins/ValueTypes/Guidelines/GuidelinesTeachMeRenderer.js +0 -2
- package/dist/cjs/plugins/ValueTypes/Guidelines/GuidelinesTeachMeRenderer.js.map +0 -1
- package/dist/features/LearningManagement/components/CreateRuleSetLegacyModal.js +0 -2
- package/dist/features/LearningManagement/components/CreateRuleSetLegacyModal.js.map +0 -1
- package/dist/index.css +0 -5038
- package/dist/index.css.map +0 -1
- package/dist/index.mjs +0 -141951
- package/dist/index.mjs.map +0 -1
- package/dist/plugins/ValueTypes/Guidelines/GuidelinesTeachMeRenderer.js +0 -2
- package/dist/plugins/ValueTypes/Guidelines/GuidelinesTeachMeRenderer.js.map +0 -1
- package/dist/types/src/features/LearningManagement/components/CreateRuleSetLegacyModal.d.ts +0 -10
- package/dist/types/src/features/LearningManagement/components/CreateRuleSetLegacyModal.d.ts.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),n=require("react/jsx-runtime"),t=require("react"),i=require("lucide-react"),r=require("primereact/toast"),a=require("uuid"),o=require("../apis/scopeApis.js"),l=require("../public/ThinkingBulbIcon.gif.js"),s=require("../store/useLearningTemplateStore.js"),u=require("../styles/InstantLearningModal.module.css.js"),d=require("../../IL-OTJ/ILOTJ.js");require("../../IL-OTJ/_components/atoms/Textarea/Textarea.js"),require("../../IL-OTJ/_components/InputDataReasoningCard.js"),require("../../IL-OTJ/_components/TooltipComponent.js");var c=require("../../IL-OTJ/_components/templates/TemplatesMap/templatesMap.js"),_=require("../../IL-OTJ/helpers/utils.js"),v=require("../../IL-OTJ/store/CitationsContext.js");require("@mui/material"),require("@mui/material/Tooltip"),require("react-markdown"),require("rehype-raw"),require("axios"),require("@e-llm-studio/streaming-response"),require("@e-llm-studio/watch-me-work"),require("../../IL-OTJ/_components/ChatComponents/ChatHeader.js"),require("remark-gfm"),require("../../IL-OTJ/_components/MarkdownComponents/MarkdownElements.js"),require("../../IL-OTJ/_components/CitationLink.js"),require("@e-llm-studio/citation"),require("@viswa-test/test-citation"),require("./ToolTip.js");var p=require("../store/useAuthStore.js");require("date-fns"),require("framer-motion"),require("@mui/icons-material/Close");var f=require("../store/useConfigStore.js"),g=require("../config.js");function m(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("@radix-ui/react-tooltip"),require("./StationOnboarding/InputField.js"),require("../store/useEnvStore.js"),require("react-router-dom");var w=m(t),y=function(){return n.jsx("img",{src:l.default,alt:"Thinking...",width:"20",height:"20"})},h="INITIAL",b="SUCCESS",S="FAILURE",A="IN_PROGRESS",T=function(e){return"string"!=typeof e?"":e.replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g,"").replace(/<!--```json[\s\S]*?```-->/g,"").trim()},I=function(e){if(!e)return!1;var n=e.toLowerCase().trim();return"default"===n||"default_variant"===n},M=function(e){return e.toLowerCase().replace(/ /g,"_").replace(/tier(\d+)/i,"tier_$1")};exports.default=function(l){var m,k,x,C,N,E,O=l.isOpen,R=l.onClose,L=l.initialScope,D=void 0===L?"global":L,j=l.ruleSet,q=l.editingRule,P=l.editingTier,V=l.editingVariants,F=l.focusedVariantIndex,G=l.setFocusedVariantIndex,U=l.triggerAddVariant,J=l.triggerFixGaps,H=l.copiedRule,W=l.copiedSourceTier,B=l.copiedTargetTier,K=l.initialDraftMessage,Y=l.initialChatMessage,Q=l.applicationIntegrationId;l.modeId;var z=t.useState({station:D,tiers:["Tier 1"]}),Z=z[0],$=z[1],X=t.useState(h),ee=X[0],ne=X[1],te=t.useState(!1),ie=te[0],re=te[1],ae=t.useState("Thank you teacher for teaching me, your rule has been saved successfully."),oe=ae[0];ae[1];var le=t.useState(""),se=le[0],ue=le[1],de=t.useState(!1),ce=de[0],_e=de[1],ve=t.useRef(null),pe=t.useState(!1),fe=pe[0],ge=pe[1],me=t.useRef(!1),we=s.useLearningTemplateStore().tiers,ye=w.default.useRef(new Set),he=t.useState(null);he[0];var be=he[1],Se=t.useState(null);Se[0];var Ae=Se[1],Te=t.useState(null);Te[0];var Ie=Te[1],Me=t.useRef(new Map),ke=t.useRef(""),xe=t.useRef(!1),Ce=t.useState(0),Ne=Ce[0],Ee=Ce[1],Oe=t.useState(!1),Re=Oe[0],Le=Oe[1],De=t.useRef(null),je=t.useRef(0),qe=t.useState(null),Pe=qe[0],Ve=qe[1],Fe=t.useState([]),Ge=Fe[0],Ue=Fe[1],Je=t.useState(null),He=Je[0],We=Je[1],Be=t.useState(null),Ke=Be[0],Ye=Be[1],Qe=t.useState(!1),ze=Qe[0],Ze=Qe[1],$e=t.useRef({}),Xe=t.useRef([]),en=t.useRef(!1),nn=t.useState(!1),tn=nn[0],rn=nn[1],an=t.useRef(!1),on=t.useRef(new Set),ln=t.useState(null),sn=ln[0],un=ln[1],dn=t.useState(null),cn=dn[0],_n=dn[1],vn=t.useState(null),pn=vn[0],fn=vn[1],gn=t.useRef(null),mn=t.useRef(null),wn=t.useRef(null),yn=t.useRef({}),hn=t.useRef([]),bn=t.useRef([]),Sn=t.useRef({}),An=f.useConfigStore(),Tn=An.configuration,In=An.ilLabels;t.useEffect(function(){sn||_n(null)},[sn]),t.useEffect(function(){var e;if(O&&q){gn.current=q.ruleId;var n=null===(e=null==V?void 0:V[F||0])||void 0===e?void 0:e.variantId;fn(n||null)}},[O,q,V,F]),t.useEffect(function(){O&&$(function(n){return e.__assign(e.__assign({},n),{station:D})})},[O,D]),t.useEffect(function(){console.log("triggered",pn),console.log(Zn,"structuredAIResponse"),$n(function(n){return Array.isArray(n)?n.map(function(n){return e.__assign(e.__assign({},n),{is_readOnly:n.variant_id!==pn&&n.new_variant_id!==pn})}):n}),rt(function(n){return Array.isArray(n)?n.map(function(n){return e.__assign(e.__assign({},n),{is_readOnly:n.variant_id!==pn&&n.new_variant_id!==pn})}):n})},[pn]),t.useEffect(function(){var n;if(!O)return ar(),void(en.current=!1);if(!en.current){var t=V,i=t&&t.length>0,r=null!=q;if(i||r){if((null==q?void 0:q.ruleTitle)&&qn(q.ruleTitle),P&&($(function(n){return e.__assign(e.__assign({},n),{tiers:[P]})}),mn.current=P.toLowerCase().replace(/ /g,"_")),i){var a=P?M(P):"tier_1",o=new Map,l=new Map,s=new Map,u=new Map,d=new Map,c=new Map,_=[];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),_.push(e.variantId||e.variant_id||"")}),o.set(a,u),l.set(a,d),s.set(a,c);var v=null===(n=null==t?void 0:t[F||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==q?void 0:q.ruleTitle)||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",scope:[a],scheduling_config:r||{},variant_id:e.variantId,question_id:(null==q?void 0:q.ruleId)||"",tier_id:a.replace("tier_",""),is_readOnly:e.variantId!==v,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"}});$n(p),$n(p),rt(p),nt(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!==(v=null===(_=null==g?void 0:g.break_code_rules)||void 0===_?void 0:_.respect_break_code)&&void 0!==v?v:null==g?void 0:g.respect_break_code)&&void 0!==p&&p},is_default_enabled:I(e.variantType||e.variant_type)})}),Cn(new Map([[a,f]])),Jn(o),Bn(l),Qn(s)}else if(r&&q){var g=q.ruleDesc;if(g&&Jn(new Map([["tier_1",new Map([[0,g]])]])),q.whenToApply){var m=q.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:""}});Bn(new Map([["tier_1",new Map([[0,m]])]]))}if(q.whenNotToApply){var w=q.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:""}});Qn(new Map([["tier_1",new Map([[0,w]])]]))}}}else if(H&&W&&B){qn(H.ruleTitle||""),$(function(n){return e.__assign(e.__assign({},n),{tiers:[B]})}),mn.current=M(B);var y=M(W),h=H.variants||[],b=(o=new Map,l=new Map,s=new Map,new Map),S=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:""}}):[];S.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,S),s.set(y,A),Jn(o),Bn(l),Qn(s);var T=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:H.ruleTitle||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",scope:[W],scheduling_config:r||{},variant_id:e.variantId,question_id:H.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"}});$n(T),rt(T),nt(function(e){var n=new Map(e);return n.set(y,JSON.parse(JSON.stringify(T))),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!==(v=null===(_=null==f?void 0:f.break_code_rules)||void 0===_?void 0:_.respect_break_code)&&void 0!==v?v:null==f?void 0:f.respect_break_code)&&void 0!==p&&p},is_default_enabled:I(e.variantType||e.variant_type)})}),Cn(new Map([[y,k]]))}}},[O,q,V,P,H,W,B]),t.useEffect(function(){if(O){if(console.log("[Accordion Init] editingTier:",P,"focusedVariantIndex:",F),P&&$(function(n){return e.__assign(e.__assign({},n),{tiers:[P]})}),ze)return console.log("[Accordion] isAddingNewVariant mode — closing all variant accordions"),void vt(void 0);if(U){console.log("[Accordion] triggerAddVariant mode — not opening any variant on RHS"),vt(void 0);var n=(P?M(P):"tier_1").replace(/_/g," ");gt("I want to add a new variant to ".concat(n))}else null!=F?(console.log("[Accordion] Opening SPECIFIC variant index ".concat(F," (from VariantCard)")),vt(F),qt(function(e){return e+1})):(q||V&&V.length>0)&&(console.log("[Accordion] Opening DEFAULT/1st variant (index 0) for RuleHeader edit"),vt(0),qt(function(e){return e+1}))}else vt(void 0)},[O,P,F,q,V,U,ze]),t.useEffect(function(){O&&J&&q&&null!==F&>("I want to fix the gaps")},[O,J,q,F]);var Mn={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},kn=t.useState(new Map([["tier_1",new Map([[0,Mn]])],["tier_2",new Map([[0,Mn]])]])),xn=kn[0],Cn=kn[1],Nn=t.useState(new Set([])),En=Nn[0],On=Nn[1],Rn=t.useState("");Rn[0];var Ln=Rn[1],Dn=t.useState(""),jn=Dn[0],qn=Dn[1],Pn=t.useState(new Map([["tier_1",new Map],["tier_2",new Map]])),Vn=Pn[0],Fn=Pn[1],Gn=t.useState(new Map([["tier_1",new Map],["tier_2",new Map]])),Un=Gn[0],Jn=Gn[1],Hn=t.useState(new Map([["tier_1",new Map],["tier_2",new Map]])),Wn=Hn[0],Bn=Hn[1],Kn=t.useState(new Map([["tier_1",new Map],["tier_2",new Map]])),Yn=Kn[0],Qn=Kn[1],zn=t.useState([]),Zn=zn[0],$n=zn[1],Xn=t.useState(new Map),et=Xn[0],nt=Xn[1],tt=t.useState([]),it=tt[0],rt=tt[1],at=t.useState(!1),ot=at[0],lt=at[1],st=t.useState([]),ut=st[0],dt=st[1],ct=t.useState(void 0),_t=ct[0],vt=ct[1],pt=t.useState(""),ft=pt[0],gt=pt[1],mt=t.useState(null),wt=mt[0],yt=mt[1],ht=t.useState([]),bt=ht[0],St=ht[1],At=t.useState([]),Tt=At[0],It=At[1],Mt=t.useState({}),kt=Mt[0],xt=Mt[1],Ct=t.useState(new Map),Nt=Ct[0],Et=Ct[1],Ot=t.useState(new Set),Rt=Ot[0],Lt=Ot[1],Dt=t.useState(0),jt=Dt[0],qt=Dt[1],Pt=t.useState({ruleTitle:"",ruleDescription:"",scopeData:"",whenToApply:"",whenNotToApply:"",configData:""}),Vt=Pt[0],Ft=Pt[1],Gt=t.useState([]),Ut=Gt[0],Jt=Gt[1],Ht=t.useState(""),Wt=Ht[0],Bt=Ht[1],Kt=t.useState({}),Yt=Kt[0],Qt=Kt[1],zt=t.useState(!1),Zt=zt[0],$t=zt[1],Xt=t.useRef(null),ei=t.useRef(null),ni=t.useRef(-1),ti=t.useRef(null);t.useEffect(function(){bn.current=Zn},[Zn]),t.useEffect(function(){var t=new Set,r=console.warn;return console.warn=function(){for(var a,o=[],l=0;l<arguments.length;l++)o[l]=arguments[l];r.apply(void 0,o);var s=o[0];if("string"==typeof s&&s.includes("Failed to parse JSON for property=")){var d=s.match(/warnId="([^"]+)"/),c=null==d?void 0:d[1];if(c&&t.has(c))return;c&&t.add(c),null===(a=ti.current)||void 0===a||a.show({severity:"warn",sticky:!1,life:5e3,className:u.default.toastWarning,content:n.jsxs("div",e.__assign({className:u.default.toastContent},{children:[n.jsxs("div",e.__assign({className:u.default.toastHeaderLeft},{children:[n.jsx(i.AlertTriangle,{className:u.default.iconWarning}),n.jsx("span",e.__assign({className:"".concat(u.default.toastTitle," ").concat(u.default.toastTitleWarning)},{children:"Parsing Issue"}))]})),n.jsx("p",e.__assign({className:"".concat(u.default.toastMessage," ").concat(u.default.toastMessageWarning)},{children:"The AI response couldn't be parsed correctly. Please try rephrasing your input or retry."}))]}))})}},function(){console.warn=r}},[]);var ii=t.useState(!1),ri=ii[0],ai=ii[1],oi=t.useState(!1),li=oi[0],si=oi[1],ui=t.useState({}),di=ui[0],ci=ui[1],_i=t.useState(""),vi=_i[0],pi=_i[1],fi=t.useState(!0),gi=fi[0],mi=fi[1],wi=t.useState(!1),yi=wi[0],hi=wi[1],bi=t.useState(!1),Si=bi[0],Ai=bi[1],Ti=t.useState(""),Ii=Ti[0],Mi=Ti[1],ki=t.useState(""),xi=ki[0],Ci=ki[1],Ni=t.useState(""),Ei=Ni[0],Oi=Ni[1],Ri=t.useState(null),Li=Ri[0],Di=Ri[1],ji=t.useState(null),qi=ji[0],Pi=ji[1],Vi=t.useState(null),Fi=Vi[0],Gi=Vi[1],Ui=p.default.getState().user,Ji=v.useCitations(),Hi=Ji.dispatch,Wi=Ji.getLatestReasoning;t.useEffect(function(){console.log("Structured AI Response updated:",Zn)},[Zn]),t.useEffect(function(){console.log("isCloseModal AI Response updated:",gi)},[gi]),t.useEffect(function(){!1===Zt?(si(!1),Mi(""),Ci("")):(_e(!1),ue(""))},[Zt]),t.useEffect(function(){null!=_t&&V&&!V[_t]&&Di(null)},[_t,V]),t.useEffect(function(){if(fe&&!me.current){me.current=!0,console.log("UseEffect triggered: Sending save message to chat agent");gt("Save this Learning"),ge(!1),setTimeout(function(){me.current=!1,gt("")},2e3)}},[fe]);var Bi=t.useCallback(function(e,n){Ge.some(function(n){return n.id===e})?(Ai(!0),We(e),Ye(n),setTimeout(function(){Ye(null),We(null)},6e3)):console.warn("Variant ID ".concat(e," not found in comparison variants."))},[Ge]),Ki=t.useMemo(function(){var e=Si&&Ne>0;return console.log("[Loader Debug] showComparison: ".concat(Si,", activeRequests: ").concat(Ne,", Result: ").concat(e)),e},[Si,Ne]),Yi=t.useCallback(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;Jn(function(e){var i=new Map(e),r=new Map(i.get(n));return r.set(t,a),i.set(n,r),i}),ci(function(i){if(i["ruleDescription-".concat(n,"-").concat(t)]){var r=e.__assign({},i);return delete r["ruleDescription-".concat(n,"-").concat(t)],r}return i})},[]),Qi=t.useCallback(function(n,t){Bn(function(i){var r=new Map(i),a=new Map(r.get(n)),o=a.get(t)||[];return a.set(t,e.__spreadArray(e.__spreadArray([],o,!0),[{id:Date.now(),text:"",reasoning:""}],!1)),r.set(n,a),r}),ci(function(i){if(i["whenToApply-".concat(n,"-").concat(t)]){var r=e.__assign({},i);return delete r["whenToApply-".concat(n,"-").concat(t)],r}return i})},[]),zi=t.useCallback(function(e,n,t){Bn(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})},[]),Zi=t.useCallback(function(n,t,i,r){Bn(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.__assign(e.__assign({},n),{text:r}):n})),o.set(n,l),o}),ci(function(i){if(i["whenToApply-".concat(n,"-").concat(t)]){var r=e.__assign({},i);return delete r["whenToApply-".concat(n,"-").concat(t)],r}return i})},[]),$i=t.useCallback(function(n,t){Qn(function(i){var r=new Map(i),a=new Map(r.get(n)),o=a.get(t)||[];return a.set(t,e.__spreadArray(e.__spreadArray([],o,!0),[{id:Date.now(),text:"",reasoning:""}],!1)),r.set(n,a),r})},[]),Xi=t.useCallback(function(e,n,t){Qn(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})},[]),er=t.useCallback(function(n,t,i,r){Qn(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.__assign(e.__assign({},n),{text:r}):n})),o.set(n,l),o})},[]),nr=t.useCallback(function(e){var n=e.replace(/_/g," ");Ze(!0),null==G||G(null),vt(void 0),gt("I want to add a new variant to ".concat(n))},[]),tr=function(n,t,i){var r="".concat(n,"_").concat(t);console.log("Highlighting ".concat(i," at ").concat(r)),Et(function(n){var t,a=new Map(n),o=a.get(r)||{};return a.set(r,e.__assign(e.__assign({},o),((t={})[i]=!0,t))),a}),setTimeout(function(){Et(function(n){var t,a=new Map(n),o=a.get(r)||{};return a.set(r,e.__assign(e.__assign({},o),((t={})[i]=!1,t))),a})},1500)},ir=t.useCallback(function(n,t){$(function(i){var r;return e.__assign(e.__assign({},i),((r={})[n]=t,r))}),ci(function(t){if(t[n]){var i=e.__assign({},t);return delete i[n],i}return t})},[]),rr=t.useCallback(function(n,t,i,r){Fn(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}),Cn(function(a){var o,l,s,u=new Map(a),d=new Map(u.get(n)||new Map),c=d.get(t)||Mn;switch(i){case"order_rules":case"advertiser_rules":s="boolean"==typeof r?e.__assign(e.__assign({},c),((o={})[i]=e.__assign(e.__assign({},c[i]),{enabled:r}),o)):"object"==typeof r&&null!==r?e.__assign(e.__assign({},c),((l={})[i]={enabled:r.enabled,global_min_separation_seconds:r.global_min_separation_seconds},l)):c;break;case"inventory_rules":s=e.__assign(e.__assign({},c),{inventory_rules:{respect_inventory_code:"boolean"==typeof r?r:r.respect_inventory_code}});break;case"break_code_rules":s=e.__assign(e.__assign({},c),{break_code_rules:{respect_break_code:"boolean"==typeof r?r:r.respect_break_code}});break;case"is_default_enabled":s=e.__assign(e.__assign({},c),{is_default_enabled:"boolean"==typeof r?r:!!r});break;default:s=c}return d.set(t,s),u.set(n,d),u})},[]);t.useEffect(function(){Zt&&(Ai(!1),Ye(null),We(null))},[Zt]);var ar=t.useCallback(function(n){var t;if(void 0===n&&(n=!1),n||(Hi({type:"RESET"}),Xt.current=null,$n([]),dt([]),Jt([]),Qt({}),Ai(!1),ye.current.clear()),qn(""),St([]),Ze(!1),ke.current="",Oi(""),Pi(null),It([]),$({station:"",tiers:[]}),Ee(0),Le(!1),Gi(null),Jn(new Map([["tier_1",new Map],["tier_2",new Map]])),Bn(new Map([["tier_1",new Map],["tier_2",new Map]])),Qn(new Map([["tier_1",new Map],["tier_2",new Map]])),Cn(new Map([["tier_1",new Map([[0,Mn]])],["tier_2",new Map([[0,Mn]])]])),Fn(new Map([["tier_1",new Map],["tier_2",new Map]])),Ln(""),vt(0),qt(0),$({station:D,tiers:["Tier 1"]}),n||xt({}),Fn(new Map([["tier_1",new Map],["tier_2",new Map]])),gt(""),Ft({ruleTitle:"",ruleDescription:"",scopeData:"",whenToApply:"",whenNotToApply:"",configData:""}),ci({}),pi(""),mi(!0),be(null),Ae(null),nt(new Map),rt([]),rn(!1),Ie(null),ei.current=null,xe.current=!1,$e.current={},on.current.clear(),gn.current=null,mn.current=null,fn(null),ue(""),ne(h),re(!1),_e(!1),ge(!1),Ve(null),Ue([]),We(null),Ye(null),un(null),lt(!1),yt(null),Mi(""),Ci(""),si(!1),On(new Set),me.current=!1,Me.current.clear(),je.current=0,De.current=null,wn.current=null,ni.current=-1,an.current=!1,en.current=!1,q){q.ruleTitle&&qn(q.ruleTitle),P&&($(function(n){return e.__assign(e.__assign({},n),{tiers:[P]})}),mn.current=P.toLowerCase().replace(/ /g,"_")),gn.current=q.ruleId;var i=null===(t=null==V?void 0:V[F||0])||void 0===t?void 0:t.variantId;if(fn(i||null),V&&V.length>0){var r=P?M(P):"tier_1",a=new Map,o=new Map,l=new Map,s=new Map,u=new Map,d=new Map;V.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),Jn(a),Bn(o),Qn(l);var c=V.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:q.ruleTitle||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",scope:[r],scheduling_config:a||{},variant_id:e.variantId,question_id:q.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"}});$n(c),rt(c),nt(function(e){var n=new Map(e);return n.set(r,JSON.parse(JSON.stringify(c))),n});var _=new Map;V.forEach(function(e,n){var t,i,r,a,o,l,s,u,d,c,v,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;_.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===(v=null==g?void 0:g.break_code_rules)||void 0===v?void 0:v.respect_break_code)&&void 0!==p?p:null==g?void 0:g.respect_break_code)&&void 0!==f&&f},is_default_enabled:I(e.variantType||e.variant_type)})}),Cn(new Map([[r,_]])),vt(null!=F?F:0)}}},[Hi,D,q,P,V,F]),or=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)},lr=t.useCallback(function(){console.log("variantIds",bt),Ai(!0)},[bt]),sr={"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;ni.current!==r&&(console.log("Opening variant accordion: AI index ".concat(i," → 0-based index ").concat(r)),vt(r),ni.current=r)}}catch(e){console.error("Failed to parse variant_index from HTML comment:",e)}}},"Crafted Instant Learning with C.A.R.E.":function(n){var t,i=_.extractAndParseWithProperty(n),r=_.extractAndParseWithProperty(n,"general_details");console.log("--- [CARE] Staging Initial Structure ---",i);var a=_.extractAndParseWithProperty(n,"critical_gaps");if(console.log("isCriticalGap",a),Le(!!a),i){if(i.variant_type&&!("is_variant"in i)){var o=null===(t=dr(i.variant_type||"").toLowerCase().match(/^(default_variant|default|variant)/i))||void 0===t?void 0:t[0];i.variant_type=I(o)?"Default":"variant",i.isDefault=I(o),console.log("parsed.variant_type",i.variant_type)}var l=i.scope&&i.scope.length>0?String(i.scope[0]):null,s=l?dr(l).toLowerCase().trim().replace(/ /g,"_"):null,u=Boolean(s&&mn.current!==s);if(u&&s){var d=mn.current;console.log("[Tier Switch Detected]",mn.current,"→",s),mn.current=s,gn.current=null;var c=(bn.current||[]).findIndex(function(e){return!0===(null==e?void 0:e.is_new_variant)});-1===c&&void 0!==_t&&(c=_t),d&&-1!==c&&(console.log("[Tier Switch] Stripping draft variant at index ".concat(c," from ").concat(d)),Jn(function(e){var n=new Map(e),t=new Map(n.get(d)||new Map);return t.delete(c),n.set(d,t),n}),Bn(function(e){var n=new Map(e),t=new Map(n.get(d)||new Map);return t.delete(c),n.set(d,t),n}),Qn(function(e){var n=new Map(e),t=new Map(n.get(d)||new Map);return t.delete(c),n.set(d,t),n}),Cn(function(e){var n=new Map(e),t=new Map(n.get(d)||new Map);return t.delete(c),n.set(d,t),n}),$n(function(n){if(!Array.isArray(n))return n;var t=e.__spreadArray([],n,!0);return t[c]&&(t[c]=e.__assign(e.__assign({},t[c]),{scope:[s],tier_id:s.replace("tier_","")})),bn.current=t,t})),ni.current=-1;var v=s.replace(/_/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()});$(function(n){return e.__assign(e.__assign({},n),{tiers:[v]})})}yt(i),be({Updated_Fields_Response:i,General_Response:r}),(null==r?void 0:r.variant_id)&&"new_variant_id"===(null==r?void 0:r.variant_id)&&(r.variant_id=null),(null==r?void 0:r.is_interpretation_ready)&&(null==r?void 0:r.question_id)&&Gr(r,i,u),(null==r?void 0:r.is_interpretation_ready)&&(null==r?void 0:r.question_id)&&gn.current&&pn?$n(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===pn?e.__assign(e.__assign({},n),i):n}),r=n.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===pn});return console.log(r,"targetIndexif"),-1!==r&&setTimeout(function(){console.log("targetIndex",r),vt(r),qt(function(e){return e+1}),ni.current=r},0),t}):(null==r?void 0:r.is_interpretation_ready)&&(null==r?void 0:r.question_id)&&gn.current&&!pn?$n(function(n){var t;if(Array.isArray(n)){var r=n.findIndex(function(e){return!0===e.is_new_variant});if(-1!==r)setTimeout(function(){vt(r),qt(function(e){return e+1}),ni.current=r},0),t=n.map(function(n,t){return t===r?e.__assign(e.__assign(e.__assign({},n),i),{is_new_variant:!0,is_variant:!0}):n});else{var a=n.length;setTimeout(function(){vt(a),qt(function(e){return e+1}),ni.current=a},0),t=e.__spreadArray(e.__spreadArray([],n,!0),[e.__assign(e.__assign({},i),{is_new_variant:!0})],!1)}}else setTimeout(function(){vt(0),qt(function(e){return e+1}),ni.current=0},0),t=[e.__assign(e.__assign({},i),{is_new_variant:!0})];return bn.current=t,t}):(null==r?void 0:r.is_interpretation_ready)&&($n([i]),setTimeout(function(){vt(0),qt(function(e){return e+1}),ni.current=0},0)),void 0!==i.is_user_accepted_risk&&$n(function(n){var t=!(!q&&!V),r=Array.isArray(n)?e.__spreadArray([],n,!0):[];if(t&&0===r.length&&V&&V.length>0&&(r=V.map(function(e,n){var t;return{variant_type:e.variantType||"variant ".concat(n+1),title:(null==q?void 0:q.ruleTitle)||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",is_valid:!0,is_readOnly:e.variantId!==pn,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}})),t){var a=Li||qi,o=r.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===a||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===a||(null==e?void 0:e.id)&&e.id===a});if(-1===o&&void 0!==_t&&(o=_t),-1!==o)return r[o]=e.__assign(e.__assign({},r[o]),{is_user_accepted_risk:!!i.is_user_accepted_risk}),r}return n})}},"RHS Validation Agent Response":function(n){var t,i,r,a=n;if("string"==typeof n)try{a=JSON.parse(n)}catch(e){a=_.parseValidationData(n)}if(Ae(a),console.log("--- [RHS] Updating Staged Logic ---"),console.log("parsed data from RHS Validation",a),a){yt(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(Zn)){var r=Li||qi,o=-1;!(!q&&!V)&&r&&(o=Zn.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===o&&void 0!==_t&&(o=_t),-1!==o&&(i=Zn[o])}t=i?e.__assign({},i):{wta:"",wnta:""}}return e.__assign(e.__assign({},t),{wta:t.wta,wnta:t.wnta,is_valid:a.is_valid,conflictingConditions:a.conflictingConditions||[],conflictMarkdown:{},conflict_view:a.conflict_view||{}})});var o=(P||"Tier 1").toLowerCase().replace(/ /g,"_"),l=function(){var e,n=bn.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(pn)if(-1!==(t=n.findIndex(function(e){return(null==e?void 0:e.variant_id)===pn||(null==e?void 0:e.new_variant_id)===pn})))return t;if(Li)if(-1!==(t=n.findIndex(function(e){return(null==e?void 0:e.variant_id)===Li||(null==e?void 0:e.new_variant_id)===Li})))return t;var r=null!==(e=null==V?void 0:V.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!==_t?_t:0;return console.log("[RHS] Fallback index used:",o),o}();if(console.log("Resolved variant index for conflict injection:",l),!1===a.is_valid)((null===(t=a.conflictingConditions)||void 0===t?void 0:t.length)||0)>0&&(ci(function(n){var t=e.__assign({},n);return a.conflictingConditions.forEach(function(e){e.condition_wnta&&!e.condition_wta?t["whenNotToApply-".concat(o,"-").concat(l)]=e.reason:t["whenToApply-".concat(o,"-").concat(l)]=e.reason}),t}),pi("")),a.conflict_view&&((null===(i=a.conflict_view.wta)||void 0===i?void 0:i.length)>0&&Bn(function(n){var t=new Map(n),i=new Map(t.get(o)||new Map),r=e.__spreadArray([],i.get(l)||[],!0);return a.conflict_view.wta.forEach(function(n){var t=r.findIndex(function(e){return e.text.trim()===n.value});-1!==t?r[t]=e.__assign(e.__assign({},r[t]),{conflict:n}):r.push({id:"conflict-wta-".concat(Date.now(),"-").concat(Math.random()),text:n.value,conflict:n})}),i.set(l,r),t.set(o,i),t}),(null===(r=a.conflict_view.wnta)||void 0===r?void 0:r.length)>0&&Qn(function(n){var t=new Map(n),i=new Map(t.get(o)||new Map),r=e.__spreadArray([],i.get(l)||[],!0);return a.conflict_view.wnta.forEach(function(n){var t=r.findIndex(function(e){return e.text.trim()===n.value});-1!==t?r[t]=e.__assign(e.__assign({},r[t]),{conflict:n}):r.push({id:"conflict-wnta-".concat(Date.now(),"-").concat(Math.random()),text:n.value,conflict:n})}),i.set(l,r),t.set(o,i),t}));else!0===a.is_valid&&(ci({}),pi(""),Bn(function(n){var t=new Map(n),i=new Map(t.get(o)||new Map),r=i.get(l)||[];return i.set(l,r.map(function(n){return e.__assign(e.__assign({},n),{conflict:void 0})})),t.set(o,i),t}),Qn(function(n){var t=new Map(n),i=new Map(t.get(o)||new Map),r=i.get(l)||[];return i.set(l,r.map(function(n){return e.__assign(e.__assign({},n),{conflict:void 0})})),t.set(o,i),t}))}},"User Action Execution":function(e){console.log("--- [User Action] Execution ---",e);var n=_.extractAndParseResponse(e);(console.log("parsedaction",n),"load"===(null==n?void 0:n.action)&&(null==n?void 0:n.question_id)&&Gr(n,null),"save"===(null==n?void 0:n.action)&&(null==n?void 0:n.is_save)&&(mi(!0),hi(!0)),"discard_rule"===(null==n?void 0:n.action))&&($n([{variant_id:void 0,rule_description:"",wta:"",wnta:"",variant_type:"variant"}]),rt([]),fn(null),vt(0),qt(0),un(null),rn(!1),Ze(!1),St([]),gn.current=null,qn(""),Gi(null),Cn(new Map([["tier_1",new Map([[0,Mn]])],["tier_2",new Map([[0,Mn]])]])),Jn(new Map([["tier_1",new Map],["tier_2",new Map]])),Bn(new Map([["tier_1",new Map],["tier_2",new Map]])),Qn(new Map([["tier_1",new Map],["tier_2",new Map]])))},"Validation Agent Response":function(n){var t,i;if(console.log("--- [Validation Agent] Committing Staged Data to UI ---"),console.log("raw data from Validation Agent",n,typeof n),"string"==typeof n){var r=n.match(/<!--\s*```json\s+property="rule_validation_card"\s+([\s\S]*?)```\s*-->/i);if(r&&r[1])try{var a=JSON.parse(r[1].trim()),o=null===(i=null===(t=null==a?void 0:a.validated_rules)||void 0===t?void 0:t[0])||void 0===i?void 0:i.rule_id;o&&(console.log("Setting default comparison ID:",o),We(o))}catch(e){console.error("Failed to parse rule_validation_card JSON",e)}}var l=_.extractAndParseWithProperty(n,"critical_gaps");console.log("isCriticalGap",l),Le(!!l);var s="string"==typeof n?_.extractAndParseResponse(n):n;console.log("parsed data from Validation Agent",s);var u=_.extractVariantIds(n);Ie(s);var d=!!(null==s?void 0:s.is_variant),c=void 0===(null==s?void 0:s.close_modal)||!!(null==s?void 0:s.close_modal),v=void 0!==(null==s?void 0:s.is_save)&&!!(null==s?void 0:s.is_save);mi(c),hi(v);var p=null==s?void 0:s.action,f="string"==typeof(null==s?void 0:s.edit_variant_id)&&s.edit_variant_id.trim()?s.edit_variant_id:"string"==typeof(null==s?void 0:s.set_variant_id)&&s.set_variant_id.trim()?s.set_variant_id:null,g="variant"===p&&d;if((null==s?void 0:s.edit_variant_id)&&!g&&Di(s.edit_variant_id),"edit"!==p&&"edit_current_rule"!==p||!f||Pi(f),g&&(Di(null),Pi(null)),"discard"===p)return console.log("Action 'discard' received: Resetting UI state but preserving chat."),en.current=!0,ar(!0),$n([]),Xt.current=null,void(ei.current=null);Oi(p);var m=null==s?void 0:s.new_variant_id,w="edit"===(null==s?void 0:s.action)&&(null==s?void 0:s.set_variant_id)&&!V;(null==s?void 0:s.is_valid)?(ci({}),yt(function(n){var t,i,r,a,o,l,u,d,c,_,v,p;if(console.log("⏮️ PREVIOUS Staged Response:",n),!n)return console.warn("⚠️ No previous staged response found"),n;var g=function(e,n){return Object.prototype.hasOwnProperty.call(e||{},n)},m=e.__assign(e.__assign({},n),s);Array.isArray(null===(t=null==s?void 0:s.condition_result)||void 0===t?void 0:t.when_to_apply)?m.wta=s.condition_result.when_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join(" OR "):g(s,"wta")&&void 0!==(null==s?void 0:s.wta)&&(m.wta=null!==(i=null==s?void 0:s.wta)&&void 0!==i?i:""),Array.isArray(null===(r=null==s?void 0:s.condition_result)||void 0===r?void 0:r.when_not_to_apply)?m.wnta=s.condition_result.when_not_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join(" OR "):g(s,"wnta")&&void 0!==(null==s?void 0:s.wnta)&&(m.wnta=null!==(a=null==s?void 0:s.wnta)&&void 0!==a?a:""),console.log("finalData",m),console.log("checking parsed here :",s);var w,y=f;if(Array.isArray(Zn)&&y&&(w=y,Zn.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===w||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===w||(null==e?void 0:e.id)&&e.id===w})),"edit"!==(null==s?void 0:s.action)||!q&&!V)return m;console.log("inside edit flow merge");var h=V||[],b=f,S=b?h.findIndex(function(e){return e.variantId===b||e.variant_id&&e.variant_id===b||e.id&&e.id===b}):-1;if(-1===S&&(null==s?void 0:s.set_variant_id)&&(S=h.findIndex(function(e){return e.variantId===s.set_variant_id||e.variant_id&&e.variant_id===s.set_variant_id||e.id&&e.id===s.set_variant_id})),-1===S&&b&&Array.isArray(Zn)&&(S=Zn.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===b||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===b||(null==e?void 0:e.id)&&e.id===b})),-1!==S){var A,T,I,M=h[S]||(null==Zn?void 0:Zn[S]),k=(null==M?void 0:M.tier_id)||(null==M?void 0:M.tierId)||"1",x=(null==P?void 0:P.toLowerCase().replace(/ /g,"_"))||"tier_".concat(k);if(ni.current!==S&&(vt(S),ni.current=S),Array.isArray(null===(o=s.condition_result)||void 0===o?void 0:o.when_to_apply)?A=s.condition_result.when_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join("\n"):g(s,"wta")&&void 0!==(null==s?void 0:s.wta)?A=null!==(l=null==s?void 0:s.wta)&&void 0!==l?l:"":g(n,"wta")&&void 0!==(null==n?void 0:n.wta)&&(A=null!==(u=null==n?void 0:n.wta)&&void 0!==u?u:""),Array.isArray(null===(d=s.condition_result)||void 0===d?void 0:d.when_not_to_apply)?T=s.condition_result.when_not_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join("\n"):g(s,"wnta")&&void 0!==(null==s?void 0:s.wnta)?T=null!==(c=null==s?void 0:s.wnta)&&void 0!==c?c:"":g(n,"wnta")&&void 0!==(null==n?void 0:n.wnta)&&(T=null!==(_=null==n?void 0:n.wnta)&&void 0!==_?_:""),void 0!==A){var C=dr(A);cr(x,S,A,C,Wn,Bn,null==s?void 0:s.conflict_view),tr(x,S,"wta")}if(void 0!==T){var N=dr(T);cr(x,S,T,N,Yn,Qn,null==s?void 0:s.conflict_view),tr(x,S,"wnta")}if(g(s,"rule_description")&&void 0!==(null==s?void 0:s.rule_description)?I=null!==(v=null==s?void 0:s.rule_description)&&void 0!==v?v:"":g(n,"rule_description")&&void 0!==(null==n?void 0:n.rule_description)&&(I=null!==(p=null==n?void 0:n.rule_description)&&void 0!==p?p:""),void 0!==I){var E=dr(I);Jn(function(e){var n=new Map(e),t=new Map(n.get(x)||new Map);return t.set(S,E),n.set(x,t),n}),tr(x,S,"ruleDescription")}var O=void 0;g(s,"scheduling_config")&&void 0!==(null==s?void 0:s.scheduling_config)?O=null==s?void 0:s.scheduling_config:g(n,"scheduling_config")&&void 0!==(null==n?void 0:n.scheduling_config)&&(O=null==n?void 0:n.scheduling_config),O&&(Cn(function(e){var t,i,r,a,o,l,s=new Map(e),u=new Map(s.get(x)||new Map);return u.set(S,{order_rules:{enabled:!!(null===(t=O.order_rules)||void 0===t?void 0:t.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(i=O.order_rules)||void 0===i?void 0:i.global_min_separation_seconds)||0)/60)},advertiser_rules:{enabled:!!(null===(r=O.advertiser_rules)||void 0===r?void 0:r.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(a=O.advertiser_rules)||void 0===a?void 0:a.global_min_separation_seconds)||0)/60)},inventory_rules:{respect_inventory_code:!!(null===(o=O.inventory_rules)||void 0===o?void 0:o.respect_inventory_code)},break_code_rules:{respect_break_code:!!(null===(l=O.break_code_rules)||void 0===l?void 0:l.respect_break_code)},is_default_enabled:"Default"===(null==n?void 0:n.variant_type)||"default_variant"===(null==n?void 0:n.variant_type)||"default"===(null==n?void 0:n.variant_type)}),s.set(x,u),s}),tr(x,S,"order_enabled"),tr(x,S,"advertiser_enabled"),tr(x,S,"respect_inventory_code"),tr(x,S,"respect_break_code")),$n(function(n){if(!Array.isArray(n)||S<0||!n[S])return n;var t=e.__spreadArray([],n,!0),i=e.__assign({},t[S]);return void 0!==A&&(i.wta=A),void 0!==T&&(i.wnta=T),void 0!==I&&(i.rule_description=dr(I)),O&&(i.scheduling_config=O),console.log("updated variantxxx",i),t[S]=i,t});var R=null==n?void 0:n.variant_type;R&&$n(function(n){var t=Array.isArray(n)?e.__spreadArray([],n,!0):[],i=t.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===b||(null==e?void 0:e.variant_id)&&e.variant_id===(null==s?void 0:s.set_variant_id)||(null==e?void 0:e.variantId)===b});return-1!==i?t[i]=e.__assign(e.__assign({},t[i]),{variant_type:R}):t[S]=e.__assign(e.__assign({},t[S]||{}),{variant_type:R,variant_id:b||(null==s?void 0:s.set_variant_id)}),t})}})):console.warn("⚠️ parsed.is_valid is false, not committing to structuredAIResponse"),w||(d?(lt(!0),m&&m!==ei.current?(console.log("🚀 New Variant detected (".concat(m,"). Triggering loader.")),si(!0),Mi("Loading a variant"),console.log("reaching here in new variant flow"),Ci("This may take a moment as we update the rule with the new variant."),ei.current=m):m||console.log("ℹ️ Variant flow detected without specific ID.")):(lt(!1),ei.current=null),u&&St(u))},"Rule comparison results":function(e){try{var n=e;if("string"==typeof e)try{n=JSON.parse(e)}catch(t){n=_.extractAndParseResponse(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 _="";if((null==o?void 0:o.nodes)&&o.nodes.title){var v=o.nodes.title;(null===(i=null===(t=null==v?void 0:v.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:_,extractedScore:p,extractedScope:f}),{id:u,title:_,similarityScoreText:p,scope:f,intentTreeData:o,behaviorTreeData:l,isLoading:!1}});Ue(t)}catch(e){console.error("[Rule comparison results] Critical Handler Error:",e)}}},ur=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},dr=function(e){return"string"!=typeof e?"":e.replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g,"").replace(/<!--```json[\s\S]*?```-->/g,"").trim()},cr=function(n,t,i,r,a,o,l){var s;if(void 0!==i){var u=(a.get(n)||new Map).get(t)||[],d=u.map(function(e){return e.text}).join("\n"),c=(null===(s=u[(null==u?void 0:u.length)-1])||void 0===s?void 0:s.reasoning)||"",_=ur(i)||"";if(""===i&&u.length>0||r.trim()!==d.trim()||_!==c){var v=""===i?{updatedItems:[],newIds:[]}:function(n,t,i){if(!n.trim())return{updatedItems:e.__spreadArray([],t,!0),newIds:[]};var r=n.match(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g)||[],a=n.replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g,"").replace(/<!--```json[\s\S]*?```-->/g,""),o=[],l=a.replace(/<conflicting>[\s\S]*?<\/conflicting>/g,function(e){return o.push(e),"__CONFLICT_BLOCK_".concat((null==o?void 0:o.length)-1,"__")}).split(/\s*(?:\r?\n|\\+n)\s*/).map(function(e){return e.trim().replace(/^-\s*/,"")}).filter(Boolean),s=new Map(t.map(function(e){return[e.text,e]})),u=[],d=[],c=Array.isArray(null==i?void 0:i.wta)&&n.includes("wta")?i.wta:Array.isArray(null==i?void 0:i.wnta)?i.wnta:[];return l.forEach(function(n,t){var i=n;i.includes("__CONFLICT_BLOCK_")&&(i=i.replace(/__CONFLICT_BLOCK_(\d+)__/g,function(e,n){return o[parseInt(n)]}));var a=r[t]||"",l=i.replace(/<conflicting>[\s\S]*?<\/conflicting>/g,"").trim(),_=null==c?void 0:c.find(function(e){return e.value===l}),v=s.get(i);if(v)d.push(e.__assign(e.__assign({},v),{reasoning:a||v.reasoning,conflict:_||v.conflict}));else{var p="new-".concat(Date.now(),"-").concat(t);u.push(p),d.push({id:p,text:i,reasoning:a,conflict:_})}}),{updatedItems:d,newIds:u}}(i,u,l),p=v.updatedItems,f=v.newIds;o(function(e){var i=new Map(e),r=new Map(i.get(n)||new Map);return r.set(t,p),i.set(n,r),i}),(null==f?void 0:f.length)>0&&(Lt(function(n){return new Set(e.__spreadArray(e.__spreadArray([],Array.from(n),!0),f,!0))}),setTimeout(function(){Lt(function(e){var n=new Set(e);return f.forEach(function(e){return n.delete(e)}),n})},1500))}}},_r=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()})})};t.useEffect(function(){ft&&!me.current&&"save this learning"!==ft.toLowerCase()&&(_e(!1),ue(""),ni.current=null!=_t?_t:-1)},[ft]),t.useEffect(function(){var n,t,i,r,a,o,l,s,u;if(hn.current=Ut,Array.isArray(Zn)&&Zn.length>0){var d=Wt||"local-".concat(Date.now()),c=["ruleTitle","ruleDescription","whenToApply","whenNotToApply","scopeData","configData"],_={},v=Xt.current||[];Zn.forEach(function(n,t){var i,r;if(n){n.is_readOnly||(je.current=t);var a=t;if((null==n?void 0:n.variant_id)&&V)-1!==(o=V.findIndex(function(e){return e.variantId===n.variant_id}))&&(a=o);else if(Li&&V&&1===Zn.length){var o;-1!==(o=V.findIndex(function(e){return e.variantId===Li}))&&(a=o)}var l=null!==(i=v[a])&&void 0!==i?i:v[t],s=null!==(r=n.scope)&&void 0!==r?r:null==l?void 0:l.scope,u=_r(s).map(function(e){return e.toLowerCase().replace(/ /g,"_")}),d=u.length>0?u:Xe.current.length>0?Xe.current:["tier_1"];d.length>0&&(Xe.current=d),console.log("prevTierRef.current",Xe.current,"targetTiers",d);var p=dr(n.title);p&&p!==dr(null==l?void 0:l.title)&&!n.is_readOnly&&function(e,n,t,i,r,a){var o=dr(i);o&&o!==r&&(tr(e,n,t),a(o))}("global",0,"ruleTitle",n.title,jn,qn),d.forEach(function(i){var r,o,l,s,u,d=null!==(r=v[a])&&void 0!==r?r:v[t],p=!d,f=void 0!==n.rule_description&&null!==n.rule_description,g=dr(n.rule_description),m=(null===(o=Un.get(i))||void 0===o?void 0:o.get(a))||"",w=dr(m);f&&(g!==w||""===g&&""!==m)&&(Jn(function(e){var t=new Map(e),r=new Map(t.get(i)||new Map);return r.set(a,n.rule_description),t.set(i,r),t}),tr(i,a,"ruleDescription"));var y=!1===(null==wt?void 0:wt.is_valid),h=dr(n.wta),b=dr(null==d?void 0:d.wta),S=(null===(l=Wn.get(i))||void 0===l?void 0:l.get(a))||[];!(y&&""===h&&S.length>0)&&void 0!==n.wta&&null!==n.wta&&(h!==b||""===h&&S.length>0||0===S.length&&""!==h)&&(cr(i,a,n.wta,h,Wn,Bn,null==wt?void 0:wt.conflict_view),tr(i,a,"wta"));var A=dr(n.wnta),T=dr(null==d?void 0:d.wnta),M=(null===(s=Yn.get(i))||void 0===s?void 0:s.get(a))||[];if(!(y&&""===A&&M.length>0)&&void 0!==n.wnta&&null!==n.wnta&&(A!==T||""===A&&M.length>0||0===M.length&&""!==A)&&(cr(i,a,n.wnta,A,Yn,Qn,null==wt?void 0:wt.conflict_view),tr(i,a,"wnta")),n.scheduling_config||p||n.variant_type||n.variantType){var k=n.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}},x=null==d?void 0:d.scheduling_config,C=null===(u=xn.get(i))||void 0===u?void 0:u.get(a),N=n.variant_type||n.variantType,E=N?I(N):void 0,O=JSON.stringify(k)!==JSON.stringify(x),R=void 0!==E&&E!==(null==C?void 0:C.is_default_enabled),L=function(n,t){if(!n)return t;if(!t)return n;var i=e.__assign({},n);for(var r in t)t[r]&&"object"==typeof t[r]&&!Array.isArray(t[r])?i[r]=e.__assign(e.__assign({},i[r]||{}),t[r]):i[r]=t[r];return i};if(xt(function(e){return L(e,k)}),O||R){xt(function(e){return L(e,k)});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}(i,a,k,xn);D.forEach(function(e){return tr(i,a,e)}),On(function(e){return new Set(e).add("config")}),Cn(function(n){var t,r,o,l,s,u,d=new Map(n),c=new Map(d.get(i)||new Map),_=c.get(a)||Mn;return c.set(a,e.__assign(e.__assign(e.__assign(e.__assign(e.__assign(e.__assign({},_),k.order_rules&&{order_rules:{enabled:!!(null===(t=k.order_rules)||void 0===t?void 0:t.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(r=k.order_rules)||void 0===r?void 0:r.global_min_separation_seconds)||0)/60)}}),k.advertiser_rules&&{advertiser_rules:{enabled:!!(null===(o=k.advertiser_rules)||void 0===o?void 0:o.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(l=k.advertiser_rules)||void 0===l?void 0:l.global_min_separation_seconds)||0)/60)}}),k.inventory_rules&&{inventory_rules:{respect_inventory_code:!!(null===(s=k.inventory_rules)||void 0===s?void 0:s.respect_inventory_code)}}),k.break_code_rules&&{break_code_rules:{respect_break_code:!!(null===(u=k.break_code_rules)||void 0===u?void 0:u.respect_break_code)}}),void 0!==E&&{is_default_enabled:E})),d.set(i,c),d}),Fn(function(e){var n=new Map(e),t=new Map(n.get(i)||new Map),r=t.get(a)||new Set;return k.order_rules&&r.add("order_rules"),k.advertiser_rules&&r.add("advertiser_rules"),k.inventory_rules&&r.add("inventory_rules"),k.break_code_rules&&r.add("break_code_rules"),void 0!==E&&r.add("is_default_enabled"),t.set(a,r),n.set(i,t),n})}}var j={ruleTitle:n.title,ruleDescription:n.rule_description,whenToApply:n.wta,whenNotToApply:n.wnta,scopeData:n.scope,configData:n.action};n.is_readOnly||c.forEach(function(e){var n=ur(j[e]),t="ruleTitle"===e||"scopeData"===e?e:"".concat(e,"_").concat(i);n&&(n!==yn.current[t]&&(yn.current[t]=n,Sn.current[t]=!0,_[t]={reasoning:n,associatedCitations:[],tier:i,variantIndex:a}))}),n.conflictingConditions&&(ci(function(t){var r=e.__assign({},t);return n.conflictingConditions.forEach(function(e){e.condition_wta&&(r["whenToApply-".concat(i,"-").concat(a)]=e.reason),e.condition_wnta&&(r["whenNotToApply-".concat(i,"-").concat(a)]=e.reason)}),r}),On(function(n){return new Set(e.__spreadArray(e.__spreadArray([],Array.from(n),!0),["conditions"],!1))}))})}});var p=-1,f=!(!q&&!V),g="edit"===Ei||"edit_current_rule"===Ei,m=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},w=function(e,n){if(!n)return-1;var t=e.find(function(e){return m(e,n)});if(!t)return-1;var i=String((null==t?void 0:t.tier_id)||"");if(!i)return e.findIndex(function(e){return m(e,n)});var r=e.filter(function(e){return String((null==e?void 0:e.tier_id)||"")===i}).findIndex(function(e){return m(e,n)});return-1!==r?r:e.findIndex(function(e){return m(e,n)})};if(f)if(ei.current&&ot)-1!==(p=Zn.findIndex(function(e){return(null==e?void 0:e.new_variant_id)&&e.new_variant_id===ei.current||(null==e?void 0:e.variant_id)&&e.variant_id===ei.current||(null==e?void 0:e.id)&&e.id===ei.current}))&&(ei.current=null);else if(Li||qi){var y;(y=Li||qi)&&(p=w(Zn,y))}else if(U&&Array.isArray(Zn)&&Zn.length>0){for(h=Zn.length-1;h>=0;h--)if(Zn[h]&&!(null===(t=Zn[h])||void 0===t?void 0:t.is_readOnly)){p=h;break}}else null==F||Xt.current&&0!==Xt.current.length||(p=F);else if((y=Li||qi||ei.current)&&g&&(p=w(Zn,y)),!g&&-1===p&&Array.isArray(Zn)&&Zn.length>0){for(var h=Zn.length-1;h>=0;h--)if(Zn[h]&&!(null===(n=Zn[h])||void 0===n?void 0:n.is_readOnly)){p=h;break}-1===p&&(p=Zn.length-1)}-1!==p&&_t!==p&&(ni.current===p||xe.current&&!g||(console.log("🎯 Setting active variant accordion to index ".concat(p," (").concat(f?"EDIT":"CREATE"," mode)")),vt(p),ni.current=p));var b=Zn[0];if(b){if(b.scope&&JSON.stringify(b.scope)!==JSON.stringify(null===(i=v[0])||void 0===i?void 0:i.scope)&&"copy"!==b.action&&(o=b.scope,l=null===(r=v[0])||void 0===r?void 0:r.scope,s=_r(o),u=l?_r(l):[],$(function(n){return e.__assign(e.__assign({},n),{tiers:s})}),s.forEach(function(e){var n=e.trim();u.includes(e)||tr("global",0,"scope_".concat(n))})),b.scope_rule_set&&b.scope_rule_set!==(null===(a=v[0])||void 0===a?void 0:a.scope_rule_set)){var S=b.scope_rule_set.toLowerCase().trim();["global","genre","custom"].includes(S)&&($(function(n){return e.__assign(e.__assign({},n),{station:S})}),tr("global",0,"scope_station"))}b.wtl&&Ln(b.wtl)}Xt.current=Zn.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&&(Hi({type:"SAVE_CITATIONS",requestId:d,reasoningMap:_,rawCitations:Ut}),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:d,keys:Object.keys(_),newReasoningMap:_,getLatestReasoning:Wi,currentCitations:Ut}),Ft(function(n){var t=e.__assign({},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}))}},[Zn,Ut,Wt]),t.useEffect(function(){var n=Object.keys(Sn.current);if(0!==n.length){var t={};n.forEach(function(n){t[n]=e.__spreadArray([],Ut,!0)}),Sn.current={},Qt(function(n){return e.__assign(e.__assign({},n),t)})}},[Ut]);var vr=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==j?void 0:j.ruleSetId)||"",value:{scopeName:(null==j?void 0:j.ruleSetName)||"",scopeId:"Audacy_"+a.v4(),customScopeGroupName:(null==Tn?void 0:Tn.CUSTOM_SCOPE_GROUP_NAME)||"",description:(null==j?void 0:j.ruleSetDesc)||""}}})},pr=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}}},fr=function(n,t,i,r){void 0===r&&(r=0);var a=e.__assign({},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 _=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.__assign(e.__assign({},s),{global_min_separation_seconds:_})}else a[n]="inventory_rules"===n?e.__assign(e.__assign({},s),{respect_inventory_code:null==c?void 0:c.respect_inventory_code}):"break_code_rules"===n?e.__assign(e.__assign({},s),{respect_break_code:null==c?void 0:c.respect_break_code}):"is_default_enabled"===n?null!=c&&c:s})}),a},gr=function(e,n,t){void 0===t&&(t="variantType");var i=null==e?void 0:e[n];if(!i)return{label:or(e),isDefault:!1};var r=i[t]||"",a=I(r);return{label:"variant ".concat(n+1),isDefault:a}},mr=function(e,n){var t=I(e);return{label:"variant ".concat(n+1),isDefault:t}},wr=function(e,n,t){var i;void 0===t&&(t="");var r=null===(i=xn.get(e))||void 0===i?void 0:i.get(n);return r?r.is_default_enabled?"Default":"Variant":I(t)?"Default":"Variant"},yr=function(t,r){return void 0===r&&(r=!1),e.__awaiter(void 0,void 0,void 0,function(){var l,d,c,_,v,p,f,m,w,y,h,T,I,M,k,x,C;return e.__generator(this,function(N){switch(N.label){case 0:l=vr(Z.tiers),d=s.useLearningTemplateStore.getState().backwardCompatibility,c=je.current,_=fr(Vn,kt,xn,c),N.label=1;case 1:return N.trys.push([1,3,,4]),ne(A),ue(""),v=pr(_),p=a.v4(),f=[],m=[],w=(Zn||[])[c]||{},console.log("originalItem check :",w,c),Z.tiers.forEach(function(n){var i,r,s,u,_,y,h,b,S,A,T,I,M,k,x,C=n.toLowerCase().replace(/ /g,"_");m.push(C);var N=(null===(i=Un.get(C))||void 0===i?void 0:i.get(c))||"",E=(null===(r=Wn.get(C))||void 0===r?void 0:r.get(c))||[],O=(null===(s=Yn.get(C))||void 0===s?void 0:s.get(c))||[];if(!1===d){var R=[e.__assign(e.__assign({},v&&{config:e.__assign({master_name:Tn.CONFIG_MASTER_NAME},v)}),{datasource:{type:"link",ref:"www.something.com",tag:"something"},tierLinkId:p,variant:dr(N),conditions_whentoapply:E.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),conditions_whennottoapply:O.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),isDefault:null===(y=null===(_=null===(u=xn.get(C))||void 0===u?void 0:u.get(c))||void 0===_?void 0:_.is_default_enabled)||void 0===y||y,tier_id:(null===(h=we.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===C||e.tier_name.toLowerCase()===C.replace(/_/g,"")}))||void 0===h?void 0:h.tier_id)||"",topic_id:null,scope_id:(null==j?void 0:j.ruleSetId)||"",question_title:jn,variantType:wr(C,c,w.variant_type||w.variantType),instantLearningType:Tn.INSTANT_LEARNING_TYPE,is_user_accepted_risk:!1,propagation:!1,applicationMappingId:Q,modeId:"019e1e39-2030-7775-8312-0ad525700588"})];f.push(o.publishFeedback(R,Tn.ASSISTANT_NAME))}else{R={status:"approved",metadata:e.__assign(e.__assign({userName:null!==(b=null==Ui?void 0:Ui.firstname)&&void 0!==b?b:"",userEmailId:null!==(S=null==Ui?void 0:Ui.email)&&void 0!==S?S:"",llm:g.IL_CONFIG_CONSTANTS.MODEL,isVariantFlow:!0},v&&{config:e.__assign({master_name:g.IL_CONFIG_CONSTANTS.CONFIG_MASTER_NAME},v)}),{datasource:{type:"link",ref:"www.something.com",tag:"something"},variant:{tierLinkId:p,variant:dr(N),conditions_whentoapply:E.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),conditions_whennottoapply:O.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),referenceVariantID:null,referenceVariantIDVersion:null,scope:l[0]||{name:g.IL_CONFIG_CONSTANTS.SCOPE_NAME,parentScopeId:null,scopeRowId:(null==j?void 0:j.ruleSetId)||"",value:{scopeName:(null==j?void 0:j.ruleSetName)||"",scopeId:"Audacy_"+a.v4(),customScopeGroupName:g.IL_CONFIG_CONSTANTS.CUSTOM_SCOPE_GROUP_NAME,description:(null==j?void 0:j.ruleSetDesc)||""}},overriden:!1,isDefault:null===(I=null===(T=null===(A=xn.get(C))||void 0===A?void 0:A.get(c))||void 0===T?void 0:T.is_default_enabled)||void 0===I||I,tier:{name:n.split(" ").join("").toLowerCase(),tierGroupName:g.IL_CONFIG_CONSTANTS.CUSTOM_SCOPE_GROUP_NAME,tierPriority:parseInt(n.split(" ")[1]||"1"),tier_id:(null===(M=we.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===C||e.tier_name.toLowerCase()===C.replace(/_/g,"")}))||void 0===M?void 0:M.tier_id)||""},topic:{id:null,value:"".concat(Z.station||D,"RuleSet"),description:null},categories:[{id:null,value:g.IL_CONFIG_CONSTANTS.CATEGORY,description:g.IL_CONFIG_CONSTANTS.CATEGORY}],originalQuestion:jn,questionId:t.get(C)||null,variantType:wr(C,c,w.variant_type||w.variantType),parameterizedQuestion:null,created_at:(new Date).toISOString(),created_by:null!==(k=null==Ui?void 0:Ui.email)&&void 0!==k?k:"",instantLearningType:g.IL_CONFIG_CONSTANTS.INSTANT_LEARNING_TYPE,appliedTagsIL:[],tagMappingInfoIL:{},is_user_accepted_risk:!!(null!==(x=null==w?void 0:w.is_user_accepted_risk)&&void 0!==x?x:null==wt?void 0:wt.is_user_accepted_risk)},isAgentsFeedback:!0})};f.push(o.publishFeedback(R,Tn.ASSISTANT_NAME))}}),[4,Promise.all(f)];case 2:return y=N.sent(),ge(!1),console.log("✅ All feedback published:",y),ne(b),re(!0),h=new Map,y.forEach(function(e,n){var t,i,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)&&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)}}),s.useLearningTemplateStore.getState().setCreatedVariantInfo(Array.from(h.entries()).map(function(e){return{tierName:e[0],variants:e[1]}})),null===(k=ti.current)||void 0===k||k.show({severity:"success",sticky:!1,life:6e3,className:u.default.toastSuccess,content:n.jsxs("div",e.__assign({className:u.default.toastContent},{children:[n.jsxs("div",e.__assign({className:u.default.toastHeaderLeft},{children:[n.jsx(i.Check,{className:u.default.iconSuccess}),n.jsx("span",e.__assign({className:"".concat(u.default.toastTitle," ").concat(u.default.toastTitleSuccess)},{children:"Success"}))]})),n.jsx("p",e.__assign({className:"".concat(u.default.toastMessage," ").concat(u.default.toastMessageSuccess)},{children:"Learning saved successfully!"}))]}))}),ve.current=setTimeout(function(){gi||r?(console.log("Closing modal after save success",{isCloseModal:gi,forceClose:r}),Vr()):ar(!0)},3e3),[3,4];case 3:return T=N.sent(),console.error("❌ Error publishing feedback:",T),ge(!1),ne(S),_e(!0),I=(null===(x=null==T?void 0:T.response)||void 0===x?void 0:x.data)||{},console.log("errorData: ",I),(M="Variant already exists"===(null==I?void 0:I.message))||409===(null==T?void 0:T.status)?ue('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>'):ue(((null==I?void 0:I.message)||(null==I?void 0:I.detail)||"Error Occurred while saving the rule.")+'Please try again.<br/><button class="clickable-button" data-value="Save this Learning">Retry</button>'),null===(C=ti.current)||void 0===C||C.show({severity:"error",sticky:!1,className:u.default.toastError,content:n.jsxs("div",e.__assign({className:u.default.toastContent},{children:[n.jsxs("div",e.__assign({className:u.default.toastHeaderLeft},{children:[n.jsx(i.AlertTriangle,{className:u.default.iconError}),n.jsx("span",e.__assign({className:"".concat(u.default.toastTitle," ").concat(u.default.toastTitleError)},{children:"Error"}))]})),n.jsx("p",e.__assign({className:"".concat(u.default.toastMessage," ").concat(u.default.toastMessageError)},{children:M||409===(null==T?void 0:T.status)?"Similar rule already exists. Please update and try again.":(null==I?void 0:I.message)||(null==I?void 0:I.detail)||"Something went wrong while saving the learning!"}))]}))}),[3,4];case 4:return[2]}})})},hr=function(){return e.__awaiter(void 0,void 0,void 0,function(){var t,r,l,d,c,_,v,p,f,g,m,w,y,h,M,k,x,C,N,E,O,R,L,D,P,F;return e.__generator(this,function(G){switch(G.label){case 0:t=s.useLearningTemplateStore.getState().tiers,r=fr(Vn,kt,xn),l=pr(r),d=je.current,c=(Zn||[])[d]||{},_=(null==wt?void 0:wt.variant_type)||c.variant_type||"",G.label=1;case 1:for(G.trys.push([1,3,,4]),ne(A),ue(""),p=(v=V||[]).length>0?null===(O=v.find(function(e){return(null==e?void 0:e.link_id)&&""!==e.link_id.trim()}))||void 0===O?void 0:O.link_id:null,f=(null===(R=Z.tiers[0])||void 0===R?void 0:R.toLowerCase().replace(/ /g,"_"))||"tier_1",g=(null===(L=Un.get(f))||void 0===L?void 0:L.size)||v.length,m=e.__spreadArray([],v,!0),w=v.length;w<g;w++)m.push({isNewVariant:!0,variantId:a.v4()});return y=[],h=[],M=vr(Z.tiers),Z.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,"")}),s=Un.get(i),u=Wn.get(i),d=Yn.get(i);m.forEach(function(t,v){var f,g,m,w,b,S,A,k,x,C,N,E,O,R,L,D,P,V,F,G,U,J,H,W,B,K,Y,Q,z=(null==s?void 0:s.get(v))||t.description||"",$=(null==u?void 0:u.get(v))||[],X=(null==d?void 0:d.get(v))||[];if(t.isNewVariant){h.push({tierKey:i,payloadType:"new"});var ee=fr(Vn,kt,xn,v),ne=pr(ee);console.log("variant in save edit add part :",t,c);var te={status:"approved",metadata:e.__assign(e.__assign({userName:null!==(f=null==Ui?void 0:Ui.firstname)&&void 0!==f?f:"",userEmailId:null!==(g=null==Ui?void 0:Ui.email)&&void 0!==g?g:"",llm:Tn.MODEL,isVariantFlow:!0},ne&&{config:e.__assign({master_name:Tn.CONFIG_MASTER_NAME},ne)}),{datasource:{type:"link",ref:"www.something.com",tag:"something"},variant:{tierLinkId:p||a.v4(),variant:dr(z),conditions_whentoapply:$.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),conditions_whennottoapply:X.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),referenceVariantID:null,referenceVariantIDVersion:null,scope:M[0]||{name:Tn.SCOPE_NAME,parentScopeId:null,scopeRowId:(null==j?void 0:j.ruleSetId)||"",value:{scopeName:(null==j?void 0:j.ruleSetName)||"",scopeId:"Audacy_"+a.v4(),customScopeGroupName:Tn.CUSTOM_SCOPE_GROUP_NAME,description:(null==j?void 0:j.ruleSetDesc)||""}},overriden:!1,isDefault:null!==(b=null===(w=null===(m=xn.get(i))||void 0===m?void 0:m.get(v))||void 0===w?void 0:w.is_default_enabled)&&void 0!==b?b:I(t.variantType||t.variant_type||(0===v?"Default":"variant")),tier:{name:n.split(" ").join("").toLowerCase(),tierGroupName:Tn.CUSTOM_SCOPE_GROUP_NAME,tierPriority:parseInt(n.split(" ")[1]||"1")},topic:{id:null,value:"".concat(Z.station,"RuleSet"),description:null},categories:[{id:null,value:Tn.CATEGORY,description:Tn.CATEGORY}],originalQuestion:jn,questionId:null==q?void 0:q.ruleId,variantType:wr(i,v,c.variant_type||""),parameterizedQuestion:null,created_at:(new Date).toISOString(),created_by:null!==(S=null==Ui?void 0:Ui.email)&&void 0!==S?S:"",instantLearningType:Tn.INSTANT_LEARNING_TYPE,appliedTagsIL:[],tagMappingInfoIL:{},is_user_accepted_risk:!!(null!==(k=null===(A=(Zn||[])[v])||void 0===A?void 0:A.is_user_accepted_risk)&&void 0!==k?k:null==wt?void 0:wt.is_user_accepted_risk)},isAgentsFeedback:!0})};console.log("payload (publish new variant)",te),y.push(o.publishFeedback(te,Tn.ASSISTANT_NAME))}else{h.push({tierKey:i,payloadType:"existing",existingId:t.variantId});var ie=t.variantId===Li,re=wr(i,v,ie?_||t.variantType||"":t.variantType||"");console.log("isThisVariantBeingEdited variantTypeToUse :",re,ie,t,Li);var ae={variantId:t.variantId,ruleDesc:(null==j?void 0:j.ruleSetDesc)||"",whenToApply:$.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),whenNotToApply:X.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),isDefault:null!==(N=null===(C=null===(x=xn.get(i))||void 0===x?void 0:x.get(v))||void 0===C?void 0:C.is_default_enabled)&&void 0!==N?N:I(t.variantType||t.variant_type||(0===v?"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!==(E=null==r?void 0:r.tier_priority)&&void 0!==E?E:null},scope_id:(null==j?void 0:j.ruleSetId)||"",description:dr(z)||"",topic:"".concat(Z.station,"RuleSet"),configuration:(null==l?void 0:l.config_data)||{},tierLinkId:null!=p?p:null,variantType:re,is_user_accepted_risk:!!(null!==(R=null===(O=(Zn||[])[v])||void 0===O?void 0:O.is_user_accepted_risk)&&void 0!==R?R:null==t?void 0:t.is_user_accepted_risk),is_enabled:t.is_enabled},oe=(et.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=T(n)).replace(/\s+/g," ").replace(/(\s*OR\s*)/g," OR ")},ue=se(jn)===se(oe.title),de=se(z)===se(oe.rule_description),ce=se(ae.whenToApply)===se(oe.wta),_e=se(ae.whenNotToApply)===se(oe.wnta),ve=!!ae.isDefault===I(oe.variant_type),pe=oe.scheduling_config||{},fe=null!==(P=null!==(L=pe.order_global_min_separation_seconds)&&void 0!==L?L:null===(D=pe.order_rules)||void 0===D?void 0:D.global_min_separation_seconds)&&void 0!==P?P:0,ge=null!==(G=null!==(V=pe.advertiser_global_min_separation_seconds)&&void 0!==V?V:null===(F=pe.advertiser_rules)||void 0===F?void 0:F.global_min_separation_seconds)&&void 0!==G?G:0,me=null!==(H=null!==(J=null===(U=pe.inventory_rules)||void 0===U?void 0:U.respect_inventory_code)&&void 0!==J?J:pe.respect_inventory_code)&&void 0!==H&&H,we=null!==(K=null!==(B=null===(W=pe.break_code_rules)||void 0===W?void 0:W.respect_break_code)&&void 0!==B?B:pe.respect_break_code)&&void 0!==K&&K,ye=(null===(Y=xn.get(i))||void 0===Y?void 0:Y.get(v))||Mn,he=ye.order_rules.enabled===fe>0&&ye.order_rules.global_min_separation_seconds===Math.floor(fe/60)&&ye.advertiser_rules.enabled===ge>0&&ye.advertiser_rules.global_min_separation_seconds===Math.floor(ge/60)&&ye.inventory_rules.respect_inventory_code===me&&ye.break_code_rules.respect_break_code===we;ue&&de&&ce&&_e&&ve&&he&&(le=!1)}le?(console.log("payloadv (update existing variant)",ae),y.push(o.updateVariant(ae,null!==(Q=null==Ui?void 0:Ui.email)&&void 0!==Q?Q:""))):(console.log("[saveEditedVariant] No changes for variant ".concat(t.variantId,", skipping API call")),y.push(Promise.resolve({data:{id:t.variantId},skipped:!0})))}})}),[4,Promise.all(y)];case 2:return k=G.sent(),console.log("✅ All variants updated:",k),ne(b),re(!0),ge(!1),x=new Map,k.forEach(function(e,n){var t,i;if(!(null==e?void 0:e.skipped)){var r=h[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=x.get(r.tierKey)||[];l.push({id:o,action:r.payloadType}),x.set(r.tierKey,l)}}}),s.useLearningTemplateStore.getState().setCreatedVariantInfo(Array.from(x.entries()).map(function(e){return{tierName:e[0],variants:e[1]}})),null===(D=ti.current)||void 0===D||D.show({severity:"success",sticky:!1,life:3e3,className:u.default.toastSuccess,content:n.jsxs("div",e.__assign({className:u.default.toastContent},{children:[n.jsxs("div",e.__assign({className:u.default.toastHeaderLeft},{children:[n.jsx(i.Check,{className:u.default.iconSuccess}),n.jsx("span",e.__assign({className:"".concat(u.default.toastTitle," ").concat(u.default.toastTitleSuccess)},{children:"Success"}))]})),n.jsx("p",e.__assign({className:"".concat(u.default.toastMessage," ").concat(u.default.toastMessageSuccess)},{children:"Changes saved successfully!"}))]}))}),ve.current=setTimeout(function(){Vr()},3e3),[3,4];case 3:return C=G.sent(),console.error("❌ Error updating variant:",C),ne(S),_e(!0),ge(!1),N=(null===(P=null==C?void 0:C.response)||void 0===P?void 0:P.data)||{},console.log("errorData: ",N),(E="Variant already exists"===(null==N?void 0:N.message))||409===(null==C?void 0:C.status)?ue('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>'):ue(((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===(F=ti.current)||void 0===F||F.show({severity:"error",sticky:!1,className:u.default.toastError,content:n.jsxs("div",e.__assign({className:u.default.toastContent},{children:[n.jsxs("div",e.__assign({className:u.default.toastHeaderLeft},{children:[n.jsx(i.AlertTriangle,{className:u.default.iconError}),n.jsx("span",e.__assign({className:"".concat(u.default.toastTitle," ").concat(u.default.toastTitleError)},{children:"Error"}))]})),n.jsx("p",e.__assign({className:"".concat(u.default.toastMessage," ").concat(u.default.toastMessageError)},{children:E||409===(null==C?void 0:C.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]}})})},br=function(){return e.__awaiter(void 0,void 0,void 0,function(){var t,r,l,d,c,_,v,p,f,g,m,w,y,h,M,k,x,C,N,E,O,R,L,q,P,V,F;return e.__generator(this,function(G){switch(G.label){case 0:t=s.useLearningTemplateStore.getState().tiers,r=fr(Vn,kt,xn),l=pr(r),G.label=1;case 1:return G.trys.push([1,9,,10]),ne(A),ue(""),0===(d=Array.isArray(Zn)?Zn:[]).length?(console.warn("No variants found to save."),ne(S),[2]):(c=d.filter(function(e){return e.is_new_variant}),_=d.filter(function(e){return!e.is_new_variant&&(null==e?void 0:e.variant_id)}),console.log("[saveLoadAndEditVariant] New: ".concat(c.length,", Existing: ").concat(_.length)),v=_.length>0?null===(q=_.find(function(e){return(null==e?void 0:e.link_id)&&""!==e.link_id.trim()}))||void 0===q?void 0:q.link_id:null,p=[],f=[],g=[],m=[],w=vr(Z.tiers),Z.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,"")}),s=Un.get(i),u=Wn.get(i),c=Yn.get(i);d.forEach(function(t,d){var _,y,h,b,S,A,M,k,x,C,N,E,O,R,L,q,P,V,F,G,U,J,H,W,B,K,Y,Q=(null==s?void 0:s.get(d))||t.rule_description||t.description||"",z=(null==u?void 0:u.get(d))||[],$=(null==c?void 0:c.get(d))||[];if(t.is_new_variant){var X=fr(Vn,kt,xn,d),ee=pr(X),ne=wr(i,d,t.variant_type||t.variantType||""),te={status:"approved",metadata:e.__assign(e.__assign({userName:null!==(_=null==Ui?void 0:Ui.firstname)&&void 0!==_?_:"",userEmailId:null!==(y=null==Ui?void 0:Ui.email)&&void 0!==y?y:"",llm:Tn.MODEL,isVariantFlow:!0},ee&&{config:e.__assign({master_name:Tn.CONFIG_MASTER_NAME},ee)}),{datasource:{type:"link",ref:"www.something.com",tag:"something"},variant:{tierLinkId:v||a.v4(),variant:dr(Q),conditions_whentoapply:z.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),conditions_whennottoapply:$.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),referenceVariantID:null,referenceVariantIDVersion:null,scope:w[0]||{name:Tn.SCOPE_NAME,parentScopeId:null,scopeRowId:(null==j?void 0:j.ruleSetId)||"",value:{scopeName:(null==j?void 0:j.ruleSetName)||"",scopeId:"Audacy_"+a.v4(),customScopeGroupName:Tn.CUSTOM_SCOPE_GROUP_NAME,description:(null==j?void 0:j.ruleSetDesc)||""}},overriden:!1,isDefault:null!==(S=null===(b=null===(h=xn.get(i))||void 0===h?void 0:h.get(d))||void 0===b?void 0:b.is_default_enabled)&&void 0!==S?S:I(t.variantType||t.variant_type||(0===d?"Default":"variant")),tier:{name:n.split(" ").join("").toLowerCase(),tierGroupName:Tn.CUSTOM_SCOPE_GROUP_NAME,tierPriority:parseInt(n.split(" ")[1]||"1"),tier_id:(null==r?void 0:r.tier_id)||""},topic:{id:null,value:"".concat(Z.station||D,"RuleSet"),description:null},categories:[{id:null,value:Tn.CATEGORY,description:Tn.CATEGORY}],originalQuestion:jn,questionId:gn.current||null,variantType:ne,parameterizedQuestion:null,created_at:(new Date).toISOString(),created_by:null!==(A=null==Ui?void 0:Ui.email)&&void 0!==A?A:"",instantLearningType:Tn.INSTANT_LEARNING_TYPE,appliedTagsIL:[],tagMappingInfoIL:{},is_user_accepted_risk:!!(null!==(M=null==t?void 0:t.is_user_accepted_risk)&&void 0!==M?M:null==wt?void 0:wt.is_user_accepted_risk)},isAgentsFeedback:!0})};console.log("[saveLoadAndEditVariant] publish payload (new variant)",te),f.push({payload:te,tierKey:i}),m.push({tierKey:i})}else if(null==t?void 0:t.variant_id){g.push({tierKey:i,existingId:t.variant_id});var ie=(null==t?void 0:t.variant_id)&&t.variant_id===Fi?(null==wt?void 0:wt.variant_type)||t.variant_type||t.variantType||"":t.variant_type||t.variantType||"",re=(ne=wr(i,d,ie),{variantId:t.variant_id,ruleDesc:(null==j?void 0:j.ruleSetDesc)||"",whenToApply:z.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),whenNotToApply:$.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),isDefault:null!==(C=null===(x=null===(k=xn.get(i))||void 0===k?void 0:k.get(d))||void 0===x?void 0:x.is_default_enabled)&&void 0!==C?C:I(t.variantType||t.variant_type||(0===d?"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==j?void 0:j.ruleSetId)||"",description:dr(Q)||"",topic:"".concat(Z.station,"RuleSet"),configuration:(null==l?void 0:l.config_data)||{},tierLinkId:null!=v?v:null,variantType:ne,is_user_accepted_risk:!!(null!==(E=null==t?void 0:t.is_user_accepted_risk)&&void 0!==E?E:null===(O=(Zn||[])[d])||void 0===O?void 0:O.is_user_accepted_risk),is_enabled:t.is_enabled}),ae=(et.get(i)||[]).find(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===(null==t?void 0:t.variant_id)}),oe=!0;if(ae){var le=function(e){var n=(e||"").trim();return(n=T(n)).replace(/\s+/g," ").replace(/(\s*OR\s*)/g," OR ")},se=le(jn)===le(ae.title),ue=le(Q)===le(ae.rule_description),de=le(re.whenToApply)===le(ae.wta),ce=le(re.whenNotToApply)===le(ae.wnta),_e=!!re.isDefault===I(ae.variant_type),ve=ae.scheduling_config||{},pe=null!==(q=null!==(R=ve.order_global_min_separation_seconds)&&void 0!==R?R:null===(L=ve.order_rules)||void 0===L?void 0:L.global_min_separation_seconds)&&void 0!==q?q:0,fe=null!==(F=null!==(P=ve.advertiser_global_min_separation_seconds)&&void 0!==P?P:null===(V=ve.advertiser_rules)||void 0===V?void 0:V.global_min_separation_seconds)&&void 0!==F?F:0,ge=null!==(J=null!==(U=null===(G=ve.inventory_rules)||void 0===G?void 0:G.respect_inventory_code)&&void 0!==U?U:ve.respect_inventory_code)&&void 0!==J&&J,me=null!==(B=null!==(W=null===(H=ve.break_code_rules)||void 0===H?void 0:H.respect_break_code)&&void 0!==W?W:ve.respect_break_code)&&void 0!==B&&B,we=(null===(K=xn.get(i))||void 0===K?void 0:K.get(d))||Mn,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;se&&ue&&de&&ce&&_e&&ye&&(oe=!1)}oe?(console.log("[saveLoadAndEditVariant] update payload (existing variant)",re),p.push(o.updateVariant(re,null!==(Y=null==Ui?void 0:Ui.email)&&void 0!==Y?Y:""))):(console.log("[saveLoadAndEditVariant] No changes for variant ".concat(t.variant_id,", skipping API call")),p.push(Promise.resolve({data:{id:t.variant_id},skipped:!0})))}})}),[4,Promise.all(p)]);case 2:y=G.sent(),console.log("✅ All existing variants updated:",y),h=[],M=0,k=f,G.label=3;case 3:if(!(M<k.length))return[3,8];x=k[M],G.label=4;case 4:return G.trys.push([4,6,,7]),[4,o.publishFeedback(x.payload,Tn.ASSISTANT_NAME)];case 5:return C=G.sent(),h.push(C),[3,7];case 6:throw N=G.sent(),console.error("❌ Error publishing new variant:",N),N;case 7:return M++,[3,3];case 8:return console.log("✅ All new variants published:",h),E=new Map,y.forEach(function(e,n){var t,i;if(!(null==e?void 0:e.skipped)){var 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;a||"string"!=typeof(null==e?void 0:e.data)||(a=e.data);var o=r.existingId||a;if(o&&"string"==typeof o){var l=E.get(r.tierKey)||[];l.push({id:o,action:"existing"}),E.set(r.tierKey,l)}}}),h.forEach(function(e,n){var t,i,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)&&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=E.get(r.tierKey)||[];o.push({id:a,action:"new"}),E.set(r.tierKey,o)}}),s.useLearningTemplateStore.getState().setCreatedVariantInfo(Array.from(E.entries()).map(function(e){return{tierName:e[0],variants:e[1]}})),ne(b),re(!0),ge(!1),xe.current=!1,null===(P=ti.current)||void 0===P||P.show({severity:"success",sticky:!1,life:3e3,className:u.default.toastSuccess,content:n.jsxs("div",e.__assign({className:u.default.toastContent},{children:[n.jsxs("div",e.__assign({className:u.default.toastHeaderLeft},{children:[n.jsx(i.Check,{className:u.default.iconSuccess}),n.jsx("span",e.__assign({className:"".concat(u.default.toastTitle," ").concat(u.default.toastTitleSuccess)},{children:"Success"}))]})),n.jsx("p",e.__assign({className:"".concat(u.default.toastMessage," ").concat(u.default.toastMessageSuccess)},{children:"Changes saved successfully!"}))]}))}),ve.current=setTimeout(function(){Vr()},3e3),[3,10];case 9:return O=G.sent(),console.error("❌ Error updating variant:",O),ne(S),_e(!0),ge(!1),R=(null===(V=null==O?void 0:O.response)||void 0===V?void 0:V.data)||{},console.log("errorData: ",R),(L="Variant already exists"===(null==R?void 0:R.message))||409===(null==O?void 0:O.status)?ue('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>'):ue(((null==R?void 0:R.message)||(null==R?void 0:R.detail)||"Error Occurred while saving the rule.")+'Please try again.<br/><button class="clickable-button" data-value="Save this Learning">Retry</button>'),null===(F=ti.current)||void 0===F||F.show({severity:"error",sticky:!1,className:u.default.toastError,content:n.jsxs("div",e.__assign({className:u.default.toastContent},{children:[n.jsxs("div",e.__assign({className:u.default.toastHeaderLeft},{children:[n.jsx(i.AlertTriangle,{className:u.default.iconError}),n.jsx("span",e.__assign({className:"".concat(u.default.toastTitle," ").concat(u.default.toastTitleError)},{children:"Error"}))]})),n.jsx("p",e.__assign({className:"".concat(u.default.toastMessage," ").concat(u.default.toastMessageError)},{children:L||409===(null==O?void 0:O.status)?"Similar rule already exists. Please update and try again.":(null==R?void 0:R.message)||(null==R?void 0:R.detail)||"Something went wrong while saving the learning!"}))]}))}),[3,10];case 10:return[2]}})})},Sr=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()};t.useEffect(function(){yi&&!Zt&&(console.log("isSaveRule received from agent — calling publish APIs directly."),hi(!1),q||V?hr():!0===xe.current?br():e.__awaiter(void 0,void 0,void 0,function(){var n,t,i,r,a,l,s,u;return e.__generator(this,function(d){switch(d.label){case 0:d.trys.push([0,5,,6]),ne(A),n=new Map,t=function(t){var i,r,a,l,s,d;return e.__generator(this,function(e){switch(e.label){case 0:if(i=t.toLowerCase().replace(/ /g,"_"),r=we.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===i||e.tier_name.toLowerCase()===i.replace(/_/g,"")}),!(a=null==r?void 0:r.tier_id))return n.set(i,null),[2,"continue"];l={question:jn,orgName:Tn.ORGANIZATION_NAME,scope_id:(null==j?void 0:j.ruleSetId)||"",tier_id:a},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,o.saveInstantLearningQuestion(l)];case 2:return s=e.sent(),n.set(i,(null===(u=null==s?void 0:s.data)||void 0===u?void 0:u.id)||null),console.log("✅ Question saved for ".concat(t,":"),s),[3,4];case 3:return d=e.sent(),console.error("❌ Error saving question for ".concat(t,":"),d),n.set(i,null),[3,4];case 4:return[2]}})},i=0,r=Z.tiers,d.label=1;case 1:return i<r.length?(a=r[i],[5,t(a)]):[3,4];case 2:d.sent(),d.label=3;case 3:return i++,[3,1];case 4:return yr(n),[3,6];case 5:return l=d.sent(),s=new Map,Z.tiers.forEach(function(e){s.set(e.toLowerCase().replace(/ /g,"_"),null)}),yr(s),console.error("❌ Error saving Instant Learning Question:",l),[3,6];case 6:return[2]}})}))},[yi,Zt]);var Ar=(null===(k=(null===(m=null==Z?void 0:Z.tiers)||void 0===m?void 0:m[0])||P||"Tier 1")||void 0===k?void 0:k.toLowerCase().replace(/ /g,"_"))||"tier_1",Tr=null!==(x=null!=_t?_t:F)&&void 0!==x?x:0,Ir=null!=_t,Mr=Ir?null==Zn?void 0:Zn[Tr]:null,kr=Zn&&(null==Zn?void 0:Zn.find(function(e){return e&&!e.is_readOnly&&((null==e?void 0:e.new_variant_id)&&Tt.includes(e.new_variant_id)||(null==e?void 0:e.variant_id)&&bt.includes(e.variant_id))})),xr=(null==Mr?void 0:Mr.new_variant_id)&&Tt.includes(Mr.new_variant_id)?Mr.new_variant_id:(null==kr?void 0:kr.new_variant_id)&&Tt.includes(kr.new_variant_id)?kr.new_variant_id:"",Cr=!(!q&&!V),Nr=function(n){var t={},i=Z.tiers.map(function(e){return null==e?void 0:e.toLowerCase().replace(/ /g,"_")}),r=(null==Z?void 0:Z.station)+"RuleSet",a=i.map(function(e){var n=we.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||bt[o]||"new_variant_".concat(o),p=(null===(l=n.scope)||void 0===l?void 0:l[0])||Ar,f=Un.get(p),g=Wn.get(p),m=Yn.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))||[],S=b.length>0?b.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" \\n "):n.wnta||"",A=xn.get(p),T=null==A?void 0:A.get(o),I={};T&&Object.keys(T).length>0?I=e.__assign(e.__assign({},T),{order_rules:e.__assign(e.__assign({},T.order_rules),{global_min_separation_seconds:60*((null===(s=T.order_rules)||void 0===s?void 0:s.global_min_separation_seconds)||0)}),advertiser_rules:e.__assign(e.__assign({},T.advertiser_rules),{global_min_separation_seconds:60*((null===(u=T.advertiser_rules)||void 0===u?void 0:u.global_min_separation_seconds)||0)})}):n.scheduling_config&&(I=n.scheduling_config),t[v]={rule_title:jn,variant_description:w,wta:h,ruleset_id:(null==j?void 0:j.ruleSetId)||"",tier_id:a,wnta:S,scope:i,scope_rule_set:r,scheduling_config:I,is_user_accepted_risk:!(null===(_=null!==(d=null==n?void 0:n.is_user_accepted_risk)&&void 0!==d?d:null===(c=(Zn||[])[o])||void 0===c?void 0:c.is_user_accepted_risk)||void 0===_||!_)}}),t};tn&&console.log("customMetaData.ui_state for addvariant flow",Nr(it));var Er={send_metadata_to_orchestrator:!1,default:["scope"],app_mapping_id:Q,ui_state:Cr?{variants:function(){var n={},t=xn.get(Ar);if(!t)return n;var i=Un.get(Ar),r=Wn.get(Ar),a=Yn.get(Ar),o=Z.tiers.map(function(e){return null==e?void 0:e.toLowerCase().replace(/ /g,"_")}),l=(null==Z?void 0:Z.station)+"RuleSet",s=o.map(function(e){var n=we.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==V?void 0:V[d])||void 0===c?void 0:c.variantId,w=(Zn||[])[d],y=(null==w?void 0:w.new_variant_id)||"",h=m||y||bt[d]||"variant_".concat(d),b=(null==i?void 0:i.get(d))||"",S=((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 ")||"",T=t.get(d),I={};T&&Object.keys(T).length>0&&(I=e.__assign(e.__assign({},T),{order_rules:e.__assign(e.__assign({},T.order_rules),{global_min_separation_seconds:60*((null===(_=T.order_rules)||void 0===_?void 0:_.global_min_separation_seconds)||0)}),advertiser_rules:e.__assign(e.__assign({},T.advertiser_rules),{global_min_separation_seconds:60*((null===(v=T.advertiser_rules)||void 0===v?void 0:v.global_min_separation_seconds)||0)})})),n[h]={rule_title:jn,variant_description:b,wta:S,ruleset_id:(null==j?void 0:j.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==V?void 0:V[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=(Zn||[]).findIndex(function(e){return!0===e.is_new_variant}),s=-1;return-1!==l?s=l:ze?s=-1:tn||(s=Tr),{new_current_variant:-1!==s?{rule_title:jn,rule_description:(null===(n=Un.get(Ar))||void 0===n?void 0:n.get(s))||"",wta:(null===(i=null===(t=Wn.get(Ar))||void 0===t?void 0:t.get(s))||void 0===i?void 0:i.map(function(e){return Sr(e.text)}).filter(function(e){return""!==e}).join(" \\n "))||"",wnta:(null===(a=null===(r=Yn.get(Ar))||void 0===r?void 0:r.get(s))||void 0===a?void 0:a.map(function(e){return Sr(e.text)}).filter(function(e){return""!==e}).join(" \\n "))||"",scope:Z.tiers.map(function(e){return null==e?void 0:e.toLowerCase().replace(/ /g,"_")}),scope_rule_set:(null==Z?void 0:Z.station)+"RuleSet",scheduling_config:function(){var n,t,i,r=null===(n=xn.get(Ar))||void 0===n?void 0:n.get(s);return r&&0!==Object.keys(r).length?e.__assign(e.__assign({},r),{order_rules:e.__assign(e.__assign({},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.__assign(e.__assign({},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=(Zn||[])[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:tn?Nr(it):{}}}(),rule_id_in_current_session:ut,new_variant_id:function(){var e;return Ir&&q?(null===(e=null==V?void 0:V[Tr])||void 0===e?void 0:e.variantId)?null:xr:null}(),edit_variant_id:pn,rule_id:gn.current,ruleset_id:(null==j?void 0:j.ruleSetId)||"",current_variants_length:q?Array.isArray(Zn)&&Zn.length>0?Math.max((null===(C=null==q?void 0:q.variants)||void 0===C?void 0:C.length)||0,Zn.length):null===(N=null==q?void 0:q.variants)||void 0===N?void 0:N.length:void 0,tiers:we,authToken:(null==Ui?void 0:Ui.accessToken)||""},Or=or(it),Rr={ruleTitle:jn,scopeData:Z,variantsByTier:Array.from(xn.keys()).reduce(function(n,t){var i=xn.get(t)||new Map,r=Un.get(t)||new Map,a=Wn.get(t)||new Map,o=Yn.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=(Zn||[])[n]||{};console.log("Original item for tier",t,"index",n,":",d);var c={label:"",isDefault:!1};if(d.is_variant&&!I(d.variant_type))c={label:"",isDefault:!1};else if(V&&V.length>0){c=gr(V,n,"variantType"),console.log("Found matching variant at index",n,":",c);var _=V[n];if(_){if(!c.label){var v=_.variantType||"",p=I(v);c={label:"variant ".concat(n+1),isDefault:p}}if(_.variantId===Li)(g=d.variant_type||(null==wt?void 0:wt.variant_type))&&(c=mr(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:or(V),isDefault:!1},console.log("No match found, using getNextVariantType:",c)}else if(it&&it.length>0){if(c=gr(it,n,"variant_type"),console.log("Found matching variant at index",n,":",c),xe.current){var f=it[n];if((null==f?void 0:f.variant_id)===Fi||(null==f?void 0:f.variantId)===Fi)(g=d.variant_type||(null==wt?void 0:wt.variant_type))&&(c=mr(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:Or,isDefault:I(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:bt[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.__assign(e.__assign({},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.__assign(e.__assign({},n),{id:"split-".concat(n.id,"-").concat(i),text:t.trim()})}):[n]}),configData:i.get(n)||Mn,isReadOnly:d.is_readOnly||!1,is_variant:d.is_variant||!1,reasoning:{ruleDescription:ur(y),whenToApply:ur(d.wta),whenNotToApply:ur(d.wnta),configData:ur(d.action)}}}),n},{}),citation:Vt,fieldCitations:Yt,citations:Ut};console.log("templateState",Rr);var Lr={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;qn(i),ci(function(n){if(n.ruleTitle){var t=e.__assign({},n);return delete t.ruleTitle,t}return n})},setRuleDescription:function(e,n,t){return Yi(e,n,t)},addWhenToApply:function(e,n){return Qi(e,n)},removeWhenToApply:function(e,n,t){return zi(e,n,t)},editWhenToApply:function(e,n,t,i){return Zi(e,n,t,i)},addWhenNotToApply:function(e,n){return $i(e,n)},removeWhenNotToApply:function(e,n,t){return Xi(e,n,t)},editWhenNotToApply:function(e,n,t,i){return er(e,n,t,i)},addNewVariant:function(e){return nr(e)},onScopeChange:ir,onConfigChange:function(e,n,t,i){return rr(e,n,t,i)}},Dr={},jr={};xn.forEach(function(n,t){Dr[t]=new Map,jr[t]=new Map,n.forEach(function(n,i){Dr[t].set(i,[e.__assign({key:"order_rules",label:"Order"},n.order_rules),e.__assign({key:"advertiser_rules",label:"Advertiser"},n.advertiser_rules)]),jr[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 qr=t.useMemo(function(){if(P){if(1===Z.tiers.length)return 0;var e=Z.tiers.findIndex(function(e){return e.toLowerCase()===P.toLowerCase()});return e>=0?e:0}},[P,Z.tiers]),Pr=e.__assign(e.__assign({defaultOpen:!0,tierOptions:["Tier 1","Tier 2"],stationOptions:[{label:"Global Scope",value:"global"},{label:"Genre Scope",value:"genre"},{label:"Custom Scope",value:"custom"}],separationItemsByTier:Dr,togglesByTier:jr,highlights:Nt,highlightedIds:Rt,openSections:En,setOpenSections:On,setSendMessageInChat:gt,isAiStreaming:Zt,defaultTierOpen:qr,defaultVariantOpen:ze?void 0:_t,autoScrollVariantIndex:ze?void 0:_t,activeVariantAccordionIndex:ze?void 0:_t,setActiveVariantAccordionIndex:function(e){vt(e),null!=e&&setTimeout(function(){Ze(!1)},100)},validationErrors:di,activeEditId:sn,setActiveEditId:un,pendingEditId:cn,setPendingEditId:_n,conflictReason:vi,usedFor:q||V?"Edit":"Create"},In),{scrollTrigger:jt});console.log(_t,"editVariantIndex checking"),t.useEffect(function(){},[O]),t.useEffect(function(){if(!Zt&&ot&&!!(!q&&!V)){var n=e.__spreadArray([],Zn,!0).reverse().findIndex(function(e){return"variant"===e.action||e.is_variant});-1===n||Zn.length,-1!==n&&(console.log("Post-stream: Focusing new variant at index",n),vt(n))}},[Zt,ot]);var Vr=function(){ve.current&&(clearTimeout(ve.current),ve.current=null),xe.current=!1,R(),ar()},Fr=function(){var e={};jn.trim()||(e.ruleTitle="Rule Title is required"),Z.station||(e.station="Station Rule Set is required"),Z.tiers&&0!==Z.tiers.length||(e.tiers="At least one tier must be selected");return Z.tiers.map(function(e){return e.toLowerCase().replace(/ /g,"_")}).forEach(function(n){var t=Un.get(n),i=Wn.get(n),r=xn.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 Gr(n,t,i){var r,a,l,s,u,d;return void 0===i&&(i=!1),e.__awaiter(this,void 0,void 0,function(){var c,_,v,p,f,g,m,w,y,h,b,S,A,M,k,x,C,N,E,O,R,L,q,P;return e.__generator(this,function(V){switch(V.label){case 0:if(c=n.question_id,_=(null==n?void 0:n.variant_id)||null,an.current&&wn.current===c)return console.log("[handleAILoadAction] Already fetching question ID, skipping duplicate request:",c),[2];if(gn.current===c&&!i)return console.log("[handleAILoadAction] Question ID unchanged, updating variant focus only:",_),fn(_),_?(-1!==(v=(Zn||[]).findIndex(function(e){return e.is_new_variant}))&&(si(!0),Mi("Removing new variant..."),Ci("Please wait while we remove new variant.")),$n(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(){vt(t),qt(function(e){return e+1}),ni.current=t},0),n}),-1!==v&&((p=function(e){e(function(e){var n=new Map;return e.forEach(function(e,t){var i=new Map(e);i.delete(v);var r=new Map,a=0;i.forEach(function(e){r.set(a,e),a++}),n.set(t,r)}),n})})(Cn),p(Jn),p(Bn),p(Qn),St(function(n){var t=e.__spreadArray([],n,!0);return t.length>v&&t.splice(v,1),t})),!1===an.current&&(an.current=!0,-1!==v&&(null===(r=ti.current)||void 0===r||r.show({severity:"success",summary:"Success",detail:"New variant removed successfully because you selected to edit an existing variant",life:4e3}))),Ze(!1)):(console.log("lastLoadedQuestionIdRef.current in else",gn.current),null===gn.current&&(si(!0),Mi("Adding new variant..."),Ci("Please wait while we add new variant."))),[2];console.log("User Action: fetching fresh variant info for question",c),on.current.clear(),on.current.add(c),si(!0),Mi("Loading variants..."),console.log("reaching here in load and edit"),Ci("Please wait while we fetch the latest variant data."),an.current=!0,wn.current=c,V.label=1;case 1:return V.trys.push([1,5,6,10]),f=Date.now(),[4,o.fetchRulesByQuestionId(c,(null==j?void 0:j.ruleSetId)||"")];case 2:return g=V.sent(),(m=Date.now()-f)<3e3?[4,new Promise(function(e){return setTimeout(e,3e3-m)})]:[3,4];case 3:V.sent(),V.label=4;case 4:return 0===(w=(null===(a=null==g?void 0:g.data)||void 0===a?void 0:a.variants)||[]).length?(console.warn("No variants found for question_id",c),si(!1),Mi(""),null===(l=ti.current)||void 0===l||l.show({severity:"error",summary:"Error",detail:"No variants found for this question.",life:3e3}),[2]):(xe.current=!0,an.current=!0,y=(null===(s=null==g?void 0:g.data)||void 0===s?void 0:s.ruleTitle)||"",qn(y),h=null===(u=null==g?void 0:g.data)||void 0===u?void 0:u.tier,b="tier_1",S="Tier 1",A="1",h&&((M=String(h).match(/(\d+)/))?(k=M[1],A=k,b="tier_".concat(k),S="Tier ".concat(k)):(b=String(h).toLowerCase().trim().replace(/ /g,"_"),S=b.replace(/_/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()}),A=b.includes("2")?"2":"1")),console.log("[handleAILoadAction] Detected Tier: ".concat(S," (ID: ").concat(A,", Key: ").concat(b,")")),$({station:D||"global",tiers:[S]}),x=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,_=e.scheduling_config||{};l.set(n,{order_rules:{enabled:!!_.order_global_min_separation_seconds||!!(null===(t=_.order_rules)||void 0===t?void 0:t.global_min_separation_seconds),global_min_separation_seconds:Math.floor((_.order_global_min_separation_seconds||(null===(i=_.order_rules)||void 0===i?void 0:i.global_min_separation_seconds)||0)/60)},advertiser_rules:{enabled:!!_.advertiser_global_min_separation_seconds||!!(null===(r=_.advertiser_rules)||void 0===r?void 0:r.global_min_separation_seconds),global_min_separation_seconds:Math.floor((_.advertiser_global_min_separation_seconds||(null===(a=_.advertiser_rules)||void 0===a?void 0:a.global_min_separation_seconds)||0)/60)},inventory_rules:{respect_inventory_code:!!_.respect_inventory_code||!!(null===(o=_.inventory_rules)||void 0===o?void 0:o.respect_inventory_code)},break_code_rules:{respect_break_code:!!_.respect_break_code||!!(null===(c=_.break_code_rules)||void 0===c?void 0:c.respect_break_code)},is_default_enabled:I(e.variantType||e.variant_type)}),s.set(n,T(e.rule_description||""));var v=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,v);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}}(w,y,b,A,c,_),C=x.transformedVariants,N=x.tierConfigMap,E=x.tierDescMap,O=x.tierWtaMap,R=x.tierWntaMap,nt(function(e){var n=new Map(e);return n.set(b,JSON.parse(JSON.stringify(C))),n}),$n(function(n){var t=(Array.isArray(n)?n:[]).filter(function(e){return"copy"===e.action||e.tier_id&&e.tier_id!==A});return e.__spreadArray(e.__spreadArray([],t,!0),C,!0)}),rt(function(n){var t=(Array.isArray(n)?n:[]).filter(function(e){return"copy"===e.action||e.tier_id&&e.tier_id!==A});return e.__spreadArray(e.__spreadArray([],t,!0),C,!0)}),rn(!0),gn.current=c,fn(_),L=0,_&&-1!==(q=C.findIndex(function(e){return e.variant_id===_}))&&(L=q),vt(L),qt(function(e){return e+1}),ni.current=L,Ze(!1),Cn(function(e){var n=new Map(e);return n.set(b,N),n}),Jn(function(e){var n=new Map(e);return n.set(b,E),n}),Bn(function(e){var n=new Map(e);return n.set(b,O),n}),Qn(function(e){var n=new Map(e);return n.set(b,R),n}),ci({}),[3,10]);case 5:return P=V.sent(),console.error("Failed to fetch variants by question ID:",P),null===(d=ti.current)||void 0===d||d.show({severity:"error",summary:"Error",detail:"Failed to fetch variants. Please try again.",life:3e3}),[3,10];case 6:return an.current=!1,si(!1),Mi(""),Ci(""),(null==n?void 0:n.is_interpretation_ready)&&(null==n?void 0:n.question_id)&&gn.current&&pn?(console.log("inside edit variant flow",gn.current,pn),$n(function(n){if(!Array.isArray(n))return n;var i=n.map(function(n){return(null==n?void 0:n.variant_id)===pn?e.__assign(e.__assign({},n),t):n}),r=n.findIndex(function(e){return(null==e?void 0:e.variant_id)===pn});return console.log(r,"targetIndexif"),-1!==r&&setTimeout(function(){console.log("targetIndex",r),vt(r),qt(function(e){return e+1}),ni.current=r},0),i}),[3,9]):[3,7];case 7:return(null==n?void 0:n.is_interpretation_ready)&&(null==n?void 0:n.question_id)&&gn.current&&!pn?(console.log("inside add new variant flow",gn.current,pn),si(!0),Mi("Adding new variant..."),Ci("Please wait while we add new variant."),[4,new Promise(function(e){return setTimeout(e,3e3)})]):[3,9];case 8:V.sent(),si(!1),Mi(""),Ci(""),$n(function(n){var i;if(Array.isArray(n)){var r=n.findIndex(function(e){return!0===e.is_new_variant});if(-1!==r)setTimeout(function(){vt(r),qt(function(e){return e+1}),ni.current=r},0),i=n.map(function(n,i){return i===r?e.__assign(e.__assign(e.__assign({},n),t),{is_new_variant:!0,is_variant:!0}):n});else{var a=n.length;setTimeout(function(){vt(a),qt(function(e){return e+1}),ni.current=a},0),i=e.__spreadArray(e.__spreadArray([],n,!0),[e.__assign(e.__assign({},t),{is_new_variant:!0,is_variant:!0})],!1)}}else setTimeout(function(){vt(0),qt(0),ni.current=0},0),i=[e.__assign(e.__assign({},t),{is_new_variant:!0})];return bn.current=i,i}),V.label=9;case 9:return[7];case 10:return[2]}})})}var Ur;return console.log("RuleSet in render",j),n.jsxs(n.Fragment,{children:[n.jsx(r.Toast,{ref:ti}),n.jsx(d.default,{open:O,chatAssistantName:Tn.ASSISTANT_NAME,organizationName:Tn.ORGANIZATION_NAME,baseUrl:Tn.BASE_URL,baseWebsocketUrl:Tn.BASE_WEBSOCKET_URL,closeFunction:Vr,ThinkingBulbIconComponent:n.jsx(y,{}),customSections:n.jsx(n.Fragment,{}),customMetaData:Er,chatTitle:q?Tn.CHAT_TITLE_EDIT.replace("<scope>",(null==j?void 0:j.ruleSetName)||""):Tn.CHAT_TITLE.replace("<scope>",(null==j?void 0:j.ruleSetName)||""),formTitle:Tn.FORM_TITLE,showSavedMessage:!1,savedMessage:oe,isError:ce,errorMessage:se,isSaving:fe,onSave:function(e){console.log("Save this Learning",e);var n=Fr();if(Object.keys(n).length>0)return console.log("validation errors",n),void ci(n);ge(!0),_e(!1),ue("")},showSaveWithoutValidation:!1,onSaveWithoutValidation:function(){return e.__awaiter(void 0,void 0,void 0,function(){var n,t,i,r,a,l,s,u,d;return e.__generator(this,function(c){switch(c.label){case 0:return n=Fr(),Object.keys(n).length>0?(ci(n),[2]):(console.log("✅ Bypass Save: Initiated"),q||V?[4,hr()]:[3,2]);case 1:return c.sent(),[3,11];case 2:return!0!==xe.current?[3,4]:[4,br()];case 3:return c.sent(),[3,11];case 4:c.trys.push([4,10,,11]),ne(A),t=new Map,i=function(n){var i,r,a,l,s,u;return e.__generator(this,function(e){switch(e.label){case 0:if(i=n.toLowerCase().replace(/ /g,"_"),r=we.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===i||e.tier_name.toLowerCase()===i.replace(/_/g,"")}),!(a=null==r?void 0:r.tier_id))return t.set(i,null),[2,"continue"];l={question:jn,orgName:Tn.ORGANIZATION_NAME,scope_id:(null==j?void 0:j.ruleSetId)||"",tier_id:a},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,o.saveInstantLearningQuestion(l)];case 2:return s=e.sent(),t.set(i,(null===(d=null==s?void 0:s.data)||void 0===d?void 0:d.id)||null),[3,4];case 3:return u=e.sent(),console.error("❌ Bypass Save: Error saving question for ".concat(n,":"),u),t.set(i,null),[3,4];case 4:return[2]}})},r=0,a=Z.tiers,c.label=5;case 5:return r<a.length?(l=a[r],[5,i(l)]):[3,8];case 6:c.sent(),c.label=7;case 7:return r++,[3,5];case 8:return[4,yr(t,!0)];case 9:return c.sent(),[3,11];case 10:return s=c.sent(),ne(S),u=new Map,Z.tiers.forEach(function(e){u.set(e.toLowerCase().replace(/ /g,"_"),null)}),yr(u,!0),console.error("❌ Bypass Save: Error",s),[3,11];case 11:return[2]}})})},headerMessageHandlers:sr,aiResponse:Zn,setAIResponse:$n,width:"90vw",height:"90vh",sendMessageInChat:ft,template:c.TemplateList.CreateRule,isLoading:ee===A,templateProps:{state:Rr,handlers:Lr,uiState:Pr},setSendMessageInChat:gt,onResetChat:function(){ar()},onResetRequest:function(){ai(!0)},isFormDirty:function(){return""!==jn.trim()||""!==Z.station||Z.tiers.length>0||Array.from(Un.values()).some(function(e){return Array.from(e.values()).some(function(e){return""!==e.trim()})})||Array.from(Wn.values()).some(function(e){return Array.from(e.values()).some(function(e){return e.length>0})})||Array.from(Yn.values()).some(function(e){return Array.from(e.values()).some(function(e){return e.length>0})})||xn.size>0||Vn.size>0},initialChatMessage:q?(Ur=q.ruleTitle||"this rule",null===(E=null==V?void 0:V[null!=F?F:0])||void 0===E||E.is_user_accepted_risk,'<p><span>Welcome back! 👋</span>\n <span>I see you want to edit <strong>"'.concat(Ur,'."</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!=Y?Y:Tn.INITIAL_CHAT_MESSAGE,validateCustom:function(){if(ee===b||ie)return!1;if(!jn||""===jn.trim())return!1;if(null!==sn)return!1;if(!Z.station||""===Z.station.trim())return!1;var e=Z.tiers&&Z.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=Un.get(r),o=Wn.get(r),l=xn.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 _=null==o?void 0:o.get(d);if(!(null==_?void 0:_.some(function(e){return e.text&&""!==e.text.trim()})))return!1}}return!(!xn||0===xn.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})})})})(Wn)&&!n(Yn)&&!Re)},setCitations:Jt,isLocked:!0,textareaPlaceholder:"Tell me more about this learning..",saveButtonConfig:{label:q?"Save Changes":"Save Learning",loadingLabel:n.jsxs("span",e.__assign({style:{display:"flex",gap:"5px",alignItems:"center"}},{children:[n.jsx(i.Loader,{size:20,color:"white",className:"animate-spin"}),n.jsx("span",{children:" Saving Changes..."})]}))},setCurrentRequestId:Bt,isAiStreaming:Zt,setIsAiStreaming:$t,showConfirmReset:ri,setShowConfirmReset:ai,confirmReset:function(){ar(),ai(!1),Vr()},isLoadingVariants:li,mainText:Ii,subText:xi,proposedRule:Pe,isFetchingComparison:Ki,handleOpenComparison:lr,showComparison:Si,setShowComparison:Ai,variants:Ge,onComparisonLinkClick:Bi,targetComparisonVariantId:He,highlightedComparisonField:Ke,onAddAsVariant:function(){Ai(!1)},isCopyEnabled:!0,onSubmitFeedback:function(n){return e.__awaiter(void 0,void 0,void 0,function(){var t,i,r,a,l;return e.__generator(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),t=e.__assign({user_id:null!==(r=null==Ui?void 0:Ui._id)&&void 0!==r?r:"",user_name:null!==(a=null==Ui?void 0:Ui.firstname)&&void 0!==a?a:"",user_email:null!==(l=null==Ui?void 0:Ui.email)&&void 0!==l?l:"",assistant_name:Tn.ASSISTANT_NAME},n),[4,o.submitChatFeedback(t)];case 1:return s.sent(),[3,3];case 2:throw i=s.sent(),console.error("Failed to submit chat feedback",i),i;case 3:return[2]}})})},handleGlobalClickCapture:function(e){null!==sn&&(e.target.closest('[data-edit-id="'.concat(sn,'"]'))||(e.preventDefault(),e.stopPropagation(),_n(sn)))},isGlobalEditActive:null!==sn,initialDraftMessage:H?K:"",socketTimeOutInMilliSeconds:Tn.SOCKET_TIMEOUT})]})},exports.filterAgentText=T;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("tslib"),n=require("react/jsx-runtime"),t=require("react"),i=require("lucide-react"),r=require("primereact/toast"),a=require("uuid"),o=require("../apis/scopeApis.js"),l=require("../public/ThinkingBulbIcon.gif.js"),s=require("../store/useLearningTemplateStore.js"),u=require("../styles/InstantLearningModal.module.css.js"),d=require("../../IL-OTJ/ILOTJ.js");require("../../IL-OTJ/_components/atoms/Textarea/Textarea.js"),require("../../IL-OTJ/_components/InputDataReasoningCard.js"),require("../../IL-OTJ/_components/TooltipComponent.js");var c=require("../../IL-OTJ/_components/templates/TemplatesMap/templatesMap.js"),_=require("../../IL-OTJ/helpers/utils.js"),v=require("../../IL-OTJ/store/CitationsContext.js");require("@mui/material"),require("@mui/material/Tooltip"),require("react-markdown"),require("rehype-raw"),require("axios"),require("@e-llm-studio/streaming-response"),require("@e-llm-studio/watch-me-work"),require("../../IL-OTJ/_components/ChatComponents/ChatHeader.js"),require("remark-gfm"),require("../../IL-OTJ/_components/MarkdownComponents/MarkdownElements.js"),require("../../IL-OTJ/_components/CitationLink.js"),require("@e-llm-studio/citation"),require("@viswa-test/test-citation"),require("./ToolTip.js");var p=require("../store/useAuthStore.js");require("date-fns"),require("framer-motion"),require("@mui/icons-material/Close");var f=require("../store/useConfigStore.js");function g(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("@radix-ui/react-tooltip"),require("./StationOnboarding/InputField.js"),require("../store/useEnvStore.js");var w=g(t),y=function(){return n.jsx("img",{src:l.default,alt:"Thinking...",width:"20",height:"20"})},m="INITIAL",h="SUCCESS",b="FAILURE",S="IN_PROGRESS",A=function(e){return"string"!=typeof e?"":e.replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g,"").replace(/<!--```json[\s\S]*?```-->/g,"").trim()},T=function(e){if(!e)return!1;var n=e.toLowerCase().trim();return"default"===n||"default_variant"===n};exports.default=function(l){var g,k,M,I,x,C,E=l.isOpen,N=l.onClose,O=l.initialScope,R=void 0===O?"global":O,L=l.ruleSet,j=l.editingRule,D=l.editingTier,q=l.editingVariants,V=l.focusedVariantIndex,P=l.setFocusedVariantIndex,F=l.triggerAddVariant,G=l.triggerFixGaps,J=l.copiedRule,U=l.copiedSourceTier,H=l.copiedTargetTier,W=l.initialDraftMessage,B=l.initialChatMessage,K=l.applicationIntegrationId;l.modeId;var Y=t.useState({station:R,tiers:["Tier 1"]}),Q=Y[0],z=Y[1],Z=t.useState(m),$=Z[0],X=Z[1],ee=t.useState(!1),ne=ee[0],te=ee[1],ie=t.useState("Thank you teacher for teaching me, your rule has been saved successfully."),re=ie[0];ie[1];var ae=t.useState(""),oe=ae[0],le=ae[1],se=t.useState(!1),ue=se[0],de=se[1],ce=t.useRef(null),_e=t.useState(!1),ve=_e[0],pe=_e[1],fe=t.useRef(!1),ge=s.useLearningTemplateStore().tiers,we=w.default.useRef(new Set),ye=t.useState(null);ye[0];var me=ye[1],he=t.useState(null);he[0];var be=he[1],Se=t.useState(null);Se[0];var Ae=Se[1],Te=t.useRef(new Map),ke=t.useRef(""),Me=t.useRef(!1),Ie=t.useState(0),xe=Ie[0],Ce=Ie[1],Ee=t.useState(!1),Ne=Ee[0],Oe=Ee[1],Re=t.useRef(null),Le=t.useRef(0),je=t.useState(null),De=je[0],qe=je[1],Ve=t.useState([]),Pe=Ve[0],Fe=Ve[1],Ge=t.useState(null),Je=Ge[0],Ue=Ge[1],He=t.useState(null),We=He[0],Be=He[1],Ke=t.useState(!1),Ye=Ke[0],Qe=Ke[1],ze=t.useRef({}),Ze=t.useRef([]),$e=t.useRef(!1),Xe=t.useState(!1),en=Xe[0],nn=Xe[1],tn=t.useRef(!1),rn=t.useRef(new Set),an=t.useState(null),on=an[0],ln=an[1],sn=t.useState(null),un=sn[0],dn=sn[1],cn=t.useState(null),_n=cn[0],vn=cn[1],pn=t.useRef(null),fn=t.useRef(null),gn=t.useRef(null),wn=t.useRef({}),yn=t.useRef([]),mn=t.useRef([]),hn=t.useRef({}),bn=f.useConfigStore(),Sn=bn.configuration,An=bn.ilLabels;t.useEffect(function(){on||dn(null)},[on]),t.useEffect(function(){var e;if(E&&j){pn.current=j.ruleId;var n=null===(e=null==q?void 0:q[V||0])||void 0===e?void 0:e.variantId;vn(n||null)}},[E,j,q,V]),t.useEffect(function(){E&&z(function(n){return e.__assign(e.__assign({},n),{station:R})})},[E,R]),t.useEffect(function(){console.log("triggered",_n),console.log(Qn,"structuredAIResponse"),zn(function(n){return Array.isArray(n)?n.map(function(n){return e.__assign(e.__assign({},n),{is_readOnly:n.variant_id!==_n&&n.new_variant_id!==_n})}):n}),tt(function(n){return Array.isArray(n)?n.map(function(n){return e.__assign(e.__assign({},n),{is_readOnly:n.variant_id!==_n&&n.new_variant_id!==_n})}):n})},[_n]),t.useEffect(function(){var n;if(!E)return ir(),void($e.current=!1);if(!$e.current){var t=q,i=t&&t.length>0,r=null!=j;if(i||r){if((null==j?void 0:j.ruleTitle)&&jn(j.ruleTitle),D&&(z(function(n){return e.__assign(e.__assign({},n),{tiers:[D]})}),fn.current=D.toLowerCase().replace(/ /g,"_")),i){var a=(null==D?void 0:D.toLowerCase().replace(/ /g,"_"))||"tier_1",o=new Map,l=new Map,s=new Map,u=new Map,d=new Map,c=new Map,_=[];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),_.push(e.variantId||e.variant_id||"")}),o.set(a,u),l.set(a,d),s.set(a,c);var v=null===(n=null==t?void 0:t[V||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==j?void 0:j.ruleTitle)||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",scope:[a],scheduling_config:r||{},variant_id:e.variantId,question_id:(null==j?void 0:j.ruleId)||"",tier_id:a.replace("tier_",""),is_readOnly:e.variantId!==v,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"}});zn(p),zn(p),tt(p),Xn(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,w=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,y=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:w>0,global_min_separation_seconds:Math.floor(w/60)},advertiser_rules:{enabled:y>0,global_min_separation_seconds:Math.floor(y/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!==(v=null===(_=null==g?void 0:g.break_code_rules)||void 0===_?void 0:_.respect_break_code)&&void 0!==v?v:null==g?void 0:g.respect_break_code)&&void 0!==p&&p},is_default_enabled:T(e.variantType||e.variant_type)})}),In(new Map([[a,f]])),Gn(o),Hn(l),Kn(s)}else if(r&&j){var g=j.ruleDesc;if(g&&Gn(new Map([["tier_1",new Map([[0,g]])]])),j.whenToApply){var w=j.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:""}});Hn(new Map([["tier_1",new Map([[0,w]])]]))}if(j.whenNotToApply){var y=j.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:""}});Kn(new Map([["tier_1",new Map([[0,y]])]]))}}}else if(J&&U&&H){jn(J.ruleTitle||""),z(function(n){return e.__assign(e.__assign({},n),{tiers:[H]})}),fn.current=H.toLowerCase().replace(/ /g,"_");var m=U.toLowerCase().replace(/ /g,"_"),h=J.variants||[],b=(o=new Map,l=new Map,s=new Map,new Map),S=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:""}}):[];S.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(m,b),l.set(m,S),s.set(m,A),Gn(o),Hn(l),Kn(s);var k=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:J.ruleTitle||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",scope:[U],scheduling_config:r||{},variant_id:e.variantId,question_id:J.ruleId||"",tier_id:m.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"}});zn(k),tt(k),Xn(function(e){var n=new Map(e);return n.set(m,JSON.parse(JSON.stringify(k))),n});var M=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,w=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;M.set(n,{order_rules:{enabled:g>0,global_min_separation_seconds:Math.floor(g/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==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!==(v=null===(_=null==f?void 0:f.break_code_rules)||void 0===_?void 0:_.respect_break_code)&&void 0!==v?v:null==f?void 0:f.respect_break_code)&&void 0!==p&&p},is_default_enabled:T(e.variantType||e.variant_type)})}),In(new Map([[m,M]]))}}},[E,j,q,D,J,U,H]),t.useEffect(function(){if(E){if(console.log("[Accordion Init] editingTier:",D,"focusedVariantIndex:",V),D&&z(function(n){return e.__assign(e.__assign({},n),{tiers:[D]})}),Ye)return console.log("[Accordion] isAddingNewVariant mode — closing all variant accordions"),void ct(void 0);if(F){console.log("[Accordion] triggerAddVariant mode — not opening any variant on RHS"),ct(void 0);var n=((null==D?void 0:D.toLowerCase().replace(/ /g,"_"))||"tier_1").replace(/_/g," ");pt("I want to add a new variant to ".concat(n))}else null!=V?(console.log("[Accordion] Opening SPECIFIC variant index ".concat(V," (from VariantCard)")),ct(V),jt(function(e){return e+1})):(j||q&&q.length>0)&&(console.log("[Accordion] Opening DEFAULT/1st variant (index 0) for RuleHeader edit"),ct(0),jt(function(e){return e+1}))}else ct(void 0)},[E,D,V,j,q,F,Ye]),t.useEffect(function(){E&&G&&j&&null!==V&&pt("I want to fix the gaps")},[E,G,j,V]);var Tn={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},kn=t.useState(new Map([["tier_1",new Map([[0,Tn]])],["tier_2",new Map([[0,Tn]])]])),Mn=kn[0],In=kn[1],xn=t.useState(new Set([])),Cn=xn[0],En=xn[1],Nn=t.useState("");Nn[0];var On=Nn[1],Rn=t.useState(""),Ln=Rn[0],jn=Rn[1],Dn=t.useState(new Map([["tier_1",new Map],["tier_2",new Map]])),qn=Dn[0],Vn=Dn[1],Pn=t.useState(new Map([["tier_1",new Map],["tier_2",new Map]])),Fn=Pn[0],Gn=Pn[1],Jn=t.useState(new Map([["tier_1",new Map],["tier_2",new Map]])),Un=Jn[0],Hn=Jn[1],Wn=t.useState(new Map([["tier_1",new Map],["tier_2",new Map]])),Bn=Wn[0],Kn=Wn[1],Yn=t.useState([]),Qn=Yn[0],zn=Yn[1],Zn=t.useState(new Map),$n=Zn[0],Xn=Zn[1],et=t.useState([]),nt=et[0],tt=et[1],it=t.useState(!1),rt=it[0],at=it[1],ot=t.useState([]),lt=ot[0],st=ot[1],ut=t.useState(void 0),dt=ut[0],ct=ut[1],_t=t.useState(""),vt=_t[0],pt=_t[1],ft=t.useState(null),gt=ft[0],wt=ft[1],yt=t.useState([]),mt=yt[0],ht=yt[1],bt=t.useState([]),St=bt[0],At=bt[1],Tt=t.useState({}),kt=Tt[0],Mt=Tt[1],It=t.useState(new Map),xt=It[0],Ct=It[1],Et=t.useState(new Set),Nt=Et[0],Ot=Et[1],Rt=t.useState(0),Lt=Rt[0],jt=Rt[1],Dt=t.useState({ruleTitle:"",ruleDescription:"",scopeData:"",whenToApply:"",whenNotToApply:"",configData:""}),qt=Dt[0],Vt=Dt[1],Pt=t.useState([]),Ft=Pt[0],Gt=Pt[1],Jt=t.useState(""),Ut=Jt[0],Ht=Jt[1],Wt=t.useState({}),Bt=Wt[0],Kt=Wt[1],Yt=t.useState(!1),Qt=Yt[0],zt=Yt[1],Zt=t.useRef(null),$t=t.useRef(null),Xt=t.useRef(-1),ei=t.useRef(null);t.useEffect(function(){mn.current=Qn},[Qn]),t.useEffect(function(){var t=new Set,r=console.warn;return console.warn=function(){for(var a,o=[],l=0;l<arguments.length;l++)o[l]=arguments[l];r.apply(void 0,o);var s=o[0];if("string"==typeof s&&s.includes("Failed to parse JSON for property=")){var d=s.match(/warnId="([^"]+)"/),c=null==d?void 0:d[1];if(c&&t.has(c))return;c&&t.add(c),null===(a=ei.current)||void 0===a||a.show({severity:"warn",sticky:!1,life:5e3,className:u.default.toastWarning,content:n.jsxs("div",e.__assign({className:u.default.toastContent},{children:[n.jsxs("div",e.__assign({className:u.default.toastHeaderLeft},{children:[n.jsx(i.AlertTriangle,{className:u.default.iconWarning}),n.jsx("span",e.__assign({className:"".concat(u.default.toastTitle," ").concat(u.default.toastTitleWarning)},{children:"Parsing Issue"}))]})),n.jsx("p",e.__assign({className:"".concat(u.default.toastMessage," ").concat(u.default.toastMessageWarning)},{children:"The AI response couldn't be parsed correctly. Please try rephrasing your input or retry."}))]}))})}},function(){console.warn=r}},[]);var ni=t.useState(!1),ti=ni[0],ii=ni[1],ri=t.useState(!1),ai=ri[0],oi=ri[1],li=t.useState({}),si=li[0],ui=li[1],di=t.useState(""),ci=di[0],_i=di[1],vi=t.useState(!0),pi=vi[0],fi=vi[1],gi=t.useState(!1),wi=gi[0],yi=gi[1],mi=t.useState(!1),hi=mi[0],bi=mi[1],Si=t.useState(""),Ai=Si[0],Ti=Si[1],ki=t.useState(""),Mi=ki[0],Ii=ki[1],xi=t.useState(""),Ci=xi[0],Ei=xi[1],Ni=t.useState(null),Oi=Ni[0],Ri=Ni[1],Li=t.useState(null),ji=Li[0],Di=Li[1],qi=t.useState(null),Vi=qi[0],Pi=qi[1],Fi=p.default.getState().user,Gi=v.useCitations(),Ji=Gi.dispatch,Ui=Gi.getLatestReasoning;t.useEffect(function(){console.log("Structured AI Response updated:",Qn)},[Qn]),t.useEffect(function(){console.log("isCloseModal AI Response updated:",pi)},[pi]),t.useEffect(function(){!1===Qt?(oi(!1),Ti(""),Ii("")):(de(!1),le(""))},[Qt]),t.useEffect(function(){null!=dt&&q&&!q[dt]&&Ri(null)},[dt,q]),t.useEffect(function(){if(ve&&!fe.current){fe.current=!0,console.log("UseEffect triggered: Sending save message to chat agent");pt("Save this Learning"),pe(!1),setTimeout(function(){fe.current=!1,pt("")},2e3)}},[ve]);var Hi=t.useCallback(function(e,n){Pe.some(function(n){return n.id===e})?(bi(!0),Ue(e),Be(n),setTimeout(function(){Be(null),Ue(null)},6e3)):console.warn("Variant ID ".concat(e," not found in comparison variants."))},[Pe]),Wi=t.useMemo(function(){var e=hi&&xe>0;return console.log("[Loader Debug] showComparison: ".concat(hi,", activeRequests: ").concat(xe,", Result: ").concat(e)),e},[hi,xe]),Bi=t.useCallback(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;Gn(function(e){var i=new Map(e),r=new Map(i.get(n));return r.set(t,a),i.set(n,r),i}),ui(function(i){if(i["ruleDescription-".concat(n,"-").concat(t)]){var r=e.__assign({},i);return delete r["ruleDescription-".concat(n,"-").concat(t)],r}return i})},[]),Ki=t.useCallback(function(n,t){Hn(function(i){var r=new Map(i),a=new Map(r.get(n)),o=a.get(t)||[];return a.set(t,e.__spreadArray(e.__spreadArray([],o,!0),[{id:Date.now(),text:"",reasoning:""}],!1)),r.set(n,a),r}),ui(function(i){if(i["whenToApply-".concat(n,"-").concat(t)]){var r=e.__assign({},i);return delete r["whenToApply-".concat(n,"-").concat(t)],r}return i})},[]),Yi=t.useCallback(function(e,n,t){Hn(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})},[]),Qi=t.useCallback(function(n,t,i,r){Hn(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.__assign(e.__assign({},n),{text:r}):n})),o.set(n,l),o}),ui(function(i){if(i["whenToApply-".concat(n,"-").concat(t)]){var r=e.__assign({},i);return delete r["whenToApply-".concat(n,"-").concat(t)],r}return i})},[]),zi=t.useCallback(function(n,t){Kn(function(i){var r=new Map(i),a=new Map(r.get(n)),o=a.get(t)||[];return a.set(t,e.__spreadArray(e.__spreadArray([],o,!0),[{id:Date.now(),text:"",reasoning:""}],!1)),r.set(n,a),r})},[]),Zi=t.useCallback(function(e,n,t){Kn(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})},[]),$i=t.useCallback(function(n,t,i,r){Kn(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.__assign(e.__assign({},n),{text:r}):n})),o.set(n,l),o})},[]),Xi=t.useCallback(function(e){var n=e.replace(/_/g," ");Qe(!0),null==P||P(null),ct(void 0),pt("I want to add a new variant to ".concat(n))},[]),er=function(n,t,i){var r="".concat(n,"_").concat(t);console.log("Highlighting ".concat(i," at ").concat(r)),Ct(function(n){var t,a=new Map(n),o=a.get(r)||{};return a.set(r,e.__assign(e.__assign({},o),((t={})[i]=!0,t))),a}),setTimeout(function(){Ct(function(n){var t,a=new Map(n),o=a.get(r)||{};return a.set(r,e.__assign(e.__assign({},o),((t={})[i]=!1,t))),a})},1500)},nr=t.useCallback(function(n,t){z(function(i){var r;return e.__assign(e.__assign({},i),((r={})[n]=t,r))}),ui(function(t){if(t[n]){var i=e.__assign({},t);return delete i[n],i}return t})},[]),tr=t.useCallback(function(n,t,i,r){Vn(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}),In(function(a){var o,l,s,u=new Map(a),d=new Map(u.get(n)||new Map),c=d.get(t)||Tn;switch(i){case"order_rules":case"advertiser_rules":s="boolean"==typeof r?e.__assign(e.__assign({},c),((o={})[i]=e.__assign(e.__assign({},c[i]),{enabled:r}),o)):"object"==typeof r&&null!==r?e.__assign(e.__assign({},c),((l={})[i]={enabled:r.enabled,global_min_separation_seconds:r.global_min_separation_seconds},l)):c;break;case"inventory_rules":s=e.__assign(e.__assign({},c),{inventory_rules:{respect_inventory_code:"boolean"==typeof r?r:r.respect_inventory_code}});break;case"break_code_rules":s=e.__assign(e.__assign({},c),{break_code_rules:{respect_break_code:"boolean"==typeof r?r:r.respect_break_code}});break;case"is_default_enabled":s=e.__assign(e.__assign({},c),{is_default_enabled:"boolean"==typeof r?r:!!r});break;default:s=c}return d.set(t,s),u.set(n,d),u})},[]);t.useEffect(function(){Qt&&(bi(!1),Be(null),Ue(null))},[Qt]);var ir=t.useCallback(function(n){var t;if(void 0===n&&(n=!1),n||(Ji({type:"RESET"}),Zt.current=null,zn([]),st([]),Gt([]),Kt({}),bi(!1),we.current.clear()),jn(""),ht([]),Qe(!1),ke.current="",Ei(""),Di(null),At([]),z({station:"",tiers:[]}),Ce(0),Oe(!1),Pi(null),Gn(new Map([["tier_1",new Map],["tier_2",new Map]])),Hn(new Map([["tier_1",new Map],["tier_2",new Map]])),Kn(new Map([["tier_1",new Map],["tier_2",new Map]])),In(new Map([["tier_1",new Map([[0,Tn]])],["tier_2",new Map([[0,Tn]])]])),Vn(new Map([["tier_1",new Map],["tier_2",new Map]])),On(""),ct(0),jt(0),z({station:R,tiers:["Tier 1"]}),n||Mt({}),Vn(new Map([["tier_1",new Map],["tier_2",new Map]])),pt(""),Vt({ruleTitle:"",ruleDescription:"",scopeData:"",whenToApply:"",whenNotToApply:"",configData:""}),ui({}),_i(""),fi(!0),me(null),be(null),Xn(new Map),tt([]),nn(!1),Ae(null),$t.current=null,Me.current=!1,ze.current={},rn.current.clear(),pn.current=null,fn.current=null,vn(null),le(""),X(m),te(!1),de(!1),pe(!1),qe(null),Fe([]),Ue(null),Be(null),ln(null),at(!1),wt(null),Ti(""),Ii(""),oi(!1),En(new Set),fe.current=!1,Te.current.clear(),Le.current=0,Re.current=null,gn.current=null,Xt.current=-1,tn.current=!1,$e.current=!1,j){j.ruleTitle&&jn(j.ruleTitle),D&&(z(function(n){return e.__assign(e.__assign({},n),{tiers:[D]})}),fn.current=D.toLowerCase().replace(/ /g,"_")),pn.current=j.ruleId;var i=null===(t=null==q?void 0:q[V||0])||void 0===t?void 0:t.variantId;if(vn(i||null),q&&q.length>0){var r=(null==D?void 0:D.toLowerCase().replace(/ /g,"_"))||"tier_1",a=new Map,o=new Map,l=new Map,s=new Map,u=new Map,d=new Map;q.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),Gn(a),Hn(o),Kn(l);var c=q.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:j.ruleTitle||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",scope:[r],scheduling_config:a||{},variant_id:e.variantId,question_id:j.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"}});zn(c),tt(c),Xn(function(e){var n=new Map(e);return n.set(r,JSON.parse(JSON.stringify(c))),n});var _=new Map;q.forEach(function(e,n){var t,i,r,a,o,l,s,u,d,c,v,p,f,g=null===(t=e.configuration)||void 0===t?void 0:t.scheduling_config,w=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,y=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;_.set(n,{order_rules:{enabled:w>0,global_min_separation_seconds:Math.floor(w/60)},advertiser_rules:{enabled:y>0,global_min_separation_seconds:Math.floor(y/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===(v=null==g?void 0:g.break_code_rules)||void 0===v?void 0:v.respect_break_code)&&void 0!==p?p:null==g?void 0:g.respect_break_code)&&void 0!==f&&f},is_default_enabled:T(e.variantType||e.variant_type)})}),In(new Map([[r,_]])),ct(null!=V?V:0)}}},[Ji,R,j,D,q,V]),rr=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)},ar=t.useCallback(function(){console.log("variantIds",mt),bi(!0)},[mt]),or={"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;Xt.current!==r&&(console.log("Opening variant accordion: AI index ".concat(i," → 0-based index ").concat(r)),ct(r),Xt.current=r)}}catch(e){console.error("Failed to parse variant_index from HTML comment:",e)}}},"Crafted Instant Learning with C.A.R.E.":function(n){var t,i=_.extractAndParseWithProperty(n),r=_.extractAndParseWithProperty(n,"general_details");console.log("--- [CARE] Staging Initial Structure ---",i);var a=_.extractAndParseWithProperty(n,"critical_gaps");if(console.log("isCriticalGap",a),Oe(!!a),i){if(i.variant_type&&!("is_variant"in i)){var o=null===(t=sr(i.variant_type||"").toLowerCase().match(/^(default_variant|default|variant)/i))||void 0===t?void 0:t[0];i.variant_type=T(o)?"Default":"variant",i.isDefault=T(o),console.log("parsed.variant_type",i.variant_type)}var l=i.scope&&i.scope.length>0?String(i.scope[0]):null,s=l?sr(l).toLowerCase().trim().replace(/ /g,"_"):null,u=Boolean(s&&fn.current!==s);if(u&&s){var d=fn.current;console.log("[Tier Switch Detected]",fn.current,"→",s),fn.current=s,pn.current=null;var c=(mn.current||[]).findIndex(function(e){return!0===(null==e?void 0:e.is_new_variant)});-1===c&&void 0!==dt&&(c=dt),d&&-1!==c&&(console.log("[Tier Switch] Stripping draft variant at index ".concat(c," from ").concat(d)),Gn(function(e){var n=new Map(e),t=new Map(n.get(d)||new Map);return t.delete(c),n.set(d,t),n}),Hn(function(e){var n=new Map(e),t=new Map(n.get(d)||new Map);return t.delete(c),n.set(d,t),n}),Kn(function(e){var n=new Map(e),t=new Map(n.get(d)||new Map);return t.delete(c),n.set(d,t),n}),In(function(e){var n=new Map(e),t=new Map(n.get(d)||new Map);return t.delete(c),n.set(d,t),n}),zn(function(n){if(!Array.isArray(n))return n;var t=e.__spreadArray([],n,!0);return t[c]&&(t[c]=e.__assign(e.__assign({},t[c]),{scope:[s],tier_id:s.replace("tier_","")})),mn.current=t,t})),Xt.current=-1;var v=s.replace(/_/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()});z(function(n){return e.__assign(e.__assign({},n),{tiers:[v]})})}wt(i),me({Updated_Fields_Response:i,General_Response:r}),(null==r?void 0:r.variant_id)&&"new_variant_id"===(null==r?void 0:r.variant_id)&&(r.variant_id=null),(null==r?void 0:r.is_interpretation_ready)&&(null==r?void 0:r.question_id)&&Fr(r,i,u),(null==r?void 0:r.is_interpretation_ready)&&(null==r?void 0:r.question_id)&&pn.current&&_n?zn(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===_n?e.__assign(e.__assign({},n),i):n}),r=n.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===_n});return console.log(r,"targetIndexif"),-1!==r&&setTimeout(function(){console.log("targetIndex",r),ct(r),jt(function(e){return e+1}),Xt.current=r},0),t}):(null==r?void 0:r.is_interpretation_ready)&&(null==r?void 0:r.question_id)&&pn.current&&!_n?zn(function(n){var t;if(Array.isArray(n)){var r=n.findIndex(function(e){return!0===e.is_new_variant});if(-1!==r)setTimeout(function(){ct(r),jt(function(e){return e+1}),Xt.current=r},0),t=n.map(function(n,t){return t===r?e.__assign(e.__assign(e.__assign({},n),i),{is_new_variant:!0,is_variant:!0}):n});else{var a=n.length;setTimeout(function(){ct(a),jt(function(e){return e+1}),Xt.current=a},0),t=e.__spreadArray(e.__spreadArray([],n,!0),[e.__assign(e.__assign({},i),{is_new_variant:!0})],!1)}}else setTimeout(function(){ct(0),jt(function(e){return e+1}),Xt.current=0},0),t=[e.__assign(e.__assign({},i),{is_new_variant:!0})];return mn.current=t,t}):(null==r?void 0:r.is_interpretation_ready)&&(zn([i]),setTimeout(function(){ct(0),jt(function(e){return e+1}),Xt.current=0},0)),void 0!==i.is_user_accepted_risk&&zn(function(n){var t=!(!j&&!q),r=Array.isArray(n)?e.__spreadArray([],n,!0):[];if(t&&0===r.length&&q&&q.length>0&&(r=q.map(function(e,n){var t;return{variant_type:e.variantType||"variant ".concat(n+1),title:(null==j?void 0:j.ruleTitle)||"",rule_description:e.description||"",wta:e.whenToApply||"",wnta:e.whenNotToApply||"",is_valid:!0,is_readOnly:e.variantId!==_n,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}})),t){var a=Oi||ji,o=r.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===a||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===a||(null==e?void 0:e.id)&&e.id===a});if(-1===o&&void 0!==dt&&(o=dt),-1!==o)return r[o]=e.__assign(e.__assign({},r[o]),{is_user_accepted_risk:!!i.is_user_accepted_risk}),r}return n})}},"RHS Validation Agent Response":function(n){var t,i,r,a=n;if("string"==typeof n)try{a=JSON.parse(n)}catch(e){a=_.parseValidationData(n)}if(be(a),console.log("--- [RHS] Updating Staged Logic ---"),console.log("parsed data from RHS Validation",a),a){wt(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(Qn)){var r=Oi||ji,o=-1;!(!j&&!q)&&r&&(o=Qn.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===o&&void 0!==dt&&(o=dt),-1!==o&&(i=Qn[o])}t=i?e.__assign({},i):{wta:"",wnta:""}}return e.__assign(e.__assign({},t),{wta:t.wta,wnta:t.wnta,is_valid:a.is_valid,conflictingConditions:a.conflictingConditions||[],conflictMarkdown:{},conflict_view:a.conflict_view||{}})});var o=(D||"Tier 1").toLowerCase().replace(/ /g,"_"),l=function(){var e,n=mn.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(_n)if(-1!==(t=n.findIndex(function(e){return(null==e?void 0:e.variant_id)===_n||(null==e?void 0:e.new_variant_id)===_n})))return t;if(Oi)if(-1!==(t=n.findIndex(function(e){return(null==e?void 0:e.variant_id)===Oi||(null==e?void 0:e.new_variant_id)===Oi})))return t;var r=null!==(e=null==q?void 0:q.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!==dt?dt:0;return console.log("[RHS] Fallback index used:",o),o}();if(console.log("Resolved variant index for conflict injection:",l),!1===a.is_valid)((null===(t=a.conflictingConditions)||void 0===t?void 0:t.length)||0)>0&&(ui(function(n){var t=e.__assign({},n);return a.conflictingConditions.forEach(function(e){e.condition_wnta&&!e.condition_wta?t["whenNotToApply-".concat(o,"-").concat(l)]=e.reason:t["whenToApply-".concat(o,"-").concat(l)]=e.reason}),t}),_i("")),a.conflict_view&&((null===(i=a.conflict_view.wta)||void 0===i?void 0:i.length)>0&&Hn(function(n){var t=new Map(n),i=new Map(t.get(o)||new Map),r=e.__spreadArray([],i.get(l)||[],!0);return a.conflict_view.wta.forEach(function(n){var t=r.findIndex(function(e){return e.text.trim()===n.value});-1!==t?r[t]=e.__assign(e.__assign({},r[t]),{conflict:n}):r.push({id:"conflict-wta-".concat(Date.now(),"-").concat(Math.random()),text:n.value,conflict:n})}),i.set(l,r),t.set(o,i),t}),(null===(r=a.conflict_view.wnta)||void 0===r?void 0:r.length)>0&&Kn(function(n){var t=new Map(n),i=new Map(t.get(o)||new Map),r=e.__spreadArray([],i.get(l)||[],!0);return a.conflict_view.wnta.forEach(function(n){var t=r.findIndex(function(e){return e.text.trim()===n.value});-1!==t?r[t]=e.__assign(e.__assign({},r[t]),{conflict:n}):r.push({id:"conflict-wnta-".concat(Date.now(),"-").concat(Math.random()),text:n.value,conflict:n})}),i.set(l,r),t.set(o,i),t}));else!0===a.is_valid&&(ui({}),_i(""),Hn(function(n){var t=new Map(n),i=new Map(t.get(o)||new Map),r=i.get(l)||[];return i.set(l,r.map(function(n){return e.__assign(e.__assign({},n),{conflict:void 0})})),t.set(o,i),t}),Kn(function(n){var t=new Map(n),i=new Map(t.get(o)||new Map),r=i.get(l)||[];return i.set(l,r.map(function(n){return e.__assign(e.__assign({},n),{conflict:void 0})})),t.set(o,i),t}))}},"User Action Execution":function(e){console.log("--- [User Action] Execution ---",e);var n=_.extractAndParseResponse(e);(console.log("parsedaction",n),"load"===(null==n?void 0:n.action)&&(null==n?void 0:n.question_id)&&Fr(n,null),"save"===(null==n?void 0:n.action)&&(null==n?void 0:n.is_save)&&(fi(!0),yi(!0)),"discard_rule"===(null==n?void 0:n.action))&&(zn([{variant_id:void 0,rule_description:"",wta:"",wnta:"",variant_type:"variant"}]),tt([]),vn(null),ct(0),jt(0),ln(null),nn(!1),Qe(!1),ht([]),pn.current=null,jn(""),Pi(null),In(new Map([["tier_1",new Map([[0,Tn]])],["tier_2",new Map([[0,Tn]])]])),Gn(new Map([["tier_1",new Map],["tier_2",new Map]])),Hn(new Map([["tier_1",new Map],["tier_2",new Map]])),Kn(new Map([["tier_1",new Map],["tier_2",new Map]])))},"Validation Agent Response":function(n){var t,i;if(console.log("--- [Validation Agent] Committing Staged Data to UI ---"),console.log("raw data from Validation Agent",n,typeof n),"string"==typeof n){var r=n.match(/<!--\s*```json\s+property="rule_validation_card"\s+([\s\S]*?)```\s*-->/i);if(r&&r[1])try{var a=JSON.parse(r[1].trim()),o=null===(i=null===(t=null==a?void 0:a.validated_rules)||void 0===t?void 0:t[0])||void 0===i?void 0:i.rule_id;o&&(console.log("Setting default comparison ID:",o),Ue(o))}catch(e){console.error("Failed to parse rule_validation_card JSON",e)}}var l=_.extractAndParseWithProperty(n,"critical_gaps");console.log("isCriticalGap",l),Oe(!!l);var s="string"==typeof n?_.extractAndParseResponse(n):n;console.log("parsed data from Validation Agent",s);var u=_.extractVariantIds(n);Ae(s);var d=!!(null==s?void 0:s.is_variant),c=void 0===(null==s?void 0:s.close_modal)||!!(null==s?void 0:s.close_modal),v=void 0!==(null==s?void 0:s.is_save)&&!!(null==s?void 0:s.is_save);fi(c),yi(v);var p=null==s?void 0:s.action,f="string"==typeof(null==s?void 0:s.edit_variant_id)&&s.edit_variant_id.trim()?s.edit_variant_id:"string"==typeof(null==s?void 0:s.set_variant_id)&&s.set_variant_id.trim()?s.set_variant_id:null,g="variant"===p&&d;if((null==s?void 0:s.edit_variant_id)&&!g&&Ri(s.edit_variant_id),"edit"!==p&&"edit_current_rule"!==p||!f||Di(f),g&&(Ri(null),Di(null)),"discard"===p)return console.log("Action 'discard' received: Resetting UI state but preserving chat."),$e.current=!0,ir(!0),zn([]),Zt.current=null,void($t.current=null);Ei(p);var w=null==s?void 0:s.new_variant_id,y="edit"===(null==s?void 0:s.action)&&(null==s?void 0:s.set_variant_id)&&!q;(null==s?void 0:s.is_valid)?(ui({}),wt(function(n){var t,i,r,a,o,l,u,d,c,_,v,p;if(console.log("⏮️ PREVIOUS Staged Response:",n),!n)return console.warn("⚠️ No previous staged response found"),n;var g=function(e,n){return Object.prototype.hasOwnProperty.call(e||{},n)},w=e.__assign(e.__assign({},n),s);Array.isArray(null===(t=null==s?void 0:s.condition_result)||void 0===t?void 0:t.when_to_apply)?w.wta=s.condition_result.when_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join(" OR "):g(s,"wta")&&void 0!==(null==s?void 0:s.wta)&&(w.wta=null!==(i=null==s?void 0:s.wta)&&void 0!==i?i:""),Array.isArray(null===(r=null==s?void 0:s.condition_result)||void 0===r?void 0:r.when_not_to_apply)?w.wnta=s.condition_result.when_not_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join(" OR "):g(s,"wnta")&&void 0!==(null==s?void 0:s.wnta)&&(w.wnta=null!==(a=null==s?void 0:s.wnta)&&void 0!==a?a:""),console.log("finalData",w),console.log("checking parsed here :",s);var y,m=f;if(Array.isArray(Qn)&&m&&(y=m,Qn.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==s?void 0:s.action)||!j&&!q)return w;console.log("inside edit flow merge");var h=q||[],b=f,S=b?h.findIndex(function(e){return e.variantId===b||e.variant_id&&e.variant_id===b||e.id&&e.id===b}):-1;if(-1===S&&(null==s?void 0:s.set_variant_id)&&(S=h.findIndex(function(e){return e.variantId===s.set_variant_id||e.variant_id&&e.variant_id===s.set_variant_id||e.id&&e.id===s.set_variant_id})),-1===S&&b&&Array.isArray(Qn)&&(S=Qn.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===b||(null==e?void 0:e.new_variant_id)&&e.new_variant_id===b||(null==e?void 0:e.id)&&e.id===b})),-1!==S){var A,T,k,M=h[S]||(null==Qn?void 0:Qn[S]),I=(null==M?void 0:M.tier_id)||(null==M?void 0:M.tierId)||"1",x=(null==D?void 0:D.toLowerCase().replace(/ /g,"_"))||"tier_".concat(I);if(Xt.current!==S&&(ct(S),Xt.current=S),Array.isArray(null===(o=s.condition_result)||void 0===o?void 0:o.when_to_apply)?A=s.condition_result.when_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join("\n"):g(s,"wta")&&void 0!==(null==s?void 0:s.wta)?A=null!==(l=null==s?void 0:s.wta)&&void 0!==l?l:"":g(n,"wta")&&void 0!==(null==n?void 0:n.wta)&&(A=null!==(u=null==n?void 0:n.wta)&&void 0!==u?u:""),Array.isArray(null===(d=s.condition_result)||void 0===d?void 0:d.when_not_to_apply)?T=s.condition_result.when_not_to_apply.filter(function(e){return e&&"none"!==e.toLowerCase()}).join("\n"):g(s,"wnta")&&void 0!==(null==s?void 0:s.wnta)?T=null!==(c=null==s?void 0:s.wnta)&&void 0!==c?c:"":g(n,"wnta")&&void 0!==(null==n?void 0:n.wnta)&&(T=null!==(_=null==n?void 0:n.wnta)&&void 0!==_?_:""),void 0!==A){var C=sr(A);ur(x,S,A,C,Un,Hn,null==s?void 0:s.conflict_view),er(x,S,"wta")}if(void 0!==T){var E=sr(T);ur(x,S,T,E,Bn,Kn,null==s?void 0:s.conflict_view),er(x,S,"wnta")}if(g(s,"rule_description")&&void 0!==(null==s?void 0:s.rule_description)?k=null!==(v=null==s?void 0:s.rule_description)&&void 0!==v?v:"":g(n,"rule_description")&&void 0!==(null==n?void 0:n.rule_description)&&(k=null!==(p=null==n?void 0:n.rule_description)&&void 0!==p?p:""),void 0!==k){var N=sr(k);Gn(function(e){var n=new Map(e),t=new Map(n.get(x)||new Map);return t.set(S,N),n.set(x,t),n}),er(x,S,"ruleDescription")}var O=void 0;g(s,"scheduling_config")&&void 0!==(null==s?void 0:s.scheduling_config)?O=null==s?void 0:s.scheduling_config:g(n,"scheduling_config")&&void 0!==(null==n?void 0:n.scheduling_config)&&(O=null==n?void 0:n.scheduling_config),O&&(In(function(e){var t,i,r,a,o,l,s=new Map(e),u=new Map(s.get(x)||new Map);return u.set(S,{order_rules:{enabled:!!(null===(t=O.order_rules)||void 0===t?void 0:t.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(i=O.order_rules)||void 0===i?void 0:i.global_min_separation_seconds)||0)/60)},advertiser_rules:{enabled:!!(null===(r=O.advertiser_rules)||void 0===r?void 0:r.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(a=O.advertiser_rules)||void 0===a?void 0:a.global_min_separation_seconds)||0)/60)},inventory_rules:{respect_inventory_code:!!(null===(o=O.inventory_rules)||void 0===o?void 0:o.respect_inventory_code)},break_code_rules:{respect_break_code:!!(null===(l=O.break_code_rules)||void 0===l?void 0:l.respect_break_code)},is_default_enabled:"Default"===(null==n?void 0:n.variant_type)||"default_variant"===(null==n?void 0:n.variant_type)||"default"===(null==n?void 0:n.variant_type)}),s.set(x,u),s}),er(x,S,"order_enabled"),er(x,S,"advertiser_enabled"),er(x,S,"respect_inventory_code"),er(x,S,"respect_break_code")),zn(function(n){if(!Array.isArray(n)||S<0||!n[S])return n;var t=e.__spreadArray([],n,!0),i=e.__assign({},t[S]);return void 0!==A&&(i.wta=A),void 0!==T&&(i.wnta=T),void 0!==k&&(i.rule_description=sr(k)),O&&(i.scheduling_config=O),console.log("updated variantxxx",i),t[S]=i,t});var R=null==n?void 0:n.variant_type;R&&zn(function(n){var t=Array.isArray(n)?e.__spreadArray([],n,!0):[],i=t.findIndex(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===b||(null==e?void 0:e.variant_id)&&e.variant_id===(null==s?void 0:s.set_variant_id)||(null==e?void 0:e.variantId)===b});return-1!==i?t[i]=e.__assign(e.__assign({},t[i]),{variant_type:R}):t[S]=e.__assign(e.__assign({},t[S]||{}),{variant_type:R,variant_id:b||(null==s?void 0:s.set_variant_id)}),t})}})):console.warn("⚠️ parsed.is_valid is false, not committing to structuredAIResponse"),y||(d?(at(!0),w&&w!==$t.current?(console.log("🚀 New Variant detected (".concat(w,"). Triggering loader.")),oi(!0),Ti("Loading a variant"),console.log("reaching here in new variant flow"),Ii("This may take a moment as we update the rule with the new variant."),$t.current=w):w||console.log("ℹ️ Variant flow detected without specific ID.")):(at(!1),$t.current=null),u&&ht(u))},"Rule comparison results":function(e){try{var n=e;if("string"==typeof e)try{n=JSON.parse(e)}catch(t){n=_.extractAndParseResponse(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 _="";if((null==o?void 0:o.nodes)&&o.nodes.title){var v=o.nodes.title;(null===(i=null===(t=null==v?void 0:v.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:_,extractedScore:p,extractedScope:f}),{id:u,title:_,similarityScoreText:p,scope:f,intentTreeData:o,behaviorTreeData:l,isLoading:!1}});Fe(t)}catch(e){console.error("[Rule comparison results] Critical Handler Error:",e)}}},lr=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},sr=function(e){return"string"!=typeof e?"":e.replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g,"").replace(/<!--```json[\s\S]*?```-->/g,"").trim()},ur=function(n,t,i,r,a,o,l){var s;if(void 0!==i){var u=(a.get(n)||new Map).get(t)||[],d=u.map(function(e){return e.text}).join("\n"),c=(null===(s=u[(null==u?void 0:u.length)-1])||void 0===s?void 0:s.reasoning)||"",_=lr(i)||"";if(""===i&&u.length>0||r.trim()!==d.trim()||_!==c){var v=""===i?{updatedItems:[],newIds:[]}:function(n,t,i){if(!n.trim())return{updatedItems:e.__spreadArray([],t,!0),newIds:[]};var r=n.match(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g)||[],a=n.replace(/<ai_reasoning>[\s\S]*?<\/ai_reasoning>/g,"").replace(/<!--```json[\s\S]*?```-->/g,""),o=[],l=a.replace(/<conflicting>[\s\S]*?<\/conflicting>/g,function(e){return o.push(e),"__CONFLICT_BLOCK_".concat((null==o?void 0:o.length)-1,"__")}).split(/\s*(?:\r?\n|\\+n)\s*/).map(function(e){return e.trim().replace(/^-\s*/,"")}).filter(Boolean),s=new Map(t.map(function(e){return[e.text,e]})),u=[],d=[],c=Array.isArray(null==i?void 0:i.wta)&&n.includes("wta")?i.wta:Array.isArray(null==i?void 0:i.wnta)?i.wnta:[];return l.forEach(function(n,t){var i=n;i.includes("__CONFLICT_BLOCK_")&&(i=i.replace(/__CONFLICT_BLOCK_(\d+)__/g,function(e,n){return o[parseInt(n)]}));var a=r[t]||"",l=i.replace(/<conflicting>[\s\S]*?<\/conflicting>/g,"").trim(),_=null==c?void 0:c.find(function(e){return e.value===l}),v=s.get(i);if(v)d.push(e.__assign(e.__assign({},v),{reasoning:a||v.reasoning,conflict:_||v.conflict}));else{var p="new-".concat(Date.now(),"-").concat(t);u.push(p),d.push({id:p,text:i,reasoning:a,conflict:_})}}),{updatedItems:d,newIds:u}}(i,u,l),p=v.updatedItems,f=v.newIds;o(function(e){var i=new Map(e),r=new Map(i.get(n)||new Map);return r.set(t,p),i.set(n,r),i}),(null==f?void 0:f.length)>0&&(Ot(function(n){return new Set(e.__spreadArray(e.__spreadArray([],Array.from(n),!0),f,!0))}),setTimeout(function(){Ot(function(e){var n=new Set(e);return f.forEach(function(e){return n.delete(e)}),n})},1500))}}},dr=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()})})};t.useEffect(function(){vt&&!fe.current&&"save this learning"!==vt.toLowerCase()&&(de(!1),le(""),Xt.current=null!=dt?dt:-1)},[vt]),t.useEffect(function(){var n,t,i,r,a,o,l,s,u;if(yn.current=Ft,Array.isArray(Qn)&&Qn.length>0){var d=Ut||"local-".concat(Date.now()),c=["ruleTitle","ruleDescription","whenToApply","whenNotToApply","scopeData","configData"],_={},v=Zt.current||[];Qn.forEach(function(n,t){var i,r;if(n){n.is_readOnly||(Le.current=t);var a=t;if((null==n?void 0:n.variant_id)&&q)-1!==(o=q.findIndex(function(e){return e.variantId===n.variant_id}))&&(a=o);else if(Oi&&q&&1===Qn.length){var o;-1!==(o=q.findIndex(function(e){return e.variantId===Oi}))&&(a=o)}var l=null!==(i=v[a])&&void 0!==i?i:v[t],s=null!==(r=n.scope)&&void 0!==r?r:null==l?void 0:l.scope,u=dr(s).map(function(e){return e.toLowerCase().replace(/ /g,"_")}),d=u.length>0?u:Ze.current.length>0?Ze.current:["tier_1"];d.length>0&&(Ze.current=d),console.log("prevTierRef.current",Ze.current,"targetTiers",d);var p=sr(n.title);p&&p!==sr(null==l?void 0:l.title)&&!n.is_readOnly&&function(e,n,t,i,r,a){var o=sr(i);o&&o!==r&&(er(e,n,t),a(o))}("global",0,"ruleTitle",n.title,Ln,jn),d.forEach(function(i){var r,o,l,s,u,d=null!==(r=v[a])&&void 0!==r?r:v[t],p=!d,f=void 0!==n.rule_description&&null!==n.rule_description,g=sr(n.rule_description),w=(null===(o=Fn.get(i))||void 0===o?void 0:o.get(a))||"",y=sr(w);f&&(g!==y||""===g&&""!==w)&&(Gn(function(e){var t=new Map(e),r=new Map(t.get(i)||new Map);return r.set(a,n.rule_description),t.set(i,r),t}),er(i,a,"ruleDescription"));var m=!1===(null==gt?void 0:gt.is_valid),h=sr(n.wta),b=sr(null==d?void 0:d.wta),S=(null===(l=Un.get(i))||void 0===l?void 0:l.get(a))||[];!(m&&""===h&&S.length>0)&&void 0!==n.wta&&null!==n.wta&&(h!==b||""===h&&S.length>0||0===S.length&&""!==h)&&(ur(i,a,n.wta,h,Un,Hn,null==gt?void 0:gt.conflict_view),er(i,a,"wta"));var A=sr(n.wnta),k=sr(null==d?void 0:d.wnta),M=(null===(s=Bn.get(i))||void 0===s?void 0:s.get(a))||[];if(!(m&&""===A&&M.length>0)&&void 0!==n.wnta&&null!==n.wnta&&(A!==k||""===A&&M.length>0||0===M.length&&""!==A)&&(ur(i,a,n.wnta,A,Bn,Kn,null==gt?void 0:gt.conflict_view),er(i,a,"wnta")),n.scheduling_config||p||n.variant_type||n.variantType){var I=n.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}},x=null==d?void 0:d.scheduling_config,C=null===(u=Mn.get(i))||void 0===u?void 0:u.get(a),E=n.variant_type||n.variantType,N=E?T(E):void 0,O=JSON.stringify(I)!==JSON.stringify(x),R=void 0!==N&&N!==(null==C?void 0:C.is_default_enabled),L=function(n,t){if(!n)return t;if(!t)return n;var i=e.__assign({},n);for(var r in t)t[r]&&"object"==typeof t[r]&&!Array.isArray(t[r])?i[r]=e.__assign(e.__assign({},i[r]||{}),t[r]):i[r]=t[r];return i};if(Mt(function(e){return L(e,I)}),O||R){Mt(function(e){return L(e,I)});var j=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}(i,a,I,Mn);j.forEach(function(e){return er(i,a,e)}),En(function(e){return new Set(e).add("config")}),In(function(n){var t,r,o,l,s,u,d=new Map(n),c=new Map(d.get(i)||new Map),_=c.get(a)||Tn;return c.set(a,e.__assign(e.__assign(e.__assign(e.__assign(e.__assign(e.__assign({},_),I.order_rules&&{order_rules:{enabled:!!(null===(t=I.order_rules)||void 0===t?void 0:t.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(r=I.order_rules)||void 0===r?void 0:r.global_min_separation_seconds)||0)/60)}}),I.advertiser_rules&&{advertiser_rules:{enabled:!!(null===(o=I.advertiser_rules)||void 0===o?void 0:o.global_min_separation_seconds),global_min_separation_seconds:Math.floor(((null===(l=I.advertiser_rules)||void 0===l?void 0:l.global_min_separation_seconds)||0)/60)}}),I.inventory_rules&&{inventory_rules:{respect_inventory_code:!!(null===(s=I.inventory_rules)||void 0===s?void 0:s.respect_inventory_code)}}),I.break_code_rules&&{break_code_rules:{respect_break_code:!!(null===(u=I.break_code_rules)||void 0===u?void 0:u.respect_break_code)}}),void 0!==N&&{is_default_enabled:N})),d.set(i,c),d}),Vn(function(e){var n=new Map(e),t=new Map(n.get(i)||new Map),r=t.get(a)||new Set;return I.order_rules&&r.add("order_rules"),I.advertiser_rules&&r.add("advertiser_rules"),I.inventory_rules&&r.add("inventory_rules"),I.break_code_rules&&r.add("break_code_rules"),void 0!==N&&r.add("is_default_enabled"),t.set(a,r),n.set(i,t),n})}}var D={ruleTitle:n.title,ruleDescription:n.rule_description,whenToApply:n.wta,whenNotToApply:n.wnta,scopeData:n.scope,configData:n.action};n.is_readOnly||c.forEach(function(e){var n=lr(D[e]),t="ruleTitle"===e||"scopeData"===e?e:"".concat(e,"_").concat(i);n&&(n!==wn.current[t]&&(wn.current[t]=n,hn.current[t]=!0,_[t]={reasoning:n,associatedCitations:[],tier:i,variantIndex:a}))}),n.conflictingConditions&&(ui(function(t){var r=e.__assign({},t);return n.conflictingConditions.forEach(function(e){e.condition_wta&&(r["whenToApply-".concat(i,"-").concat(a)]=e.reason),e.condition_wnta&&(r["whenNotToApply-".concat(i,"-").concat(a)]=e.reason)}),r}),En(function(n){return new Set(e.__spreadArray(e.__spreadArray([],Array.from(n),!0),["conditions"],!1))}))})}});var p=-1,f=!(!j&&!q),g="edit"===Ci||"edit_current_rule"===Ci,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(f)if($t.current&&rt)-1!==(p=Qn.findIndex(function(e){return(null==e?void 0:e.new_variant_id)&&e.new_variant_id===$t.current||(null==e?void 0:e.variant_id)&&e.variant_id===$t.current||(null==e?void 0:e.id)&&e.id===$t.current}))&&($t.current=null);else if(Oi||ji){var m;(m=Oi||ji)&&(p=y(Qn,m))}else if(F&&Array.isArray(Qn)&&Qn.length>0){for(h=Qn.length-1;h>=0;h--)if(Qn[h]&&!(null===(t=Qn[h])||void 0===t?void 0:t.is_readOnly)){p=h;break}}else null==V||Zt.current&&0!==Zt.current.length||(p=V);else if((m=Oi||ji||$t.current)&&g&&(p=y(Qn,m)),!g&&-1===p&&Array.isArray(Qn)&&Qn.length>0){for(var h=Qn.length-1;h>=0;h--)if(Qn[h]&&!(null===(n=Qn[h])||void 0===n?void 0:n.is_readOnly)){p=h;break}-1===p&&(p=Qn.length-1)}-1!==p&&dt!==p&&(Xt.current===p||Me.current&&!g||(console.log("🎯 Setting active variant accordion to index ".concat(p," (").concat(f?"EDIT":"CREATE"," mode)")),ct(p),Xt.current=p));var b=Qn[0];if(b){if(b.scope&&JSON.stringify(b.scope)!==JSON.stringify(null===(i=v[0])||void 0===i?void 0:i.scope)&&"copy"!==b.action&&(o=b.scope,l=null===(r=v[0])||void 0===r?void 0:r.scope,s=dr(o),u=l?dr(l):[],z(function(n){return e.__assign(e.__assign({},n),{tiers:s})}),s.forEach(function(e){var n=e.trim();u.includes(e)||er("global",0,"scope_".concat(n))})),b.scope_rule_set&&b.scope_rule_set!==(null===(a=v[0])||void 0===a?void 0:a.scope_rule_set)){var S=b.scope_rule_set.toLowerCase().trim();["global","genre","custom"].includes(S)&&(z(function(n){return e.__assign(e.__assign({},n),{station:S})}),er("global",0,"scope_station"))}b.wtl&&On(b.wtl)}Zt.current=Qn.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&&(Ji({type:"SAVE_CITATIONS",requestId:d,reasoningMap:_,rawCitations:Ft}),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:d,keys:Object.keys(_),newReasoningMap:_,getLatestReasoning:Ui,currentCitations:Ft}),Vt(function(n){var t=e.__assign({},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}))}},[Qn,Ft,Ut]),t.useEffect(function(){var n=Object.keys(hn.current);if(0!==n.length){var t={};n.forEach(function(n){t[n]=e.__spreadArray([],Ft,!0)}),hn.current={},Kt(function(n){return e.__assign(e.__assign({},n),t)})}},[Ft]);var cr=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==L?void 0:L.ruleSetId)||"",value:{scopeName:(null==L?void 0:L.ruleSetName)||"",scopeId:"Audacy_"+a.v4(),customScopeGroupName:(null==Sn?void 0:Sn.CUSTOM_SCOPE_GROUP_NAME)||"",description:(null==L?void 0:L.ruleSetDesc)||""}}})},_r=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}}},vr=function(n,t,i,r){void 0===r&&(r=0);var a=e.__assign({},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 _=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.__assign(e.__assign({},s),{global_min_separation_seconds:_})}else a[n]="inventory_rules"===n?e.__assign(e.__assign({},s),{respect_inventory_code:null==c?void 0:c.respect_inventory_code}):"break_code_rules"===n?e.__assign(e.__assign({},s),{respect_break_code:null==c?void 0:c.respect_break_code}):"is_default_enabled"===n?null!=c&&c:s})}),a},pr=function(e,n,t){void 0===t&&(t="variantType");var i=null==e?void 0:e[n];if(!i)return{label:rr(e),isDefault:!1};var r=i[t]||"",a=T(r);return{label:"variant ".concat(n+1),isDefault:a}},fr=function(e,n){var t=T(e);return{label:"variant ".concat(n+1),isDefault:t}},gr=function(e,n,t){var i;void 0===t&&(t="");var r=null===(i=Mn.get(e))||void 0===i?void 0:i.get(n);return r?r.is_default_enabled?"Default":"Variant":T(t)?"Default":"Variant"},wr=function(t,r){return void 0===r&&(r=!1),e.__awaiter(void 0,void 0,void 0,function(){var t,l,d,c,_,v,p,f,g,w,y,m,A,T,k;return e.__generator(this,function(M){switch(M.label){case 0:cr(Q.tiers),t=Le.current,l=vr(qn,kt,Mn,t),M.label=1;case 1:return M.trys.push([1,3,,4]),X(S),le(""),d=_r(l),c=a.v4(),_=[],v=[],p=(Qn||[])[t]||{},console.log("originalItem check :",p,t),Q.tiers.forEach(function(n){var i,r,a,l,s,u,f,g=n.toLowerCase().replace(/ /g,"_");v.push(g);var w=(null===(i=Fn.get(g))||void 0===i?void 0:i.get(t))||"",y=(null===(r=Un.get(g))||void 0===r?void 0:r.get(t))||[],m=(null===(a=Bn.get(g))||void 0===a?void 0:a.get(t))||[],h=[e.__assign(e.__assign({},d&&{config:e.__assign({master_name:Sn.CONFIG_MASTER_NAME},d)}),{datasource:{type:"link",ref:"www.something.com",tag:"something"},tierLinkId:c,variant:sr(w),conditions_whentoapply:y.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),conditions_whennottoapply:m.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),isDefault:null===(u=null===(s=null===(l=Mn.get(g))||void 0===l?void 0:l.get(t))||void 0===s?void 0:s.is_default_enabled)||void 0===u||u,tier_id:(null===(f=ge.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===g||e.tier_name.toLowerCase()===g.replace(/_/g,"")}))||void 0===f?void 0:f.tier_id)||"",topic_id:null,scope_id:(null==L?void 0:L.ruleSetId)||"",question_title:Ln,variantType:gr(g,t,p.variant_type||p.variantType),instantLearningType:Sn.INSTANT_LEARNING_TYPE,is_user_accepted_risk:!1,propagation:!1,applicationMappingId:K,modeId:"019e1e39-2030-7775-8312-0ad525700588"})];_.push(o.publishFeedback(h,Sn.ASSISTANT_NAME))}),[4,Promise.all(_)];case 2:return f=M.sent(),pe(!1),console.log("✅ All feedback published:",f),X(h),te(!0),g=new Map,f.forEach(function(e,n){var t,i,r=v[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=g.get(r)||[];o.push({id:a,action:"new"}),g.set(r,o)}}),s.useLearningTemplateStore.getState().setCreatedVariantInfo(Array.from(g.entries()).map(function(e){return{tierName:e[0],variants:e[1]}})),null===(A=ei.current)||void 0===A||A.show({severity:"success",sticky:!1,life:6e3,className:u.default.toastSuccess,content:n.jsxs("div",e.__assign({className:u.default.toastContent},{children:[n.jsxs("div",e.__assign({className:u.default.toastHeaderLeft},{children:[n.jsx(i.Check,{className:u.default.iconSuccess}),n.jsx("span",e.__assign({className:"".concat(u.default.toastTitle," ").concat(u.default.toastTitleSuccess)},{children:"Success"}))]})),n.jsx("p",e.__assign({className:"".concat(u.default.toastMessage," ").concat(u.default.toastMessageSuccess)},{children:"Learning saved successfully!"}))]}))}),ce.current=setTimeout(function(){pi||r?(console.log("Closing modal after save success",{isCloseModal:pi,forceClose:r}),Vr()):ir(!0)},3e3),[3,4];case 3:return w=M.sent(),console.error("❌ Error publishing feedback:",w),pe(!1),X(b),de(!0),y=(null===(T=null==w?void 0:w.response)||void 0===T?void 0:T.data)||{},console.log("errorData: ",y),(m="Variant already exists"===(null==y?void 0:y.message))||409===(null==w?void 0:w.status)?le('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>'):le(((null==y?void 0:y.message)||(null==y?void 0:y.detail)||"Error Occurred while saving the rule.")+'Please try again.<br/><button class="clickable-button" data-value="Save this Learning">Retry</button>'),null===(k=ei.current)||void 0===k||k.show({severity:"error",sticky:!1,className:u.default.toastError,content:n.jsxs("div",e.__assign({className:u.default.toastContent},{children:[n.jsxs("div",e.__assign({className:u.default.toastHeaderLeft},{children:[n.jsx(i.AlertTriangle,{className:u.default.iconError}),n.jsx("span",e.__assign({className:"".concat(u.default.toastTitle," ").concat(u.default.toastTitleError)},{children:"Error"}))]})),n.jsx("p",e.__assign({className:"".concat(u.default.toastMessage," ").concat(u.default.toastMessageError)},{children:m||409===(null==w?void 0:w.status)?"Similar rule already exists. Please update and try again.":(null==y?void 0:y.message)||(null==y?void 0:y.detail)||"Something went wrong while saving the learning!"}))]}))}),[3,4];case 4:return[2]}})})},yr=function(){return e.__awaiter(void 0,void 0,void 0,function(){var t,r,l,d,c,_,v,p,f,g,w,y,m,k,M,I,x,C,E,N,O,R,D,V,P,F;return e.__generator(this,function(G){switch(G.label){case 0:t=s.useLearningTemplateStore.getState().tiers,r=vr(qn,kt,Mn),l=_r(r),d=Le.current,c=(Qn||[])[d]||{},_=(null==gt?void 0:gt.variant_type)||c.variant_type||"",G.label=1;case 1:for(G.trys.push([1,3,,4]),X(S),le(""),p=(v=q||[]).length>0?null===(O=v.find(function(e){return(null==e?void 0:e.link_id)&&""!==e.link_id.trim()}))||void 0===O?void 0:O.link_id:null,f=(null===(R=Q.tiers[0])||void 0===R?void 0:R.toLowerCase().replace(/ /g,"_"))||"tier_1",g=(null===(D=Fn.get(f))||void 0===D?void 0:D.size)||v.length,w=e.__spreadArray([],v,!0),y=v.length;y<g;y++)w.push({isNewVariant:!0,variantId:a.v4()});return m=[],k=[],M=cr(Q.tiers),Q.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,"")}),s=Fn.get(i),u=Un.get(i),d=Bn.get(i);w.forEach(function(t,v){var f,g,w,y,h,b,S,I,x,C,E,N,O,R,D,q,V,P,F,G,J,U,H,W,B,K,Y,z,Z=(null==s?void 0:s.get(v))||t.description||"",$=(null==u?void 0:u.get(v))||[],X=(null==d?void 0:d.get(v))||[];if(t.isNewVariant){k.push({tierKey:i,payloadType:"new"});var ee=vr(qn,kt,Mn,v),ne=_r(ee);console.log("variant in save edit add part :",t,c);var te={status:"approved",metadata:e.__assign(e.__assign({userName:null!==(f=null==Fi?void 0:Fi.firstname)&&void 0!==f?f:"",userEmailId:null!==(g=null==Fi?void 0:Fi.email)&&void 0!==g?g:"",llm:Sn.MODEL,isVariantFlow:!0},ne&&{config:e.__assign({master_name:Sn.CONFIG_MASTER_NAME},ne)}),{datasource:{type:"link",ref:"www.something.com",tag:"something"},variant:{tierLinkId:p||a.v4(),variant:sr(Z),conditions_whentoapply:$.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),conditions_whennottoapply:X.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),referenceVariantID:null,referenceVariantIDVersion:null,scope:M[0]||{name:Sn.SCOPE_NAME,parentScopeId:null,scopeRowId:(null==L?void 0:L.ruleSetId)||"",value:{scopeName:(null==L?void 0:L.ruleSetName)||"",scopeId:"Audacy_"+a.v4(),customScopeGroupName:Sn.CUSTOM_SCOPE_GROUP_NAME,description:(null==L?void 0:L.ruleSetDesc)||""}},overriden:!1,isDefault:null!==(h=null===(y=null===(w=Mn.get(i))||void 0===w?void 0:w.get(v))||void 0===y?void 0:y.is_default_enabled)&&void 0!==h?h:T(t.variantType||t.variant_type||(0===v?"Default":"variant")),tier:{name:n.split(" ").join("").toLowerCase(),tierGroupName:Sn.CUSTOM_SCOPE_GROUP_NAME,tierPriority:parseInt(n.split(" ")[1]||"1")},topic:{id:null,value:"".concat(Q.station,"RuleSet"),description:null},categories:[{id:null,value:Sn.CATEGORY,description:Sn.CATEGORY}],originalQuestion:Ln,questionId:null==j?void 0:j.ruleId,variantType:gr(i,v,c.variant_type||""),parameterizedQuestion:null,created_at:(new Date).toISOString(),created_by:null!==(b=null==Fi?void 0:Fi.email)&&void 0!==b?b:"",instantLearningType:Sn.INSTANT_LEARNING_TYPE,appliedTagsIL:[],tagMappingInfoIL:{},is_user_accepted_risk:!!(null!==(I=null===(S=(Qn||[])[v])||void 0===S?void 0:S.is_user_accepted_risk)&&void 0!==I?I:null==gt?void 0:gt.is_user_accepted_risk)},isAgentsFeedback:!0})};console.log("payload (publish new variant)",te),m.push(o.publishFeedback(te,Sn.ASSISTANT_NAME))}else{k.push({tierKey:i,payloadType:"existing",existingId:t.variantId});var ie=t.variantId===Oi,re=gr(i,v,ie?_||t.variantType||"":t.variantType||"");console.log("isThisVariantBeingEdited variantTypeToUse :",re,ie,t,Oi);var ae={variantId:t.variantId,ruleDesc:(null==L?void 0:L.ruleSetDesc)||"",whenToApply:$.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),whenNotToApply:X.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),isDefault:null!==(E=null===(C=null===(x=Mn.get(i))||void 0===x?void 0:x.get(v))||void 0===C?void 0:C.is_default_enabled)&&void 0!==E?E:T(t.variantType||t.variant_type||(0===v?"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==L?void 0:L.ruleSetId)||"",description:sr(Z)||"",topic:"".concat(Q.station,"RuleSet"),configuration:(null==l?void 0:l.config_data)||{},tierLinkId:null!=p?p:null,variantType:re,is_user_accepted_risk:!!(null!==(R=null===(O=(Qn||[])[v])||void 0===O?void 0:O.is_user_accepted_risk)&&void 0!==R?R:null==t?void 0:t.is_user_accepted_risk),is_enabled:t.is_enabled},oe=($n.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=A(n)).replace(/\s+/g," ").replace(/(\s*OR\s*)/g," OR ")},ue=se(Ln)===se(oe.title),de=se(Z)===se(oe.rule_description),ce=se(ae.whenToApply)===se(oe.wta),_e=se(ae.whenNotToApply)===se(oe.wnta),ve=!!ae.isDefault===T(oe.variant_type),pe=oe.scheduling_config||{},fe=null!==(V=null!==(D=pe.order_global_min_separation_seconds)&&void 0!==D?D:null===(q=pe.order_rules)||void 0===q?void 0:q.global_min_separation_seconds)&&void 0!==V?V:0,ge=null!==(G=null!==(P=pe.advertiser_global_min_separation_seconds)&&void 0!==P?P:null===(F=pe.advertiser_rules)||void 0===F?void 0:F.global_min_separation_seconds)&&void 0!==G?G:0,we=null!==(H=null!==(U=null===(J=pe.inventory_rules)||void 0===J?void 0:J.respect_inventory_code)&&void 0!==U?U:pe.respect_inventory_code)&&void 0!==H&&H,ye=null!==(K=null!==(B=null===(W=pe.break_code_rules)||void 0===W?void 0:W.respect_break_code)&&void 0!==B?B:pe.respect_break_code)&&void 0!==K&&K,me=(null===(Y=Mn.get(i))||void 0===Y?void 0:Y.get(v))||Tn,he=me.order_rules.enabled===fe>0&&me.order_rules.global_min_separation_seconds===Math.floor(fe/60)&&me.advertiser_rules.enabled===ge>0&&me.advertiser_rules.global_min_separation_seconds===Math.floor(ge/60)&&me.inventory_rules.respect_inventory_code===we&&me.break_code_rules.respect_break_code===ye;ue&&de&&ce&&_e&&ve&&he&&(le=!1)}le?(console.log("payloadv (update existing variant)",ae),m.push(o.updateVariant(ae,null!==(z=null==Fi?void 0:Fi.email)&&void 0!==z?z:""))):(console.log("[saveEditedVariant] No changes for variant ".concat(t.variantId,", skipping API call")),m.push(Promise.resolve({data:{id:t.variantId},skipped:!0})))}})}),[4,Promise.all(m)];case 2:return I=G.sent(),console.log("✅ All variants updated:",I),X(h),te(!0),pe(!1),x=new Map,I.forEach(function(e,n){var t,i;if(!(null==e?void 0:e.skipped)){var r=k[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=x.get(r.tierKey)||[];l.push({id:o,action:r.payloadType}),x.set(r.tierKey,l)}}}),s.useLearningTemplateStore.getState().setCreatedVariantInfo(Array.from(x.entries()).map(function(e){return{tierName:e[0],variants:e[1]}})),null===(V=ei.current)||void 0===V||V.show({severity:"success",sticky:!1,life:3e3,className:u.default.toastSuccess,content:n.jsxs("div",e.__assign({className:u.default.toastContent},{children:[n.jsxs("div",e.__assign({className:u.default.toastHeaderLeft},{children:[n.jsx(i.Check,{className:u.default.iconSuccess}),n.jsx("span",e.__assign({className:"".concat(u.default.toastTitle," ").concat(u.default.toastTitleSuccess)},{children:"Success"}))]})),n.jsx("p",e.__assign({className:"".concat(u.default.toastMessage," ").concat(u.default.toastMessageSuccess)},{children:"Changes saved successfully!"}))]}))}),ce.current=setTimeout(function(){Vr()},3e3),[3,4];case 3:return C=G.sent(),console.error("❌ Error updating variant:",C),X(b),de(!0),pe(!1),E=(null===(P=null==C?void 0:C.response)||void 0===P?void 0:P.data)||{},console.log("errorData: ",E),(N="Variant already exists"===(null==E?void 0:E.message))||409===(null==C?void 0:C.status)?le('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>'):le(((null==E?void 0:E.message)||(null==E?void 0:E.detail)||"Error Occurred while saving the rule.")+'Please try again.<br/><button class="clickable-button" data-value="Save this Learning">Retry</button>'),null===(F=ei.current)||void 0===F||F.show({severity:"error",sticky:!1,className:u.default.toastError,content:n.jsxs("div",e.__assign({className:u.default.toastContent},{children:[n.jsxs("div",e.__assign({className:u.default.toastHeaderLeft},{children:[n.jsx(i.AlertTriangle,{className:u.default.iconError}),n.jsx("span",e.__assign({className:"".concat(u.default.toastTitle," ").concat(u.default.toastTitleError)},{children:"Error"}))]})),n.jsx("p",e.__assign({className:"".concat(u.default.toastMessage," ").concat(u.default.toastMessageError)},{children:N||409===(null==C?void 0:C.status)?"Similar rule already exists. Please update and try again.":(null==E?void 0:E.message)||(null==E?void 0:E.detail)||"Something went wrong while saving the learning!"}))]}))}),[3,4];case 4:return[2]}})})},mr=function(){return e.__awaiter(void 0,void 0,void 0,function(){var t,r,l,d,c,_,v,p,f,g,w,y,m,k,M,I,x,C,E,N,O,j,D,q,V,P,F;return e.__generator(this,function(G){switch(G.label){case 0:t=s.useLearningTemplateStore.getState().tiers,r=vr(qn,kt,Mn),l=_r(r),G.label=1;case 1:return G.trys.push([1,9,,10]),X(S),le(""),0===(d=Array.isArray(Qn)?Qn:[]).length?(console.warn("No variants found to save."),X(b),[2]):(c=d.filter(function(e){return e.is_new_variant}),_=d.filter(function(e){return!e.is_new_variant&&(null==e?void 0:e.variant_id)}),console.log("[saveLoadAndEditVariant] New: ".concat(c.length,", Existing: ").concat(_.length)),v=_.length>0?null===(q=_.find(function(e){return(null==e?void 0:e.link_id)&&""!==e.link_id.trim()}))||void 0===q?void 0:q.link_id:null,p=[],f=[],g=[],w=[],y=cr(Q.tiers),Q.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,"")}),s=Fn.get(i),u=Un.get(i),c=Bn.get(i);d.forEach(function(t,d){var _,m,h,b,S,k,M,I,x,C,E,N,O,j,D,q,V,P,F,G,J,U,H,W,B,K,Y,z=(null==s?void 0:s.get(d))||t.rule_description||t.description||"",Z=(null==u?void 0:u.get(d))||[],$=(null==c?void 0:c.get(d))||[];if(t.is_new_variant){var X=vr(qn,kt,Mn,d),ee=_r(X),ne=gr(i,d,t.variant_type||t.variantType||""),te={status:"approved",metadata:e.__assign(e.__assign({userName:null!==(_=null==Fi?void 0:Fi.firstname)&&void 0!==_?_:"",userEmailId:null!==(m=null==Fi?void 0:Fi.email)&&void 0!==m?m:"",llm:Sn.MODEL,isVariantFlow:!0},ee&&{config:e.__assign({master_name:Sn.CONFIG_MASTER_NAME},ee)}),{datasource:{type:"link",ref:"www.something.com",tag:"something"},variant:{tierLinkId:v||a.v4(),variant:sr(z),conditions_whentoapply:Z.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),conditions_whennottoapply:$.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),referenceVariantID:null,referenceVariantIDVersion:null,scope:y[0]||{name:Sn.SCOPE_NAME,parentScopeId:null,scopeRowId:(null==L?void 0:L.ruleSetId)||"",value:{scopeName:(null==L?void 0:L.ruleSetName)||"",scopeId:"Audacy_"+a.v4(),customScopeGroupName:Sn.CUSTOM_SCOPE_GROUP_NAME,description:(null==L?void 0:L.ruleSetDesc)||""}},overriden:!1,isDefault:null!==(S=null===(b=null===(h=Mn.get(i))||void 0===h?void 0:h.get(d))||void 0===b?void 0:b.is_default_enabled)&&void 0!==S?S:T(t.variantType||t.variant_type||(0===d?"Default":"variant")),tier:{name:n.split(" ").join("").toLowerCase(),tierGroupName:Sn.CUSTOM_SCOPE_GROUP_NAME,tierPriority:parseInt(n.split(" ")[1]||"1"),tier_id:(null==r?void 0:r.tier_id)||""},topic:{id:null,value:"".concat(Q.station||R,"RuleSet"),description:null},categories:[{id:null,value:Sn.CATEGORY,description:Sn.CATEGORY}],originalQuestion:Ln,questionId:pn.current||null,variantType:ne,parameterizedQuestion:null,created_at:(new Date).toISOString(),created_by:null!==(k=null==Fi?void 0:Fi.email)&&void 0!==k?k:"",instantLearningType:Sn.INSTANT_LEARNING_TYPE,appliedTagsIL:[],tagMappingInfoIL:{},is_user_accepted_risk:!!(null!==(M=null==t?void 0:t.is_user_accepted_risk)&&void 0!==M?M:null==gt?void 0:gt.is_user_accepted_risk)},isAgentsFeedback:!0})};console.log("[saveLoadAndEditVariant] publish payload (new variant)",te),f.push({payload:te,tierKey:i}),w.push({tierKey:i})}else if(null==t?void 0:t.variant_id){g.push({tierKey:i,existingId:t.variant_id});var ie=(null==t?void 0:t.variant_id)&&t.variant_id===Vi?(null==gt?void 0:gt.variant_type)||t.variant_type||t.variantType||"":t.variant_type||t.variantType||"",re=(ne=gr(i,d,ie),{variantId:t.variant_id,ruleDesc:(null==L?void 0:L.ruleSetDesc)||"",whenToApply:Z.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),whenNotToApply:$.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" OR "),isDefault:null!==(C=null===(x=null===(I=Mn.get(i))||void 0===I?void 0:I.get(d))||void 0===x?void 0:x.is_default_enabled)&&void 0!==C?C:T(t.variantType||t.variant_type||(0===d?"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!==(E=null==r?void 0:r.tier_priority)&&void 0!==E?E:null},scope_id:(null==L?void 0:L.ruleSetId)||"",description:sr(z)||"",topic:"".concat(Q.station,"RuleSet"),configuration:(null==l?void 0:l.config_data)||{},tierLinkId:null!=v?v:null,variantType:ne,is_user_accepted_risk:!!(null!==(N=null==t?void 0:t.is_user_accepted_risk)&&void 0!==N?N:null===(O=(Qn||[])[d])||void 0===O?void 0:O.is_user_accepted_risk),is_enabled:t.is_enabled}),ae=($n.get(i)||[]).find(function(e){return(null==e?void 0:e.variant_id)&&e.variant_id===(null==t?void 0:t.variant_id)}),oe=!0;if(ae){var le=function(e){var n=(e||"").trim();return(n=A(n)).replace(/\s+/g," ").replace(/(\s*OR\s*)/g," OR ")},se=le(Ln)===le(ae.title),ue=le(z)===le(ae.rule_description),de=le(re.whenToApply)===le(ae.wta),ce=le(re.whenNotToApply)===le(ae.wnta),_e=!!re.isDefault===T(ae.variant_type),ve=ae.scheduling_config||{},pe=null!==(q=null!==(j=ve.order_global_min_separation_seconds)&&void 0!==j?j:null===(D=ve.order_rules)||void 0===D?void 0:D.global_min_separation_seconds)&&void 0!==q?q:0,fe=null!==(F=null!==(V=ve.advertiser_global_min_separation_seconds)&&void 0!==V?V:null===(P=ve.advertiser_rules)||void 0===P?void 0:P.global_min_separation_seconds)&&void 0!==F?F:0,ge=null!==(U=null!==(J=null===(G=ve.inventory_rules)||void 0===G?void 0:G.respect_inventory_code)&&void 0!==J?J:ve.respect_inventory_code)&&void 0!==U&&U,we=null!==(B=null!==(W=null===(H=ve.break_code_rules)||void 0===H?void 0:H.respect_break_code)&&void 0!==W?W:ve.respect_break_code)&&void 0!==B&&B,ye=(null===(K=Mn.get(i))||void 0===K?void 0:K.get(d))||Tn,me=ye.order_rules.enabled===pe>0&&ye.order_rules.global_min_separation_seconds===Math.floor(pe/60)&&ye.advertiser_rules.enabled===fe>0&&ye.advertiser_rules.global_min_separation_seconds===Math.floor(fe/60)&&ye.inventory_rules.respect_inventory_code===ge&&ye.break_code_rules.respect_break_code===we;se&&ue&&de&&ce&&_e&&me&&(oe=!1)}oe?(console.log("[saveLoadAndEditVariant] update payload (existing variant)",re),p.push(o.updateVariant(re,null!==(Y=null==Fi?void 0:Fi.email)&&void 0!==Y?Y:""))):(console.log("[saveLoadAndEditVariant] No changes for variant ".concat(t.variant_id,", skipping API call")),p.push(Promise.resolve({data:{id:t.variant_id},skipped:!0})))}})}),[4,Promise.all(p)]);case 2:m=G.sent(),console.log("✅ All existing variants updated:",m),k=[],M=0,I=f,G.label=3;case 3:if(!(M<I.length))return[3,8];x=I[M],G.label=4;case 4:return G.trys.push([4,6,,7]),[4,o.publishFeedback(x.payload,Sn.ASSISTANT_NAME)];case 5:return C=G.sent(),k.push(C),[3,7];case 6:throw E=G.sent(),console.error("❌ Error publishing new variant:",E),E;case 7:return M++,[3,3];case 8:return console.log("✅ All new variants published:",k),N=new Map,m.forEach(function(e,n){var t,i;if(!(null==e?void 0:e.skipped)){var 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;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)}}}),k.forEach(function(e,n){var t,i,r=w[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)}}),s.useLearningTemplateStore.getState().setCreatedVariantInfo(Array.from(N.entries()).map(function(e){return{tierName:e[0],variants:e[1]}})),X(h),te(!0),pe(!1),Me.current=!1,null===(V=ei.current)||void 0===V||V.show({severity:"success",sticky:!1,life:3e3,className:u.default.toastSuccess,content:n.jsxs("div",e.__assign({className:u.default.toastContent},{children:[n.jsxs("div",e.__assign({className:u.default.toastHeaderLeft},{children:[n.jsx(i.Check,{className:u.default.iconSuccess}),n.jsx("span",e.__assign({className:"".concat(u.default.toastTitle," ").concat(u.default.toastTitleSuccess)},{children:"Success"}))]})),n.jsx("p",e.__assign({className:"".concat(u.default.toastMessage," ").concat(u.default.toastMessageSuccess)},{children:"Changes saved successfully!"}))]}))}),ce.current=setTimeout(function(){Vr()},3e3),[3,10];case 9:return O=G.sent(),console.error("❌ Error updating variant:",O),X(b),de(!0),pe(!1),j=(null===(P=null==O?void 0:O.response)||void 0===P?void 0:P.data)||{},console.log("errorData: ",j),(D="Variant already exists"===(null==j?void 0:j.message))||409===(null==O?void 0:O.status)?le('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>'):le(((null==j?void 0:j.message)||(null==j?void 0:j.detail)||"Error Occurred while saving the rule.")+'Please try again.<br/><button class="clickable-button" data-value="Save this Learning">Retry</button>'),null===(F=ei.current)||void 0===F||F.show({severity:"error",sticky:!1,className:u.default.toastError,content:n.jsxs("div",e.__assign({className:u.default.toastContent},{children:[n.jsxs("div",e.__assign({className:u.default.toastHeaderLeft},{children:[n.jsx(i.AlertTriangle,{className:u.default.iconError}),n.jsx("span",e.__assign({className:"".concat(u.default.toastTitle," ").concat(u.default.toastTitleError)},{children:"Error"}))]})),n.jsx("p",e.__assign({className:"".concat(u.default.toastMessage," ").concat(u.default.toastMessageError)},{children:D||409===(null==O?void 0:O.status)?"Similar rule already exists. Please update and try again.":(null==j?void 0:j.message)||(null==j?void 0:j.detail)||"Something went wrong while saving the learning!"}))]}))}),[3,10];case 10:return[2]}})})},hr=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()};t.useEffect(function(){wi&&!Qt&&(console.log("isSaveRule received from agent — calling publish APIs directly."),yi(!1),j||q?yr():!0===Me.current?mr():e.__awaiter(void 0,void 0,void 0,function(){var n,t,i,r,a,l,s,u;return e.__generator(this,function(d){switch(d.label){case 0:d.trys.push([0,5,,6]),X(S),n=new Map,t=function(t){var i,r,a,l,s,d;return e.__generator(this,function(e){switch(e.label){case 0:if(i=t.toLowerCase().replace(/ /g,"_"),r=ge.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===i||e.tier_name.toLowerCase()===i.replace(/_/g,"")}),!(a=null==r?void 0:r.tier_id))return n.set(i,null),[2,"continue"];l={question:Ln,orgName:Sn.ORGANIZATION_NAME,scope_id:(null==L?void 0:L.ruleSetId)||"",tier_id:a},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,o.saveInstantLearningQuestion(l)];case 2:return s=e.sent(),n.set(i,(null===(u=null==s?void 0:s.data)||void 0===u?void 0:u.id)||null),console.log("✅ Question saved for ".concat(t,":"),s),[3,4];case 3:return d=e.sent(),console.error("❌ Error saving question for ".concat(t,":"),d),n.set(i,null),[3,4];case 4:return[2]}})},i=0,r=Q.tiers,d.label=1;case 1:return i<r.length?(a=r[i],[5,t(a)]):[3,4];case 2:d.sent(),d.label=3;case 3:return i++,[3,1];case 4:return wr(),[3,6];case 5:return l=d.sent(),s=new Map,Q.tiers.forEach(function(e){s.set(e.toLowerCase().replace(/ /g,"_"),null)}),wr(),console.error("❌ Error saving Instant Learning Question:",l),[3,6];case 6:return[2]}})}))},[wi,Qt]);var br=(null===(k=(null===(g=null==Q?void 0:Q.tiers)||void 0===g?void 0:g[0])||D||"Tier 1")||void 0===k?void 0:k.toLowerCase().replace(/ /g,"_"))||"tier_1",Sr=null!==(M=null!=dt?dt:V)&&void 0!==M?M:0,Ar=null!=dt,Tr=Ar?null==Qn?void 0:Qn[Sr]:null,kr=Qn&&(null==Qn?void 0:Qn.find(function(e){return e&&!e.is_readOnly&&((null==e?void 0:e.new_variant_id)&&St.includes(e.new_variant_id)||(null==e?void 0:e.variant_id)&&mt.includes(e.variant_id))})),Mr=(null==Tr?void 0:Tr.new_variant_id)&&St.includes(Tr.new_variant_id)?Tr.new_variant_id:(null==kr?void 0:kr.new_variant_id)&&St.includes(kr.new_variant_id)?kr.new_variant_id:"",Ir=!(!j&&!q),xr=function(n){var t={},i=Q.tiers.map(function(e){return null==e?void 0:e.toLowerCase().replace(/ /g,"_")}),r=(null==Q?void 0:Q.station)+"RuleSet",a=i.map(function(e){var n=ge.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||mt[o]||"new_variant_".concat(o),p=(null===(l=n.scope)||void 0===l?void 0:l[0])||br,f=Fn.get(p),g=Un.get(p),w=Bn.get(p),y=(null==f?void 0:f.get(o))||n.rule_description||"",m=(null==g?void 0:g.get(o))||[],h=m.length>0?m.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" \\n "):n.wta||"",b=(null==w?void 0:w.get(o))||[],S=b.length>0?b.map(function(e){return e.text}).filter(function(e){return""!==e.trim()}).join(" \\n "):n.wnta||"",A=Mn.get(p),T=null==A?void 0:A.get(o),k={};T&&Object.keys(T).length>0?k=e.__assign(e.__assign({},T),{order_rules:e.__assign(e.__assign({},T.order_rules),{global_min_separation_seconds:60*((null===(s=T.order_rules)||void 0===s?void 0:s.global_min_separation_seconds)||0)}),advertiser_rules:e.__assign(e.__assign({},T.advertiser_rules),{global_min_separation_seconds:60*((null===(u=T.advertiser_rules)||void 0===u?void 0:u.global_min_separation_seconds)||0)})}):n.scheduling_config&&(k=n.scheduling_config),t[v]={rule_title:Ln,variant_description:y,wta:h,ruleset_id:(null==L?void 0:L.ruleSetId)||"",tier_id:a,wnta:S,scope:i,scope_rule_set:r,scheduling_config:k,is_user_accepted_risk:!(null===(_=null!==(d=null==n?void 0:n.is_user_accepted_risk)&&void 0!==d?d:null===(c=(Qn||[])[o])||void 0===c?void 0:c.is_user_accepted_risk)||void 0===_||!_)}}),t};en&&console.log("customMetaData.ui_state for addvariant flow",xr(nt));var Cr=s.useLearningTemplateStore(function(e){return e.selectedRuleSetId}),Er={send_metadata_to_orchestrator:!1,default:["scope"],app_mapping_id:K,ui_state:Ir?{variants:function(){var n={},t=Mn.get(br);if(!t)return n;var i=Fn.get(br),r=Un.get(br),a=Bn.get(br),o=Q.tiers.map(function(e){return null==e?void 0:e.toLowerCase().replace(/ /g,"_")}),l=(null==Q?void 0:Q.station)+"RuleSet",s=o.map(function(e){var n=ge.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,w=null===(c=null==q?void 0:q[d])||void 0===c?void 0:c.variantId,y=(Qn||[])[d],m=(null==y?void 0:y.new_variant_id)||"",h=w||m||mt[d]||"variant_".concat(d),b=(null==i?void 0:i.get(d))||"",S=((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 ")||"",T=t.get(d),k={};T&&Object.keys(T).length>0&&(k=e.__assign(e.__assign({},T),{order_rules:e.__assign(e.__assign({},T.order_rules),{global_min_separation_seconds:60*((null===(_=T.order_rules)||void 0===_?void 0:_.global_min_separation_seconds)||0)}),advertiser_rules:e.__assign(e.__assign({},T.advertiser_rules),{global_min_separation_seconds:60*((null===(v=T.advertiser_rules)||void 0===v?void 0:v.global_min_separation_seconds)||0)})})),n[h]={rule_title:Ln,variant_description:b,wta:S,ruleset_id:(null==L?void 0:L.ruleSetId)||"",tier_id:s,wnta:A,scope:o,scope_rule_set:l,scheduling_config:k,is_user_accepted_risk:!(null===(g=null!==(p=null==y?void 0:y.is_user_accepted_risk)&&void 0!==p?p:null===(f=null==q?void 0:q[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=(Qn||[]).findIndex(function(e){return!0===e.is_new_variant}),s=-1;return-1!==l?s=l:Ye?s=-1:en||(s=Sr),{new_current_variant:-1!==s?{rule_title:Ln,rule_description:(null===(n=Fn.get(br))||void 0===n?void 0:n.get(s))||"",wta:(null===(i=null===(t=Un.get(br))||void 0===t?void 0:t.get(s))||void 0===i?void 0:i.map(function(e){return hr(e.text)}).filter(function(e){return""!==e}).join(" \\n "))||"",wnta:(null===(a=null===(r=Bn.get(br))||void 0===r?void 0:r.get(s))||void 0===a?void 0:a.map(function(e){return hr(e.text)}).filter(function(e){return""!==e}).join(" \\n "))||"",scope:Q.tiers.map(function(e){return null==e?void 0:e.toLowerCase().replace(/ /g,"_")}),scope_rule_set:(null==Q?void 0:Q.station)+"RuleSet",scheduling_config:function(){var n,t,i,r=null===(n=Mn.get(br))||void 0===n?void 0:n.get(s);return r&&0!==Object.keys(r).length?e.__assign(e.__assign({},r),{order_rules:e.__assign(e.__assign({},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.__assign(e.__assign({},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=(Qn||[])[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:en?xr(nt):{}}}(),rule_id_in_current_session:lt,new_variant_id:function(){var e;return Ar&&j?(null===(e=null==q?void 0:q[Sr])||void 0===e?void 0:e.variantId)?null:Mr:null}(),edit_variant_id:_n,rule_id:pn.current,ruleset_id:Cr,current_variants_length:j?Array.isArray(Qn)&&Qn.length>0?Math.max((null===(I=null==j?void 0:j.variants)||void 0===I?void 0:I.length)||0,Qn.length):null===(x=null==j?void 0:j.variants)||void 0===x?void 0:x.length:void 0,tiers:ge,authToken:(null==Fi?void 0:Fi.accessToken)||""},Nr=rr(nt),Or={ruleTitle:Ln,scopeData:Q,variantsByTier:Array.from(Mn.keys()).reduce(function(n,t){var i=Mn.get(t)||new Map,r=Fn.get(t)||new Map,a=Un.get(t)||new Map,o=Bn.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=(Qn||[])[n]||{};console.log("Original item for tier",t,"index",n,":",d);var c={label:"",isDefault:!1};if(d.is_variant&&!T(d.variant_type))c={label:"",isDefault:!1};else if(q&&q.length>0){c=pr(q,n,"variantType"),console.log("Found matching variant at index",n,":",c);var _=q[n];if(_){if(!c.label){var v=_.variantType||"",p=T(v);c={label:"variant ".concat(n+1),isDefault:p}}if(_.variantId===Oi)(g=d.variant_type||(null==gt?void 0:gt.variant_type))&&(c=fr(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:rr(q),isDefault:!1},console.log("No match found, using getNextVariantType:",c)}else if(nt&&nt.length>0){if(c=pr(nt,n,"variant_type"),console.log("Found matching variant at index",n,":",c),Me.current){var f=nt[n];if((null==f?void 0:f.variant_id)===Vi||(null==f?void 0:f.variantId)===Vi)(g=d.variant_type||(null==gt?void 0:gt.variant_type))&&(c=fr(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:Nr,isDefault:T(g)}}console.log("Computed variant data for tier",t,"index",n,":",c);var w=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 :",w);var y="variant ".concat(l+1),m=r.get(n)||"";return{variantId:mt[n]||d.variant_id||d.variantId,variantType:y,isDefault:w,isModified:d.is_modified,tier:t,index:n,ruleDescription:m.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.__assign(e.__assign({},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.__assign(e.__assign({},n),{id:"split-".concat(n.id,"-").concat(i),text:t.trim()})}):[n]}),configData:i.get(n)||Tn,isReadOnly:d.is_readOnly||!1,is_variant:d.is_variant||!1,reasoning:{ruleDescription:lr(m),whenToApply:lr(d.wta),whenNotToApply:lr(d.wnta),configData:lr(d.action)}}}),n},{}),citation:qt,fieldCitations:Bt,citations:Ft};console.log("templateState",Or);var Rr={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;jn(i),ui(function(n){if(n.ruleTitle){var t=e.__assign({},n);return delete t.ruleTitle,t}return n})},setRuleDescription:function(e,n,t){return Bi(e,n,t)},addWhenToApply:function(e,n){return Ki(e,n)},removeWhenToApply:function(e,n,t){return Yi(e,n,t)},editWhenToApply:function(e,n,t,i){return Qi(e,n,t,i)},addWhenNotToApply:function(e,n){return zi(e,n)},removeWhenNotToApply:function(e,n,t){return Zi(e,n,t)},editWhenNotToApply:function(e,n,t,i){return $i(e,n,t,i)},addNewVariant:function(e){return Xi(e)},onScopeChange:nr,onConfigChange:function(e,n,t,i){return tr(e,n,t,i)}},Lr={},jr={};Mn.forEach(function(n,t){Lr[t]=new Map,jr[t]=new Map,n.forEach(function(n,i){Lr[t].set(i,[e.__assign({key:"order_rules",label:"Order"},n.order_rules),e.__assign({key:"advertiser_rules",label:"Advertiser"},n.advertiser_rules)]),jr[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 Dr=t.useMemo(function(){if(D){if(1===Q.tiers.length)return 0;var e=Q.tiers.findIndex(function(e){return e.toLowerCase()===D.toLowerCase()});return e>=0?e:0}},[D,Q.tiers]),qr=e.__assign(e.__assign({defaultOpen:!0,tierOptions:["Tier 1","Tier 2"],stationOptions:[{label:"Global Scope",value:"global"},{label:"Genre Scope",value:"genre"},{label:"Custom Scope",value:"custom"}],separationItemsByTier:Lr,togglesByTier:jr,highlights:xt,highlightedIds:Nt,openSections:Cn,setOpenSections:En,setSendMessageInChat:pt,isAiStreaming:Qt,defaultTierOpen:Dr,defaultVariantOpen:Ye?void 0:dt,autoScrollVariantIndex:Ye?void 0:dt,activeVariantAccordionIndex:Ye?void 0:dt,setActiveVariantAccordionIndex:function(e){ct(e),null!=e&&setTimeout(function(){Qe(!1)},100)},validationErrors:si,activeEditId:on,setActiveEditId:ln,pendingEditId:un,setPendingEditId:dn,conflictReason:ci,usedFor:j||q?"Edit":"Create"},An),{scrollTrigger:Lt});console.log(dt,"editVariantIndex checking"),t.useEffect(function(){},[E]),t.useEffect(function(){if(!Qt&&rt&&!!(!j&&!q)){var n=e.__spreadArray([],Qn,!0).reverse().findIndex(function(e){return"variant"===e.action||e.is_variant});-1===n||Qn.length,-1!==n&&(console.log("Post-stream: Focusing new variant at index",n),ct(n))}},[Qt,rt]);var Vr=function(){ce.current&&(clearTimeout(ce.current),ce.current=null),Me.current=!1,N(),ir()},Pr=function(){var e={};Ln.trim()||(e.ruleTitle="Rule Title is required"),Q.station||(e.station="Station Rule Set is required"),Q.tiers&&0!==Q.tiers.length||(e.tiers="At least one tier must be selected");return Q.tiers.map(function(e){return e.toLowerCase().replace(/ /g,"_")}).forEach(function(n){var t=Fn.get(n),i=Un.get(n),r=Mn.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 Fr(n,t,i){var r,a,l,s,u,d;return void 0===i&&(i=!1),e.__awaiter(this,void 0,void 0,function(){var c,_,v,p,f,g,w,y,m,h,b,S,k,M,I,x,C,E,N,O,j,D,q,V;return e.__generator(this,function(P){switch(P.label){case 0:if(c=n.question_id,_=(null==n?void 0:n.variant_id)||null,tn.current&&gn.current===c)return console.log("[handleAILoadAction] Already fetching question ID, skipping duplicate request:",c),[2];if(pn.current===c&&!i)return console.log("[handleAILoadAction] Question ID unchanged, updating variant focus only:",_),vn(_),_?(-1!==(v=(Qn||[]).findIndex(function(e){return e.is_new_variant}))&&(oi(!0),Ti("Removing new variant..."),Ii("Please wait while we remove new variant.")),zn(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(){ct(t),jt(function(e){return e+1}),Xt.current=t},0),n}),-1!==v&&((p=function(e){e(function(e){var n=new Map;return e.forEach(function(e,t){var i=new Map(e);i.delete(v);var r=new Map,a=0;i.forEach(function(e){r.set(a,e),a++}),n.set(t,r)}),n})})(In),p(Gn),p(Hn),p(Kn),ht(function(n){var t=e.__spreadArray([],n,!0);return t.length>v&&t.splice(v,1),t})),!1===tn.current&&(tn.current=!0,-1!==v&&(null===(r=ei.current)||void 0===r||r.show({severity:"success",summary:"Success",detail:"New variant removed successfully because you selected to edit an existing variant",life:4e3}))),Qe(!1)):(console.log("lastLoadedQuestionIdRef.current in else",pn.current),null===pn.current&&(oi(!0),Ti("Adding new variant..."),Ii("Please wait while we add new variant."))),[2];console.log("User Action: fetching fresh variant info for question",c),rn.current.clear(),rn.current.add(c),oi(!0),Ti("Loading variants..."),console.log("reaching here in load and edit"),Ii("Please wait while we fetch the latest variant data."),tn.current=!0,gn.current=c,P.label=1;case 1:return P.trys.push([1,5,6,10]),f=Date.now(),[4,o.fetchRulesByQuestionId(c,(null==L?void 0:L.ruleSetId)||"")];case 2:return g=P.sent(),(w=Date.now()-f)<3e3?[4,new Promise(function(e){return setTimeout(e,3e3-w)})]:[3,4];case 3:P.sent(),P.label=4;case 4:return 0===(y=(null===(a=null==g?void 0:g.data)||void 0===a?void 0:a.variants)||[]).length?(console.warn("No variants found for question_id",c),oi(!1),Ti(""),null===(l=ei.current)||void 0===l||l.show({severity:"error",summary:"Error",detail:"No variants found for this question.",life:3e3}),[2]):(Me.current=!0,tn.current=!0,m=(null===(s=null==g?void 0:g.data)||void 0===s?void 0:s.ruleTitle)||"",jn(m),h=null===(u=null==g?void 0:g.data)||void 0===u?void 0:u.tier,b="tier_1",S="Tier 1",k="1",h&&((M=String(h).match(/(\d+)/))?(I=M[1],k=I,b="tier_".concat(I),S="Tier ".concat(I)):(b=String(h).toLowerCase().trim().replace(/ /g,"_"),S=b.replace(/_/g," ").replace(/\b\w/g,function(e){return e.toUpperCase()}),k=b.includes("2")?"2":"1")),console.log("[handleAILoadAction] Detected Tier: ".concat(S," (ID: ").concat(k,", Key: ").concat(b,")")),z({station:R||"global",tiers:[S]}),x=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,_=e.scheduling_config||{};l.set(n,{order_rules:{enabled:!!_.order_global_min_separation_seconds||!!(null===(t=_.order_rules)||void 0===t?void 0:t.global_min_separation_seconds),global_min_separation_seconds:Math.floor((_.order_global_min_separation_seconds||(null===(i=_.order_rules)||void 0===i?void 0:i.global_min_separation_seconds)||0)/60)},advertiser_rules:{enabled:!!_.advertiser_global_min_separation_seconds||!!(null===(r=_.advertiser_rules)||void 0===r?void 0:r.global_min_separation_seconds),global_min_separation_seconds:Math.floor((_.advertiser_global_min_separation_seconds||(null===(a=_.advertiser_rules)||void 0===a?void 0:a.global_min_separation_seconds)||0)/60)},inventory_rules:{respect_inventory_code:!!_.respect_inventory_code||!!(null===(o=_.inventory_rules)||void 0===o?void 0:o.respect_inventory_code)},break_code_rules:{respect_break_code:!!_.respect_break_code||!!(null===(c=_.break_code_rules)||void 0===c?void 0:c.respect_break_code)},is_default_enabled:T(e.variantType||e.variant_type)}),s.set(n,A(e.rule_description||""));var v=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,v);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,m,b,k,c,_),C=x.transformedVariants,E=x.tierConfigMap,N=x.tierDescMap,O=x.tierWtaMap,j=x.tierWntaMap,Xn(function(e){var n=new Map(e);return n.set(b,JSON.parse(JSON.stringify(C))),n}),zn(function(n){var t=(Array.isArray(n)?n:[]).filter(function(e){return"copy"===e.action||e.tier_id&&e.tier_id!==k});return e.__spreadArray(e.__spreadArray([],t,!0),C,!0)}),tt(function(n){var t=(Array.isArray(n)?n:[]).filter(function(e){return"copy"===e.action||e.tier_id&&e.tier_id!==k});return e.__spreadArray(e.__spreadArray([],t,!0),C,!0)}),nn(!0),pn.current=c,vn(_),D=0,_&&-1!==(q=C.findIndex(function(e){return e.variant_id===_}))&&(D=q),ct(D),jt(function(e){return e+1}),Xt.current=D,Qe(!1),In(function(e){var n=new Map(e);return n.set(b,E),n}),Gn(function(e){var n=new Map(e);return n.set(b,N),n}),Hn(function(e){var n=new Map(e);return n.set(b,O),n}),Kn(function(e){var n=new Map(e);return n.set(b,j),n}),ui({}),[3,10]);case 5:return V=P.sent(),console.error("Failed to fetch variants by question ID:",V),null===(d=ei.current)||void 0===d||d.show({severity:"error",summary:"Error",detail:"Failed to fetch variants. Please try again.",life:3e3}),[3,10];case 6:return tn.current=!1,oi(!1),Ti(""),Ii(""),(null==n?void 0:n.is_interpretation_ready)&&(null==n?void 0:n.question_id)&&pn.current&&_n?(console.log("inside edit variant flow",pn.current,_n),zn(function(n){if(!Array.isArray(n))return n;var i=n.map(function(n){return(null==n?void 0:n.variant_id)===_n?e.__assign(e.__assign({},n),t):n}),r=n.findIndex(function(e){return(null==e?void 0:e.variant_id)===_n});return console.log(r,"targetIndexif"),-1!==r&&setTimeout(function(){console.log("targetIndex",r),ct(r),jt(function(e){return e+1}),Xt.current=r},0),i}),[3,9]):[3,7];case 7:return(null==n?void 0:n.is_interpretation_ready)&&(null==n?void 0:n.question_id)&&pn.current&&!_n?(console.log("inside add new variant flow",pn.current,_n),oi(!0),Ti("Adding new variant..."),Ii("Please wait while we add new variant."),[4,new Promise(function(e){return setTimeout(e,3e3)})]):[3,9];case 8:P.sent(),oi(!1),Ti(""),Ii(""),zn(function(n){var i;if(Array.isArray(n)){var r=n.findIndex(function(e){return!0===e.is_new_variant});if(-1!==r)setTimeout(function(){ct(r),jt(function(e){return e+1}),Xt.current=r},0),i=n.map(function(n,i){return i===r?e.__assign(e.__assign(e.__assign({},n),t),{is_new_variant:!0,is_variant:!0}):n});else{var a=n.length;setTimeout(function(){ct(a),jt(function(e){return e+1}),Xt.current=a},0),i=e.__spreadArray(e.__spreadArray([],n,!0),[e.__assign(e.__assign({},t),{is_new_variant:!0,is_variant:!0})],!1)}}else setTimeout(function(){ct(0),jt(0),Xt.current=0},0),i=[e.__assign(e.__assign({},t),{is_new_variant:!0})];return mn.current=i,i}),P.label=9;case 9:return[7];case 10:return[2]}})})}var Gr;return console.log("RuleSet in render",L),n.jsxs(n.Fragment,{children:[n.jsx(r.Toast,{ref:ei}),n.jsx(d.default,{open:E,chatAssistantName:Sn.ASSISTANT_NAME,organizationName:Sn.ORGANIZATION_NAME,baseUrl:Sn.BASE_URL,baseWebsocketUrl:Sn.BASE_WEBSOCKET_URL,closeFunction:Vr,ThinkingBulbIconComponent:n.jsx(y,{}),customSections:n.jsx(n.Fragment,{}),customMetaData:Er,chatTitle:j?Sn.CHAT_TITLE_EDIT.replace("<scope>",(null==L?void 0:L.ruleSetName)||""):Sn.CHAT_TITLE.replace("<scope>",(null==L?void 0:L.ruleSetName)||""),formTitle:Sn.FORM_TITLE,showSavedMessage:!1,savedMessage:re,isError:ue,errorMessage:oe,isSaving:ve,onSave:function(e){console.log("Save this Learning",e);var n=Pr();if(Object.keys(n).length>0)return console.log("validation errors",n),void ui(n);pe(!0),de(!1),le("")},showSaveWithoutValidation:!1,onSaveWithoutValidation:function(){return e.__awaiter(void 0,void 0,void 0,function(){var n,t,i,r,a,l,s,u,d;return e.__generator(this,function(c){switch(c.label){case 0:return n=Pr(),Object.keys(n).length>0?(ui(n),[2]):(console.log("✅ Bypass Save: Initiated"),j||q?[4,yr()]:[3,2]);case 1:return c.sent(),[3,11];case 2:return!0!==Me.current?[3,4]:[4,mr()];case 3:return c.sent(),[3,11];case 4:c.trys.push([4,10,,11]),X(S),t=new Map,i=function(n){var i,r,a,l,s,u;return e.__generator(this,function(e){switch(e.label){case 0:if(i=n.toLowerCase().replace(/ /g,"_"),r=ge.find(function(e){return e.tier_name.toLowerCase().replace(/ /g,"_")===i||e.tier_name.toLowerCase()===i.replace(/_/g,"")}),!(a=null==r?void 0:r.tier_id))return t.set(i,null),[2,"continue"];l={question:Ln,orgName:Sn.ORGANIZATION_NAME,scope_id:(null==L?void 0:L.ruleSetId)||"",tier_id:a},e.label=1;case 1:return e.trys.push([1,3,,4]),[4,o.saveInstantLearningQuestion(l)];case 2:return s=e.sent(),t.set(i,(null===(d=null==s?void 0:s.data)||void 0===d?void 0:d.id)||null),[3,4];case 3:return u=e.sent(),console.error("❌ Bypass Save: Error saving question for ".concat(n,":"),u),t.set(i,null),[3,4];case 4:return[2]}})},r=0,a=Q.tiers,c.label=5;case 5:return r<a.length?(l=a[r],[5,i(l)]):[3,8];case 6:c.sent(),c.label=7;case 7:return r++,[3,5];case 8:return[4,wr(t,!0)];case 9:return c.sent(),[3,11];case 10:return s=c.sent(),X(b),u=new Map,Q.tiers.forEach(function(e){u.set(e.toLowerCase().replace(/ /g,"_"),null)}),wr(u,!0),console.error("❌ Bypass Save: Error",s),[3,11];case 11:return[2]}})})},headerMessageHandlers:or,aiResponse:Qn,setAIResponse:zn,width:"90vw",height:"90vh",sendMessageInChat:vt,template:c.TemplateList.CreateRule,isLoading:$===S,templateProps:{state:Or,handlers:Rr,uiState:qr},setSendMessageInChat:pt,onResetChat:function(){ir()},onResetRequest:function(){ii(!0)},isFormDirty:function(){return""!==Ln.trim()||""!==Q.station||Q.tiers.length>0||Array.from(Fn.values()).some(function(e){return Array.from(e.values()).some(function(e){return""!==e.trim()})})||Array.from(Un.values()).some(function(e){return Array.from(e.values()).some(function(e){return e.length>0})})||Array.from(Bn.values()).some(function(e){return Array.from(e.values()).some(function(e){return e.length>0})})||Mn.size>0||qn.size>0},initialChatMessage:j?(Gr=j.ruleTitle||"this rule",null===(C=null==q?void 0:q[null!=V?V:0])||void 0===C||C.is_user_accepted_risk,'<p><span>Welcome back! 👋</span>\n <span>I see you want to edit <strong>"'.concat(Gr,'."</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!=B?B:Sn.INITIAL_CHAT_MESSAGE,validateCustom:function(){if($===h||ne)return!1;if(!Ln||""===Ln.trim())return!1;if(null!==on)return!1;if(!Q.station||""===Q.station.trim())return!1;var e=Q.tiers&&Q.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=Fn.get(r),o=Un.get(r),l=Mn.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 _=null==o?void 0:o.get(d);if(!(null==_?void 0:_.some(function(e){return e.text&&""!==e.text.trim()})))return!1}}return!(!Mn||0===Mn.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})})})})(Un)&&!n(Bn)&&!Ne)},setCitations:Gt,isLocked:!0,textareaPlaceholder:"Tell me more about this learning..",saveButtonConfig:{label:j?"Save Changes":"Save Learning",loadingLabel:n.jsxs("span",e.__assign({style:{display:"flex",gap:"5px",alignItems:"center"}},{children:[n.jsx(i.Loader,{size:20,color:"white",className:"animate-spin"}),n.jsx("span",{children:" Saving Changes..."})]}))},setCurrentRequestId:Ht,isAiStreaming:Qt,setIsAiStreaming:zt,showConfirmReset:ti,setShowConfirmReset:ii,confirmReset:function(){ir(),ii(!1),Vr()},isLoadingVariants:ai,mainText:Ai,subText:Mi,proposedRule:De,isFetchingComparison:Wi,handleOpenComparison:ar,showComparison:hi,setShowComparison:bi,variants:Pe,onComparisonLinkClick:Hi,targetComparisonVariantId:Je,highlightedComparisonField:We,onAddAsVariant:function(){bi(!1)},isCopyEnabled:!0,onSubmitFeedback:function(n){return e.__awaiter(void 0,void 0,void 0,function(){var t,i,r,a,l;return e.__generator(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),t=e.__assign({user_id:null!==(r=null==Fi?void 0:Fi._id)&&void 0!==r?r:"",user_name:null!==(a=null==Fi?void 0:Fi.firstname)&&void 0!==a?a:"",user_email:null!==(l=null==Fi?void 0:Fi.email)&&void 0!==l?l:"",assistant_name:Sn.ASSISTANT_NAME},n),[4,o.submitChatFeedback(t)];case 1:return s.sent(),[3,3];case 2:throw i=s.sent(),console.error("Failed to submit chat feedback",i),i;case 3:return[2]}})})},handleGlobalClickCapture:function(e){null!==on&&(e.target.closest('[data-edit-id="'.concat(on,'"]'))||(e.preventDefault(),e.stopPropagation(),dn(on)))},isGlobalEditActive:null!==on,initialDraftMessage:J?W:"",socketTimeOutInMilliSeconds:Sn.SOCKET_TIMEOUT})]})},exports.filterAgentText=A;
|
|
2
2
|
//# sourceMappingURL=InstantLearningModal.js.map
|