File: /home/pclast/public_html/wp-content/plugins/zhaket-updater/assets/admin/ai/ai-modal.min.js
!function(e){"use strict";function t(t,n){return(e.zhaketAIConfig&&e.zhaketAIConfig.lang||{})[t]||n||t}function n(n){const a=e.zhaketAIConfig||{};return n.replace(/\$\{([^}]+)\}/g,(n,o)=>{try{const i=o.trim(),l=i.match(/zhAiGetString\(['"]([^'"]+)['"](?:,\s*['"]([^'"]+)['"])?\)/);if(l)return t(l[1],l[2]);if("config"===i)return JSON.stringify(a);const s=i.replace(/^(config|window\.zhaketAIConfig)\.?/,"");if(s!==i){const t=s.split(".").reduce((e,t)=>e&&e[t],e.zhaketAIConfig||{});return void 0!==t?t:n}return n}catch(e){return console.warn("Error processing template variable:",o,e),n}})}const a="zhaket-ai-modal-overlay",o={"gpt-5":t("modelGpt5","GPT-5 (تحلیلی)"),"gpt-4.1":t("modelGpt41","GPT-4.1 (تحلیلی)"),"gpt-4o-mini":t("modelGpt4oMini","GPT-4o mini (بصرفه)")},i={"dall-e-3":t("modelDallE3","OpenAI dall 3 (رایج ولی گران)"),"dall-e-2":t("modelDallE2","OpenAI dall 2 (استاندارد و به صرفه)"),"gpt-image-1":t("modelGptImage1","OpenAI flagship (کیفیت و قیمت بالا)")},l={photography:t("typePhotography","Photography"),cartoon:t("typeCartoon","Cartoon"),portrait:t("typePortrait","Portrait"),realistic:t("typeRealistic","Realistic"),abstract:t("typeAbstract","Abstract"),illustration:t("typeIllustration","Illustration"),"3d":t("type3D","3D"),sketch:t("typeSketch","Sketch"),watercolor:t("typeWatercolor","Watercolor"),"oil-painting":t("typeOilPainting","Oil Painting")},s={"":t("toneDefault","Default"),conversational:t("toneConversational","Conversational"),friendly:t("toneFriendly","Friendly"),formal:t("toneFormal","Formal"),professional:t("toneProfessional","Professional"),casual:t("toneCasual","Casual"),humorous:t("toneHumorous","Humorous"),serious:t("toneSerious","Serious"),persuasive:t("tonePersuasive","Persuasive")};e.ZhaketAIModal=class{constructor(e={}){this.config={restUrl:e.restUrl||"/wp-json/zhaket-ai/v1/generate",nonce:e.nonce||"",textModels:e.textModels||o,imageModels:e.imageModels||i,imageTypes:e.imageTypes||l,tones:e.tones||s,cssUrl:e.cssUrl||"",htmlUrl:e.htmlUrl||"",loginHtmlUrl:e.loginHtmlUrl||"",...e},this.isOpen=!1,this.currentType="text",this.callback=null,this.pendingCallback=null,this.streamingController=null,this.init()}async init(){try{this.config.cssUrl&&await(e=this.config.cssUrl,new Promise((t,n)=>{if(document.querySelector(`link[href="${e}"]`))return void t();const a=document.createElement("link");a.rel="stylesheet",a.href=e,a.onload=t,a.onerror=n,document.head.appendChild(a)})),this.config.htmlUrl&&await function(e){return fetch(e).then(e=>e.text()).then(e=>{if(!document.getElementById(a)){const t=n(e);document.body.insertAdjacentHTML("beforeend",t)}})}(this.config.htmlUrl),"loading"===document.readyState&&await new Promise(e=>document.addEventListener("DOMContentLoaded",e)),setTimeout(()=>{this.setupEventListeners(),this.populateModelOptions(),this.populateImageTypeOptions(),this.populateToneOptions(),this.updateChargeDisplay(),this.initCustomSelects()},100)}catch(e){console.error("Error initializing AI Modal:",e)}var e}setupEventListeners(){const t=document.getElementById(a);if(!t)return;if("true"===t.dataset.listenersAttached)return;const n=t.querySelector(".zhaket-ai-modal-close"),o=t.querySelector(".zhaket-ai-btn-cancel"),i=document.getElementById("zhaket-ai-modal-form"),l=document.getElementById("zhaket-ai-advanced-toggle");if(!(n&&o&&i&&l))return;this.boundClose=()=>this.close(),this.boundHandleSubmit=e=>{e.preventDefault(),this.handleSubmit()},this.boundHandleAdvancedToggle=()=>{const e=document.getElementById("zhaket-ai-advanced-options"),t="none"!==e.style.display;e.style.display=t?"none":"block",l.classList.toggle("expanded",!t)},this.boundHandleOverlayClick=e=>{e.target===t&&this.close()},t.addEventListener("click",this.boundHandleOverlayClick),n.addEventListener("click",this.boundClose),o.addEventListener("click",this.boundClose),l.addEventListener("click",this.boundHandleAdvancedToggle);const s=t.querySelector('[data-select-id="zhaket-ai-dimensions"]');if(s&&"true"!==s.dataset.dimensionsInitialized){const e=s.querySelector(".custom-select-list"),t=s.querySelector(".custom-select-trigger"),n=s.querySelector('input[type="hidden"]'),a=document.getElementById("zhaket-ai-custom-dimensions"),o=document.getElementById("zhaket-ai-width"),i=document.getElementById("zhaket-ai-height");e&&t&&n&&(e.addEventListener("click",l=>{const r=l.target.closest(".custom-select-option");if(!r)return;l.stopPropagation();const c=r.dataset.value,d=r.querySelector("div")?.textContent||r.textContent;if(t.dataset.value=c,t.querySelector(".custom-select-text").textContent=d,n.value=c,"custom"===c)a&&(a.style.display="flex",s.style.display="none");else{a&&(a.style.display="none");const e=c.split("x");o&&e[0]&&(o.value=e[0]),i&&e[1]&&(i.value=e[1])}e.style.display="none",e.querySelectorAll(".custom-select-option").forEach(e=>e.classList.remove("active")),r.classList.add("active")}),s.dataset.dimensionsInitialized="true")}i.addEventListener("submit",this.boundHandleSubmit),t.dataset.listenersAttached="true",e._zhaketAIEscapeHandler||(e._zhaketAIEscapeHandler=t=>{if("Escape"===t.key){const t=document.getElementById("zhaket-ai-login-modal");if(t&&"none"!==t.style.display)return t.style.display="none",void(document.body.style.overflow="");const n=document.getElementById(a);if(n&&"none"!==n.style.display){const t=n._zhaketAIModalInstance||e.zhaketAIModalInstance;t&&t.isOpen&&t.close()}}},document.addEventListener("keydown",e._zhaketAIEscapeHandler)),t._zhaketAIModalInstance=this}createSelectOption(e,t){const n=document.createElement("li");n.className="custom-select-option flex",n.dataset.value=e;const a=document.createElement("div");return a.className="hover:bg-[#FFF5E6] group transition-all duration-300 w-full justify-start text-[#424244] text-[13px] px-4 py-[9px] rounded cursor-pointer",a.textContent=t,n.appendChild(a),n}populateSelectList(e,t,n=!1){const a=document.getElementById(e);if(!a)return null;a.innerHTML="",Object.entries(t).forEach(([e,t])=>{const o=n?t:e;a.appendChild(this.createSelectOption(o,t))});const o=a.closest(".custom-select-wrapper");if(o){const e=o.querySelector(".custom-select-trigger"),t=o.querySelector('input[type="hidden"]');e&&t&&this.attachListDelegation(a,e,t)}return o}populateModelOptions(){this.populateSelectList("zhaket-ai-text-model-list",this.config.textModels),this.populateSelectList("zhaket-ai-image-model-list",this.config.imageModels)}populateSelectListWithUL(e,t,n=!1){const a=document.getElementById(e);if(!a)return null;let o=a.classList.contains("custom-select-list")?a:a.querySelector(".custom-select-list");o||(o=a.querySelector("ul")),o?(o.classList.contains("custom-select-list")||o.classList.add("custom-select-list"),o.innerHTML=""):(o=document.createElement("ul"),o.className="custom-select-list flex flex-col [&>*]:flex [&>*]:rounded-sm [&>*]:items-stretch [&>*]:cursor-pointer [&>*]:!m-0 p-2",a.appendChild(o));const i=Object.entries(t);let l="",s="";i.forEach(([e,t],a)=>{const i=t,r=this.createSelectOption(i,t);o.appendChild(r),n&&0===a&&(l=e,s=t,r.classList.add("active"))});const r=a.closest(".custom-select-wrapper");if(r){const e=r.querySelector(".custom-select-trigger"),t=r.querySelector('input[type="hidden"]');e&&t&&(n&&l&&s&&(e.dataset.value=l,e.querySelector(".custom-select-text").textContent=s,t.value=l),this.attachListDelegation(o,e,t))}return r}populateImageTypeOptions(){this.populateSelectListWithUL("zhaket-ai-image-type-list",this.config.imageTypes,!0)}populateToneOptions(){this.populateSelectListWithUL("zhaket-ai-tone-list",this.config.tones)}initCustomSelects(){document.querySelectorAll(".custom-select-wrapper").forEach(e=>{const t=e.querySelector(".custom-select-trigger"),n=e.querySelector(".custom-select-list"),a=e.querySelector('input[type="hidden"]');t&&n&&a&&("true"!==e.dataset.triggerInitialized?(t.addEventListener("click",e=>{e.stopPropagation();const t="none"!==n.style.display;document.querySelectorAll(".custom-select-list").forEach(e=>{e!==n&&(e.style.display="none")}),n.style.display=t?"none":"flex"}),this.attachListDelegation(n,t,a),e.dataset.triggerInitialized="true",e.dataset.listInitialized="true"):"true"!==e.dataset.listInitialized&&(this.attachListDelegation(n,t,a),e.dataset.listInitialized="true"))}),e._zhaketAICustomSelectClickHandler||(e._zhaketAICustomSelectClickHandler=e=>{document.querySelectorAll(".custom-select-list").forEach(t=>{t.closest(".custom-select-wrapper")?.contains(e.target)||(t.style.display="none")})},document.addEventListener("click",e._zhaketAICustomSelectClickHandler))}extractCallbackData(e){return{nonce:e.data?.nonce||null,content:e.data?.content||e.data?.text||e.content||e.text||"",image_url:e.data?.image_url||e.data?.image||e.image_url||e.image||"",text_model:e.data?.text_model||e.text_model||"",image_model:e.data?.image_model||e.image_model||""}}attachListDelegation(e,t,n){"true"!==e.dataset.delegationAttached&&(e.addEventListener("click",a=>{const o=a.target.closest(".custom-select-option");if(!o)return;a.stopPropagation();const i=o.dataset.value,l=o.querySelector("div")?.textContent||o.textContent;t.dataset.value=i,t.querySelector(".custom-select-text").textContent=l,n.value=i,e.style.display="none",e.querySelectorAll(".custom-select-option").forEach(e=>e.classList.remove("active")),o.classList.add("active")}),e.dataset.delegationAttached="true")}async showLoginRequiredModal(){let e=document.getElementById("zhaket-ai-login-modal");if(!e){if(this.config.loginHtmlUrl)try{const t=n(await fetch(this.config.loginHtmlUrl).then(e=>e.text()));document.body.insertAdjacentHTML("beforeend",t),e=document.getElementById("zhaket-ai-login-modal")}catch(t){console.error("Error loading login modal HTML:",t),e=document.getElementById("zhaket-ai-login-modal")}else e=document.getElementById("zhaket-ai-login-modal");if(!e)return void console.error("Failed to create login modal");this.setupLoginModalListeners(e)}e.style.display="flex",document.body.style.overflow="hidden"}setupLoginModalListeners(e){const t=e.querySelector(".zhaket-ai-modal-close"),n=e.querySelector(".zhaket-ai-btn-cancel"),a=()=>{e.style.display="none",document.body.style.overflow=""};t&&t.addEventListener("click",a),n&&n.addEventListener("click",a),e.addEventListener("click",t=>{t.target===e&&a()}),this.initLoginModal(e)}initLoginModal(n){const a={digits:["","","","","",""],mobile:null,zhaket_updater:e.zhaketAIConfig||{},loginRequestError:null,showLoginLoading:!1,codeLoading:!1,getCode:!1,resendTimer:120,timerId:null,resendWaiting:!1},o=n.querySelector("#zhaket-ai-login-form"),i=n.querySelector("#zhaket-ai-mobile-input"),l=n.querySelector("#zhaket-ai-login-btn"),s=n.querySelector("#zhaket-ai-login-btn-text"),r=n.querySelector("#zhaket-ai-login-loading"),c=n.querySelector("#zhaket-ai-login-error"),d=n.querySelector("#zhaket-ai-code-section"),u=n.querySelector("#zhaket-ai-mobile-section"),m=n.querySelector("#zhaket-ai-validate-btn"),g=n.querySelector("#zhaket-ai-validate-btn-text"),h=n.querySelector("#zhaket-ai-code-loading"),p=n.querySelector("#zhaket-ai-resend-btn"),y=n.querySelector("#zhaket-ai-resend-text"),f=n.querySelector("#zhaket-ai-code-inputs-container");let k=[];if(o&&a.zhaket_updater.ajaxUrl){let e=o.querySelector('input[name="nonce"]');e||(e=document.createElement("input"),e.type="hidden",e.name="nonce",e.value=a.zhaket_updater.ajaxNonce||"",o.appendChild(e));let t=o.querySelector('input[name="action"]');t||(t=document.createElement("input"),t.type="hidden",t.name="action",t.value="zhaket_ai_login",o.appendChild(t)),i&&!i.name&&(i.name="mobile")}const v=e.zhaketAIConfig&&e.zhaketAIConfig.imagePath||"";function z(e,t){"Enter"===e.key&&(e.preventDefault(),a.getCode&&m&&S(e))}function I(e,t){let n=e.target.value.replace(/\D/g,"");n.length>1&&(n=n.charAt(0)),a.digits[t]=n,e.target.value=n,1===n.length&&t<a.digits.length-1&&setTimeout(()=>{k[t+1]&&k[t+1].focus()},0)}function E(e){e.preventDefault(),a.getCode||a.showLoginLoading||a.resendWaiting||(i&&(a.mobile=i.value),a.showLoginLoading=!0,a.loginRequestError="",L(),async function(){try{const e=new URLSearchParams;e.append("nonce",a.zhaket_updater.ajaxNonce||""),e.append("action","zhaket_ai_login"),e.append("mobile",a.mobile||"");const n=await fetch(a.zhaket_updater.ajaxUrl||"",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},credentials:"include",body:e}),o=await n.json();o.success?(a.getCode=!0,function(){a.resendTimer=120,a.resendWaiting=!0,a.timerId&&clearInterval(a.timerId);a.timerId=setInterval(()=>{a.resendTimer--,a.resendTimer<=0&&(a.resendWaiting=!1,clearInterval(a.timerId),a.timerId=null),x()},1e3),x()}(),L()):!1===o.success&&C(o.data||t("errorOccurredCheckConsole","Error occurred. Please check console."))}catch(e){C(t("errorOccurredCheckConsole","Error occurred. Please check console.")),console.error("Error fetching logs:",e)}a.showLoginLoading=!1,L()}())}function S(n){if(n.preventDefault(),!a.getCode)return;a.loginRequestError="",L();if(!a.digits.every(e=>1===e.length))return void C(t("pleaseFillAllInput","Please fill all fields"));a.codeLoading=!0,L();!async function(n){try{const o=new URLSearchParams;o.append("nonce",a.zhaket_updater.ajaxNonce||""),o.append("action","zhaket_ai_validate_code"),o.append("mobile",a.mobile||""),o.append("code",n);const i=await fetch(a.zhaket_updater.ajaxUrl||"",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},credentials:"include",body:o}),l=await i.json();l.success?e.location.reload():!1===l.success&&C(l.data||t("errorOccurredCheckConsole","Error occurred. Please check console."))}catch(e){C(t("errorOccurredCheckConsole","Error occurred. Please check console.")),console.error("Error fetching logs:",e)}a.codeLoading=!1,L()}(a.digits.join(""))}function C(e){if("undefined"!=typeof Swal){const t=v+"toast-warning.svg",n=v+"toast-close.svg";Swal.fire({text:e,icon:"error",toast:!0,position:"bottom",showConfirmButton:!1,timer:3e3,color:"#ffffff",timerProgressBar:!0,iconHtml:`<img src="${t}" style="width: 20px; height: 20px;">`,closeButtonHtml:`<img src="${n}">`,showCloseButton:!0,width:"fit-content",customClass:{}})}else alert(e)}function x(){p&&y&&(a.resendWaiting?(p.classList.add("cursor-wait"),y.textContent=t("sendCodeAgainIn","Send code again in")+" "+a.resendTimer+" "+t("second","seconds")):(p.classList.remove("cursor-wait"),y.textContent=t("sendAgain","Send again")))}function L(){c&&(c.textContent=a.loginRequestError||""),l&&(a.showLoginLoading?(l.classList.add("cursor-wait"),s&&(s.style.display="none"),r&&(r.style.display="block")):(l.classList.remove("cursor-wait"),s&&(s.style.display="inline"),r&&(r.style.display="none"))),m&&(a.codeLoading?(m.classList.add("cursor-wait"),g&&(g.style.display="none"),h&&(h.style.display="block")):(m.classList.remove("cursor-wait"),g&&(g.style.display="inline"),h&&(h.style.display="none"))),a.getCode?(u&&(u.style.display="none"),d&&(d.style.display="flex")):(u&&(u.style.display="flex"),d&&(d.style.display="none")),x()}n.querySelectorAll("[data-image]").forEach(e=>{const t=e.getAttribute("data-image");t&&(e.src=v+t)}),l&&l.addEventListener("click",E),i&&(i.addEventListener("keydown",e=>{"Enter"!==e.key||a.getCode||(e.preventDefault(),E(e))}),i.addEventListener("input",e=>{a.mobile=e.target.value})),m&&m.addEventListener("click",S),p&&p.addEventListener("click",function(e){if(e.preventDefault(),a.resendWaiting)return;E(e)}),function(){if(f){f.innerHTML="",k=[];for(let e=0;e<6;e++){const t=document.createElement("input");t.type="text",t.maxLength=1,t.inputMode="numeric",t.pattern="[0-9]*",t.autocomplete="one-time-code",t.className="flex w-full rounded-lg border border-gray-300 bg-white text-[#76767C] outline-hidden transition duration-100 focus:border-[#FF9606] focus:shadow-[0px_20px_60px_-15px_rgba(0,0,0,0.15)] focus:ring-[#FF9606] h-[48px] !w-[48px] text-2xl hiden-arrow justify-center items-center text-center font-medium zhaket-ai-code-input",t.dataset.index=e,t.value=a.digits[e]||"",t.addEventListener("input",t=>I(t,e)),t.addEventListener("keydown",e=>z(e)),t.addEventListener("paste",e=>e.preventDefault()),f.appendChild(t),k.push(t)}}}()}open(n="text",o=null,i=""){if(!("1"===(e.zhaketAIConfig&&e.zhaketAIConfig.isLogin)))return void this.showLoginRequiredModal();this.currentType=n,this.callback=o,this.pendingCallback=o,this.isOpen=!0;const l=document.getElementById(a);if(!l)return;const s=l.querySelector(".zhaket-ai-modal-title"),r=document.getElementById("zhaket-ai-prompt"),c=document.getElementById("zhaket-ai-text-model-group"),d=document.getElementById("zhaket-ai-image-model-group"),u=document.getElementById("zhaket-ai-tone-group"),m=document.getElementById("zhaket-ai-image-type-group"),g=(document.getElementById("zhaket-ai-dimensions-group"),document.getElementById("zhaket-ai-modal-form"));if(r&&r.setAttribute("data-selected",i),g&&(g._zhaketAICallback=o),!s||!r||!g)return;s.innerHTML=`<img src="${e?.zhaketAIConfig?.imagePath}zhaket-ai2.svg" >`+("image"===n?t("generateImageWithAi","Generate Image with AI"):t("generateTextWithAi","Generate Text with AI")),d&&(d.style.display="image"===n?"flex":"none"),c&&(c.style.display="image"===n?"none":"flex"),u&&(u.style.display="text"===n?"flex":"none"),m&&(m.style.display="image"===n?"flex":"none"),g.reset();const h=l.querySelector('[data-select-id="zhaket-ai-dimensions"]'),p=document.getElementById("zhaket-ai-custom-dimensions");if(h){const e=h.querySelector(".custom-select-trigger"),t=h.querySelector('input[type="hidden"]'),n=h.querySelector(".custom-select-list");if(e&&t&&(e.dataset.value="1024x1024",e.querySelector(".custom-select-text").textContent="1:1 (1024×1024)",t.value="1024x1024",p&&(p.style.display="none"),n)){n.querySelectorAll(".custom-select-option").forEach(e=>e.classList.remove("active"));const e=n.querySelector('.custom-select-option[data-value="1024x1024"]');e&&e.classList.add("active")}}const y=document.getElementById("zhaket-ai-width"),f=document.getElementById("zhaket-ai-height");if(y&&(y.value="1024"),f&&(f.value="1024"),"image"===n){const e=l.querySelector('[data-select-id="zhaket-ai-image-type"]');if(e){const t=e.querySelector(".custom-select-trigger"),n=e.querySelector('input[type="hidden"]'),a=document.getElementById("zhaket-ai-image-type-list");if(t&&n&&this.config.imageTypes){const e=Object.entries(this.config.imageTypes);if(e.length>0){const[o,i]=e[0];if(t.dataset.value=o,t.querySelector(".custom-select-text").textContent=i,n.value=o,a){const e=a.querySelector("ul");if(e){e.querySelectorAll(".custom-select-option").forEach(e=>e.classList.remove("active"));const t=e.querySelector(`.custom-select-option[data-value="${o}"]`);t&&t.classList.add("active")}}}}}}r.focus(),this.updateChargeDisplay(),l.style.display="flex",document.body.style.overflow="hidden"}updateChargeDisplay(){const t=document.getElementById("zhaket-ai-charge-display"),n=document.getElementById("zhaket-ai-charge-value");if(!t||!n)return;const a=e.zhaketAIConfig&&e.zhaketAIConfig.charge||"0";n.textContent=a,t.style.display="flex"}close(){this.streamingController&&(this.streamingController.abort(),this.streamingController=null),this.isOpen=!1;const e=document.getElementById(a);e&&(e.style.display="none"),document.body.style.overflow="",this.callback=null}async handleSubmit(){const n=document.getElementById("zhaket-ai-modal-form");if(!n)return;const a=n.querySelector(".zhaket-ai-cta-btn");if(a&&a.disabled)return;const o=n._zhaketAICallback||this.pendingCallback||this.callback,i=a?.querySelector(".btn-text"),l=a?.querySelector(".btn-loader"),s=document.getElementById("zhaket-ai-prompt"),r=document.getElementById("zhaket-ai-text-model"),c=document.getElementById("zhaket-ai-image-model"),d=document.getElementById("zhaket-ai-tone"),u=document.getElementById("zhaket-ai-image-type"),m=document.getElementById("zhaket-ai-width"),g=document.getElementById("zhaket-ai-height"),h=s?.getAttribute("data-selected"),p=s?.value.trim();if(!p)return void alert(t("enterPrompt","Please enter a prompt"));const y=document.getElementById("zhaket-ai-image-model-group"),f=document.getElementById("zhaket-ai-tone-group"),k=t=>{if(!t)return!1;const n=t.style.display,a=e.getComputedStyle(t).display;return"none"!==n&&"none"!==a},v=k(y),z=k(f);let I="text";I=v&&!z?"image":z&&!v?"text":this.currentType||"text";let E="1024",S="1024";const C=document.querySelector('[data-select-id="zhaket-ai-dimensions"]'),x=C?C.querySelector('input[type="hidden"]'):null;if("image"===I)if(x&&"custom"===x.value&&m&&g)E=m.value||"1024",S=g.value||"1024";else if(x&&x.value){const e=x.value.split("x");E=e[0]||"1024",S=e[1]||"1024"}const L=!1!==this.config.stream&&(!0===this.config.stream||e.zhaketAIConfig&&!1!==e.zhaketAIConfig.stream);if(a&&(a.disabled=!0,a.classList.add("cursor-wait")),i&&(i.style.display="none"),l){if("IMG"===l.tagName){const t=e.zhaketAIConfig&&e.zhaketAIConfig.imagePath||"",n=l.getAttribute("data-loader-img")||"spinner/white-loading.svg";l.src&&l.src!==e.location.href||(l.src=t+n)}l.style.display="inline-block"}const b={make_image:"image"===I,manual_prompt:p,additionalData:h,text_models:"image"===I?"":r?.value||"",image_models:"image"===I&&c?.value||"",auto_prompt:!1,tone:"image"===I?"":d?.value||"",image_type:"image"===I&&u?.value||"",width:E,height:S,stream:L?"true":"false"};try{this.streamingController=new AbortController;const e=await fetch(this.config.restUrl,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":this.config.nonce},body:JSON.stringify(b),credentials:"same-origin",signal:this.streamingController.signal});if(!e.ok)throw new Error(`HTTP error! status: ${e.status}`);const a=e.headers.get("content-type"),i=a&&a.includes("text/event-stream");if(L&&i)await this.handleStreamingResponse(e,o);else{const a=await e.json();if(a.success||a.data||a.content||a.image_url){const e=this.extractCallbackData(a);if(o&&"function"==typeof o)try{o(e)}catch(e){console.error("Error in callback:",e)}this.pendingCallback=null,n&&(n._zhaketAICallback=null),this.close()}else{const e=a.message||a.error||t("errorGeneratingContent","Error generating content. Please try again.");console.error("Request failed:",e,a),alert(e)}}}catch(e){"AbortError"!==e.name&&(console.error("AI Generation Error:",e),alert(t("networkError","Network error. Please check your connection and try again.")))}finally{a&&(a.disabled=!1,a.classList.remove("cursor-wait")),i&&(i.style.display="inline-block"),l&&(l.style.display="none"),this.streamingController=null}}async handleStreamingResponse(e,n=null){const a=n||this.callback,o=e.body.getReader(),i=new TextDecoder;let l="",s="",r="";this.showStreamingIndicator();try{for(;;){const{done:e,value:n}=await o.read();if(e)break;l+=i.decode(n,{stream:!0});const c=l.split("\n");l=c.pop()||"";for(const e of c)if(e.startsWith("data: "))try{const n=JSON.parse(e.slice(6));if("chunk"===n.type&&n.content)s+=n.content,this.updateStreamingIndicator(n.content);else{if("done"===n.type){n.content&&(s=n.content),n.image_url&&(r=n.image_url),a&&"function"==typeof a&&a(this.extractCallbackData({content:s,image_url:r,text_model:n.text_model,image_model:n.image_model})),this.pendingCallback=null;const e=document.getElementById("zhaket-ai-modal-form");return e&&(e._zhaketAICallback=null),this.hideStreamingIndicator(),void this.close()}if("error"===n.type)throw new Error(n.message||t("streamingError","Streaming error"))}}catch(e){console.error("Error parsing streaming data:",e)}}}catch(e){throw console.error("Streaming error:",e),this.hideStreamingIndicator(),e}}showStreamingIndicator(){let e=document.getElementById("zhaket-ai-streaming-indicator");if(!e){e=document.createElement("div"),e.id="zhaket-ai-streaming-indicator",e.className="zhaket-ai-streaming-indicator",e.innerHTML=`<span>${t("generating","Generating...")}</span><span class="streaming-text"></span>`;const n=document.getElementById("zhaket-ai-modal-form");n&&n.insertBefore(e,n.querySelector(".zhaket-ai-modal-footer"))}e.classList.add("active")}updateStreamingIndicator(e){const t=document.getElementById("zhaket-ai-streaming-indicator");if(t){const n=t.querySelector(".streaming-text");n&&(n.textContent+=e)}}hideStreamingIndicator(){const e=document.getElementById("zhaket-ai-streaming-indicator");e&&e.classList.remove("active")}}}(window);