@nice2dev/ui-ai 1.2.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,21 +1,21 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),l=require("react"),T=require("@nice2dev/ui-core"),Ma=require("@nice2dev/ui");class Ve{constructor(a={},i){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1,this.config={maxRequestsPerMinute:a.maxRequestsPerMinute??30,maxTokensPerSession:a.maxTokensPerSession??1e4,warnThresholdPercent:a.warnThresholdPercent??80},this.onWarning=i}canRequest(){return this.pruneOldTimestamps(),!(this.timestamps.length>=this.config.maxRequestsPerMinute||this.tokenCount>=this.config.maxTokensPerSession)}recordRequest(){return this.canRequest()?(this.timestamps.push(Date.now()),!0):!1}recordTokens(a){this.tokenCount+=a,this.checkWarning()}getStatus(){this.pruneOldTimestamps();const a=this.config.maxTokensPerSession>0?this.tokenCount/this.config.maxTokensPerSession*100:0,i=this.config.maxRequestsPerMinute>0?this.timestamps.length/this.config.maxRequestsPerMinute*100:0;return{requestsThisMinute:this.timestamps.length,tokensThisSession:this.tokenCount,isLimited:!this.canRequest(),isWarning:a>=this.config.warnThresholdPercent||i>=this.config.warnThresholdPercent}}reset(){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1}pruneOldTimestamps(){const a=Date.now()-6e4;this.timestamps=this.timestamps.filter(i=>i>a)}checkWarning(){var i;if(this.warningEmitted)return;this.getStatus().isWarning&&(this.warningEmitted=!0,(i=this.onWarning)==null||i.call(this))}}const Xe=l.createContext(null);function $a({config:t,rateLimits:a,enabled:i=!0,onRateLimitWarning:r,children:n}){const s=l.useRef(null);s.current||(s.current=new Ve(a,r));const o=l.useCallback(()=>s.current.getStatus(),[]),c=l.useMemo(()=>({config:t,enabled:i,rateLimiter:s.current,getRateLimitStatus:o}),[t,i,o]);return e.jsx(Xe.Provider,{value:c,children:n})}function ee(){return l.useContext(Xe)}async function*Qe(t,a){var s,o,c,m,p,u,v,w,A;const i=(s=t.body)==null?void 0:s.getReader();if(!i)throw new Error("Response body is not readable");const r=new TextDecoder;let n="";try{for(;!(a!=null&&a.aborted);){const{done:R,value:M}=await i.read();if(R)break;n+=r.decode(M,{stream:!0});const P=n.split(`
2
- `);n=P.pop()??"";for(const g of P){const d=g.trim();if(!(!d||d===":")){if(d.startsWith("data:")){const j=d.slice(5).trim();if(j==="[DONE]"){yield{token:"",done:!0};return}try{const y=JSON.parse(j),I=((m=(c=(o=y.choices)==null?void 0:o[0])==null?void 0:c.delta)==null?void 0:m.content)??"",b=((u=(p=y.choices)==null?void 0:p[0])==null?void 0:u.finish_reason)==="stop";(I||b)&&(yield{token:I,done:b,usage:y.usage})}catch{j&&(yield{token:j,done:!1})}continue}try{const j=JSON.parse(d),y=j.text??j.content??j.token??"";y&&(yield{token:y,done:!1})}catch{d&&(yield{token:d,done:!1})}}}}if(n.trim()){const R=n.trim();if(R.startsWith("data:")){const M=R.slice(5).trim();if(M&&M!=="[DONE]")try{const g=((A=(w=(v=JSON.parse(M).choices)==null?void 0:v[0])==null?void 0:w.delta)==null?void 0:A.content)??"";g&&(yield{token:g,done:!0})}catch{yield{token:M,done:!0}}}}}finally{i.releaseLock()}}async function Ze(t){var i,r,n,s;const a=await t.json();if((n=(r=(i=a.choices)==null?void 0:i[0])==null?void 0:r.message)!=null&&n.content)return{text:a.choices[0].message.content,usage:a.usage};if((s=a.message)!=null&&s.content)return{text:a.message.content};if(typeof a.text=="string")return{text:a.text};if(typeof a.content=="string")return{text:a.content};if(typeof a.response=="string")return{text:a.response};throw new Error("Unrecognized AI response format")}const se=new Map;function Be(t,a){const i=a?{...t,fieldValue:void 0,formContext:void 0}:t;return JSON.stringify(i)}function Pa(t,a){const i=[],r=a.systemPrompt??"You are a helpful assistant providing concise contextual hints for form fields. Keep responses short (1-3 sentences). Be specific and actionable.";i.push({role:"system",content:r});const n=[];if(t.fieldLabel&&n.push(`Field: "${t.fieldLabel}"`),t.fieldType&&n.push(`Type: ${t.fieldType}`),!a.privacyMode&&t.fieldValue!==void 0){const o=typeof t.fieldValue=="string"?t.fieldValue:JSON.stringify(t.fieldValue);n.push(`Current value: ${o}`)}t.validationRules&&Object.keys(t.validationRules).length>0&&n.push(`Validation: ${JSON.stringify(t.validationRules)}`),t.schema&&Object.keys(t.schema).length>0&&n.push(`Schema: ${JSON.stringify(t.schema)}`),!a.privacyMode&&t.formContext&&Object.keys(t.formContext).length>0&&n.push(`Form context: ${JSON.stringify(t.formContext)}`),t.customPrompt&&n.push(t.customPrompt);const s=n.length>0?`Provide a helpful hint for this field:
3
- ${n.join(`
4
- `)}`:"Provide a helpful suggestion.";return i.push({role:"user",content:s}),i}function Z(t={},a={}){t=t??{},a=a??{};const{debounceMs:i=500,disabled:r=!1}=a,n=ee(),[s,o]=l.useState(""),[c,m]=l.useState(!1),[p,u]=l.useState(null),[v,w]=l.useState(!1),A=l.useRef(null),R=l.useRef(0),M=l.useCallback(async()=>{var f,k,S;if(!n||!n.enabled||r)return;const{config:d,rateLimiter:j}=n;if(!j.recordRequest()){u("Rate limit exceeded. Please wait before requesting another hint.");return}const y=Be(t,d.privacyMode??!1),I=se.get(y);if(I){o(I),m(!1),u(null),w(!1);return}(f=A.current)==null||f.abort();const b=new AbortController;A.current=b,m(!0),u(null),o(""),w(!1);const h=Pa(t,d),_=d.stream!==!1;try{const N={"Content-Type":"application/json",...d.headers};d.apiKey&&(N.Authorization=`Bearer ${d.apiKey}`);const $=JSON.stringify({model:d.model??"gpt-3.5-turbo",messages:h,temperature:d.temperature??.7,max_tokens:d.maxTokens??256,stream:_}),E=await fetch(d.endpoint,{method:"POST",headers:N,body:$,signal:b.signal});if(!E.ok){const z=await E.text().catch(()=>E.statusText);throw new Error(`AI request failed (${E.status}): ${z}`)}if(_){w(!0);let z="";for await(const F of Qe(E,b.signal))if(b.signal.aborted||(z+=F.token,o(z),(k=F.usage)!=null&&k.completion_tokens&&j.recordTokens(F.usage.completion_tokens),F.done))break;if(z.length>0){const F=Math.ceil(z.length/4);j.recordTokens(F)}se.set(y,z)}else{const z=await Ze(E);o(z.text),se.set(y,z.text),(S=z.usage)!=null&&S.completion_tokens?j.recordTokens(z.usage.completion_tokens):j.recordTokens(Math.ceil(z.text.length/4))}}catch(N){if(N instanceof DOMException&&N.name==="AbortError")return;u(N instanceof Error?N.message:"AI hint request failed")}finally{b.signal.aborted||(m(!1),w(!1))}},[n,t,r]);l.useEffect(()=>{if(!n||!n.enabled||r)return;const d=setTimeout(M,i);return()=>clearTimeout(d)},[t==null?void 0:t.fieldLabel,t==null?void 0:t.fieldType,t==null?void 0:t.fieldValue,t==null?void 0:t.customPrompt,i,r,n==null?void 0:n.enabled,R.current]),l.useEffect(()=>()=>{var d;(d=A.current)==null||d.abort()},[]);const P=l.useCallback(()=>{var d;(d=A.current)==null||d.abort(),m(!1),w(!1)},[]),g=l.useCallback(()=>{if(n){const d=Be(t,n.config.privacyMode??!1);se.delete(d)}R.current+=1,M()},[n,t,M]);return!n||!n.enabled?{text:"",loading:!1,error:null,streaming:!1,abort:()=>{},refresh:()=>{},hint:null,fetchHint:async()=>{}}:{text:s,loading:c,error:p,streaming:v,abort:P,refresh:g,hint:s?{content:s}:null,fetchHint:async()=>{await M()}}}function Oa(t,a){if(t!=="auto"||!a)return t==="auto"?"top":t;const i=a.top,r=window.innerHeight-a.bottom,n=a.left,s=window.innerWidth-a.right,o=Math.max(i,r,n,s);return o===i?"top":o===r?"bottom":o===s?"right":"left"}function Ea(t){const a={position:"absolute",zIndex:9999,minWidth:200,maxWidth:320,padding:"8px 12px",borderRadius:8,fontSize:13,lineHeight:1.5,backgroundColor:"var(--ntd-ai-bg, #1e1e2e)",color:"var(--ntd-ai-fg, #cdd6f4)",border:"1px solid var(--ntd-ai-border, #45475a)",boxShadow:"0 4px 16px var(--nice-overlay-25, rgba(0, 0, 0, 0.25))",wordWrap:"break-word"};switch(t){case"top":return{...a,bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:6};case"bottom":return{...a,top:"100%",left:"50%",transform:"translateX(-50%)",marginTop:6};case"left":return{...a,right:"100%",top:"50%",transform:"translateY(-50%)",marginRight:6};case"right":return{...a,left:"100%",top:"50%",transform:"translateY(-50%)",marginLeft:6};default:return{...a,bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:6}}}const ea=Object.assign(l.forwardRef(({context:t,position:a="auto",debounceMs:i=500,showOnHover:r=!1,triggerIcon:n,className:s,style:o},c)=>{var I;const{t:m}=T.useNiceTranslation(),p=ee(),[u,v]=l.useState(!1),[w,A]=l.useState(!1),R=l.useRef(null),M=l.useRef(null),P=Z(t,{debounceMs:i,disabled:!w});l.useEffect(()=>{if(!u)return;const b=h=>{var f,k;const _=h.target;(f=R.current)!=null&&f.contains(_)||(k=M.current)!=null&&k.contains(_)||(v(!1),A(!1))};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[u]),l.useEffect(()=>{if(!u)return;const b=h=>{h.key==="Escape"&&(v(!1),A(!1),P.abort())};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[u,P]);const g=l.useCallback(b=>{if(b.stopPropagation(),r)return;const h=!u;v(h),A(h)},[u,r]),d=l.useCallback(()=>{r&&(v(!0),A(!0))},[r]),j=l.useCallback(()=>{r&&(v(!1),A(!1))},[r]);if(!p||!p.enabled)return null;const y=Oa(a,((I=R.current)==null?void 0:I.getBoundingClientRect())??null);return e.jsxs("span",{ref:c,className:s,style:{position:"relative",display:"inline-flex",...o},onMouseEnter:d,onMouseLeave:j,children:[e.jsx("button",{ref:R,type:"button",onClick:g,"aria-label":m("aiHintBubble.aiHint","AI hint"),"aria-expanded":u,className:"ntd-ai-trigger",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",border:"none",background:"transparent",cursor:"pointer",padding:2,borderRadius:4,color:"var(--ntd-ai-trigger-color, #a78bfa)",opacity:.7,transition:"opacity 0.2s, transform 0.2s"},children:n??e.jsx(T.NiceIcon,{name:"wand",size:16})}),u&&e.jsxs("div",{ref:M,role:"tooltip",className:"ntd-ai-popover",style:Ea(y),children:[P.loading&&!P.text&&e.jsxs("div",{className:"ntd-ai-loading",style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{display:"inline-block",width:12,height:12,border:"2px solid var(--ntd-ai-border, #45475a)",borderTopColor:"var(--ntd-ai-trigger-color, #a78bfa)",borderRadius:"50%",animation:"ntd-ai-spin 0.8s linear infinite"}}),e.jsx("span",{style:{opacity:.6},children:m("aiHintBubble.thinking","Thinking...")})]}),P.text&&e.jsxs("div",{className:"ntd-ai-content",children:[P.text,P.streaming&&e.jsx("span",{className:"ntd-ai-cursor",style:{display:"inline-block",width:2,height:"1em",backgroundColor:"var(--ntd-ai-trigger-color, #a78bfa)",marginLeft:1,animation:"ntd-ai-blink 0.8s step-end infinite",verticalAlign:"text-bottom"}})]}),P.error&&e.jsx("div",{className:"ntd-ai-error",style:{color:"var(--ntd-ai-error, #f38ba8)"},children:P.error}),P.text&&!P.streaming&&e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:4,marginTop:6,paddingTop:6,borderTop:"1px solid var(--ntd-ai-border, #45475a)"},children:[e.jsxs("button",{type:"button",onClick:()=>P.refresh(),className:"ntd-ai-action",style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:11,padding:"2px 6px",border:"1px solid var(--ntd-ai-border, #45475a)",borderRadius:4,background:"transparent",color:"inherit",cursor:"pointer"},children:[e.jsx(T.NiceIcon,{name:"refresh",size:12})," ",m("aiHintBubble.refresh","Refresh")]}),e.jsxs("button",{type:"button",onClick:()=>{var b;(b=navigator.clipboard)==null||b.writeText(P.text)},className:"ntd-ai-action",style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:11,padding:"2px 6px",border:"1px solid var(--ntd-ai-border, #45475a)",borderRadius:4,background:"transparent",color:"inherit",cursor:"pointer"},children:[e.jsx(T.NiceIcon,{name:"copy",size:12})," ",m("aiHintBubble.copy","Copy")]})]})]})]})}),{displayName:"NiceAIHintBubble"});function Le(t,a,i){return{fieldLabel:t,fieldType:"text",fieldValue:a,validationRules:{...(i==null?void 0:i.maxLength)!=null?{maxLength:i.maxLength}:{},...i!=null&&i.pattern?{pattern:i.pattern}:{}},customPrompt:i!=null&&i.placeholder?`Placeholder: "${i.placeholder}". Suggest content or correct grammar.`:"Suggest content, correct grammar, or auto-complete the text."}}function ze(t,a,i){return{fieldLabel:t,fieldType:"number",fieldValue:a,validationRules:{...(i==null?void 0:i.min)!=null?{min:i.min}:{},...(i==null?void 0:i.max)!=null?{max:i.max}:{},...(i==null?void 0:i.step)!=null?{step:i.step}:{}},customPrompt:i!=null&&i.unit?`Unit: ${i.unit}. Suggest a reasonable value or range for this field.`:"Suggest a reasonable value or range for this field based on the label and constraints."}}function Me(t,a,i){return{fieldLabel:t,fieldType:i!=null&&i.multiple?"multi-select":"select",fieldValue:a,schema:i!=null&&i.options?{availableOptions:i.options.slice(0,20).map(r=>r.label)}:{},customPrompt:"Suggest the most likely selection. Explain why this option is recommended."}}function $e(t,a,i){const r=a instanceof Date?a.toISOString().split("T")[0]:a;return{fieldLabel:t,fieldType:"date",fieldValue:r,validationRules:{...i!=null&&i.min?{min:i.min}:{},...i!=null&&i.max?{max:i.max}:{},...i!=null&&i.disableWeekends?{noWeekends:!0}:{}},customPrompt:'Suggest a date. For example: "next business day", "end of month", "in 2 weeks". Explain your suggestion briefly.'}}function Pe(t,a,i){return{fieldLabel:t,fieldType:"color",fieldValue:a,schema:i!=null&&i.palette?{currentPalette:i.palette}:{},customPrompt:i!=null&&i.industry?`Industry: ${i.industry}. Suggest a color palette (3-5 hex colors) suitable for this context.`:"Suggest a color or palette of colors that works well for this context. Provide hex values."}}function Da(t,a){return{fieldLabel:t,fieldType:"data-grid",schema:{...a!=null&&a.columns?{columns:a.columns}:{},...(a==null?void 0:a.rowCount)!=null?{totalRows:a.rowCount}:{}},formContext:{...a!=null&&a.currentFilters?{filters:a.currentFilters}:{},...a!=null&&a.currentSorts?{sorts:a.currentSorts}:{}},customPrompt:"Suggest column configuration, useful filters, or highlight potential data anomalies."}}function Ba(t,a){return{fieldLabel:t,fieldType:"chart",schema:{...a!=null&&a.currentType?{chartType:a.currentType}:{},...(a==null?void 0:a.seriesCount)!=null?{series:a.seriesCount}:{},...(a==null?void 0:a.pointCount)!=null?{dataPoints:a.pointCount}:{}},customPrompt:a!=null&&a.dataDescription?`Data: ${a.dataDescription}. Suggest the best chart type and labeling strategy.`:"Suggest the most effective chart type for this data. Explain your recommendation."}}function aa(t,a){return{fieldLabel:"Form auto-fill",fieldType:"form",schema:{fields:a},customPrompt:`User description: "${t}"
5
- Parse this description and return suggested values for each field as JSON: { ${a.map(i=>`"${i.label}": "value"`).join(", ")} }`}}function ia(t,a,i,r,n){return{fieldLabel:t,fieldType:a,fieldValue:i,validationRules:n==null?void 0:n.rules,customPrompt:`Current validation error: "${r}". Provide a friendly, specific error message with an example of a valid value. Do NOT say "field is required" — instead explain what the user should enter.`}}function Fa(t,a,i){const r=l.useMemo(()=>Le(t,a,i),[t,a,i==null?void 0:i.placeholder,i==null?void 0:i.maxLength,i==null?void 0:i.pattern]);return Z(r,i)}function Ja(t,a,i){const r=l.useMemo(()=>ze(t,a,i),[t,a,i==null?void 0:i.min,i==null?void 0:i.max,i==null?void 0:i.step,i==null?void 0:i.unit]);return Z(r,i)}function qa(t,a,i){const r=l.useMemo(()=>Me(t,a,i),[t,a,i==null?void 0:i.multiple]);return Z(r,i)}function Ga(t,a,i){const r=l.useMemo(()=>$e(t,a,i),[t,a,i==null?void 0:i.min,i==null?void 0:i.max,i==null?void 0:i.disableWeekends]);return Z(r,i)}function Ua(t,a,i){const r=l.useMemo(()=>Pe(t,a,i),[t,a,i==null?void 0:i.industry]);return Z(r,i)}function Wa(t,a,i,r,n){const s=l.useMemo(()=>r?ia(t,a,i,r,n):{fieldLabel:t,fieldType:a},[t,a,i,r]);return Z(s,{...n,disabled:!r||(n==null?void 0:n.disabled)})}function Ha(t,a,i){const r=l.useMemo(()=>t?aa(t,a):{fieldLabel:"Form"},[t,a]);return Z(r,{...i,disabled:!t||(i==null?void 0:i.disabled)})}function ta(t,a,i){const n=(a==null?void 0:a.split(`
6
- `))??[],s=(i==null?void 0:i.cursorLine)!=null?n.slice(Math.max(0,i.cursorLine-8),i.cursorLine+3).join(`
7
- `):n.slice(0,16).join(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),l=require("react"),T=require("@nice2dev/ui-core"),Ma=require("@nice2dev/ui");class Ye{constructor(a={},i){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1,this.config={maxRequestsPerMinute:a.maxRequestsPerMinute??30,maxTokensPerSession:a.maxTokensPerSession??1e4,warnThresholdPercent:a.warnThresholdPercent??80},this.onWarning=i}canRequest(){return this.pruneOldTimestamps(),!(this.timestamps.length>=this.config.maxRequestsPerMinute||this.tokenCount>=this.config.maxTokensPerSession)}recordRequest(){return this.canRequest()?(this.timestamps.push(Date.now()),!0):!1}recordTokens(a){this.tokenCount+=a,this.checkWarning()}getStatus(){this.pruneOldTimestamps();const a=this.config.maxTokensPerSession>0?this.tokenCount/this.config.maxTokensPerSession*100:0,i=this.config.maxRequestsPerMinute>0?this.timestamps.length/this.config.maxRequestsPerMinute*100:0;return{requestsThisMinute:this.timestamps.length,tokensThisSession:this.tokenCount,isLimited:!this.canRequest(),isWarning:a>=this.config.warnThresholdPercent||i>=this.config.warnThresholdPercent}}reset(){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1}pruneOldTimestamps(){const a=Date.now()-6e4;this.timestamps=this.timestamps.filter(i=>i>a)}checkWarning(){var i;if(this.warningEmitted)return;this.getStatus().isWarning&&(this.warningEmitted=!0,(i=this.onWarning)==null||i.call(this))}}const Xe=l.createContext(null);function $a({config:t,rateLimits:a,enabled:i=!0,onRateLimitWarning:n,children:r}){const s=l.useRef(null);s.current||(s.current=new Ye(a,n));const o=l.useCallback(()=>s.current.getStatus(),[]),c=l.useMemo(()=>({config:t,enabled:i,rateLimiter:s.current,getRateLimitStatus:o}),[t,i,o]);return e.jsx(Xe.Provider,{value:c,children:r})}function Z(){return l.useContext(Xe)}async function*Qe(t,a){var s,o,c,m,p,d,x,N,A;const i=(s=t.body)==null?void 0:s.getReader();if(!i)throw new Error("Response body is not readable");const n=new TextDecoder;let r="";try{for(;!(a!=null&&a.aborted);){const{done:R,value:$}=await i.read();if(R)break;r+=n.decode($,{stream:!0});const M=r.split(`
2
+ `);r=M.pop()??"";for(const g of M){const u=g.trim();if(!(!u||u===":")){if(u.startsWith("data:")){const y=u.slice(5).trim();if(y==="[DONE]"){yield{token:"",done:!0};return}try{const _=JSON.parse(y),C=((m=(c=(o=_.choices)==null?void 0:o[0])==null?void 0:c.delta)==null?void 0:m.content)??"",v=((d=(p=_.choices)==null?void 0:p[0])==null?void 0:d.finish_reason)==="stop";(C||v)&&(yield{token:C,done:v,usage:_.usage})}catch{y&&(yield{token:y,done:!1})}continue}try{const y=JSON.parse(u),_=y.text??y.content??y.token??"";_&&(yield{token:_,done:!1})}catch{u&&(yield{token:u,done:!1})}}}}if(r.trim()){const R=r.trim();if(R.startsWith("data:")){const $=R.slice(5).trim();if($&&$!=="[DONE]")try{const g=((A=(N=(x=JSON.parse($).choices)==null?void 0:x[0])==null?void 0:N.delta)==null?void 0:A.content)??"";g&&(yield{token:g,done:!0})}catch{yield{token:$,done:!0}}}}}finally{i.releaseLock()}}async function Ze(t){var i,n,r,s;const a=await t.json();if((r=(n=(i=a.choices)==null?void 0:i[0])==null?void 0:n.message)!=null&&r.content)return{text:a.choices[0].message.content,usage:a.usage};if((s=a.message)!=null&&s.content)return{text:a.message.content};if(typeof a.text=="string")return{text:a.text};if(typeof a.content=="string")return{text:a.content};if(typeof a.response=="string")return{text:a.response};throw new Error("Unrecognized AI response format")}const se=new Map;function Be(t,a){const i=a?{...t,fieldValue:void 0,formContext:void 0}:t;return JSON.stringify(i)}function Pa(t,a){const i=[],n=a.systemPrompt??"You are a helpful assistant providing concise contextual hints for form fields. Keep responses short (1-3 sentences). Be specific and actionable.";i.push({role:"system",content:n});const r=[];if(t.fieldLabel&&r.push(`Field: "${t.fieldLabel}"`),t.fieldType&&r.push(`Type: ${t.fieldType}`),!a.privacyMode&&t.fieldValue!==void 0){const o=typeof t.fieldValue=="string"?t.fieldValue:JSON.stringify(t.fieldValue);r.push(`Current value: ${o}`)}t.validationRules&&Object.keys(t.validationRules).length>0&&r.push(`Validation: ${JSON.stringify(t.validationRules)}`),t.schema&&Object.keys(t.schema).length>0&&r.push(`Schema: ${JSON.stringify(t.schema)}`),!a.privacyMode&&t.formContext&&Object.keys(t.formContext).length>0&&r.push(`Form context: ${JSON.stringify(t.formContext)}`),t.customPrompt&&r.push(t.customPrompt);const s=r.length>0?`Provide a helpful hint for this field:
3
+ ${r.join(`
4
+ `)}`:"Provide a helpful suggestion.";return i.push({role:"user",content:s}),i}function Q(t={},a={}){const{t:i}=T.useNiceTranslation();t=t??{},a=a??{};const{debounceMs:n=500,disabled:r=!1}=a,s=Z(),[o,c]=l.useState(""),[m,p]=l.useState(!1),[d,x]=l.useState(null),[N,A]=l.useState(!1),R=l.useRef(null),$=l.useRef(0),M=l.useCallback(async()=>{var j,k,I;if(!s||!s.enabled||r)return;const{config:y,rateLimiter:_}=s;if(!_.recordRequest()){x(i("useNiceAIHint.rateLimitExceededPleaseWait","Rate limit exceeded. Please wait before requesting another hint."));return}const C=Be(t,y.privacyMode??!1),v=se.get(C);if(v){c(v),p(!1),x(null),A(!1);return}(j=R.current)==null||j.abort();const h=new AbortController;R.current=h,p(!0),x(null),c(""),A(!1);const w=Pa(t,y),f=y.stream!==!1;try{const z={"Content-Type":"application/json",...y.headers};y.apiKey&&(z.Authorization=`Bearer ${y.apiKey}`);const E=JSON.stringify({model:y.model??"gpt-3.5-turbo",messages:w,temperature:y.temperature??.7,max_tokens:y.maxTokens??256,stream:f}),P=await fetch(y.endpoint,{method:"POST",headers:z,body:E,signal:h.signal});if(!P.ok){const F=await P.text().catch(()=>P.statusText);throw new Error(`AI request failed (${P.status}): ${F}`)}if(f){A(!0);let F="";for await(const G of Qe(P,h.signal))if(h.signal.aborted||(F+=G.token,c(F),(k=G.usage)!=null&&k.completion_tokens&&_.recordTokens(G.usage.completion_tokens),G.done))break;if(F.length>0){const G=Math.ceil(F.length/4);_.recordTokens(G)}se.set(C,F)}else{const F=await Ze(P);c(F.text),se.set(C,F.text),(I=F.usage)!=null&&I.completion_tokens?_.recordTokens(F.usage.completion_tokens):_.recordTokens(Math.ceil(F.text.length/4))}}catch(z){if(z instanceof DOMException&&z.name==="AbortError")return;x(z instanceof Error?z.message:i("useNiceAIHint.aiHintRequestFailed","AI hint request failed"))}finally{h.signal.aborted||(p(!1),A(!1))}},[s,t,r,i]);l.useEffect(()=>{if(!s||!s.enabled||r)return;const y=setTimeout(M,n);return()=>clearTimeout(y)},[t==null?void 0:t.fieldLabel,t==null?void 0:t.fieldType,t==null?void 0:t.fieldValue,t==null?void 0:t.customPrompt,n,r,s==null?void 0:s.enabled,$.current]),l.useEffect(()=>()=>{var y;(y=R.current)==null||y.abort()},[]);const g=l.useCallback(()=>{var y;(y=R.current)==null||y.abort(),p(!1),A(!1)},[]),u=l.useCallback(()=>{if(s){const y=Be(t,s.config.privacyMode??!1);se.delete(y)}$.current+=1,M()},[s,t,M]);return!s||!s.enabled?{text:"",loading:!1,error:null,streaming:!1,abort:()=>{},refresh:()=>{},hint:null,fetchHint:async()=>{}}:{text:o,loading:m,error:d,streaming:N,abort:g,refresh:u,hint:o?{content:o}:null,fetchHint:async()=>{await M()}}}function Oa(t,a){if(t!=="auto"||!a)return t==="auto"?"top":t;const i=a.top,n=window.innerHeight-a.bottom,r=a.left,s=window.innerWidth-a.right,o=Math.max(i,n,r,s);return o===i?"top":o===n?"bottom":o===s?"right":"left"}function Ea(t){const a={position:"absolute",zIndex:9999,minWidth:200,maxWidth:320,padding:"8px 12px",borderRadius:8,fontSize:13,lineHeight:1.5,backgroundColor:"var(--ntd-ai-bg, #1e1e2e)",color:"var(--ntd-ai-fg, #cdd6f4)",border:"1px solid var(--ntd-ai-border, #45475a)",boxShadow:"0 4px 16px var(--nice-overlay-25, rgba(0, 0, 0, 0.25))",wordWrap:"break-word"};switch(t){case"top":return{...a,bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:6};case"bottom":return{...a,top:"100%",left:"50%",transform:"translateX(-50%)",marginTop:6};case"left":return{...a,right:"100%",top:"50%",transform:"translateY(-50%)",marginRight:6};case"right":return{...a,left:"100%",top:"50%",transform:"translateY(-50%)",marginLeft:6};default:return{...a,bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:6}}}const ea=Object.assign(l.forwardRef(({context:t,position:a="auto",debounceMs:i=500,showOnHover:n=!1,triggerIcon:r,className:s,style:o},c)=>{var C;const{t:m}=T.useNiceTranslation(),p=Z(),[d,x]=l.useState(!1),[N,A]=l.useState(!1),R=l.useRef(null),$=l.useRef(null),M=Q(t,{debounceMs:i,disabled:!N});l.useEffect(()=>{if(!d)return;const v=h=>{var f,j;const w=h.target;(f=R.current)!=null&&f.contains(w)||(j=$.current)!=null&&j.contains(w)||(x(!1),A(!1))};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[d]),l.useEffect(()=>{if(!d)return;const v=h=>{h.key==="Escape"&&(x(!1),A(!1),M.abort())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[d,M]);const g=l.useCallback(v=>{if(v.stopPropagation(),n)return;const h=!d;x(h),A(h)},[d,n]),u=l.useCallback(()=>{n&&(x(!0),A(!0))},[n]),y=l.useCallback(()=>{n&&(x(!1),A(!1))},[n]);if(!p||!p.enabled)return null;const _=Oa(a,((C=R.current)==null?void 0:C.getBoundingClientRect())??null);return e.jsxs("span",{ref:c,className:s,style:{position:"relative",display:"inline-flex",...o},onMouseEnter:u,onMouseLeave:y,children:[e.jsx("button",{ref:R,type:"button",onClick:g,"aria-label":m("aiHintBubble.aiHint","AI hint"),"aria-expanded":d,className:"ntd-ai-trigger",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",border:"none",background:"transparent",cursor:"pointer",padding:2,borderRadius:4,color:"var(--ntd-ai-trigger-color, #a78bfa)",opacity:.7,transition:"opacity 0.2s, transform 0.2s"},children:r??e.jsx(T.NiceIcon,{name:"wand",size:16})}),d&&e.jsxs("div",{ref:$,role:"tooltip",className:"ntd-ai-popover",style:Ea(_),children:[M.loading&&!M.text&&e.jsxs("div",{className:"ntd-ai-loading",style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{display:"inline-block",width:12,height:12,border:"2px solid var(--ntd-ai-border, #45475a)",borderTopColor:"var(--ntd-ai-trigger-color, #a78bfa)",borderRadius:"50%",animation:"ntd-ai-spin 0.8s linear infinite"}}),e.jsx("span",{style:{opacity:.6},children:m("aiHintBubble.thinking","Thinking...")})]}),M.text&&e.jsxs("div",{className:"ntd-ai-content",children:[M.text,M.streaming&&e.jsx("span",{className:"ntd-ai-cursor",style:{display:"inline-block",width:2,height:"1em",backgroundColor:"var(--ntd-ai-trigger-color, #a78bfa)",marginLeft:1,animation:"ntd-ai-blink 0.8s step-end infinite",verticalAlign:"text-bottom"}})]}),M.error&&e.jsx("div",{className:"ntd-ai-error",style:{color:"var(--ntd-ai-error, #f38ba8)"},children:M.error}),M.text&&!M.streaming&&e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:4,marginTop:6,paddingTop:6,borderTop:"1px solid var(--ntd-ai-border, #45475a)"},children:[e.jsxs("button",{type:"button",onClick:()=>M.refresh(),className:"ntd-ai-action",style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:11,padding:"2px 6px",border:"1px solid var(--ntd-ai-border, #45475a)",borderRadius:4,background:"transparent",color:"inherit",cursor:"pointer"},children:[e.jsx(T.NiceIcon,{name:"refresh",size:12})," ",m("aiHintBubble.refresh","Refresh")]}),e.jsxs("button",{type:"button",onClick:()=>{var v;(v=navigator.clipboard)==null||v.writeText(M.text)},className:"ntd-ai-action",style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:11,padding:"2px 6px",border:"1px solid var(--ntd-ai-border, #45475a)",borderRadius:4,background:"transparent",color:"inherit",cursor:"pointer"},children:[e.jsx(T.NiceIcon,{name:"copy",size:12})," ",m("aiHintBubble.copy","Copy")]})]})]})]})}),{displayName:"NiceAIHintBubble"});function Le(t,a,i){return{fieldLabel:t,fieldType:"text",fieldValue:a,validationRules:{...(i==null?void 0:i.maxLength)!=null?{maxLength:i.maxLength}:{},...i!=null&&i.pattern?{pattern:i.pattern}:{}},customPrompt:i!=null&&i.placeholder?`Placeholder: "${i.placeholder}". Suggest content or correct grammar.`:"Suggest content, correct grammar, or auto-complete the text."}}function ze(t,a,i){return{fieldLabel:t,fieldType:"number",fieldValue:a,validationRules:{...(i==null?void 0:i.min)!=null?{min:i.min}:{},...(i==null?void 0:i.max)!=null?{max:i.max}:{},...(i==null?void 0:i.step)!=null?{step:i.step}:{}},customPrompt:i!=null&&i.unit?`Unit: ${i.unit}. Suggest a reasonable value or range for this field.`:"Suggest a reasonable value or range for this field based on the label and constraints."}}function Me(t,a,i){return{fieldLabel:t,fieldType:i!=null&&i.multiple?"multi-select":"select",fieldValue:a,schema:i!=null&&i.options?{availableOptions:i.options.slice(0,20).map(n=>n.label)}:{},customPrompt:"Suggest the most likely selection. Explain why this option is recommended."}}function $e(t,a,i){const n=a instanceof Date?a.toISOString().split("T")[0]:a;return{fieldLabel:t,fieldType:"date",fieldValue:n,validationRules:{...i!=null&&i.min?{min:i.min}:{},...i!=null&&i.max?{max:i.max}:{},...i!=null&&i.disableWeekends?{noWeekends:!0}:{}},customPrompt:'Suggest a date. For example: "next business day", "end of month", "in 2 weeks". Explain your suggestion briefly.'}}function Pe(t,a,i){return{fieldLabel:t,fieldType:"color",fieldValue:a,schema:i!=null&&i.palette?{currentPalette:i.palette}:{},customPrompt:i!=null&&i.industry?`Industry: ${i.industry}. Suggest a color palette (3-5 hex colors) suitable for this context.`:"Suggest a color or palette of colors that works well for this context. Provide hex values."}}function Da(t,a){return{fieldLabel:t,fieldType:"data-grid",schema:{...a!=null&&a.columns?{columns:a.columns}:{},...(a==null?void 0:a.rowCount)!=null?{totalRows:a.rowCount}:{}},formContext:{...a!=null&&a.currentFilters?{filters:a.currentFilters}:{},...a!=null&&a.currentSorts?{sorts:a.currentSorts}:{}},customPrompt:"Suggest column configuration, useful filters, or highlight potential data anomalies."}}function Ba(t,a){return{fieldLabel:t,fieldType:"chart",schema:{...a!=null&&a.currentType?{chartType:a.currentType}:{},...(a==null?void 0:a.seriesCount)!=null?{series:a.seriesCount}:{},...(a==null?void 0:a.pointCount)!=null?{dataPoints:a.pointCount}:{}},customPrompt:a!=null&&a.dataDescription?`Data: ${a.dataDescription}. Suggest the best chart type and labeling strategy.`:"Suggest the most effective chart type for this data. Explain your recommendation."}}function aa(t,a){return{fieldLabel:"Form auto-fill",fieldType:"form",schema:{fields:a},customPrompt:`User description: "${t}"
5
+ Parse this description and return suggested values for each field as JSON: { ${a.map(i=>`"${i.label}": "value"`).join(", ")} }`}}function ia(t,a,i,n,r){return{fieldLabel:t,fieldType:a,fieldValue:i,validationRules:r==null?void 0:r.rules,customPrompt:`Current validation error: "${n}". Provide a friendly, specific error message with an example of a valid value. Do NOT say "field is required" — instead explain what the user should enter.`}}function Fa(t,a,i){const{placeholder:n,maxLength:r,pattern:s}=i??{},o=l.useMemo(()=>Le(t,a,{placeholder:n,maxLength:r,pattern:s}),[t,a,n,r,s]);return Q(o,i)}function Ja(t,a,i){const{min:n,max:r,step:s,unit:o}=i??{},c=l.useMemo(()=>ze(t,a,{min:n,max:r,step:s,unit:o}),[t,a,n,r,s,o]);return Q(c,i)}function qa(t,a,i){const n=i==null?void 0:i.multiple,r=JSON.stringify((i==null?void 0:i.options)??null),s=l.useMemo(()=>Me(t,a,{options:JSON.parse(r)??void 0,multiple:n}),[t,a,r,n]);return Q(s,i)}function Ga(t,a,i){const{min:n,max:r,disableWeekends:s}=i??{},o=l.useMemo(()=>$e(t,a,{min:n,max:r,disableWeekends:s}),[t,a,n,r,s]);return Q(o,i)}function Ua(t,a,i){const n=i==null?void 0:i.industry,r=JSON.stringify((i==null?void 0:i.palette)??null),s=l.useMemo(()=>Pe(t,a,{palette:JSON.parse(r)??void 0,industry:n}),[t,a,r,n]);return Q(s,i)}function Wa(t,a,i,n,r){const s=JSON.stringify((r==null?void 0:r.rules)??null),o=l.useMemo(()=>n?ia(t,a,i,n,{rules:JSON.parse(s)??void 0}):{fieldLabel:t,fieldType:a},[t,a,i,n,s]);return Q(o,{...r,disabled:!n||(r==null?void 0:r.disabled)})}function Ha(t,a,i){const n=l.useMemo(()=>t?aa(t,a):{fieldLabel:"Form"},[t,a]);return Q(n,{...i,disabled:!t||(i==null?void 0:i.disabled)})}function ta(t,a,i){const r=(a==null?void 0:a.split(`
6
+ `))??[],s=(i==null?void 0:i.cursorLine)!=null?r.slice(Math.max(0,i.cursorLine-8),i.cursorLine+3).join(`
7
+ `):r.slice(0,16).join(`
8
8
  `);return{fieldLabel:`Code editor (${t})`,fieldType:"code-editor",fieldValue:s||a,schema:{language:t,...i!=null&&i.framework?{framework:i.framework}:{},...(i==null?void 0:i.cursorLine)!=null?{cursorLine:i.cursorLine,cursorCol:i.cursorCol}:{}},customPrompt:`Language: ${t}${i!=null&&i.framework?`, framework: ${i.framework}`:""}.
9
- Provide a concise inline completion or improvement hint for the code near the cursor. Limit response to ${(i==null?void 0:i.maxSuggestLines)??5} lines of code. If unsure, suggest the most idiomatic approach for this language/framework.`}}function ra(t,a,i){var s;const r=(i==null?void 0:i.mode)??"grammar",n={seo:"Analyze this HTML for SEO: missing meta tags, heading hierarchy (h1→h2→h3), keyword density, image alt attributes. Return a prioritized list of improvements.",accessibility:"Audit this HTML for WCAG 2.1 AA issues: missing aria labels, alt text, heading structure, color contrast hints, keyboard navigation. List specific fixes.",grammar:"Fix grammar, punctuation, and writing style in the visible text content. Return the corrected text only (no HTML tags in response).",cleanup:"Clean up malformed, redundant, or overly nested HTML. Simplify structure while preserving semantics and content."};return{fieldLabel:t,fieldType:"html-editor",fieldValue:a==null?void 0:a.slice(0,2e3),schema:{mode:r,...(s=i==null?void 0:i.targetKeywords)!=null&&s.length?{targetKeywords:i.targetKeywords}:{},...i!=null&&i.locale?{locale:i.locale}:{}},customPrompt:n[r]}}function na(t,a){const i=(a==null?void 0:a.mode)??"tag",r=`"${t}"`+((a==null?void 0:a.bpm)!=null?`, BPM: ${a.bpm}`:"")+(a!=null&&a.key?`, Key: ${a.key}`:"")+(a!=null&&a.genre?`, Genre: ${a.genre}`:"")+((a==null?void 0:a.duration)!=null?`, Duration: ${a.duration}s`:""),n={tag:`Audio: ${r}. Suggest genre tags, mood descriptors and playlist categories. Return as JSON array of strings.`,bpm:`Audio: ${r}. Suggest likely BPM range and musical key based on metadata. Return as JSON: { bpm: number, key: string }.`,mix:`Track: ${r}. Suggest EQ curve (JSON array of {freq, gain, q}), compression settings, and 2-3 compatible tracks for mixing.`,transcribe:"Return a transcription of the spoken audio content as JSON: { transcript: string, language: string, confidence: number }."};return{fieldLabel:`Audio: ${t}`,fieldType:"audio",schema:{mode:i,...(a==null?void 0:a.bpm)!=null?{bpm:a.bpm}:{},...a!=null&&a.key?{key:a.key}:{},...(a==null?void 0:a.duration)!=null?{duration:a.duration}:{},...a!=null&&a.genre?{genre:a.genre}:{}},customPrompt:n[i]}}function sa(t,a){var s;const i=(a==null?void 0:a.mode)??"material",r=(a==null?void 0:a.targetDevice)??"web",n={material:`Scene "${t}", ${(a==null?void 0:a.meshCount)??"?"} meshes. Materials: ${((s=a==null?void 0:a.materials)==null?void 0:s.join(", "))||"none"}. Suggest PBR properties (roughness, metalness, baseColor) and texture maps for each material.`,optimize:`Scene "${t}", triangles: ${(a==null?void 0:a.triangleCount)??"?"}, target: ${r}. Identify budget issues and suggest LOD levels, mesh merging, and texture atlas strategy.`,lighting:`Scene "${t}", target: ${r}. Suggest a complete lighting setup (types, intensity, color, shadow settings) for realistic rendering.`,animation:`Rig in scene "${t}". Suggest animation approach (FK/IK, bone count), keyframe timing and easing curves for natural movement.`};return{fieldLabel:`3D scene: ${t}`,fieldType:"3d-scene",schema:{mode:i,...(a==null?void 0:a.meshCount)!=null?{meshes:a.meshCount}:{},...(a==null?void 0:a.triangleCount)!=null?{triangles:a.triangleCount}:{},...a!=null&&a.targetDevice?{target:a.targetDevice}:{}},customPrompt:n[i]}}function ca(t,a){const i=(a==null?void 0:a.mode)??"palette",r=(a==null?void 0:a.width)!=null?`${a.width}×${a.height??"?"}px`:"unknown dimensions",n={filter:`Image "${t}" (${r}). Suggest CSS/SVG filter parameters (brightness, contrast, saturate, hue-rotate, blur) as JSON: { brightness, contrast, saturate, hueRotate, blur }.`,palette:`Image "${t}". Extract or suggest a harmonious 5-color palette as JSON: { primary, secondary, accent, background, text }.`,upscale:`Image "${t}" at ${r}. Recommend upscaling strategy: model (ESRGAN/RealSR/SRCNN), scale factor, and expected quality gain.`,"style-transfer":`Image "${t}", target style: "${(a==null?void 0:a.targetStyle)??"artistic"}". Suggest style-transfer settings as JSON: { contentWeight, styleWeight, iterations, patchSize }.`};return{fieldLabel:`Graphics: ${t}`,fieldType:"graphics",schema:{mode:i,...(a==null?void 0:a.width)!=null?{width:a.width,height:a.height}:{},...a!=null&&a.targetStyle?{targetStyle:a.targetStyle}:{}},customPrompt:n[i]}}function oa(t,a){var i;return{fieldLabel:"Icon search",fieldType:"icon-picker",fieldValue:t,schema:{...a!=null&&a.style?{iconStyle:a.style}:{},...(a==null?void 0:a.limit)!=null?{maxResults:a.limit}:{},...(i=a==null?void 0:a.availableIcons)!=null&&i.length?{sampleIcons:a.availableIcons.slice(0,30)}:{}},customPrompt:`User query: "${t}"
10
- Return the ${(a==null?void 0:a.limit)??5} most semantically relevant icon names from the available set as a JSON array of strings, ordered by relevance. Prefer specific over generic names.`}}function Ka(t,a,i){const r=l.useMemo(()=>ta(t,a,i),[t,a,i==null?void 0:i.cursorLine,i==null?void 0:i.cursorCol,i==null?void 0:i.framework]);return Z(r,i)}function Ya(t,a,i){const r=l.useMemo(()=>ra(t,a,i),[t,a,i==null?void 0:i.mode,i==null?void 0:i.locale]);return Z(r,i)}function Va(t,a){const i=l.useMemo(()=>na(t,a),[t,a==null?void 0:a.bpm,a==null?void 0:a.key,a==null?void 0:a.duration,a==null?void 0:a.mode]);return Z(i,a)}function Xa(t,a){const i=l.useMemo(()=>sa(t,a),[t,a==null?void 0:a.meshCount,a==null?void 0:a.triangleCount,a==null?void 0:a.targetDevice,a==null?void 0:a.mode]);return Z(i,a)}function Qa(t,a){const i=l.useMemo(()=>ca(t,a),[t,a==null?void 0:a.width,a==null?void 0:a.height,a==null?void 0:a.mode,a==null?void 0:a.targetStyle]);return Z(i,a)}function Za(t,a){const i=l.useMemo(()=>oa(t,a),[t,a==null?void 0:a.limit,a==null?void 0:a.style]);return Z(i,{...a,disabled:!t||(a==null?void 0:a.disabled)})}function la(t,a){var s;const i=(a==null?void 0:a.mode)??"npc-decision",r=(a==null?void 0:a.genre)??"fantasy",n={"npc-decision":`You are an AI game director. The NPC "${t}" must make a decision. Available BT nodes: ${JSON.stringify((a==null?void 0:a.btStatus)??[])}. Game state: ${JSON.stringify((a==null?void 0:a.gameState)??{})}. Return the name of the BT node to activate next, and one sentence of reasoning.`,dialogue:`You are a ${r} RPG writer. Write a short in-character dialogue line for NPC "${t}". Game state: ${JSON.stringify((a==null?void 0:a.gameState)??{})}. Max 2 sentences, no narrative descriptions.`,"procedural-level":`You are a ${r} game designer. Suggest a procedural level layout for a zone containing "${t}". Describe room count, enemy placement, loot, and one unique mechanic. Keep it under 150 words.`,"quest-description":`You are a ${r} quest designer. Write a compelling quest description involving "${t}". Include: objective, giver NPC, rewards, and a short flavour paragraph. Keep it under 120 words.`,"item-description":`You are a ${r} lore writer. Write a short item description for an item related to "${t}". Include: item name, rarity, flavour text, and one special property. Keep it under 80 words.`};return{fieldLabel:t,fieldType:`game-engine:${i}`,fieldValue:a==null?void 0:a.gameState,customPrompt:n[i],schema:{genre:r,mode:i,btNodes:(s=a==null?void 0:a.btStatus)==null?void 0:s.map(o=>o.node)}}}function ei(t,a){const i=l.useMemo(()=>la(t,a),[t,a==null?void 0:a.mode,a==null?void 0:a.genre,JSON.stringify(a==null?void 0:a.btStatus),JSON.stringify(a==null?void 0:a.gameState)]);return Z(i,a)}function da(t,a,i){const r=(i==null?void 0:i.mode)??"layout",n=(i==null?void 0:i.diagramType)??"flowchart",s={layout:`You are a diagram layout optimizer. Given this ${n} with ${t.length} nodes and ${a.length} edges, suggest optimal positions for each node to minimize edge crossings and improve readability. Return JSON: { suggestions: [{ id: string, x: number, y: number, reason: string }] }. Consider flow direction (top-to-bottom or left-to-right) and grouping related nodes.`,structure:`You are a diagram analyst. Analyze this ${n} structure. Identify: 1) Missing connections, 2) Potential bottlenecks, 3) Orphan nodes, 4) Cycles or loops. Return JSON: { issues: [{ type: string, description: string, nodeIds: string[] }], score: number }`,simplify:`You are a diagram simplifier. Suggest how to simplify this ${n} while preserving meaning. Identify: nodes that could be merged, redundant edges, or overly complex branches. Return JSON: { simplifications: [{ action: 'merge'|'remove'|'group', ids: string[], reason: string }] }`,group:`You are a diagram organizer. Suggest logical groupings for nodes in this ${n}. Consider semantic relationships, data flow patterns, and visual clustering. Return JSON: { groups: [{ name: string, nodeIds: string[], color?: string }] }`},o=t.map(m=>{var p;return{id:m.id,type:m.type,label:(p=m.label)==null?void 0:p.slice(0,30),pos:[Math.round(m.x),Math.round(m.y)]}}),c=a.map(m=>({id:m.id,src:m.source,tgt:m.target}));return{fieldLabel:`Diagram (${n})`,fieldType:`diagram:${r}`,fieldValue:JSON.stringify({nodes:o,edges:c}),schema:{diagramType:n,mode:r,nodeCount:t.length,edgeCount:a.length,containerSize:i==null?void 0:i.containerSize},customPrompt:s[r]}}function ai(t,a,i){const r=l.useMemo(()=>da(t,a,i),[JSON.stringify(t),JSON.stringify(a),i==null?void 0:i.mode,i==null?void 0:i.diagramType]);return Z(r,{...i,disabled:t.length===0||(i==null?void 0:i.disabled)})}function ua(t,a){const i=(a==null?void 0:a.mode)??"generate",r=(a==null?void 0:a.presentationType)??"business",n=(a==null?void 0:a.duration)??15,s=Math.ceil(n/2),o={generate:`You are a presentation designer. Create a ${r} presentation outline based on: "${t}". Target audience: ${(a==null?void 0:a.audience)??"general"}. Duration: ${n} minutes (~${s} slides). Return JSON: { title: string, slides: [{ title: string, layout: 'title'|'content'|'two-column'|'chart'|'image', bullets?: string[], chartType?: string, speakerNotes?: string }] }. Include: clear slide titles, 3-5 bullet points per content slide, and brief speaker notes.`,summarize:`You are a presentation optimizer. Summarize this presentation to be more concise: "${t}". Reduce slide count by 30% while preserving key messages. Return JSON: { summary: string, reducedSlides: [{ title: string, keyPoints: string[] }] }`,expand:`You are a presentation expert. Expand this brief outline into a detailed presentation: "${t}". Add supporting details, examples, and transitions. Target: ${s} slides. Return JSON: { slides: [{ title: string, content: string, transitions?: string, animations?: string[] }] }`,improve:`You are a presentation coach. Review and improve this presentation structure: "${t}". Suggest: better flow, stronger opening/closing, clearer data visualization. Return JSON: { improvements: [{ slide: number, issue: string, suggestion: string }], score: number }`};return{fieldLabel:`Presentation (${r})`,fieldType:`presentation:${i}`,fieldValue:t,schema:{presentationType:r,mode:i,duration:n,slideCount:s,audience:a==null?void 0:a.audience,hasData:(a==null?void 0:a.dataContext)!=null},customPrompt:o[i]}}function ii(t,a){const i=l.useMemo(()=>ua(t,a),[t,a==null?void 0:a.mode,a==null?void 0:a.presentationType,a==null?void 0:a.duration,a==null?void 0:a.audience]);return Z(i,{...a,disabled:!t||(a==null?void 0:a.disabled)})}function ma(t,a){var n;const i=(a==null?void 0:a.mode)??"all",r={alignment:"Analyze element alignment on this slide. Suggest adjustments to create visual harmony. Return JSON: { suggestions: [{ elementIndex: number, issue: string, fixX?: number, fixY?: number }] }",contrast:"Analyze color contrast and readability. Suggest improvements for accessibility (WCAG AA). Return JSON: { suggestions: [{ area: string, currentContrast: number, suggestedFix: string }] }",spacing:"Analyze whitespace and element spacing. Apply the rule of thirds and consistent margins. Return JSON: { suggestions: [{ elementIndex: number, issue: string, suggestedMargin: number }] }",typography:"Analyze typography: hierarchy, font sizes, line heights, readability. Return JSON: { suggestions: [{ area: string, issue: string, suggestedFontSize?: number }] }",all:"Perform a complete design review of this slide. Check alignment, contrast, spacing, and typography. Return JSON: { score: number, suggestions: [{ category: string, issue: string, fix: string }] }. Prioritize issues by impact on visual clarity."};return{fieldLabel:t.title??"Slide Design",fieldType:`slide-design:${i}`,fieldValue:JSON.stringify(t),schema:{mode:i,hasElements:(((n=t.elements)==null?void 0:n.length)??0)>0,layout:t.layout,brandColors:a==null?void 0:a.brandColors},customPrompt:r[i]}}function ti(t,a){const i=l.useMemo(()=>ma(t,a),[JSON.stringify(t),a==null?void 0:a.mode,JSON.stringify(a==null?void 0:a.brandColors)]);return Z(i,a)}function ri(t,a,i){const r=l.forwardRef((n,s)=>{const{aiEnabled:o=!0,aiPosition:c="right",aiPrompt:m,aiDebounceMs:p=500,aiShowOnHover:u=!1,aiTriggerIcon:v,...w}=n,A=l.useMemo(()=>{const R=a(w);return m&&(R.customPrompt=m),R},[w,m]);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(t,{...w,ref:s}),o&&e.jsx(ea,{context:A,position:c,debounceMs:p,showOnHover:u,triggerIcon:v})]})});return r.displayName=i??`withAIHint(${t.displayName??t.name??"Component"})`,r}function ni(t){return Le(t.label??"Text",t.value,{placeholder:t.placeholder,maxLength:t.maxLength})}function si(t){return ze(t.label??"Number",t.value,{min:t.min,max:t.max,step:t.step})}function ci(t){return Me(t.label??"Select",t.value,{options:t.options,multiple:t.multiple})}function oi(t){return $e(t.label??"Date",t.value,{min:t.min,max:t.max})}function li(t){return Pe(t.label??"Color",t.value)}const di=t=>({id:T.createId(),name:t,type:"classification",status:"draft",datasets:[],experiments:[],models:[],createdAt:new Date,updatedAt:new Date}),je={classification:[{id:"logistic-regression",key:"mlStudio.alg.logisticRegression",name:"Logistic Regression"},{id:"random-forest",key:"mlStudio.alg.randomForest",name:"Random Forest"},{id:"gradient-boosting",key:"mlStudio.alg.gradientBoosting",name:"Gradient Boosting"},{id:"svm",key:"mlStudio.alg.svm",name:"Support Vector Machine"},{id:"neural-network",key:"mlStudio.alg.neuralNetwork",name:"Neural Network"},{id:"xgboost",key:"mlStudio.alg.xgboost",name:"XGBoost"}],regression:[{id:"linear-regression",key:"mlStudio.alg.linearRegression",name:"Linear Regression"},{id:"ridge",key:"mlStudio.alg.ridge",name:"Ridge Regression"},{id:"lasso",key:"mlStudio.alg.lasso",name:"Lasso Regression"},{id:"random-forest-reg",key:"mlStudio.alg.randomForest",name:"Random Forest"},{id:"gradient-boosting-reg",key:"mlStudio.alg.gradientBoosting",name:"Gradient Boosting"}],clustering:[{id:"kmeans",key:"mlStudio.alg.kmeans",name:"K-Means"},{id:"dbscan",key:"mlStudio.alg.dbscan",name:"DBSCAN"},{id:"hierarchical",key:"mlStudio.alg.hierarchical",name:"Hierarchical Clustering"}]},ui=Object.values(je).flat(),Fe=(t,a)=>{const i=ui.find(r=>r.id===t);return i?a(i.key,i.name):t},mi=[["classification","mlStudio.type.classification","Classification"],["regression","mlStudio.type.regression","Regression"],["clustering","mlStudio.type.clustering","Clustering"],["object-detection","mlStudio.type.objectDetection","Object Detection"],["nlp","mlStudio.type.nlp","NLP"],["time-series","mlStudio.type.timeSeries","Time Series"]],pi=[["data","mlStudio.tab.data","Data"],["experiments","mlStudio.tab.experiments","Experiments"],["models","mlStudio.tab.models","Models"],["deploy","mlStudio.tab.deploy","Deploy"]],gi=[["numeric","mlStudio.colType.numeric","Numeric"],["categorical","mlStudio.colType.categorical","Categorical"],["text","mlStudio.colType.text","Text"],["datetime","mlStudio.colType.datetime","DateTime"],["boolean","mlStudio.colType.boolean","Boolean"],["embedding","mlStudio.colType.embedding","Embedding"]],hi={train:["mlStudio.split.train","Train"],validation:["mlStudio.split.validation","Validation"],test:["mlStudio.split.test","Test"]},fi={pending:["mlStudio.experimentStatus.pending","Pending"],running:["mlStudio.experimentStatus.running","Running"],completed:["mlStudio.experimentStatus.completed","Completed"],failed:["mlStudio.experimentStatus.failed","Failed"],cancelled:["mlStudio.experimentStatus.cancelled","Cancelled"]},xi={draft:["mlStudio.modelStatus.draft","Draft"],registered:["mlStudio.modelStatus.registered","Registered"],staging:["mlStudio.modelStatus.staging","Staging"],production:["mlStudio.modelStatus.production","Production"],archived:["mlStudio.modelStatus.archived","Archived"]},bi={pending:["mlStudio.deploymentStatus.pending","Pending"],deploying:["mlStudio.deploymentStatus.deploying","Deploying"],running:["mlStudio.deploymentStatus.running","Running"],stopped:["mlStudio.deploymentStatus.stopped","Stopped"],failed:["mlStudio.deploymentStatus.failed","Failed"]},ce=(t,a,i)=>t?i(t[0],t[1]):a,yi=new Set(["accuracy","precision","recall","f1-score","auc-roc"]),Je=({name:t,value:a},i)=>yi.has(t)?`${(a*100).toLocaleString(i,{minimumFractionDigits:1,maximumFractionDigits:1})}%`:a.toLocaleString(i,{maximumFractionDigits:3}),vi=[{target:".nice-ml-studio",titleKey:"tutorial.mlStudio.intro.title",title:"ML studio",contentKey:"tutorial.mlStudio.intro.content",content:"Work through the tabs: prepare datasets, run experiments, compare and pick models, then deploy the best one.",placement:"auto"}],_i=({project:t,onProjectChange:a,onExperimentRun:i,onModelDeploy:r,onModelDownload:n,className:s="",tutorial:o})=>{var X;const{t:c,lang:m}=T.useNiceTranslation(),[p,u]=l.useState(()=>t||di(c("mlStudio.newProject","New ML Project"))),[v,w]=l.useState("data"),[A,R]=l.useState(null),[M,P]=l.useState(null),[g,d]=l.useState(null),[j,y]=l.useState(!1),[I,b]=l.useState({algorithm:"",hyperparameters:{},preprocessing:[]}),h=l.useRef(p),_=l.useCallback(C=>{const x=h.current,B={...x,...typeof C=="function"?C(x):C,updatedAt:new Date};h.current=B,u(B),a==null||a(B)},[a]),f=async C=>{for(const x of Array.from(C)){const B={id:T.createId(),name:x.name.replace(/\.[^.]+$/,""),type:"tabular",source:{type:"file",uri:x.name},size:x.size,rowCount:0,columns:[],splits:[{name:"train",ratio:.8,rowCount:0},{name:"validation",ratio:.1,rowCount:0},{name:"test",ratio:.1,rowCount:0}],createdAt:new Date};if(x.name.endsWith(".csv")){const q=(await x.text()).split(`
11
- `),W=q[0].split(",").map(Q=>Q.trim());B.rowCount=q.length-1,B.columns=W.map(Q=>({name:Q,type:"text",nullable:!0,unique:0,missing:0})),B.splits=B.splits.map(Q=>({...Q,rowCount:Math.floor(B.rowCount*Q.ratio)}))}_(G=>({datasets:[...G.datasets,B]}))}},k=C=>{_({datasets:p.datasets.filter(x=>x.id!==C)}),A===C&&R(null)},S=async()=>{if(!I.algorithm||!A)return;const C={id:T.createId(),name:c("mlStudio.experimentName","Experiment {n}").replace("{n}",String(p.experiments.length+1)),status:"pending",config:I,metrics:[],artifacts:[],logs:[]},x=G=>_(q=>({experiments:q.experiments.map(W=>W.id===C.id?{...W,...G}:W)}));if(_(G=>({experiments:[...G.experiments,C]})),y(!1),!i)return;const B=new Date;x({status:"running",startedAt:B});try{const G=await i(C),q=typeof G=="object"&&G!==null?G:{},W=new Date;x({status:"completed",completedAt:W,duration:q.duration??(W.getTime()-B.getTime())/1e3,metrics:q.metrics??[],artifacts:q.artifacts??[],logs:q.logs??[]})}catch{x({status:"failed"})}},N=C=>{const x=p.experiments.find(q=>q.id===C);if(!x)return;const B=x.artifacts.filter(q=>q.type==="model"),G={id:T.createId(),name:c("mlStudio.modelFrom","Model from {name}").replace("{name}",x.name),version:"1.0.0",algorithm:x.config.algorithm,experimentId:C,status:"registered",metrics:x.metrics,size:B.reduce((q,W)=>q+W.size,0),artifacts:B,deployments:[],createdAt:new Date};_(q=>({models:[...q.models,G]}))},$=async C=>{const x=p.models.find(G=>G.id===C);if(!x||!r)return;const B=await r(x);_(G=>({models:G.models.map(q=>q.id===C?{...q,status:"production",deployments:[...q.deployments,B]}:q)}))},E=C=>C<1024?`${C} B`:C<1024*1024?`${(C/1024).toFixed(1)} KB`:C<1024*1024*1024?`${(C/1024/1024).toFixed(1)} MB`:`${(C/1024/1024/1024).toFixed(1)} GB`,z=C=>{switch(C){case"completed":case"production":case"running":return"success";case"pending":case"staging":return"pending";case"failed":return"error";case"deploying":case"stopped":return C;default:return"neutral"}},F=e.jsxs("div",{className:"nice-ml-studio__header-info",children:[e.jsx("input",{type:"text",value:p.name,onChange:C=>_({name:C.target.value}),className:"nice-ml-studio__project-name-input","aria-label":c("mlStudio.projectName","Project name")}),e.jsx("select",{value:p.type,onChange:C=>_({type:C.target.value}),className:"nice-ml-studio__project-type-select","aria-label":c("mlStudio.projectType","Project type"),children:mi.map(([C,x,B])=>e.jsx("option",{value:C,children:c(x,B)},C))})]}),U=e.jsx("div",{className:"nice-ml-studio__header-tabs",children:pi.map(([C,x,B])=>e.jsx("button",{className:`nice-ml-studio__tab-button ${v===C?"nice-ml-studio__tab-button--active":""}`,onClick:()=>w(C),children:c(x,B)},C))}),H=e.jsxs("div",{className:"nice-ml-studio__content",children:[v==="data"&&e.jsxs("div",{className:"nice-ml-studio__data-panel",children:[e.jsxs("div",{className:"nice-ml-studio__panel-header",children:[e.jsx("h2",{children:c("mlStudio.datasets","Datasets")}),e.jsxs("label",{className:"nice-ml-studio__upload-button",children:[e.jsx("input",{type:"file",multiple:!0,accept:".csv,.json,.parquet",onChange:C=>C.target.files&&f(C.target.files),hidden:!0}),e.jsx(T.NiceIcon,{name:"plus",size:14})," ",c("mlStudio.uploadDataset","Upload Dataset")]})]}),e.jsx("div",{className:"nice-ml-studio__datasets-grid",children:p.datasets.length===0?e.jsxs("div",{className:"nice-ml-studio__empty-state",children:[e.jsx("span",{className:"nice-ml-studio__icon",children:e.jsx(T.NiceIcon,{name:"bar-chart",size:32})}),e.jsx("p",{children:c("mlStudio.noDatasets","No datasets uploaded yet")}),e.jsx("p",{className:"nice-ml-studio__hint",children:c("mlStudio.noDatasetsHint","Upload CSV, JSON, or Parquet files to get started")})]}):p.datasets.map(C=>e.jsxs("div",{className:`nice-ml-studio__dataset-card ${A===C.id?"nice-ml-studio__dataset-card--selected":""}`,onClick:()=>R(C.id),children:[e.jsxs("div",{className:"nice-ml-studio__card-header",children:[e.jsx("span",{className:"nice-ml-studio__dataset-icon",children:e.jsx(T.NiceIcon,{name:"folder",size:16})}),e.jsx("h3",{children:C.name}),e.jsx("button",{className:"nice-ml-studio__remove-button","aria-label":c("mlStudio.removeDataset","Remove dataset"),onClick:x=>{x.stopPropagation(),k(C.id)},children:e.jsx(T.NiceIcon,{name:"close",size:14})})]}),e.jsxs("div",{className:"nice-ml-studio__card-stats",children:[e.jsx("span",{children:c("mlStudio.rows","{count} rows").replace("{count}",C.rowCount.toLocaleString(m))}),e.jsx("span",{children:c("mlStudio.columnCount","{count} columns").replace("{count}",String(C.columns.length))}),e.jsx("span",{children:E(C.size)})]}),e.jsx("div",{className:"nice-ml-studio__splits-bar",children:C.splits.map(x=>e.jsx("div",{className:`nice-ml-studio__split nice-ml-studio__split--${x.name}`,style:{width:`${x.ratio*100}%`},title:`${ce(hi[x.name],x.name,c)}: ${(x.ratio*100).toFixed(0)}%`},x.name))})]},C.id))}),A&&e.jsx("div",{className:"nice-ml-studio__dataset-details",children:(()=>{const C=p.datasets.find(x=>x.id===A);return C?e.jsxs(e.Fragment,{children:[e.jsx("h3",{children:c("mlStudio.columns","Columns")}),e.jsxs("table",{className:"nice-ml-studio__columns-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:c("mlStudio.col.name","Name")}),e.jsx("th",{children:c("mlStudio.col.type","Type")}),e.jsx("th",{children:c("mlStudio.col.missing","Missing")}),e.jsx("th",{children:c("mlStudio.col.unique","Unique")})]})}),e.jsx("tbody",{children:C.columns.map(x=>e.jsxs("tr",{children:[e.jsx("td",{children:x.name}),e.jsx("td",{children:e.jsx("select",{value:x.type,"aria-label":c("mlStudio.col.type","Type"),onChange:B=>{_({datasets:p.datasets.map(G=>G.id===C.id?{...G,columns:G.columns.map(q=>q.name===x.name?{...q,type:B.target.value}:q)}:G)})},children:gi.map(([B,G,q])=>e.jsx("option",{value:B,children:c(G,q)},B))})}),e.jsx("td",{children:x.missing}),e.jsx("td",{children:x.unique})]},x.name))})]})]}):null})()})]}),v==="experiments"&&e.jsxs("div",{className:"nice-ml-studio__experiments-panel",children:[e.jsxs("div",{className:"nice-ml-studio__panel-header",children:[e.jsx("h2",{children:c("mlStudio.tab.experiments","Experiments")}),e.jsxs("button",{className:"nice-ml-studio__primary-button",onClick:()=>y(!0),disabled:p.datasets.length===0,children:[e.jsx(T.NiceIcon,{name:"plus",size:14})," ",c("mlStudio.newExperiment","New Experiment")]})]}),j&&e.jsxs("div",{className:"nice-ml-studio__new-experiment-form",children:[e.jsx("h3",{children:c("mlStudio.configureExperiment","Configure Experiment")}),e.jsxs("div",{className:"nice-ml-studio__form-grid",children:[e.jsxs("label",{children:[c("mlStudio.dataset","Dataset"),e.jsxs("select",{value:A||"",onChange:C=>R(C.target.value),children:[e.jsx("option",{value:"",children:c("mlStudio.selectDataset","Select dataset...")}),p.datasets.map(C=>e.jsx("option",{value:C.id,children:C.name},C.id))]})]}),e.jsxs("label",{children:[c("mlStudio.algorithm","Algorithm"),e.jsxs("select",{value:I.algorithm,onChange:C=>b({...I,algorithm:C.target.value}),children:[e.jsx("option",{value:"",children:c("mlStudio.selectAlgorithm","Select algorithm...")}),(je[p.type]||je.classification).map(C=>e.jsx("option",{value:C.id,children:c(C.key,C.name)},C.id))]})]}),A&&e.jsxs("label",{children:[c("mlStudio.targetColumn","Target Column"),e.jsxs("select",{value:I.targetColumn||"",onChange:C=>b({...I,targetColumn:C.target.value}),children:[e.jsx("option",{value:"",children:c("mlStudio.selectTarget","Select target...")}),(X=p.datasets.find(C=>C.id===A))==null?void 0:X.columns.map(C=>e.jsx("option",{value:C.name,children:C.name},C.name))]})]})]}),e.jsxs("div",{className:"nice-ml-studio__form-actions",children:[e.jsx("button",{className:"nice-ml-studio__secondary-button",onClick:()=>y(!1),children:c("cancel","Cancel")}),e.jsx("button",{className:"nice-ml-studio__primary-button",onClick:S,disabled:!I.algorithm||!A,children:c("mlStudio.runExperiment","Run Experiment")})]})]}),e.jsx("div",{className:"nice-ml-studio__experiments-list",children:p.experiments.length===0?e.jsxs("div",{className:"nice-ml-studio__empty-state",children:[e.jsx("span",{className:"nice-ml-studio__icon",children:e.jsx(T.NiceIcon,{name:"flask",size:32})}),e.jsx("p",{children:c("mlStudio.noExperiments","No experiments yet")}),e.jsx("p",{className:"nice-ml-studio__hint",children:c("mlStudio.noExperimentsHint","Create an experiment to train and evaluate models")})]}):p.experiments.map(C=>e.jsxs("div",{className:`nice-ml-studio__experiment-card ${M===C.id?"nice-ml-studio__experiment-card--selected":""}`,onClick:()=>P(C.id),children:[e.jsxs("div",{className:"nice-ml-studio__card-header",children:[e.jsx("h3",{children:C.name}),e.jsx("span",{className:`nice-ml-studio__status-badge nice-ml-studio__status-badge--${z(C.status)}`,children:ce(fi[C.status],C.status,c)})]}),e.jsxs("div",{className:"nice-ml-studio__card-meta",children:[e.jsx("span",{children:c("mlStudio.algorithmValue","Algorithm: {name}").replace("{name}",Fe(C.config.algorithm,c))}),C.duration!==void 0&&e.jsx("span",{children:c("mlStudio.duration","Duration: {seconds}s").replace("{seconds}",String(Math.round(C.duration)))})]}),C.metrics.length>0&&e.jsx("div",{className:"nice-ml-studio__metrics-row",children:C.metrics.slice(0,3).map(x=>e.jsxs("div",{className:"nice-ml-studio__metric-item",children:[e.jsx("span",{className:"nice-ml-studio__metric-name",children:x.name}),e.jsx("span",{className:"nice-ml-studio__metric-value",children:Je(x,m)})]},x.name))}),C.status==="completed"&&e.jsx("button",{className:"nice-ml-studio__action-button",onClick:x=>{x.stopPropagation(),N(C.id)},children:c("mlStudio.registerModel","Register Model")})]},C.id))})]}),v==="models"&&e.jsxs("div",{className:"nice-ml-studio__models-panel",children:[e.jsx("div",{className:"nice-ml-studio__panel-header",children:e.jsx("h2",{children:c("mlStudio.tab.models","Models")})}),e.jsx("div",{className:"nice-ml-studio__models-list",children:p.models.length===0?e.jsxs("div",{className:"nice-ml-studio__empty-state",children:[e.jsx("span",{className:"nice-ml-studio__icon",children:e.jsx(T.NiceIcon,{name:"wand",size:32})}),e.jsx("p",{children:c("mlStudio.noModels","No models registered yet")}),e.jsx("p",{className:"nice-ml-studio__hint",children:c("mlStudio.noModelsHint","Complete experiments and register models")})]}):p.models.map(C=>e.jsxs("div",{className:`nice-ml-studio__model-card ${g===C.id?"nice-ml-studio__model-card--selected":""}`,onClick:()=>d(C.id),children:[e.jsxs("div",{className:"nice-ml-studio__card-header",children:[e.jsx("h3",{children:C.name}),e.jsx("span",{className:`nice-ml-studio__status-badge nice-ml-studio__status-badge--${z(C.status)}`,children:ce(xi[C.status],C.status,c)})]}),e.jsxs("div",{className:"nice-ml-studio__card-meta",children:[e.jsx("span",{children:c("mlStudio.algorithmValue","Algorithm: {name}").replace("{name}",Fe(C.algorithm,c))}),e.jsx("span",{children:c("mlStudio.version","Version: {version}").replace("{version}",C.version)}),C.size>0&&e.jsx("span",{children:c("mlStudio.size","Size: {size}").replace("{size}",E(C.size))})]}),C.metrics.length>0&&e.jsx("div",{className:"nice-ml-studio__metrics-row",children:C.metrics.slice(0,3).map(x=>e.jsxs("div",{className:"nice-ml-studio__metric-item",children:[e.jsx("span",{className:"nice-ml-studio__metric-name",children:x.name}),e.jsx("span",{className:"nice-ml-studio__metric-value",children:Je(x,m)})]},x.name))}),e.jsxs("div",{className:"nice-ml-studio__card-actions",children:[e.jsx("button",{className:"nice-ml-studio__action-button",onClick:x=>{x.stopPropagation(),n==null||n(C)},disabled:!n,title:n?void 0:c("mlStudio.downloadNotSetUp","Downloading models is not set up"),children:c("download","Download")}),e.jsx("button",{className:"nice-ml-studio__action-button nice-ml-studio__action-button--primary",onClick:x=>{x.stopPropagation(),$(C.id)},disabled:C.status==="production"||!r,title:r?void 0:c("mlStudio.deployNotSetUp","Deploying models is not set up"),children:C.status==="production"?c("mlStudio.deployed","Deployed"):c("mlStudio.deploy","Deploy")})]})]},C.id))})]}),v==="deploy"&&e.jsxs("div",{className:"nice-ml-studio__deploy-panel",children:[e.jsx("div",{className:"nice-ml-studio__panel-header",children:e.jsx("h2",{children:c("mlStudio.deployments","Deployments")})}),e.jsx("div",{className:"nice-ml-studio__deployments-list",children:p.models.filter(C=>C.deployments.length>0).length===0?e.jsxs("div",{className:"nice-ml-studio__empty-state",children:[e.jsx("span",{className:"nice-ml-studio__icon",children:e.jsx(T.NiceIcon,{name:"rocket",size:32})}),e.jsx("p",{children:c("mlStudio.noDeployments","No deployments yet")}),e.jsx("p",{className:"nice-ml-studio__hint",children:c("mlStudio.noDeploymentsHint","Deploy a model to create inference endpoints")})]}):p.models.filter(C=>C.deployments.length>0).flatMap(C=>C.deployments.map(x=>({model:C,deployment:x}))).map(({model:C,deployment:x})=>e.jsxs("div",{className:"nice-ml-studio__deployment-card",children:[e.jsxs("div",{className:"nice-ml-studio__card-header",children:[e.jsx("h3",{children:x.name}),e.jsx("span",{className:`nice-ml-studio__status-badge nice-ml-studio__status-badge--${z(x.status)}`,children:ce(bi[x.status],x.status,c)})]}),e.jsxs("div",{className:"nice-ml-studio__card-meta",children:[e.jsx("span",{children:c("mlStudio.modelValue","Model: {name}").replace("{name}",C.name)}),e.jsx("span",{children:c("mlStudio.endpoint","Endpoint: {url}").replace("{url}",x.endpoint)})]}),e.jsxs("div",{className:"nice-ml-studio__resources-info",children:[e.jsx("span",{children:c("mlStudio.cpu","CPU: {count} cores").replace("{count}",String(x.resources.cpu))}),e.jsx("span",{children:c("mlStudio.memory","Memory: {gb} GB").replace("{gb}",String(x.resources.memory))}),e.jsx("span",{children:c("mlStudio.replicas","Replicas: {count}").replace("{count}",String(x.resources.replicas))})]})]},x.id))})]})]});return e.jsxs("div",{className:`nice-ml-studio ${s}`,style:{position:"relative"},children:[e.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:e.jsx(T.NiceTutorialButton,{steps:T.resolveTutorial(o,vi)})}),e.jsx(Ma.NiceAppShell,{flush:!0,menubar:F,toolbar:U,children:H})]})},wi={id:T.createId(),name:"New Labeling Project",type:"classification",dataType:"image",status:"setup",labelSchema:{classes:[],attributes:[]},items:[],collaborators:[],statistics:{totalItems:0,labeled:0,reviewed:0,approved:0,byClass:[]},createdAt:new Date},qe=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #f59e0b)","var(--nice-success, #84cc16)","var(--nice-success, #22c55e)","var(--nice-info, #14b8a6)","var(--nice-info, #06b6d4)","var(--nice-primary, #3b82f6)","var(--nice-info, #6366f1)","var(--nice-accent, #8b5cf6)","var(--nice-accent, #a855f7)","var(--nice-color-accent-pink, #d946ef)","var(--nice-color-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)"],ji={label:"Label",schema:"Schema",review:"Review",export:"Export"},ki=({project:t,onProjectChange:a,onLabelSave:i,onExport:r,className:n=""})=>{var re;const{t:s}=T.useNiceTranslation(),[o,c]=l.useState(t||wi),[m,p]=l.useState("label"),[u,v]=l.useState(0),[w,A]=l.useState(null),[R,M]=l.useState("select"),[P,g]=l.useState(!1),[d,j]=l.useState(null),[y,I]=l.useState(1),[b,h]=l.useState(!1),[_,f]=l.useState("all"),k=l.useRef(null),S=l.useRef(null),N=o.items[u];l.useEffect(()=>{t&&c(t)},[t]);const $=l.useCallback(L=>{const O={...o,...L};O.statistics={totalItems:O.items.length,labeled:O.items.filter(J=>J.status!=="pending").length,reviewed:O.items.filter(J=>J.status==="review"||J.status==="approved").length,approved:O.items.filter(J=>J.status==="approved").length,byClass:O.labelSchema.classes.map(J=>({classId:J.id,count:O.items.flatMap(Y=>Y.labels).filter(Y=>Y.classId===J.id).length}))},c(O),a==null||a(O)},[o,a]),E=()=>{const L={id:T.createId(),name:`Class ${o.labelSchema.classes.length+1}`,color:qe[o.labelSchema.classes.length%qe.length],shortcut:String(o.labelSchema.classes.length+1)};$({labelSchema:{...o.labelSchema,classes:[...o.labelSchema.classes,L]}})},z=L=>{$({labelSchema:{...o.labelSchema,classes:o.labelSchema.classes.filter(O=>O.id!==L)},items:o.items.map(O=>({...O,labels:O.labels.filter(J=>J.classId!==L)}))})},F=(L,O)=>{$({labelSchema:{...o.labelSchema,classes:o.labelSchema.classes.map(J=>J.id===L?{...J,...O}:J)}})},U=(L,O)=>{if(!N)return;const J={id:T.createId(),classId:L,type:o.type==="classification"?"class":o.type==="bounding-box"?"bbox":"class",data:O||{},createdBy:"current-user",createdAt:new Date},Y={...N,labels:[...N.labels,J],status:"labeled"};$({items:o.items.map(D=>D.id===N.id?Y:D)}),i==null||i(Y)},H=L=>{if(!N)return;const O={...N,labels:N.labels.filter(J=>J.id!==L),status:N.labels.length<=1?"pending":"labeled"};$({items:o.items.map(J=>J.id===N.id?O:J)})},X=L=>{var D;if(R!=="bbox"||!w)return;const O=(D=k.current)==null?void 0:D.getBoundingClientRect();if(!O)return;const J=(L.clientX-O.left)/y,Y=(L.clientY-O.top)/y;g(!0),j({x:J,y:Y,width:0,height:0})},C=L=>{var D;if(!P||!d)return;const O=(D=k.current)==null?void 0:D.getBoundingClientRect();if(!O)return;const J=(L.clientX-O.left)/y,Y=(L.clientY-O.top)/y;j({...d,width:J-d.x,height:Y-d.y})},x=()=>{!P||!d||!w||(g(!1),Math.abs(d.width)>10&&Math.abs(d.height)>10&&U(w,{x:d.width<0?d.x+d.width:d.x,y:d.height<0?d.y+d.height:d.y,width:Math.abs(d.width),height:Math.abs(d.height)}),j(null))},B=L=>{const O=_==="all"?o.items:o.items.filter(Y=>Y.status===_),J=O.findIndex(Y=>Y.id===(N==null?void 0:N.id));if(L==="prev"&&J>0){const Y=O[J-1];v(o.items.findIndex(D=>D.id===Y.id))}else if(L==="next"&&J<O.length-1){const Y=O[J+1];v(o.items.findIndex(D=>D.id===Y.id))}},G=()=>{if(!N)return;const L={...N,status:"approved"};$({items:o.items.map(O=>O.id===N.id?L:O)}),B("next")},q=()=>{if(!N)return;const L={...N,status:"rejected"};$({items:o.items.map(O=>O.id===N.id?L:O)}),B("next")},W=async L=>{r&&await r(L)};l.useEffect(()=>{const L=O=>{const J=O.target instanceof HTMLElement?O.target:null;if(m!=="label"||O.defaultPrevented||O.ctrlKey||O.metaKey||O.altKey||J!=null&&J.isContentEditable||J&&/^(INPUT|TEXTAREA|SELECT)$/.test(J.tagName)||O.key==="Enter"&&(J!=null&&J.closest("button, a")))return;const Y=O.key,D=o.labelSchema.classes.find(K=>K.shortcut===Y);D&&(o.type==="classification"?(U(D.id),B("next")):A(D.id)),O.key==="ArrowLeft"||O.key==="a"?B("prev"):(O.key==="ArrowRight"||O.key==="d")&&B("next"),O.key==="Enter"?G():O.key==="Backspace"&&q()};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[m,N,o.labelSchema.classes,o.type]);const Q=L=>{switch(L){case"approved":return"var(--nice-success, #22c55e)";case"labeled":return"var(--nice-primary, #3b82f6)";case"review":return"var(--nice-warning, #f59e0b)";case"rejected":return"var(--nice-danger, #ef4444)";default:return"var(--nice-text-secondary, #6b7280)"}};return e.jsxs("div",{className:`nice-data-labeler ${n}`,children:[e.jsxs("header",{className:"nice-data-labeler__header",children:[e.jsxs("div",{className:"nice-data-labeler__header-info",children:[e.jsx("input",{type:"text",value:o.name,onChange:L=>$({name:L.target.value}),className:"nice-data-labeler__project-name-input"}),e.jsxs("div",{className:"nice-data-labeler__progress-bar",children:[e.jsx("div",{className:"nice-data-labeler__progress-fill",style:{width:`${o.statistics.labeled/Math.max(o.statistics.totalItems,1)*100}%`}}),e.jsx("span",{className:"nice-data-labeler__progress-text",children:s("dataLabeler.progress","{labeled} / {total} labeled").replace("{labeled}",String(o.statistics.labeled)).replace("{total}",String(o.statistics.totalItems))})]})]}),e.jsx("div",{className:"nice-data-labeler__header-tabs",children:["label","schema","review","export"].map(L=>e.jsx("button",{className:`nice-data-labeler__tab-button ${m===L?"nice-data-labeler__tab-button--active":""}`,onClick:()=>p(L),children:s(`dataLabeler.tab.${L}`,ji[L])},L))}),e.jsx("button",{className:"nice-data-labeler__shortcuts-button",onClick:()=>h(!b),children:s("dataLabeler.shortcuts","Shortcuts")})]}),e.jsxs("div",{className:"nice-data-labeler__content",children:[m==="label"&&e.jsxs("div",{className:"nice-data-labeler__label-panel",children:[e.jsxs("div",{className:"nice-data-labeler__label-toolbar",children:[e.jsxs("div",{className:"nice-data-labeler__tool-group",children:[e.jsxs("button",{className:`nice-data-labeler__tool-button ${R==="select"?"nice-data-labeler__tool-button--active":""}`,onClick:()=>M("select"),children:[e.jsx(T.NiceIcon,{name:"cursor",size:14})," ",s("dataLabeler.select","Select")]}),(o.type==="bounding-box"||o.type==="multi-label")&&e.jsxs("button",{className:`nice-data-labeler__tool-button ${R==="bbox"?"nice-data-labeler__tool-button--active":""}`,onClick:()=>M("bbox"),children:[e.jsx(T.NiceIcon,{name:"square",size:14})," Box"]}),o.type==="polygon"&&e.jsxs("button",{className:`nice-data-labeler__tool-button ${R==="polygon"?"nice-data-labeler__tool-button--active":""}`,onClick:()=>M("polygon"),children:[e.jsx(T.NiceIcon,{name:"hexagon",size:14})," ",s("dataLabeler.polygon","Polygon")]})]}),e.jsxs("div",{className:"nice-data-labeler__zoom-group",children:[e.jsx("button",{"aria-label":s("dataLabeler.zoomOut","Zoom out"),onClick:()=>I(Math.max(.25,y-.25)),children:e.jsx(T.NiceIcon,{name:"minus",size:14})}),e.jsxs("span",{children:[Math.round(y*100),"%"]}),e.jsx("button",{"aria-label":s("dataLabeler.zoomIn","Zoom in"),onClick:()=>I(Math.min(4,y+.25)),children:e.jsx(T.NiceIcon,{name:"plus",size:14})})]}),e.jsxs("div",{className:"nice-data-labeler__navigation-group",children:[e.jsxs("button",{onClick:()=>B("prev"),disabled:u===0,children:[e.jsx(T.NiceIcon,{name:"arrow-left",size:14})," ",s("dataLabeler.prev","Prev")]}),e.jsxs("span",{children:[u+1," / ",o.items.length]}),e.jsxs("button",{onClick:()=>B("next"),disabled:u>=o.items.length-1,children:[s("dataLabeler.next","Next")," ",e.jsx(T.NiceIcon,{name:"arrow-right",size:14})]})]})]}),e.jsxs("div",{className:"nice-data-labeler__label-workspace",children:[e.jsx("div",{className:"nice-data-labeler__canvas-container",ref:S,children:N?e.jsxs(e.Fragment,{children:[N.data.type==="image"&&e.jsxs(e.Fragment,{children:[e.jsx("img",{src:N.data.url,alt:s("dataLabeler.labelingItem","Labeling item"),className:"nice-data-labeler__labeling-image",style:{transform:`scale(${y})`}}),e.jsx("canvas",{ref:k,className:"nice-data-labeler__labeling-canvas",onMouseDown:X,onMouseMove:C,onMouseUp:x,onMouseLeave:x,style:{transform:`scale(${y})`,cursor:R==="bbox"?"crosshair":"default"}}),e.jsxs("div",{className:"nice-data-labeler__annotations-overlay",style:{transform:`scale(${y})`},children:[N.labels.filter(L=>L.type==="bbox"&&L.data.x!==void 0).map(L=>{const O=o.labelSchema.classes.find(J=>J.id===L.classId);return e.jsxs("div",{className:"nice-data-labeler__bbox-annotation",style:{left:L.data.x,top:L.data.y,width:L.data.width,height:L.data.height,borderColor:(O==null?void 0:O.color)||"var(--nice-danger, #ff0000)"},children:[e.jsx("span",{className:"nice-data-labeler__bbox-label",style:{backgroundColor:(O==null?void 0:O.color)||"var(--nice-danger, #ff0000)"},children:O==null?void 0:O.name}),e.jsx("button",{className:"nice-data-labeler__bbox-remove","aria-label":s("dataLabeler.removeLabel","Remove label"),onClick:()=>H(L.id),children:e.jsx(T.NiceIcon,{name:"close",size:12})})]},L.id)}),d&&e.jsx("div",{className:"nice-data-labeler__bbox-drawing",style:{left:d.width<0?d.x+d.width:d.x,top:d.height<0?d.y+d.height:d.y,width:Math.abs(d.width),height:Math.abs(d.height),borderColor:(re=o.labelSchema.classes.find(L=>L.id===w))==null?void 0:re.color}})]})]}),N.data.type==="text"&&e.jsx("div",{className:"nice-data-labeler__text-labeling",children:e.jsx("p",{className:"nice-data-labeler__text-content",children:N.data.text})})]}):e.jsxs("div",{className:"nice-data-labeler__empty-state",children:[e.jsx("span",{className:"nice-data-labeler__icon",children:e.jsx(T.NiceIcon,{name:"clipboard",size:32})}),e.jsx("p",{children:s("dataLabeler.noItemsToLabel","No items to label")})]})}),e.jsxs("aside",{className:"nice-data-labeler__class-sidebar",children:[e.jsx("h3",{children:s("dataLabeler.classes","Classes")}),e.jsx("div",{className:"nice-data-labeler__class-list",children:o.labelSchema.classes.map(L=>e.jsxs("button",{className:`nice-data-labeler__class-button ${w===L.id?"nice-data-labeler__class-button--active":""}`,style:{borderLeftColor:L.color},onClick:()=>{o.type==="classification"?(U(L.id),B("next")):A(L.id)},children:[e.jsx("span",{className:"nice-data-labeler__class-color",style:{backgroundColor:L.color}}),e.jsx("span",{className:"nice-data-labeler__class-name",children:L.name}),L.shortcut&&e.jsx("span",{className:"nice-data-labeler__class-shortcut",children:L.shortcut})]},L.id))}),N&&N.labels.length>0&&e.jsxs("div",{className:"nice-data-labeler__current-labels",children:[e.jsx("h4",{children:s("dataLabeler.labels","Labels")}),N.labels.map(L=>{const O=o.labelSchema.classes.find(J=>J.id===L.classId);return e.jsxs("div",{className:"nice-data-labeler__label-item",children:[e.jsx("span",{className:"nice-data-labeler__label-color",style:{backgroundColor:O==null?void 0:O.color}}),e.jsx("span",{className:"nice-data-labeler__label-name",children:O==null?void 0:O.name}),e.jsx("button",{"aria-label":s("dataLabeler.removeLabel","Remove label"),onClick:()=>H(L.id),children:e.jsx(T.NiceIcon,{name:"close",size:14})})]},L.id)})]}),m==="label"&&N&&e.jsxs("div",{className:"nice-data-labeler__label-actions",children:[e.jsxs("button",{className:"nice-data-labeler__approve-button",onClick:G,children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",s("dataLabeler.approve","Approve")]}),e.jsxs("button",{className:"nice-data-labeler__reject-button",onClick:q,children:[e.jsx(T.NiceIcon,{name:"close",size:14})," ",s("dataLabeler.reject","Reject")]})]})]})]})]}),m==="schema"&&e.jsxs("div",{className:"nice-data-labeler__schema-panel",children:[e.jsxs("div",{className:"nice-data-labeler__panel-header",children:[e.jsx("h2",{children:s("dataLabeler.labelSchema","Label Schema")}),e.jsxs("button",{className:"nice-data-labeler__primary-button",onClick:E,children:[e.jsx(T.NiceIcon,{name:"plus",size:14})," ",s("dataLabeler.addClass","Add Class")]})]}),e.jsxs("div",{className:"nice-data-labeler__schema-settings",children:[e.jsxs("label",{children:[s("dataLabeler.labelingType","Labeling Type"),e.jsxs("select",{value:o.type,onChange:L=>$({type:L.target.value}),children:[e.jsx("option",{value:"classification",children:s("dataLabeler.singleClassification","Single Classification")}),e.jsx("option",{value:"multi-label",children:s("dataLabeler.multiLabelClassification","Multi-Label Classification")}),e.jsx("option",{value:"bounding-box",children:s("dataLabeler.boundingBox","Bounding Box")}),e.jsx("option",{value:"polygon",children:s("dataLabeler.polygon","Polygon")}),e.jsx("option",{value:"segmentation",children:s("dataLabeler.segmentation","Segmentation")}),e.jsx("option",{value:"ner",children:s("dataLabeler.namedEntityRecognition","Named Entity Recognition")})]})]}),e.jsxs("label",{children:[s("dataLabeler.dataType","Data Type"),e.jsxs("select",{value:o.dataType,onChange:L=>$({dataType:L.target.value}),children:[e.jsx("option",{value:"image",children:s("dataLabeler.image","Image")}),e.jsx("option",{value:"text",children:s("dataLabeler.text","Text")}),e.jsx("option",{value:"audio",children:s("dataLabeler.audio","Audio")}),e.jsx("option",{value:"video",children:s("dataLabeler.video","Video")})]})]})]}),e.jsx("div",{className:"nice-data-labeler__classes-list",children:o.labelSchema.classes.map((L,O)=>e.jsxs("div",{className:"nice-data-labeler__class-editor",children:[e.jsx("input",{type:"color",value:L.color,onChange:J=>F(L.id,{color:J.target.value}),className:"nice-data-labeler__color-picker"}),e.jsx("input",{type:"text",value:L.name,onChange:J=>F(L.id,{name:J.target.value}),className:"nice-data-labeler__class-name-input",placeholder:s("dataLabeler.classNamePlaceholder","Class name")}),e.jsx("input",{type:"text",value:L.shortcut||"",onChange:J=>F(L.id,{shortcut:J.target.value}),className:"nice-data-labeler__shortcut-input",placeholder:s("dataLabeler.shortcutKeyPlaceholder","Key"),maxLength:1}),e.jsx("button",{className:"nice-data-labeler__remove-class-button","aria-label":s("dataLabeler.removeClass","Remove class"),onClick:()=>z(L.id),children:e.jsx(T.NiceIcon,{name:"trash",size:16})})]},L.id))}),e.jsxs("div",{className:"nice-data-labeler__guidelines-section",children:[e.jsx("h3",{children:s("dataLabeler.labelingGuidelines","Labeling Guidelines")}),e.jsx("textarea",{value:o.guidelines||"",onChange:L=>$({guidelines:L.target.value}),placeholder:s("dataLabeler.guidelinesPlaceholder","Enter labeling guidelines for annotators..."),rows:6})]})]}),m==="review"&&e.jsxs("div",{className:"nice-data-labeler__review-panel",children:[e.jsxs("div",{className:"nice-data-labeler__panel-header",children:[e.jsx("h2",{children:s("dataLabeler.reviewLabels","Review Labels")}),e.jsx("div",{className:"nice-data-labeler__filter-group",children:e.jsxs("select",{value:_,onChange:L=>f(L.target.value),children:[e.jsx("option",{value:"all",children:s("dataLabeler.allItems","All Items")}),e.jsx("option",{value:"labeled",children:s("dataLabeler.labeled","Labeled")}),e.jsx("option",{value:"review",children:s("dataLabeler.needsReview","Needs Review")}),e.jsx("option",{value:"approved",children:s("dataLabeler.approved","Approved")}),e.jsx("option",{value:"rejected",children:s("dataLabeler.rejected","Rejected")})]})})]}),e.jsx("div",{className:"nice-data-labeler__items-grid",children:o.items.filter(L=>_==="all"||L.status===_).map((L,O)=>{var J;return e.jsxs("div",{className:`nice-data-labeler__item-card ${u===o.items.indexOf(L)?"nice-data-labeler__item-card--active":""}`,onClick:()=>{v(o.items.indexOf(L)),p("label")},children:[L.data.type==="image"&&e.jsx("img",{src:L.data.url,alt:`Item ${O+1}`,className:"nice-data-labeler__item-thumbnail"}),L.data.type==="text"&&e.jsxs("p",{className:"nice-data-labeler__item-text-preview",children:[(J=L.data.text)==null?void 0:J.slice(0,100),"..."]}),e.jsxs("div",{className:"nice-data-labeler__item-footer",children:[e.jsx("span",{className:"nice-data-labeler__status-dot",style:{backgroundColor:Q(L.status)}}),e.jsx("span",{children:s("dataLabeler.labelCount","{count} labels").replace("{count}",String(L.labels.length))})]})]},L.id)})})]}),m==="export"&&e.jsxs("div",{className:"nice-data-labeler__export-panel",children:[e.jsx("div",{className:"nice-data-labeler__panel-header",children:e.jsx("h2",{children:s("dataLabeler.exportLabels","Export Labels")})}),e.jsxs("div",{className:"nice-data-labeler__export-stats",children:[e.jsxs("div",{className:"nice-data-labeler__stat-card",children:[e.jsx("span",{className:"nice-data-labeler__stat-value",children:o.statistics.totalItems}),e.jsx("span",{className:"nice-data-labeler__stat-label",children:s("dataLabeler.totalItems","Total Items")})]}),e.jsxs("div",{className:"nice-data-labeler__stat-card",children:[e.jsx("span",{className:"nice-data-labeler__stat-value",children:o.statistics.labeled}),e.jsx("span",{className:"nice-data-labeler__stat-label",children:s("dataLabeler.labeled","Labeled")})]}),e.jsxs("div",{className:"nice-data-labeler__stat-card",children:[e.jsx("span",{className:"nice-data-labeler__stat-value",children:o.statistics.approved}),e.jsx("span",{className:"nice-data-labeler__stat-label",children:s("dataLabeler.approved","Approved")})]}),e.jsxs("div",{className:"nice-data-labeler__stat-card",children:[e.jsx("span",{className:"nice-data-labeler__stat-value",children:o.labelSchema.classes.length}),e.jsx("span",{className:"nice-data-labeler__stat-label",children:s("dataLabeler.classes","Classes")})]})]}),e.jsxs("div",{className:"nice-data-labeler__export-formats",children:[e.jsx("h3",{children:s("dataLabeler.exportFormat","Export Format")}),e.jsxs("div",{className:"nice-data-labeler__format-grid",children:[e.jsxs("button",{className:"nice-data-labeler__format-button",onClick:()=>W("coco"),children:[e.jsx("span",{className:"nice-data-labeler__format-icon",children:e.jsx(T.NiceIcon,{name:"box",size:24})}),e.jsx("span",{className:"nice-data-labeler__format-name",children:s("dataLabeler.cocoJson","COCO JSON")}),e.jsx("span",{className:"nice-data-labeler__format-desc",children:s("dataLabeler.cocoDesc","Common format for object detection")})]}),e.jsxs("button",{className:"nice-data-labeler__format-button",onClick:()=>W("voc"),children:[e.jsx("span",{className:"nice-data-labeler__format-icon",children:e.jsx(T.NiceIcon,{name:"file",size:24})}),e.jsx("span",{className:"nice-data-labeler__format-name",children:s("dataLabeler.pascalVoc","Pascal VOC")}),e.jsx("span",{className:"nice-data-labeler__format-desc",children:s("dataLabeler.vocDesc","XML format for bounding boxes")})]}),e.jsxs("button",{className:"nice-data-labeler__format-button",onClick:()=>W("yolo"),children:[e.jsx("span",{className:"nice-data-labeler__format-icon",children:e.jsx(T.NiceIcon,{name:"zap",size:24})}),e.jsx("span",{className:"nice-data-labeler__format-name",children:s("dataLabeler.yolo","YOLO")}),e.jsx("span",{className:"nice-data-labeler__format-desc",children:s("dataLabeler.yoloDesc","Text format for YOLO models")})]}),e.jsxs("button",{className:"nice-data-labeler__format-button",onClick:()=>W("csv"),children:[e.jsx("span",{className:"nice-data-labeler__format-icon",children:e.jsx(T.NiceIcon,{name:"bar-chart",size:24})}),e.jsx("span",{className:"nice-data-labeler__format-name",children:"CSV"}),e.jsx("span",{className:"nice-data-labeler__format-desc",children:s("dataLabeler.csvDesc","Tabular format for classification")})]})]})]}),e.jsxs("div",{className:"nice-data-labeler__class-distribution",children:[e.jsx("h3",{children:s("dataLabeler.classDistribution","Class Distribution")}),e.jsx("div",{className:"nice-data-labeler__distribution-bars",children:o.statistics.byClass.map(L=>{const O=o.labelSchema.classes.find(Y=>Y.id===L.classId),J=L.count/Math.max(o.statistics.labeled,1)*100;return e.jsxs("div",{className:"nice-data-labeler__distribution-row",children:[e.jsx("span",{className:"nice-data-labeler__class-name",style:{color:O==null?void 0:O.color},children:O==null?void 0:O.name}),e.jsx("div",{className:"nice-data-labeler__bar-container",children:e.jsx("div",{className:"nice-data-labeler__bar-fill",style:{width:`${J}%`,backgroundColor:O==null?void 0:O.color}})}),e.jsx("span",{className:"nice-data-labeler__count",children:L.count})]},L.classId)})})]})]})]}),b&&e.jsx("div",{className:"nice-data-labeler__shortcuts-modal",children:e.jsxs("div",{className:"nice-data-labeler__modal-content",children:[e.jsxs("div",{className:"nice-data-labeler__modal-header",children:[e.jsx("h3",{children:s("dataLabeler.keyboardShortcuts","Keyboard Shortcuts")}),e.jsx("button",{"aria-label":s("dataLabeler.close","Close"),onClick:()=>h(!1),children:e.jsx(T.NiceIcon,{name:"close",size:16})})]}),e.jsxs("div",{className:"nice-data-labeler__shortcuts-list",children:[e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsxs("span",{className:"nice-data-labeler__keys",children:[e.jsx(T.NiceIcon,{name:"arrow-left",size:14})," / A"]}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.previousItem","Previous item")})]}),e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsxs("span",{className:"nice-data-labeler__keys",children:[e.jsx(T.NiceIcon,{name:"arrow-right",size:14})," / D"]}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.nextItem","Next item")})]}),e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsx("span",{className:"nice-data-labeler__keys",children:s("dataLabeler.enterKey","Enter")}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.approveItem","Approve item")})]}),e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsx("span",{className:"nice-data-labeler__keys",children:s("dataLabeler.backspaceKey","Backspace")}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.rejectItem","Reject item")})]}),o.labelSchema.classes.map(L=>L.shortcut&&e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsx("span",{className:"nice-data-labeler__keys",children:L.shortcut}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.labelAs","Label as {name}").replace("{name}",L.name)})]},L.id))]})]})})]})},Ni={id:T.createId(),name:"Model Endpoint",modelId:"",modelVersion:"1.0.0",status:"stopped",url:"",authentication:{type:"api-key"},metrics:{requestsTotal:0,requestsPerSecond:0,latencyP50:0,latencyP95:0,latencyP99:0,errorRate:0,successRate:100},logs:[]},Si=({endpoint:t,onInference:a,showMetrics:i=!0,showLogs:r=!0,className:n=""})=>{const{t:s}=T.useNiceTranslation(),[o,c]=l.useState(t||Ni),[m,p]=l.useState("test"),[u,v]=l.useState("text"),[w,A]=l.useState(""),[R,M]=l.useState("{}"),[P,g]=l.useState(null),[d,j]=l.useState({temperature:.7,topK:50,topP:.9,maxTokens:256,threshold:.5}),[y,I]=l.useState(null),[b,h]=l.useState(!1),[_,f]=l.useState(null),[k,S]=l.useState([]),[N,$]=l.useState(null),E=l.useRef(null),z=x=>{var G;const B=(G=x.target.files)==null?void 0:G[0];if(B){const q=new FileReader;q.onload=W=>{var Q;g((Q=W.target)==null?void 0:Q.result)},q.readAsDataURL(B)}},F=async()=>{if(!a){f("No inference handler provided");return}h(!0),f(null),I(null);const x=[];switch(u){case"text":x.push({type:"text",data:w});break;case"image":P&&x.push({type:"image",data:P});break;case"json":try{x.push({type:"json",data:JSON.parse(R)})}catch{f("Invalid JSON input"),h(!1);return}break;case"tabular":try{x.push({type:"tabular",data:JSON.parse(R)})}catch{f("Invalid tabular data"),h(!1);return}break}const B={inputs:x,parameters:d};try{const G=Date.now(),q=await a(B),W=Date.now()-G;I(q),c(Q=>({...Q,metrics:{...Q.metrics,requestsTotal:Q.metrics.requestsTotal+1,latencyP50:(Q.metrics.latencyP50+W)/2},logs:[{timestamp:new Date,requestId:q.requestId,duration:W,status:"success",inputSize:JSON.stringify(x).length,outputSize:JSON.stringify(q.predictions).length},...Q.logs.slice(0,99)]}))}catch(G){const q=G instanceof Error?G.message:"Inference failed";f(q),c(W=>({...W,metrics:{...W.metrics,requestsTotal:W.metrics.requestsTotal+1,errorRate:(W.metrics.errorRate*W.metrics.requestsTotal+1)/(W.metrics.requestsTotal+1)},logs:[{timestamp:new Date,requestId:T.createId(),duration:0,status:"error",inputSize:JSON.stringify(x).length,outputSize:0,error:q},...W.logs.slice(0,99)]}))}finally{h(!1)}},U=async x=>{if(a){$(0),S([]);for(let B=0;B<x.length;B++){const G={inputs:[x[B]],parameters:d};try{const q=await a(G);S(W=>[...W,q])}catch(q){console.error("Batch item failed:",q)}$((B+1)/x.length*100)}$(null)}},H=x=>x<1e3?`${x.toFixed(0)}ms`:`${(x/1e3).toFixed(2)}s`,X=x=>x.toLocaleTimeString(),C=(x,B)=>e.jsxs("div",{className:"nice-model-inference__prediction-item",children:[x.label&&e.jsxs("div",{className:"nice-model-inference__prediction-label",children:[e.jsx("span",{className:"nice-model-inference__label-name",children:x.label}),x.confidence!==void 0&&e.jsxs("span",{className:"nice-model-inference__confidence-badge",style:{backgroundColor:`hsl(${x.confidence*120}, 70%, 40%)`},children:[(x.confidence*100).toFixed(1),"%"]})]}),x.score!==void 0&&e.jsxs("div",{className:"nice-model-inference__prediction-score",children:[e.jsx("span",{className:"nice-model-inference__score-label",children:"Score:"}),e.jsx("span",{className:"nice-model-inference__score-value",children:x.score.toFixed(4)})]}),x.text&&e.jsx("div",{className:"nice-model-inference__prediction-text",children:e.jsx("pre",{children:x.text})}),x.bbox&&e.jsx("div",{className:"nice-model-inference__prediction-bbox",children:e.jsxs("span",{children:["Box: (",x.bbox.x,", ",x.bbox.y,") - ",x.bbox.width,"×",x.bbox.height]})}),x.raw!==void 0&&x.raw!==null&&e.jsxs("details",{className:"nice-model-inference__raw-output",children:[e.jsx("summary",{children:s("modelInference.rawOutput","Raw Output")}),e.jsx("pre",{children:JSON.stringify(x.raw,null,2)})]})]},B);return e.jsxs("div",{className:`nice-model-inference ${n}`,children:[e.jsxs("header",{className:"nice-model-inference__header",children:[e.jsxs("div",{className:"nice-model-inference__header-info",children:[e.jsx("h2",{children:o.name}),e.jsx("span",{className:`nice-model-inference__status-badge nice-model-inference__status-badge--${o.status}`,children:o.status})]}),e.jsxs("div",{className:"nice-model-inference__header-tabs",children:[e.jsx("button",{className:`nice-model-inference__tab-button ${m==="test"?"nice-model-inference__tab-button--active":""}`,onClick:()=>p("test"),children:s("modelInference.test","Test")}),e.jsx("button",{className:`nice-model-inference__tab-button ${m==="batch"?"nice-model-inference__tab-button--active":""}`,onClick:()=>p("batch"),children:s("modelInference.batch","Batch")}),i&&e.jsx("button",{className:`nice-model-inference__tab-button ${m==="metrics"?"nice-model-inference__tab-button--active":""}`,onClick:()=>p("metrics"),children:s("modelInference.metrics","Metrics")}),r&&e.jsx("button",{className:`nice-model-inference__tab-button ${m==="logs"?"nice-model-inference__tab-button--active":""}`,onClick:()=>p("logs"),children:s("modelInference.logs","Logs")})]})]}),e.jsxs("div",{className:"nice-model-inference__content",children:[m==="test"&&e.jsxs("div",{className:"nice-model-inference__test-panel",children:[e.jsxs("div",{className:"nice-model-inference__input-section",children:[e.jsx("div",{className:"nice-model-inference__input-type-selector",children:["text","image","json","tabular"].map(x=>e.jsx("button",{className:`nice-model-inference__type-button ${u===x?"nice-model-inference__type-button--active":""}`,onClick:()=>v(x),children:x.charAt(0).toUpperCase()+x.slice(1)},x))}),e.jsxs("div",{className:"nice-model-inference__input-area",children:[u==="text"&&e.jsx("textarea",{value:w,onChange:x=>A(x.target.value),placeholder:s("modelInference.enterTextInput","Enter text input..."),rows:6,className:"nice-model-inference__text-input"}),u==="image"&&e.jsx("div",{className:"nice-model-inference__image-input",children:P?e.jsxs("div",{className:"nice-model-inference__image-preview",children:[e.jsx("img",{src:P,alt:s("modelInference.inputPreview","Input preview")}),e.jsx("button",{className:"nice-model-inference__clear-button",onClick:()=>g(null),children:s("modelInference.clear","Clear")})]}):e.jsxs("label",{className:"nice-model-inference__upload-zone",children:[e.jsx("input",{ref:E,type:"file",accept:"image/*",onChange:z,hidden:!0}),e.jsx("span",{className:"nice-model-inference__upload-icon",children:e.jsx(T.NiceIcon,{name:"image",size:32})}),e.jsx("span",{children:s("modelInference.clickOrDragToUpload","Click or drag to upload image")})]})}),(u==="json"||u==="tabular")&&e.jsx("textarea",{value:R,onChange:x=>M(x.target.value),placeholder:u==="json"?`{
9
+ Provide a concise inline completion or improvement hint for the code near the cursor. Limit response to ${(i==null?void 0:i.maxSuggestLines)??5} lines of code. If unsure, suggest the most idiomatic approach for this language/framework.`}}function ra(t,a,i){var s;const n=(i==null?void 0:i.mode)??"grammar",r={seo:"Analyze this HTML for SEO: missing meta tags, heading hierarchy (h1→h2→h3), keyword density, image alt attributes. Return a prioritized list of improvements.",accessibility:"Audit this HTML for WCAG 2.1 AA issues: missing aria labels, alt text, heading structure, color contrast hints, keyboard navigation. List specific fixes.",grammar:"Fix grammar, punctuation, and writing style in the visible text content. Return the corrected text only (no HTML tags in response).",cleanup:"Clean up malformed, redundant, or overly nested HTML. Simplify structure while preserving semantics and content."};return{fieldLabel:t,fieldType:"html-editor",fieldValue:a==null?void 0:a.slice(0,2e3),schema:{mode:n,...(s=i==null?void 0:i.targetKeywords)!=null&&s.length?{targetKeywords:i.targetKeywords}:{},...i!=null&&i.locale?{locale:i.locale}:{}},customPrompt:r[n]}}function na(t,a){const i=(a==null?void 0:a.mode)??"tag",n=`"${t}"`+((a==null?void 0:a.bpm)!=null?`, BPM: ${a.bpm}`:"")+(a!=null&&a.key?`, Key: ${a.key}`:"")+(a!=null&&a.genre?`, Genre: ${a.genre}`:"")+((a==null?void 0:a.duration)!=null?`, Duration: ${a.duration}s`:""),r={tag:`Audio: ${n}. Suggest genre tags, mood descriptors and playlist categories. Return as JSON array of strings.`,bpm:`Audio: ${n}. Suggest likely BPM range and musical key based on metadata. Return as JSON: { bpm: number, key: string }.`,mix:`Track: ${n}. Suggest EQ curve (JSON array of {freq, gain, q}), compression settings, and 2-3 compatible tracks for mixing.`,transcribe:"Return a transcription of the spoken audio content as JSON: { transcript: string, language: string, confidence: number }."};return{fieldLabel:`Audio: ${t}`,fieldType:"audio",schema:{mode:i,...(a==null?void 0:a.bpm)!=null?{bpm:a.bpm}:{},...a!=null&&a.key?{key:a.key}:{},...(a==null?void 0:a.duration)!=null?{duration:a.duration}:{},...a!=null&&a.genre?{genre:a.genre}:{}},customPrompt:r[i]}}function sa(t,a){var s;const i=(a==null?void 0:a.mode)??"material",n=(a==null?void 0:a.targetDevice)??"web",r={material:`Scene "${t}", ${(a==null?void 0:a.meshCount)??"?"} meshes. Materials: ${((s=a==null?void 0:a.materials)==null?void 0:s.join(", "))||"none"}. Suggest PBR properties (roughness, metalness, baseColor) and texture maps for each material.`,optimize:`Scene "${t}", triangles: ${(a==null?void 0:a.triangleCount)??"?"}, target: ${n}. Identify budget issues and suggest LOD levels, mesh merging, and texture atlas strategy.`,lighting:`Scene "${t}", target: ${n}. Suggest a complete lighting setup (types, intensity, color, shadow settings) for realistic rendering.`,animation:`Rig in scene "${t}". Suggest animation approach (FK/IK, bone count), keyframe timing and easing curves for natural movement.`};return{fieldLabel:`3D scene: ${t}`,fieldType:"3d-scene",schema:{mode:i,...(a==null?void 0:a.meshCount)!=null?{meshes:a.meshCount}:{},...(a==null?void 0:a.triangleCount)!=null?{triangles:a.triangleCount}:{},...a!=null&&a.targetDevice?{target:a.targetDevice}:{}},customPrompt:r[i]}}function ca(t,a){const i=(a==null?void 0:a.mode)??"palette",n=(a==null?void 0:a.width)!=null?`${a.width}×${a.height??"?"}px`:"unknown dimensions",r={filter:`Image "${t}" (${n}). Suggest CSS/SVG filter parameters (brightness, contrast, saturate, hue-rotate, blur) as JSON: { brightness, contrast, saturate, hueRotate, blur }.`,palette:`Image "${t}". Extract or suggest a harmonious 5-color palette as JSON: { primary, secondary, accent, background, text }.`,upscale:`Image "${t}" at ${n}. Recommend upscaling strategy: model (ESRGAN/RealSR/SRCNN), scale factor, and expected quality gain.`,"style-transfer":`Image "${t}", target style: "${(a==null?void 0:a.targetStyle)??"artistic"}". Suggest style-transfer settings as JSON: { contentWeight, styleWeight, iterations, patchSize }.`};return{fieldLabel:`Graphics: ${t}`,fieldType:"graphics",schema:{mode:i,...(a==null?void 0:a.width)!=null?{width:a.width,height:a.height}:{},...a!=null&&a.targetStyle?{targetStyle:a.targetStyle}:{}},customPrompt:r[i]}}function oa(t,a){var i;return{fieldLabel:"Icon search",fieldType:"icon-picker",fieldValue:t,schema:{...a!=null&&a.style?{iconStyle:a.style}:{},...(a==null?void 0:a.limit)!=null?{maxResults:a.limit}:{},...(i=a==null?void 0:a.availableIcons)!=null&&i.length?{sampleIcons:a.availableIcons.slice(0,30)}:{}},customPrompt:`User query: "${t}"
10
+ Return the ${(a==null?void 0:a.limit)??5} most semantically relevant icon names from the available set as a JSON array of strings, ordered by relevance. Prefer specific over generic names.`}}function Ka(t,a,i){const n=l.useMemo(()=>ta(t,a,i),[t,a,i==null?void 0:i.cursorLine,i==null?void 0:i.cursorCol,i==null?void 0:i.framework]);return Q(n,i)}function Va(t,a,i){const n=l.useMemo(()=>ra(t,a,i),[t,a,i==null?void 0:i.mode,i==null?void 0:i.locale]);return Q(n,i)}function Ya(t,a){const i=l.useMemo(()=>na(t,a),[t,a==null?void 0:a.bpm,a==null?void 0:a.key,a==null?void 0:a.duration,a==null?void 0:a.mode]);return Q(i,a)}function Xa(t,a){const i=l.useMemo(()=>sa(t,a),[t,a==null?void 0:a.meshCount,a==null?void 0:a.triangleCount,a==null?void 0:a.targetDevice,a==null?void 0:a.mode]);return Q(i,a)}function Qa(t,a){const i=l.useMemo(()=>ca(t,a),[t,a==null?void 0:a.width,a==null?void 0:a.height,a==null?void 0:a.mode,a==null?void 0:a.targetStyle]);return Q(i,a)}function Za(t,a){const i=l.useMemo(()=>oa(t,a),[t,a==null?void 0:a.limit,a==null?void 0:a.style]);return Q(i,{...a,disabled:!t||(a==null?void 0:a.disabled)})}function la(t,a){var s;const i=(a==null?void 0:a.mode)??"npc-decision",n=(a==null?void 0:a.genre)??"fantasy",r={"npc-decision":`You are an AI game director. The NPC "${t}" must make a decision. Available BT nodes: ${JSON.stringify((a==null?void 0:a.btStatus)??[])}. Game state: ${JSON.stringify((a==null?void 0:a.gameState)??{})}. Return the name of the BT node to activate next, and one sentence of reasoning.`,dialogue:`You are a ${n} RPG writer. Write a short in-character dialogue line for NPC "${t}". Game state: ${JSON.stringify((a==null?void 0:a.gameState)??{})}. Max 2 sentences, no narrative descriptions.`,"procedural-level":`You are a ${n} game designer. Suggest a procedural level layout for a zone containing "${t}". Describe room count, enemy placement, loot, and one unique mechanic. Keep it under 150 words.`,"quest-description":`You are a ${n} quest designer. Write a compelling quest description involving "${t}". Include: objective, giver NPC, rewards, and a short flavour paragraph. Keep it under 120 words.`,"item-description":`You are a ${n} lore writer. Write a short item description for an item related to "${t}". Include: item name, rarity, flavour text, and one special property. Keep it under 80 words.`};return{fieldLabel:t,fieldType:`game-engine:${i}`,fieldValue:a==null?void 0:a.gameState,customPrompt:r[i],schema:{genre:n,mode:i,btNodes:(s=a==null?void 0:a.btStatus)==null?void 0:s.map(o=>o.node)}}}function ei(t,a){const i=JSON.stringify(a==null?void 0:a.btStatus),n=JSON.stringify(a==null?void 0:a.gameState),r=l.useMemo(()=>la(t,a),[t,a==null?void 0:a.mode,a==null?void 0:a.genre,i,n]);return Q(r,a)}function da(t,a,i){const n=(i==null?void 0:i.mode)??"layout",r=(i==null?void 0:i.diagramType)??"flowchart",s={layout:`You are a diagram layout optimizer. Given this ${r} with ${t.length} nodes and ${a.length} edges, suggest optimal positions for each node to minimize edge crossings and improve readability. Return JSON: { suggestions: [{ id: string, x: number, y: number, reason: string }] }. Consider flow direction (top-to-bottom or left-to-right) and grouping related nodes.`,structure:`You are a diagram analyst. Analyze this ${r} structure. Identify: 1) Missing connections, 2) Potential bottlenecks, 3) Orphan nodes, 4) Cycles or loops. Return JSON: { issues: [{ type: string, description: string, nodeIds: string[] }], score: number }`,simplify:`You are a diagram simplifier. Suggest how to simplify this ${r} while preserving meaning. Identify: nodes that could be merged, redundant edges, or overly complex branches. Return JSON: { simplifications: [{ action: 'merge'|'remove'|'group', ids: string[], reason: string }] }`,group:`You are a diagram organizer. Suggest logical groupings for nodes in this ${r}. Consider semantic relationships, data flow patterns, and visual clustering. Return JSON: { groups: [{ name: string, nodeIds: string[], color?: string }] }`},o=t.map(m=>{var p;return{id:m.id,type:m.type,label:(p=m.label)==null?void 0:p.slice(0,30),pos:[Math.round(m.x),Math.round(m.y)]}}),c=a.map(m=>({id:m.id,src:m.source,tgt:m.target}));return{fieldLabel:`Diagram (${r})`,fieldType:`diagram:${n}`,fieldValue:JSON.stringify({nodes:o,edges:c}),schema:{diagramType:r,mode:n,nodeCount:t.length,edgeCount:a.length,containerSize:i==null?void 0:i.containerSize},customPrompt:s[n]}}function ai(t,a,i){const n=l.useMemo(()=>da(t,a,i),[JSON.stringify(t),JSON.stringify(a),i==null?void 0:i.mode,i==null?void 0:i.diagramType]);return Q(n,{...i,disabled:t.length===0||(i==null?void 0:i.disabled)})}function ua(t,a){const i=(a==null?void 0:a.mode)??"generate",n=(a==null?void 0:a.presentationType)??"business",r=(a==null?void 0:a.duration)??15,s=Math.ceil(r/2),o={generate:`You are a presentation designer. Create a ${n} presentation outline based on: "${t}". Target audience: ${(a==null?void 0:a.audience)??"general"}. Duration: ${r} minutes (~${s} slides). Return JSON: { title: string, slides: [{ title: string, layout: 'title'|'content'|'two-column'|'chart'|'image', bullets?: string[], chartType?: string, speakerNotes?: string }] }. Include: clear slide titles, 3-5 bullet points per content slide, and brief speaker notes.`,summarize:`You are a presentation optimizer. Summarize this presentation to be more concise: "${t}". Reduce slide count by 30% while preserving key messages. Return JSON: { summary: string, reducedSlides: [{ title: string, keyPoints: string[] }] }`,expand:`You are a presentation expert. Expand this brief outline into a detailed presentation: "${t}". Add supporting details, examples, and transitions. Target: ${s} slides. Return JSON: { slides: [{ title: string, content: string, transitions?: string, animations?: string[] }] }`,improve:`You are a presentation coach. Review and improve this presentation structure: "${t}". Suggest: better flow, stronger opening/closing, clearer data visualization. Return JSON: { improvements: [{ slide: number, issue: string, suggestion: string }], score: number }`};return{fieldLabel:`Presentation (${n})`,fieldType:`presentation:${i}`,fieldValue:t,schema:{presentationType:n,mode:i,duration:r,slideCount:s,audience:a==null?void 0:a.audience,hasData:(a==null?void 0:a.dataContext)!=null},customPrompt:o[i]}}function ii(t,a){const i=l.useMemo(()=>ua(t,a),[t,a==null?void 0:a.mode,a==null?void 0:a.presentationType,a==null?void 0:a.duration,a==null?void 0:a.audience]);return Q(i,{...a,disabled:!t||(a==null?void 0:a.disabled)})}function ma(t,a){var r;const i=(a==null?void 0:a.mode)??"all",n={alignment:"Analyze element alignment on this slide. Suggest adjustments to create visual harmony. Return JSON: { suggestions: [{ elementIndex: number, issue: string, fixX?: number, fixY?: number }] }",contrast:"Analyze color contrast and readability. Suggest improvements for accessibility (WCAG AA). Return JSON: { suggestions: [{ area: string, currentContrast: number, suggestedFix: string }] }",spacing:"Analyze whitespace and element spacing. Apply the rule of thirds and consistent margins. Return JSON: { suggestions: [{ elementIndex: number, issue: string, suggestedMargin: number }] }",typography:"Analyze typography: hierarchy, font sizes, line heights, readability. Return JSON: { suggestions: [{ area: string, issue: string, suggestedFontSize?: number }] }",all:"Perform a complete design review of this slide. Check alignment, contrast, spacing, and typography. Return JSON: { score: number, suggestions: [{ category: string, issue: string, fix: string }] }. Prioritize issues by impact on visual clarity."};return{fieldLabel:t.title??"Slide Design",fieldType:`slide-design:${i}`,fieldValue:JSON.stringify(t),schema:{mode:i,hasElements:(((r=t.elements)==null?void 0:r.length)??0)>0,layout:t.layout,brandColors:a==null?void 0:a.brandColors},customPrompt:n[i]}}function ti(t,a){const i=l.useMemo(()=>ma(t,a),[JSON.stringify(t),a==null?void 0:a.mode,JSON.stringify(a==null?void 0:a.brandColors)]);return Q(i,a)}function ri(t,a,i){const n=l.forwardRef((r,s)=>{const{aiEnabled:o=!0,aiPosition:c="right",aiPrompt:m,aiDebounceMs:p=500,aiShowOnHover:d=!1,aiTriggerIcon:x,...N}=r,A=l.useMemo(()=>{const R=a(N);return m&&(R.customPrompt=m),R},[N,m]);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(t,{...N,ref:s}),o&&e.jsx(ea,{context:A,position:c,debounceMs:p,showOnHover:d,triggerIcon:x})]})});return n.displayName=i??`withAIHint(${t.displayName??t.name??"Component"})`,n}function ni(t){return Le(t.label??"Text",t.value,{placeholder:t.placeholder,maxLength:t.maxLength})}function si(t){return ze(t.label??"Number",t.value,{min:t.min,max:t.max,step:t.step})}function ci(t){return Me(t.label??"Select",t.value,{options:t.options,multiple:t.multiple})}function oi(t){return $e(t.label??"Date",t.value,{min:t.min,max:t.max})}function li(t){return Pe(t.label??"Color",t.value)}const di=t=>({id:T.createId(),name:t,type:"classification",status:"draft",datasets:[],experiments:[],models:[],createdAt:new Date,updatedAt:new Date}),je={classification:[{id:"logistic-regression",key:"mlStudio.alg.logisticRegression",name:"Logistic Regression"},{id:"random-forest",key:"mlStudio.alg.randomForest",name:"Random Forest"},{id:"gradient-boosting",key:"mlStudio.alg.gradientBoosting",name:"Gradient Boosting"},{id:"svm",key:"mlStudio.alg.svm",name:"Support Vector Machine"},{id:"neural-network",key:"mlStudio.alg.neuralNetwork",name:"Neural Network"},{id:"xgboost",key:"mlStudio.alg.xgboost",name:"XGBoost"}],regression:[{id:"linear-regression",key:"mlStudio.alg.linearRegression",name:"Linear Regression"},{id:"ridge",key:"mlStudio.alg.ridge",name:"Ridge Regression"},{id:"lasso",key:"mlStudio.alg.lasso",name:"Lasso Regression"},{id:"random-forest-reg",key:"mlStudio.alg.randomForest",name:"Random Forest"},{id:"gradient-boosting-reg",key:"mlStudio.alg.gradientBoosting",name:"Gradient Boosting"}],clustering:[{id:"kmeans",key:"mlStudio.alg.kmeans",name:"K-Means"},{id:"dbscan",key:"mlStudio.alg.dbscan",name:"DBSCAN"},{id:"hierarchical",key:"mlStudio.alg.hierarchical",name:"Hierarchical Clustering"}]},ui=Object.values(je).flat(),Fe=(t,a)=>{const i=ui.find(n=>n.id===t);return i?a(i.key,i.name):t},mi=[["classification","mlStudio.type.classification","Classification"],["regression","mlStudio.type.regression","Regression"],["clustering","mlStudio.type.clustering","Clustering"],["object-detection","mlStudio.type.objectDetection","Object Detection"],["nlp","mlStudio.type.nlp","NLP"],["time-series","mlStudio.type.timeSeries","Time Series"]],pi=[["data","mlStudio.tab.data","Data"],["experiments","mlStudio.tab.experiments","Experiments"],["models","mlStudio.tab.models","Models"],["deploy","mlStudio.tab.deploy","Deploy"]],gi=[["numeric","mlStudio.colType.numeric","Numeric"],["categorical","mlStudio.colType.categorical","Categorical"],["text","mlStudio.colType.text","Text"],["datetime","mlStudio.colType.datetime","DateTime"],["boolean","mlStudio.colType.boolean","Boolean"],["embedding","mlStudio.colType.embedding","Embedding"]],hi={train:["mlStudio.split.train","Train"],validation:["mlStudio.split.validation","Validation"],test:["mlStudio.split.test","Test"]},fi={pending:["mlStudio.experimentStatus.pending","Pending"],running:["mlStudio.experimentStatus.running","Running"],completed:["mlStudio.experimentStatus.completed","Completed"],failed:["mlStudio.experimentStatus.failed","Failed"],cancelled:["mlStudio.experimentStatus.cancelled","Cancelled"]},xi={draft:["mlStudio.modelStatus.draft","Draft"],registered:["mlStudio.modelStatus.registered","Registered"],staging:["mlStudio.modelStatus.staging","Staging"],production:["mlStudio.modelStatus.production","Production"],archived:["mlStudio.modelStatus.archived","Archived"]},bi={pending:["mlStudio.deploymentStatus.pending","Pending"],deploying:["mlStudio.deploymentStatus.deploying","Deploying"],running:["mlStudio.deploymentStatus.running","Running"],stopped:["mlStudio.deploymentStatus.stopped","Stopped"],failed:["mlStudio.deploymentStatus.failed","Failed"]},ce=(t,a,i)=>t?i(t[0],t[1]):a,yi=new Set(["accuracy","precision","recall","f1-score","auc-roc"]),Je=({name:t,value:a},i)=>yi.has(t)?`${(a*100).toLocaleString(i,{minimumFractionDigits:1,maximumFractionDigits:1})}%`:a.toLocaleString(i,{maximumFractionDigits:3}),vi=[{target:".nice-ml-studio",titleKey:"tutorial.mlStudio.intro.title",title:"ML studio",contentKey:"tutorial.mlStudio.intro.content",content:"Work through the tabs: prepare datasets, run experiments, compare and pick models, then deploy the best one.",placement:"auto"}],_i=({project:t,onProjectChange:a,onExperimentRun:i,onModelDeploy:n,onModelDownload:r,className:s="",tutorial:o})=>{var X;const{t:c,lang:m}=T.useNiceTranslation(),[p,d]=l.useState(()=>t||di(c("mlStudio.newProject","New ML Project"))),[x,N]=l.useState("data"),[A,R]=l.useState(null),[$,M]=l.useState(null),[g,u]=l.useState(null),[y,_]=l.useState(!1),[C,v]=l.useState({algorithm:"",hyperparameters:{},preprocessing:[]}),h=l.useRef(p),w=l.useCallback(S=>{const b=h.current,B={...b,...typeof S=="function"?S(b):S,updatedAt:new Date};h.current=B,d(B),a==null||a(B)},[a]),f=async S=>{for(const b of Array.from(S)){const B={id:T.createId(),name:b.name.replace(/\.[^.]+$/,""),type:"tabular",source:{type:"file",uri:b.name},size:b.size,rowCount:0,columns:[],splits:[{name:"train",ratio:.8,rowCount:0},{name:"validation",ratio:.1,rowCount:0},{name:"test",ratio:.1,rowCount:0}],createdAt:new Date};if(b.name.endsWith(".csv")){const J=(await b.text()).split(`
11
+ `),H=J[0].split(",").map(V=>V.trim());B.rowCount=J.length-1,B.columns=H.map(V=>({name:V,type:"text",nullable:!0,unique:0,missing:0})),B.splits=B.splits.map(V=>({...V,rowCount:Math.floor(B.rowCount*V.ratio)}))}w(U=>({datasets:[...U.datasets,B]}))}},j=S=>{w({datasets:p.datasets.filter(b=>b.id!==S)}),A===S&&R(null)},k=async()=>{if(!C.algorithm||!A)return;const S={id:T.createId(),name:c("mlStudio.experimentName","Experiment {n}").replace("{n}",String(p.experiments.length+1)),status:"pending",config:C,metrics:[],artifacts:[],logs:[]},b=U=>w(J=>({experiments:J.experiments.map(H=>H.id===S.id?{...H,...U}:H)}));if(w(U=>({experiments:[...U.experiments,S]})),_(!1),!i)return;const B=new Date;b({status:"running",startedAt:B});try{const U=await i(S),J=typeof U=="object"&&U!==null?U:{},H=new Date;b({status:"completed",completedAt:H,duration:J.duration??(H.getTime()-B.getTime())/1e3,metrics:J.metrics??[],artifacts:J.artifacts??[],logs:J.logs??[]})}catch{b({status:"failed"})}},I=S=>{const b=p.experiments.find(J=>J.id===S);if(!b)return;const B=b.artifacts.filter(J=>J.type==="model"),U={id:T.createId(),name:c("mlStudio.modelFrom","Model from {name}").replace("{name}",b.name),version:"1.0.0",algorithm:b.config.algorithm,experimentId:S,status:"registered",metrics:b.metrics,size:B.reduce((J,H)=>J+H.size,0),artifacts:B,deployments:[],createdAt:new Date};w(J=>({models:[...J.models,U]}))},z=async S=>{const b=p.models.find(U=>U.id===S);if(!b||!n)return;const B=await n(b);w(U=>({models:U.models.map(J=>J.id===S?{...J,status:"production",deployments:[...J.deployments,B]}:J)}))},E=S=>S<1024?`${S} B`:S<1024*1024?`${(S/1024).toFixed(1)} KB`:S<1024*1024*1024?`${(S/1024/1024).toFixed(1)} MB`:`${(S/1024/1024/1024).toFixed(1)} GB`,P=S=>{switch(S){case"completed":case"production":case"running":return"success";case"pending":case"staging":return"pending";case"failed":return"error";case"deploying":case"stopped":return S;default:return"neutral"}},F=e.jsxs("div",{className:"nice-ml-studio__header-info",children:[e.jsx("input",{type:"text",value:p.name,onChange:S=>w({name:S.target.value}),className:"nice-ml-studio__project-name-input","aria-label":c("mlStudio.projectName","Project name")}),e.jsx("select",{value:p.type,onChange:S=>w({type:S.target.value}),className:"nice-ml-studio__project-type-select","aria-label":c("mlStudio.projectType","Project type"),children:mi.map(([S,b,B])=>e.jsx("option",{value:S,children:c(b,B)},S))})]}),G=e.jsx("div",{className:"nice-ml-studio__header-tabs",children:pi.map(([S,b,B])=>e.jsx("button",{className:`nice-ml-studio__tab-button ${x===S?"nice-ml-studio__tab-button--active":""}`,onClick:()=>N(S),children:c(b,B)},S))}),K=e.jsxs("div",{className:"nice-ml-studio__content",children:[x==="data"&&e.jsxs("div",{className:"nice-ml-studio__data-panel",children:[e.jsxs("div",{className:"nice-ml-studio__panel-header",children:[e.jsx("h2",{children:c("mlStudio.datasets","Datasets")}),e.jsxs("label",{className:"nice-ml-studio__upload-button",children:[e.jsx("input",{type:"file",multiple:!0,accept:".csv,.json,.parquet",onChange:S=>S.target.files&&f(S.target.files),hidden:!0}),e.jsx(T.NiceIcon,{name:"plus",size:14})," ",c("mlStudio.uploadDataset","Upload Dataset")]})]}),e.jsx("div",{className:"nice-ml-studio__datasets-grid",children:p.datasets.length===0?e.jsxs("div",{className:"nice-ml-studio__empty-state",children:[e.jsx("span",{className:"nice-ml-studio__icon",children:e.jsx(T.NiceIcon,{name:"bar-chart",size:32})}),e.jsx("p",{children:c("mlStudio.noDatasets","No datasets uploaded yet")}),e.jsx("p",{className:"nice-ml-studio__hint",children:c("mlStudio.noDatasetsHint","Upload CSV, JSON, or Parquet files to get started")})]}):p.datasets.map(S=>e.jsxs("div",{className:`nice-ml-studio__dataset-card ${A===S.id?"nice-ml-studio__dataset-card--selected":""}`,onClick:()=>R(S.id),children:[e.jsxs("div",{className:"nice-ml-studio__card-header",children:[e.jsx("span",{className:"nice-ml-studio__dataset-icon",children:e.jsx(T.NiceIcon,{name:"folder",size:16})}),e.jsx("h3",{children:S.name}),e.jsx("button",{className:"nice-ml-studio__remove-button","aria-label":c("mlStudio.removeDataset","Remove dataset"),onClick:b=>{b.stopPropagation(),j(S.id)},children:e.jsx(T.NiceIcon,{name:"close",size:14})})]}),e.jsxs("div",{className:"nice-ml-studio__card-stats",children:[e.jsx("span",{children:c("mlStudio.rows","{count} rows").replace("{count}",S.rowCount.toLocaleString(m))}),e.jsx("span",{children:c("mlStudio.columnCount","{count} columns").replace("{count}",String(S.columns.length))}),e.jsx("span",{children:E(S.size)})]}),e.jsx("div",{className:"nice-ml-studio__splits-bar",children:S.splits.map(b=>e.jsx("div",{className:`nice-ml-studio__split nice-ml-studio__split--${b.name}`,style:{width:`${b.ratio*100}%`},title:`${ce(hi[b.name],b.name,c)}: ${(b.ratio*100).toFixed(0)}%`},b.name))})]},S.id))}),A&&e.jsx("div",{className:"nice-ml-studio__dataset-details",children:(()=>{const S=p.datasets.find(b=>b.id===A);return S?e.jsxs(e.Fragment,{children:[e.jsx("h3",{children:c("mlStudio.columns","Columns")}),e.jsxs("table",{className:"nice-ml-studio__columns-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:c("mlStudio.col.name","Name")}),e.jsx("th",{children:c("mlStudio.col.type","Type")}),e.jsx("th",{children:c("mlStudio.col.missing","Missing")}),e.jsx("th",{children:c("mlStudio.col.unique","Unique")})]})}),e.jsx("tbody",{children:S.columns.map(b=>e.jsxs("tr",{children:[e.jsx("td",{children:b.name}),e.jsx("td",{children:e.jsx("select",{value:b.type,"aria-label":c("mlStudio.col.type","Type"),onChange:B=>{w({datasets:p.datasets.map(U=>U.id===S.id?{...U,columns:U.columns.map(J=>J.name===b.name?{...J,type:B.target.value}:J)}:U)})},children:gi.map(([B,U,J])=>e.jsx("option",{value:B,children:c(U,J)},B))})}),e.jsx("td",{children:b.missing}),e.jsx("td",{children:b.unique})]},b.name))})]})]}):null})()})]}),x==="experiments"&&e.jsxs("div",{className:"nice-ml-studio__experiments-panel",children:[e.jsxs("div",{className:"nice-ml-studio__panel-header",children:[e.jsx("h2",{children:c("mlStudio.tab.experiments","Experiments")}),e.jsxs("button",{className:"nice-ml-studio__primary-button",onClick:()=>_(!0),disabled:p.datasets.length===0,children:[e.jsx(T.NiceIcon,{name:"plus",size:14})," ",c("mlStudio.newExperiment","New Experiment")]})]}),y&&e.jsxs("div",{className:"nice-ml-studio__new-experiment-form",children:[e.jsx("h3",{children:c("mlStudio.configureExperiment","Configure Experiment")}),e.jsxs("div",{className:"nice-ml-studio__form-grid",children:[e.jsxs("label",{children:[c("mlStudio.dataset","Dataset"),e.jsxs("select",{value:A||"",onChange:S=>R(S.target.value),children:[e.jsx("option",{value:"",children:c("mlStudio.selectDataset","Select dataset...")}),p.datasets.map(S=>e.jsx("option",{value:S.id,children:S.name},S.id))]})]}),e.jsxs("label",{children:[c("mlStudio.algorithm","Algorithm"),e.jsxs("select",{value:C.algorithm,onChange:S=>v({...C,algorithm:S.target.value}),children:[e.jsx("option",{value:"",children:c("mlStudio.selectAlgorithm","Select algorithm...")}),(je[p.type]||je.classification).map(S=>e.jsx("option",{value:S.id,children:c(S.key,S.name)},S.id))]})]}),A&&e.jsxs("label",{children:[c("mlStudio.targetColumn","Target Column"),e.jsxs("select",{value:C.targetColumn||"",onChange:S=>v({...C,targetColumn:S.target.value}),children:[e.jsx("option",{value:"",children:c("mlStudio.selectTarget","Select target...")}),(X=p.datasets.find(S=>S.id===A))==null?void 0:X.columns.map(S=>e.jsx("option",{value:S.name,children:S.name},S.name))]})]})]}),e.jsxs("div",{className:"nice-ml-studio__form-actions",children:[e.jsx("button",{className:"nice-ml-studio__secondary-button",onClick:()=>_(!1),children:c("cancel","Cancel")}),e.jsx("button",{className:"nice-ml-studio__primary-button",onClick:k,disabled:!C.algorithm||!A,children:c("mlStudio.runExperiment","Run Experiment")})]})]}),e.jsx("div",{className:"nice-ml-studio__experiments-list",children:p.experiments.length===0?e.jsxs("div",{className:"nice-ml-studio__empty-state",children:[e.jsx("span",{className:"nice-ml-studio__icon",children:e.jsx(T.NiceIcon,{name:"flask",size:32})}),e.jsx("p",{children:c("mlStudio.noExperiments","No experiments yet")}),e.jsx("p",{className:"nice-ml-studio__hint",children:c("mlStudio.noExperimentsHint","Create an experiment to train and evaluate models")})]}):p.experiments.map(S=>e.jsxs("div",{className:`nice-ml-studio__experiment-card ${$===S.id?"nice-ml-studio__experiment-card--selected":""}`,onClick:()=>M(S.id),children:[e.jsxs("div",{className:"nice-ml-studio__card-header",children:[e.jsx("h3",{children:S.name}),e.jsx("span",{className:`nice-ml-studio__status-badge nice-ml-studio__status-badge--${P(S.status)}`,children:ce(fi[S.status],S.status,c)})]}),e.jsxs("div",{className:"nice-ml-studio__card-meta",children:[e.jsx("span",{children:c("mlStudio.algorithmValue","Algorithm: {name}").replace("{name}",Fe(S.config.algorithm,c))}),S.duration!==void 0&&e.jsx("span",{children:c("mlStudio.duration","Duration: {seconds}s").replace("{seconds}",String(Math.round(S.duration)))})]}),S.metrics.length>0&&e.jsx("div",{className:"nice-ml-studio__metrics-row",children:S.metrics.slice(0,3).map(b=>e.jsxs("div",{className:"nice-ml-studio__metric-item",children:[e.jsx("span",{className:"nice-ml-studio__metric-name",children:b.name}),e.jsx("span",{className:"nice-ml-studio__metric-value",children:Je(b,m)})]},b.name))}),S.status==="completed"&&e.jsx("button",{className:"nice-ml-studio__action-button",onClick:b=>{b.stopPropagation(),I(S.id)},children:c("mlStudio.registerModel","Register Model")})]},S.id))})]}),x==="models"&&e.jsxs("div",{className:"nice-ml-studio__models-panel",children:[e.jsx("div",{className:"nice-ml-studio__panel-header",children:e.jsx("h2",{children:c("mlStudio.tab.models","Models")})}),e.jsx("div",{className:"nice-ml-studio__models-list",children:p.models.length===0?e.jsxs("div",{className:"nice-ml-studio__empty-state",children:[e.jsx("span",{className:"nice-ml-studio__icon",children:e.jsx(T.NiceIcon,{name:"wand",size:32})}),e.jsx("p",{children:c("mlStudio.noModels","No models registered yet")}),e.jsx("p",{className:"nice-ml-studio__hint",children:c("mlStudio.noModelsHint","Complete experiments and register models")})]}):p.models.map(S=>e.jsxs("div",{className:`nice-ml-studio__model-card ${g===S.id?"nice-ml-studio__model-card--selected":""}`,onClick:()=>u(S.id),children:[e.jsxs("div",{className:"nice-ml-studio__card-header",children:[e.jsx("h3",{children:S.name}),e.jsx("span",{className:`nice-ml-studio__status-badge nice-ml-studio__status-badge--${P(S.status)}`,children:ce(xi[S.status],S.status,c)})]}),e.jsxs("div",{className:"nice-ml-studio__card-meta",children:[e.jsx("span",{children:c("mlStudio.algorithmValue","Algorithm: {name}").replace("{name}",Fe(S.algorithm,c))}),e.jsx("span",{children:c("mlStudio.version","Version: {version}").replace("{version}",S.version)}),S.size>0&&e.jsx("span",{children:c("mlStudio.size","Size: {size}").replace("{size}",E(S.size))})]}),S.metrics.length>0&&e.jsx("div",{className:"nice-ml-studio__metrics-row",children:S.metrics.slice(0,3).map(b=>e.jsxs("div",{className:"nice-ml-studio__metric-item",children:[e.jsx("span",{className:"nice-ml-studio__metric-name",children:b.name}),e.jsx("span",{className:"nice-ml-studio__metric-value",children:Je(b,m)})]},b.name))}),e.jsxs("div",{className:"nice-ml-studio__card-actions",children:[e.jsx("button",{className:"nice-ml-studio__action-button",onClick:b=>{b.stopPropagation(),r==null||r(S)},disabled:!r,title:r?void 0:c("mlStudio.downloadNotSetUp","Downloading models is not set up"),children:c("download","Download")}),e.jsx("button",{className:"nice-ml-studio__action-button nice-ml-studio__action-button--primary",onClick:b=>{b.stopPropagation(),z(S.id)},disabled:S.status==="production"||!n,title:n?void 0:c("mlStudio.deployNotSetUp","Deploying models is not set up"),children:S.status==="production"?c("mlStudio.deployed","Deployed"):c("mlStudio.deploy","Deploy")})]})]},S.id))})]}),x==="deploy"&&e.jsxs("div",{className:"nice-ml-studio__deploy-panel",children:[e.jsx("div",{className:"nice-ml-studio__panel-header",children:e.jsx("h2",{children:c("mlStudio.deployments","Deployments")})}),e.jsx("div",{className:"nice-ml-studio__deployments-list",children:p.models.filter(S=>S.deployments.length>0).length===0?e.jsxs("div",{className:"nice-ml-studio__empty-state",children:[e.jsx("span",{className:"nice-ml-studio__icon",children:e.jsx(T.NiceIcon,{name:"rocket",size:32})}),e.jsx("p",{children:c("mlStudio.noDeployments","No deployments yet")}),e.jsx("p",{className:"nice-ml-studio__hint",children:c("mlStudio.noDeploymentsHint","Deploy a model to create inference endpoints")})]}):p.models.filter(S=>S.deployments.length>0).flatMap(S=>S.deployments.map(b=>({model:S,deployment:b}))).map(({model:S,deployment:b})=>e.jsxs("div",{className:"nice-ml-studio__deployment-card",children:[e.jsxs("div",{className:"nice-ml-studio__card-header",children:[e.jsx("h3",{children:b.name}),e.jsx("span",{className:`nice-ml-studio__status-badge nice-ml-studio__status-badge--${P(b.status)}`,children:ce(bi[b.status],b.status,c)})]}),e.jsxs("div",{className:"nice-ml-studio__card-meta",children:[e.jsx("span",{children:c("mlStudio.modelValue","Model: {name}").replace("{name}",S.name)}),e.jsx("span",{children:c("mlStudio.endpoint","Endpoint: {url}").replace("{url}",b.endpoint)})]}),e.jsxs("div",{className:"nice-ml-studio__resources-info",children:[e.jsx("span",{children:c("mlStudio.cpu","CPU: {count} cores").replace("{count}",String(b.resources.cpu))}),e.jsx("span",{children:c("mlStudio.memory","Memory: {gb} GB").replace("{gb}",String(b.resources.memory))}),e.jsx("span",{children:c("mlStudio.replicas","Replicas: {count}").replace("{count}",String(b.resources.replicas))})]})]},b.id))})]})]});return e.jsxs("div",{className:`nice-ml-studio ${s}`,style:{position:"relative"},children:[e.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:e.jsx(T.NiceTutorialButton,{steps:T.resolveTutorial(o,vi)})}),e.jsx(Ma.NiceAppShell,{flush:!0,menubar:F,toolbar:G,children:K})]})},wi={id:T.createId(),name:"New Labeling Project",type:"classification",dataType:"image",status:"setup",labelSchema:{classes:[],attributes:[]},items:[],collaborators:[],statistics:{totalItems:0,labeled:0,reviewed:0,approved:0,byClass:[]},createdAt:new Date},qe=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #f59e0b)","var(--nice-success, #84cc16)","var(--nice-success, #22c55e)","var(--nice-info, #14b8a6)","var(--nice-info, #06b6d4)","var(--nice-primary, #3b82f6)","var(--nice-info, #6366f1)","var(--nice-accent, #8b5cf6)","var(--nice-accent, #a855f7)","var(--nice-color-accent-pink, #d946ef)","var(--nice-color-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)"],ji={label:"Label",schema:"Schema",review:"Review",export:"Export"},ki=({project:t,onProjectChange:a,onLabelSave:i,onExport:n,className:r=""})=>{var ne;const{t:s}=T.useNiceTranslation(),[o,c]=l.useState(t||wi),[m,p]=l.useState("label"),[d,x]=l.useState(0),[N,A]=l.useState(null),[R,$]=l.useState("select"),[M,g]=l.useState(!1),[u,y]=l.useState(null),[_,C]=l.useState(1),[v,h]=l.useState(!1),[w,f]=l.useState("all"),j=l.useRef(null),k=l.useRef(null),I=o.items[d];l.useEffect(()=>{t&&c(t)},[t]);const z=l.useCallback(L=>{const O={...o,...L};O.statistics={totalItems:O.items.length,labeled:O.items.filter(q=>q.status!=="pending").length,reviewed:O.items.filter(q=>q.status==="review"||q.status==="approved").length,approved:O.items.filter(q=>q.status==="approved").length,byClass:O.labelSchema.classes.map(q=>({classId:q.id,count:O.items.flatMap(D=>D.labels).filter(D=>D.classId===q.id).length}))},c(O),a==null||a(O)},[o,a]),E=()=>{const L={id:T.createId(),name:`Class ${o.labelSchema.classes.length+1}`,color:qe[o.labelSchema.classes.length%qe.length],shortcut:String(o.labelSchema.classes.length+1)};z({labelSchema:{...o.labelSchema,classes:[...o.labelSchema.classes,L]}})},P=L=>{z({labelSchema:{...o.labelSchema,classes:o.labelSchema.classes.filter(O=>O.id!==L)},items:o.items.map(O=>({...O,labels:O.labels.filter(q=>q.classId!==L)}))})},F=(L,O)=>{z({labelSchema:{...o.labelSchema,classes:o.labelSchema.classes.map(q=>q.id===L?{...q,...O}:q)}})},G=(L,O)=>{if(!I)return;const q={id:T.createId(),classId:L,type:o.type==="classification"?"class":o.type==="bounding-box"?"bbox":"class",data:O||{},createdBy:"current-user",createdAt:new Date},D={...I,labels:[...I.labels,q],status:"labeled"};z({items:o.items.map(W=>W.id===I.id?D:W)}),i==null||i(D)},K=L=>{if(!I)return;const O={...I,labels:I.labels.filter(q=>q.id!==L),status:I.labels.length<=1?"pending":"labeled"};z({items:o.items.map(q=>q.id===I.id?O:q)})},X=L=>{var W;if(R!=="bbox"||!N)return;const O=(W=j.current)==null?void 0:W.getBoundingClientRect();if(!O)return;const q=(L.clientX-O.left)/_,D=(L.clientY-O.top)/_;g(!0),y({x:q,y:D,width:0,height:0})},S=L=>{var W;if(!M||!u)return;const O=(W=j.current)==null?void 0:W.getBoundingClientRect();if(!O)return;const q=(L.clientX-O.left)/_,D=(L.clientY-O.top)/_;y({...u,width:q-u.x,height:D-u.y})},b=()=>{!M||!u||!N||(g(!1),Math.abs(u.width)>10&&Math.abs(u.height)>10&&G(N,{x:u.width<0?u.x+u.width:u.x,y:u.height<0?u.y+u.height:u.y,width:Math.abs(u.width),height:Math.abs(u.height)}),y(null))},B=L=>{const O=w==="all"?o.items:o.items.filter(D=>D.status===w),q=O.findIndex(D=>D.id===(I==null?void 0:I.id));if(L==="prev"&&q>0){const D=O[q-1];x(o.items.findIndex(W=>W.id===D.id))}else if(L==="next"&&q<O.length-1){const D=O[q+1];x(o.items.findIndex(W=>W.id===D.id))}},U=()=>{if(!I)return;const L={...I,status:"approved"};z({items:o.items.map(O=>O.id===I.id?L:O)}),B("next")},J=()=>{if(!I)return;const L={...I,status:"rejected"};z({items:o.items.map(O=>O.id===I.id?L:O)}),B("next")},H=async L=>{n&&await n(L)},V=l.useRef(()=>{});V.current=L=>{const O=L.target instanceof HTMLElement?L.target:null;if(m!=="label"||L.defaultPrevented||L.ctrlKey||L.metaKey||L.altKey||O!=null&&O.isContentEditable||O&&/^(INPUT|TEXTAREA|SELECT)$/.test(O.tagName)||L.key==="Enter"&&(O!=null&&O.closest("button, a")))return;const q=L.key,D=o.labelSchema.classes.find(W=>W.shortcut===q);D&&(o.type==="classification"?(G(D.id),B("next")):A(D.id)),L.key==="ArrowLeft"||L.key==="a"?B("prev"):(L.key==="ArrowRight"||L.key==="d")&&B("next"),L.key==="Enter"?U():L.key==="Backspace"&&J()},l.useEffect(()=>{const L=O=>V.current(O);return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[]);const te=L=>{switch(L){case"approved":return"var(--nice-success, #22c55e)";case"labeled":return"var(--nice-primary, #3b82f6)";case"review":return"var(--nice-warning, #f59e0b)";case"rejected":return"var(--nice-danger, #ef4444)";default:return"var(--nice-text-secondary, #6b7280)"}};return e.jsxs("div",{className:`nice-data-labeler ${r}`,children:[e.jsxs("header",{className:"nice-data-labeler__header",children:[e.jsxs("div",{className:"nice-data-labeler__header-info",children:[e.jsx("input",{type:"text",value:o.name,onChange:L=>z({name:L.target.value}),className:"nice-data-labeler__project-name-input"}),e.jsxs("div",{className:"nice-data-labeler__progress-bar",children:[e.jsx("div",{className:"nice-data-labeler__progress-fill",style:{width:`${o.statistics.labeled/Math.max(o.statistics.totalItems,1)*100}%`}}),e.jsx("span",{className:"nice-data-labeler__progress-text",children:s("dataLabeler.progress","{labeled} / {total} labeled").replace("{labeled}",String(o.statistics.labeled)).replace("{total}",String(o.statistics.totalItems))})]})]}),e.jsx("div",{className:"nice-data-labeler__header-tabs",children:["label","schema","review","export"].map(L=>e.jsx("button",{className:`nice-data-labeler__tab-button ${m===L?"nice-data-labeler__tab-button--active":""}`,onClick:()=>p(L),children:s(`dataLabeler.tab.${L}`,ji[L])},L))}),e.jsx("button",{className:"nice-data-labeler__shortcuts-button",onClick:()=>h(!v),children:s("dataLabeler.shortcuts","Shortcuts")})]}),e.jsxs("div",{className:"nice-data-labeler__content",children:[m==="label"&&e.jsxs("div",{className:"nice-data-labeler__label-panel",children:[e.jsxs("div",{className:"nice-data-labeler__label-toolbar",children:[e.jsxs("div",{className:"nice-data-labeler__tool-group",children:[e.jsxs("button",{className:`nice-data-labeler__tool-button ${R==="select"?"nice-data-labeler__tool-button--active":""}`,onClick:()=>$("select"),children:[e.jsx(T.NiceIcon,{name:"cursor",size:14})," ",s("dataLabeler.select","Select")]}),(o.type==="bounding-box"||o.type==="multi-label")&&e.jsxs("button",{className:`nice-data-labeler__tool-button ${R==="bbox"?"nice-data-labeler__tool-button--active":""}`,onClick:()=>$("bbox"),children:[e.jsx(T.NiceIcon,{name:"square",size:14})," ",s("dataLabeler.box","Box")]}),o.type==="polygon"&&e.jsxs("button",{className:`nice-data-labeler__tool-button ${R==="polygon"?"nice-data-labeler__tool-button--active":""}`,onClick:()=>$("polygon"),children:[e.jsx(T.NiceIcon,{name:"hexagon",size:14})," ",s("dataLabeler.polygon","Polygon")]})]}),e.jsxs("div",{className:"nice-data-labeler__zoom-group",children:[e.jsx("button",{"aria-label":s("dataLabeler.zoomOut","Zoom out"),onClick:()=>C(Math.max(.25,_-.25)),children:e.jsx(T.NiceIcon,{name:"minus",size:14})}),e.jsxs("span",{children:[Math.round(_*100),"%"]}),e.jsx("button",{"aria-label":s("dataLabeler.zoomIn","Zoom in"),onClick:()=>C(Math.min(4,_+.25)),children:e.jsx(T.NiceIcon,{name:"plus",size:14})})]}),e.jsxs("div",{className:"nice-data-labeler__navigation-group",children:[e.jsxs("button",{onClick:()=>B("prev"),disabled:d===0,children:[e.jsx(T.NiceIcon,{name:"arrow-left",size:14})," ",s("dataLabeler.prev","Prev")]}),e.jsxs("span",{children:[d+1," / ",o.items.length]}),e.jsxs("button",{onClick:()=>B("next"),disabled:d>=o.items.length-1,children:[s("dataLabeler.next","Next")," ",e.jsx(T.NiceIcon,{name:"arrow-right",size:14})]})]})]}),e.jsxs("div",{className:"nice-data-labeler__label-workspace",children:[e.jsx("div",{className:"nice-data-labeler__canvas-container",ref:k,children:I?e.jsxs(e.Fragment,{children:[I.data.type==="image"&&e.jsxs(e.Fragment,{children:[e.jsx("img",{src:I.data.url,alt:s("dataLabeler.labelingItem","Labeling item"),className:"nice-data-labeler__labeling-image",style:{transform:`scale(${_})`}}),e.jsx("canvas",{ref:j,className:"nice-data-labeler__labeling-canvas",onMouseDown:X,onMouseMove:S,onMouseUp:b,onMouseLeave:b,style:{transform:`scale(${_})`,cursor:R==="bbox"?"crosshair":"default"}}),e.jsxs("div",{className:"nice-data-labeler__annotations-overlay",style:{transform:`scale(${_})`},children:[I.labels.filter(L=>L.type==="bbox"&&L.data.x!==void 0).map(L=>{const O=o.labelSchema.classes.find(q=>q.id===L.classId);return e.jsxs("div",{className:"nice-data-labeler__bbox-annotation",style:{left:L.data.x,top:L.data.y,width:L.data.width,height:L.data.height,borderColor:(O==null?void 0:O.color)||"var(--nice-danger, #ff0000)"},children:[e.jsx("span",{className:"nice-data-labeler__bbox-label",style:{backgroundColor:(O==null?void 0:O.color)||"var(--nice-danger, #ff0000)"},children:O==null?void 0:O.name}),e.jsx("button",{className:"nice-data-labeler__bbox-remove","aria-label":s("dataLabeler.removeLabel","Remove label"),onClick:()=>K(L.id),children:e.jsx(T.NiceIcon,{name:"close",size:12})})]},L.id)}),u&&e.jsx("div",{className:"nice-data-labeler__bbox-drawing",style:{left:u.width<0?u.x+u.width:u.x,top:u.height<0?u.y+u.height:u.y,width:Math.abs(u.width),height:Math.abs(u.height),borderColor:(ne=o.labelSchema.classes.find(L=>L.id===N))==null?void 0:ne.color}})]})]}),I.data.type==="text"&&e.jsx("div",{className:"nice-data-labeler__text-labeling",children:e.jsx("p",{className:"nice-data-labeler__text-content",children:I.data.text})})]}):e.jsxs("div",{className:"nice-data-labeler__empty-state",children:[e.jsx("span",{className:"nice-data-labeler__icon",children:e.jsx(T.NiceIcon,{name:"clipboard",size:32})}),e.jsx("p",{children:s("dataLabeler.noItemsToLabel","No items to label")})]})}),e.jsxs("aside",{className:"nice-data-labeler__class-sidebar",children:[e.jsx("h3",{children:s("dataLabeler.classes","Classes")}),e.jsx("div",{className:"nice-data-labeler__class-list",children:o.labelSchema.classes.map(L=>e.jsxs("button",{className:`nice-data-labeler__class-button ${N===L.id?"nice-data-labeler__class-button--active":""}`,style:{borderLeftColor:L.color},onClick:()=>{o.type==="classification"?(G(L.id),B("next")):A(L.id)},children:[e.jsx("span",{className:"nice-data-labeler__class-color",style:{backgroundColor:L.color}}),e.jsx("span",{className:"nice-data-labeler__class-name",children:L.name}),L.shortcut&&e.jsx("span",{className:"nice-data-labeler__class-shortcut",children:L.shortcut})]},L.id))}),I&&I.labels.length>0&&e.jsxs("div",{className:"nice-data-labeler__current-labels",children:[e.jsx("h4",{children:s("dataLabeler.labels","Labels")}),I.labels.map(L=>{const O=o.labelSchema.classes.find(q=>q.id===L.classId);return e.jsxs("div",{className:"nice-data-labeler__label-item",children:[e.jsx("span",{className:"nice-data-labeler__label-color",style:{backgroundColor:O==null?void 0:O.color}}),e.jsx("span",{className:"nice-data-labeler__label-name",children:O==null?void 0:O.name}),e.jsx("button",{"aria-label":s("dataLabeler.removeLabel","Remove label"),onClick:()=>K(L.id),children:e.jsx(T.NiceIcon,{name:"close",size:14})})]},L.id)})]}),m==="label"&&I&&e.jsxs("div",{className:"nice-data-labeler__label-actions",children:[e.jsxs("button",{className:"nice-data-labeler__approve-button",onClick:U,children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",s("dataLabeler.approve","Approve")]}),e.jsxs("button",{className:"nice-data-labeler__reject-button",onClick:J,children:[e.jsx(T.NiceIcon,{name:"close",size:14})," ",s("dataLabeler.reject","Reject")]})]})]})]})]}),m==="schema"&&e.jsxs("div",{className:"nice-data-labeler__schema-panel",children:[e.jsxs("div",{className:"nice-data-labeler__panel-header",children:[e.jsx("h2",{children:s("dataLabeler.labelSchema","Label Schema")}),e.jsxs("button",{className:"nice-data-labeler__primary-button",onClick:E,children:[e.jsx(T.NiceIcon,{name:"plus",size:14})," ",s("dataLabeler.addClass","Add Class")]})]}),e.jsxs("div",{className:"nice-data-labeler__schema-settings",children:[e.jsxs("label",{children:[s("dataLabeler.labelingType","Labeling Type"),e.jsxs("select",{value:o.type,onChange:L=>z({type:L.target.value}),children:[e.jsx("option",{value:"classification",children:s("dataLabeler.singleClassification","Single Classification")}),e.jsx("option",{value:"multi-label",children:s("dataLabeler.multiLabelClassification","Multi-Label Classification")}),e.jsx("option",{value:"bounding-box",children:s("dataLabeler.boundingBox","Bounding Box")}),e.jsx("option",{value:"polygon",children:s("dataLabeler.polygon","Polygon")}),e.jsx("option",{value:"segmentation",children:s("dataLabeler.segmentation","Segmentation")}),e.jsx("option",{value:"ner",children:s("dataLabeler.namedEntityRecognition","Named Entity Recognition")})]})]}),e.jsxs("label",{children:[s("dataLabeler.dataType","Data Type"),e.jsxs("select",{value:o.dataType,onChange:L=>z({dataType:L.target.value}),children:[e.jsx("option",{value:"image",children:s("dataLabeler.image","Image")}),e.jsx("option",{value:"text",children:s("dataLabeler.text","Text")}),e.jsx("option",{value:"audio",children:s("dataLabeler.audio","Audio")}),e.jsx("option",{value:"video",children:s("dataLabeler.video","Video")})]})]})]}),e.jsx("div",{className:"nice-data-labeler__classes-list",children:o.labelSchema.classes.map((L,O)=>e.jsxs("div",{className:"nice-data-labeler__class-editor",children:[e.jsx("input",{type:"color",value:L.color,onChange:q=>F(L.id,{color:q.target.value}),className:"nice-data-labeler__color-picker"}),e.jsx("input",{type:"text",value:L.name,onChange:q=>F(L.id,{name:q.target.value}),className:"nice-data-labeler__class-name-input",placeholder:s("dataLabeler.classNamePlaceholder","Class name")}),e.jsx("input",{type:"text",value:L.shortcut||"",onChange:q=>F(L.id,{shortcut:q.target.value}),className:"nice-data-labeler__shortcut-input",placeholder:s("dataLabeler.shortcutKeyPlaceholder","Key"),maxLength:1}),e.jsx("button",{className:"nice-data-labeler__remove-class-button","aria-label":s("dataLabeler.removeClass","Remove class"),onClick:()=>P(L.id),children:e.jsx(T.NiceIcon,{name:"trash",size:16})})]},L.id))}),e.jsxs("div",{className:"nice-data-labeler__guidelines-section",children:[e.jsx("h3",{children:s("dataLabeler.labelingGuidelines","Labeling Guidelines")}),e.jsx("textarea",{value:o.guidelines||"",onChange:L=>z({guidelines:L.target.value}),placeholder:s("dataLabeler.guidelinesPlaceholder","Enter labeling guidelines for annotators..."),rows:6})]})]}),m==="review"&&e.jsxs("div",{className:"nice-data-labeler__review-panel",children:[e.jsxs("div",{className:"nice-data-labeler__panel-header",children:[e.jsx("h2",{children:s("dataLabeler.reviewLabels","Review Labels")}),e.jsx("div",{className:"nice-data-labeler__filter-group",children:e.jsxs("select",{value:w,onChange:L=>f(L.target.value),children:[e.jsx("option",{value:"all",children:s("dataLabeler.allItems","All Items")}),e.jsx("option",{value:"labeled",children:s("dataLabeler.labeled","Labeled")}),e.jsx("option",{value:"review",children:s("dataLabeler.needsReview","Needs Review")}),e.jsx("option",{value:"approved",children:s("dataLabeler.approved","Approved")}),e.jsx("option",{value:"rejected",children:s("dataLabeler.rejected","Rejected")})]})})]}),e.jsx("div",{className:"nice-data-labeler__items-grid",children:o.items.filter(L=>w==="all"||L.status===w).map((L,O)=>{var q;return e.jsxs("div",{className:`nice-data-labeler__item-card ${d===o.items.indexOf(L)?"nice-data-labeler__item-card--active":""}`,onClick:()=>{x(o.items.indexOf(L)),p("label")},children:[L.data.type==="image"&&e.jsx("img",{src:L.data.url,alt:s("dataLabeler.item","Item {index}").replace("{index}",String(O+1)),className:"nice-data-labeler__item-thumbnail"}),L.data.type==="text"&&e.jsxs("p",{className:"nice-data-labeler__item-text-preview",children:[(q=L.data.text)==null?void 0:q.slice(0,100),"..."]}),e.jsxs("div",{className:"nice-data-labeler__item-footer",children:[e.jsx("span",{className:"nice-data-labeler__status-dot",style:{backgroundColor:te(L.status)}}),e.jsx("span",{children:s("dataLabeler.labelCount","{count} labels").replace("{count}",String(L.labels.length))})]})]},L.id)})})]}),m==="export"&&e.jsxs("div",{className:"nice-data-labeler__export-panel",children:[e.jsx("div",{className:"nice-data-labeler__panel-header",children:e.jsx("h2",{children:s("dataLabeler.exportLabels","Export Labels")})}),e.jsxs("div",{className:"nice-data-labeler__export-stats",children:[e.jsxs("div",{className:"nice-data-labeler__stat-card",children:[e.jsx("span",{className:"nice-data-labeler__stat-value",children:o.statistics.totalItems}),e.jsx("span",{className:"nice-data-labeler__stat-label",children:s("dataLabeler.totalItems","Total Items")})]}),e.jsxs("div",{className:"nice-data-labeler__stat-card",children:[e.jsx("span",{className:"nice-data-labeler__stat-value",children:o.statistics.labeled}),e.jsx("span",{className:"nice-data-labeler__stat-label",children:s("dataLabeler.labeled","Labeled")})]}),e.jsxs("div",{className:"nice-data-labeler__stat-card",children:[e.jsx("span",{className:"nice-data-labeler__stat-value",children:o.statistics.approved}),e.jsx("span",{className:"nice-data-labeler__stat-label",children:s("dataLabeler.approved","Approved")})]}),e.jsxs("div",{className:"nice-data-labeler__stat-card",children:[e.jsx("span",{className:"nice-data-labeler__stat-value",children:o.labelSchema.classes.length}),e.jsx("span",{className:"nice-data-labeler__stat-label",children:s("dataLabeler.classes","Classes")})]})]}),e.jsxs("div",{className:"nice-data-labeler__export-formats",children:[e.jsx("h3",{children:s("dataLabeler.exportFormat","Export Format")}),e.jsxs("div",{className:"nice-data-labeler__format-grid",children:[e.jsxs("button",{className:"nice-data-labeler__format-button",onClick:()=>H("coco"),children:[e.jsx("span",{className:"nice-data-labeler__format-icon",children:e.jsx(T.NiceIcon,{name:"box",size:24})}),e.jsx("span",{className:"nice-data-labeler__format-name",children:s("dataLabeler.cocoJson","COCO JSON")}),e.jsx("span",{className:"nice-data-labeler__format-desc",children:s("dataLabeler.cocoDesc","Common format for object detection")})]}),e.jsxs("button",{className:"nice-data-labeler__format-button",onClick:()=>H("voc"),children:[e.jsx("span",{className:"nice-data-labeler__format-icon",children:e.jsx(T.NiceIcon,{name:"file",size:24})}),e.jsx("span",{className:"nice-data-labeler__format-name",children:s("dataLabeler.pascalVoc","Pascal VOC")}),e.jsx("span",{className:"nice-data-labeler__format-desc",children:s("dataLabeler.vocDesc","XML format for bounding boxes")})]}),e.jsxs("button",{className:"nice-data-labeler__format-button",onClick:()=>H("yolo"),children:[e.jsx("span",{className:"nice-data-labeler__format-icon",children:e.jsx(T.NiceIcon,{name:"zap",size:24})}),e.jsx("span",{className:"nice-data-labeler__format-name",children:s("dataLabeler.yolo","YOLO")}),e.jsx("span",{className:"nice-data-labeler__format-desc",children:s("dataLabeler.yoloDesc","Text format for YOLO models")})]}),e.jsxs("button",{className:"nice-data-labeler__format-button",onClick:()=>H("csv"),children:[e.jsx("span",{className:"nice-data-labeler__format-icon",children:e.jsx(T.NiceIcon,{name:"bar-chart",size:24})}),e.jsx("span",{className:"nice-data-labeler__format-name",children:"CSV"}),e.jsx("span",{className:"nice-data-labeler__format-desc",children:s("dataLabeler.csvDesc","Tabular format for classification")})]})]})]}),e.jsxs("div",{className:"nice-data-labeler__class-distribution",children:[e.jsx("h3",{children:s("dataLabeler.classDistribution","Class Distribution")}),e.jsx("div",{className:"nice-data-labeler__distribution-bars",children:o.statistics.byClass.map(L=>{const O=o.labelSchema.classes.find(D=>D.id===L.classId),q=L.count/Math.max(o.statistics.labeled,1)*100;return e.jsxs("div",{className:"nice-data-labeler__distribution-row",children:[e.jsx("span",{className:"nice-data-labeler__class-name",style:{color:O==null?void 0:O.color},children:O==null?void 0:O.name}),e.jsx("div",{className:"nice-data-labeler__bar-container",children:e.jsx("div",{className:"nice-data-labeler__bar-fill",style:{width:`${q}%`,backgroundColor:O==null?void 0:O.color}})}),e.jsx("span",{className:"nice-data-labeler__count",children:L.count})]},L.classId)})})]})]})]}),v&&e.jsx("div",{className:"nice-data-labeler__shortcuts-modal",children:e.jsxs("div",{className:"nice-data-labeler__modal-content",children:[e.jsxs("div",{className:"nice-data-labeler__modal-header",children:[e.jsx("h3",{children:s("dataLabeler.keyboardShortcuts","Keyboard Shortcuts")}),e.jsx("button",{"aria-label":s("dataLabeler.close","Close"),onClick:()=>h(!1),children:e.jsx(T.NiceIcon,{name:"close",size:16})})]}),e.jsxs("div",{className:"nice-data-labeler__shortcuts-list",children:[e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsxs("span",{className:"nice-data-labeler__keys",children:[e.jsx(T.NiceIcon,{name:"arrow-left",size:14})," / A"]}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.previousItem","Previous item")})]}),e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsxs("span",{className:"nice-data-labeler__keys",children:[e.jsx(T.NiceIcon,{name:"arrow-right",size:14})," / D"]}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.nextItem","Next item")})]}),e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsx("span",{className:"nice-data-labeler__keys",children:s("dataLabeler.enterKey","Enter")}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.approveItem","Approve item")})]}),e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsx("span",{className:"nice-data-labeler__keys",children:s("dataLabeler.backspaceKey","Backspace")}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.rejectItem","Reject item")})]}),o.labelSchema.classes.map(L=>L.shortcut&&e.jsxs("div",{className:"nice-data-labeler__shortcut-item",children:[e.jsx("span",{className:"nice-data-labeler__keys",children:L.shortcut}),e.jsx("span",{className:"nice-data-labeler__description",children:s("dataLabeler.labelAs","Label as {name}").replace("{name}",L.name)})]},L.id))]})]})})]})},Ni={id:T.createId(),name:"Model Endpoint",modelId:"",modelVersion:"1.0.0",status:"stopped",url:"",authentication:{type:"api-key"},metrics:{requestsTotal:0,requestsPerSecond:0,latencyP50:0,latencyP95:0,latencyP99:0,errorRate:0,successRate:100},logs:[]},Si=({endpoint:t,onInference:a,showMetrics:i=!0,showLogs:n=!0,className:r=""})=>{const{t:s}=T.useNiceTranslation(),[o,c]=l.useState(t||Ni),[m,p]=l.useState("test"),[d,x]=l.useState("text"),[N,A]=l.useState(""),[R,$]=l.useState("{}"),[M,g]=l.useState(null),[u,y]=l.useState({temperature:.7,topK:50,topP:.9,maxTokens:256,threshold:.5}),[_,C]=l.useState(null),[v,h]=l.useState(!1),[w,f]=l.useState(null),[j,k]=l.useState([]),[I,z]=l.useState(null),E=l.useRef(null),P=b=>{var U;const B=(U=b.target.files)==null?void 0:U[0];if(B){const J=new FileReader;J.onload=H=>{var V;g((V=H.target)==null?void 0:V.result)},J.readAsDataURL(B)}},F=async()=>{if(!a){f(s("modelInference.noInferenceHandlerProvided","No inference handler provided"));return}h(!0),f(null),C(null);const b=[];switch(d){case"text":b.push({type:"text",data:N});break;case"image":M&&b.push({type:"image",data:M});break;case"json":try{b.push({type:"json",data:JSON.parse(R)})}catch{f(s("modelInference.invalidJsonInput","Invalid JSON input")),h(!1);return}break;case"tabular":try{b.push({type:"tabular",data:JSON.parse(R)})}catch{f(s("modelInference.invalidTabularData","Invalid tabular data")),h(!1);return}break}const B={inputs:b,parameters:u};try{const U=Date.now(),J=await a(B),H=Date.now()-U;C(J),c(V=>({...V,metrics:{...V.metrics,requestsTotal:V.metrics.requestsTotal+1,latencyP50:(V.metrics.latencyP50+H)/2},logs:[{timestamp:new Date,requestId:J.requestId,duration:H,status:"success",inputSize:JSON.stringify(b).length,outputSize:JSON.stringify(J.predictions).length},...V.logs.slice(0,99)]}))}catch(U){const J=U instanceof Error?U.message:s("modelInference.inferenceFailed","Inference failed");f(J),c(H=>({...H,metrics:{...H.metrics,requestsTotal:H.metrics.requestsTotal+1,errorRate:(H.metrics.errorRate*H.metrics.requestsTotal+1)/(H.metrics.requestsTotal+1)},logs:[{timestamp:new Date,requestId:T.createId(),duration:0,status:"error",inputSize:JSON.stringify(b).length,outputSize:0,error:J},...H.logs.slice(0,99)]}))}finally{h(!1)}},G=async b=>{if(a){z(0),k([]);for(let B=0;B<b.length;B++){const U={inputs:[b[B]],parameters:u};try{const J=await a(U);k(H=>[...H,J])}catch(J){console.error("Batch item failed:",J)}z((B+1)/b.length*100)}z(null)}},K=b=>b<1e3?`${b.toFixed(0)}ms`:`${(b/1e3).toFixed(2)}s`,X=b=>b.toLocaleTimeString(),S=(b,B)=>e.jsxs("div",{className:"nice-model-inference__prediction-item",children:[b.label&&e.jsxs("div",{className:"nice-model-inference__prediction-label",children:[e.jsx("span",{className:"nice-model-inference__label-name",children:b.label}),b.confidence!==void 0&&e.jsxs("span",{className:"nice-model-inference__confidence-badge",style:{backgroundColor:`hsl(${b.confidence*120}, 70%, 40%)`},children:[(b.confidence*100).toFixed(1),"%"]})]}),b.score!==void 0&&e.jsxs("div",{className:"nice-model-inference__prediction-score",children:[e.jsx("span",{className:"nice-model-inference__score-label",children:s("modelInference.score","Score:")}),e.jsx("span",{className:"nice-model-inference__score-value",children:b.score.toFixed(4)})]}),b.text&&e.jsx("div",{className:"nice-model-inference__prediction-text",children:e.jsx("pre",{children:b.text})}),b.bbox&&e.jsx("div",{className:"nice-model-inference__prediction-bbox",children:e.jsx("span",{children:s("modelInference.box","Box: ({x}, {y}) - {width}×{height}").replace("{x}",String(b.bbox.x)).replace("{y}",String(b.bbox.y)).replace("{width}",String(b.bbox.width)).replace("{height}",String(b.bbox.height))})}),b.raw!==void 0&&b.raw!==null&&e.jsxs("details",{className:"nice-model-inference__raw-output",children:[e.jsx("summary",{children:s("modelInference.rawOutput","Raw Output")}),e.jsx("pre",{children:JSON.stringify(b.raw,null,2)})]})]},B);return e.jsxs("div",{className:`nice-model-inference ${r}`,children:[e.jsxs("header",{className:"nice-model-inference__header",children:[e.jsxs("div",{className:"nice-model-inference__header-info",children:[e.jsx("h2",{children:o.name}),e.jsx("span",{className:`nice-model-inference__status-badge nice-model-inference__status-badge--${o.status}`,children:o.status})]}),e.jsxs("div",{className:"nice-model-inference__header-tabs",children:[e.jsx("button",{className:`nice-model-inference__tab-button ${m==="test"?"nice-model-inference__tab-button--active":""}`,onClick:()=>p("test"),children:s("modelInference.test","Test")}),e.jsx("button",{className:`nice-model-inference__tab-button ${m==="batch"?"nice-model-inference__tab-button--active":""}`,onClick:()=>p("batch"),children:s("modelInference.batch","Batch")}),i&&e.jsx("button",{className:`nice-model-inference__tab-button ${m==="metrics"?"nice-model-inference__tab-button--active":""}`,onClick:()=>p("metrics"),children:s("modelInference.metrics","Metrics")}),n&&e.jsx("button",{className:`nice-model-inference__tab-button ${m==="logs"?"nice-model-inference__tab-button--active":""}`,onClick:()=>p("logs"),children:s("modelInference.logs","Logs")})]})]}),e.jsxs("div",{className:"nice-model-inference__content",children:[m==="test"&&e.jsxs("div",{className:"nice-model-inference__test-panel",children:[e.jsxs("div",{className:"nice-model-inference__input-section",children:[e.jsx("div",{className:"nice-model-inference__input-type-selector",children:["text","image","json","tabular"].map(b=>e.jsx("button",{className:`nice-model-inference__type-button ${d===b?"nice-model-inference__type-button--active":""}`,onClick:()=>x(b),children:b.charAt(0).toUpperCase()+b.slice(1)},b))}),e.jsxs("div",{className:"nice-model-inference__input-area",children:[d==="text"&&e.jsx("textarea",{value:N,onChange:b=>A(b.target.value),placeholder:s("modelInference.enterTextInput","Enter text input..."),rows:6,className:"nice-model-inference__text-input"}),d==="image"&&e.jsx("div",{className:"nice-model-inference__image-input",children:M?e.jsxs("div",{className:"nice-model-inference__image-preview",children:[e.jsx("img",{src:M,alt:s("modelInference.inputPreview","Input preview")}),e.jsx("button",{className:"nice-model-inference__clear-button",onClick:()=>g(null),children:s("modelInference.clear","Clear")})]}):e.jsxs("label",{className:"nice-model-inference__upload-zone",children:[e.jsx("input",{ref:E,type:"file",accept:"image/*",onChange:P,hidden:!0}),e.jsx("span",{className:"nice-model-inference__upload-icon",children:e.jsx(T.NiceIcon,{name:"image",size:32})}),e.jsx("span",{children:s("modelInference.clickOrDragToUpload","Click or drag to upload image")})]})}),(d==="json"||d==="tabular")&&e.jsx("textarea",{value:R,onChange:b=>$(b.target.value),placeholder:d==="json"?`{
12
12
  "key": "value"
13
13
  }`:`[
14
14
  {"col1": "value1", "col2": "value2"}
15
- ]`,rows:10,className:"nice-model-inference__json-input"})]}),e.jsxs("div",{className:"nice-model-inference__parameters-section",children:[e.jsx("h4",{children:s("modelInference.parameters","Parameters")}),e.jsxs("div",{className:"nice-model-inference__parameters-grid",children:[e.jsxs("label",{children:[s("modelInference.temperature","Temperature"),e.jsx("input",{type:"number",value:d.temperature,onChange:x=>j({...d,temperature:parseFloat(x.target.value)}),min:"0",max:"2",step:"0.1"})]}),e.jsxs("label",{children:[s("modelInference.topK","Top K"),e.jsx("input",{type:"number",value:d.topK,onChange:x=>j({...d,topK:parseInt(x.target.value)}),min:"1",max:"100"})]}),e.jsxs("label",{children:[s("modelInference.topP","Top P"),e.jsx("input",{type:"number",value:d.topP,onChange:x=>j({...d,topP:parseFloat(x.target.value)}),min:"0",max:"1",step:"0.05"})]}),e.jsxs("label",{children:[s("modelInference.threshold","Threshold"),e.jsx("input",{type:"number",value:d.threshold,onChange:x=>j({...d,threshold:parseFloat(x.target.value)}),min:"0",max:"1",step:"0.05"})]})]})]}),e.jsx("button",{className:"nice-model-inference__run-button",onClick:F,disabled:b||!w&&!P&&R==="{}",children:b?"Running...":"Run Inference"})]}),e.jsxs("div",{className:"nice-model-inference__output-section",children:[e.jsx("h3",{children:s("modelInference.output","Output")}),_&&e.jsxs("div",{className:"nice-model-inference__error-message",children:[e.jsx("span",{className:"nice-model-inference__error-icon",children:e.jsx(T.NiceIcon,{name:"warning",size:16})}),_]}),y&&e.jsxs("div",{className:"nice-model-inference__result-container",children:[e.jsxs("div",{className:"nice-model-inference__result-meta",children:[e.jsxs("span",{children:["Request ID: ",y.requestId]}),e.jsxs("span",{children:["Latency: ",H(y.latency)]}),e.jsxs("span",{children:["Model: ",y.modelVersion]})]}),e.jsx("div",{className:"nice-model-inference__predictions-list",children:y.predictions.map((x,B)=>C(x,B))})]}),!_&&!y&&e.jsxs("div",{className:"nice-model-inference__empty-output",children:[e.jsx("span",{className:"nice-model-inference__icon",children:e.jsx(T.NiceIcon,{name:"upload",size:32})}),e.jsx("p",{children:s("modelInference.runInferenceToSeeResults","Run inference to see results")})]})]})]}),m==="batch"&&e.jsxs("div",{className:"nice-model-inference__batch-panel",children:[e.jsxs("div",{className:"nice-model-inference__batch-upload",children:[e.jsx("h3",{children:s("modelInference.batchInference","Batch Inference")}),e.jsx("p",{className:"nice-model-inference__hint",children:s("modelInference.uploadAFileWithMultiple","Upload a file with multiple inputs for batch processing")}),e.jsxs("label",{className:"nice-model-inference__upload-zone",children:[e.jsx("input",{type:"file",accept:".json,.csv,.txt",onChange:async x=>{var G;const B=(G=x.target.files)==null?void 0:G[0];if(B){const q=await B.text();try{const W=JSON.parse(q);if(Array.isArray(W)){const Q=W.map(re=>({type:"json",data:re}));U(Q)}}catch{f("Invalid batch file format")}}},hidden:!0}),e.jsx("span",{className:"nice-model-inference__upload-icon",children:e.jsx(T.NiceIcon,{name:"folder",size:32})}),e.jsx("span",{children:s("modelInference.uploadJsonArrayFile","Upload JSON array file")})]})]}),N!==null&&e.jsxs("div",{className:"nice-model-inference__batch-progress",children:[e.jsx("div",{className:"nice-model-inference__progress-bar",children:e.jsx("div",{className:"nice-model-inference__progress-fill",style:{width:`${N}%`}})}),e.jsxs("span",{children:[Math.round(N),"%"]})]}),k.length>0&&e.jsxs("div",{className:"nice-model-inference__batch-results",children:[e.jsxs("h3",{children:["Results (",k.length,")"]}),e.jsx("div",{className:"nice-model-inference__results-list",children:k.map((x,B)=>e.jsxs("div",{className:"nice-model-inference__batch-result-item",children:[e.jsxs("span",{className:"nice-model-inference__result-index",children:["#",B+1]}),x.predictions.map((G,q)=>e.jsxs("span",{className:"nice-model-inference__result-prediction",children:[G.label,": ",(G.confidence||G.score||0).toFixed(1),"%"]},q))]},B))})]})]}),m==="metrics"&&i&&e.jsxs("div",{className:"nice-model-inference__metrics-panel",children:[e.jsxs("div",{className:"nice-model-inference__metrics-grid",children:[e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:o.metrics.requestsTotal}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.totalRequests","Total Requests")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:o.metrics.requestsPerSecond.toFixed(1)}),e.jsx("span",{className:"nice-model-inference__metric-label",children:"Requests/sec"})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:H(o.metrics.latencyP50)}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.p50Latency","P50 Latency")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:H(o.metrics.latencyP95)}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.p95Latency","P95 Latency")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:H(o.metrics.latencyP99)}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.p99Latency","P99 Latency")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsxs("span",{className:"nice-model-inference__metric-value",children:[o.metrics.successRate.toFixed(1),"%"]}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.successRate","Success Rate")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsxs("span",{className:"nice-model-inference__metric-value",children:[(o.metrics.errorRate*100).toFixed(2),"%"]}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.errorRate","Error Rate")})]})]}),e.jsxs("div",{className:"nice-model-inference__latency-histogram",children:[e.jsx("h3",{children:s("modelInference.latencyDistribution","Latency Distribution")}),e.jsx("div",{className:"nice-model-inference__histogram-bars",children:[10,25,50,75,90,95,99].map(x=>e.jsxs("div",{className:"nice-model-inference__histogram-bar",children:[e.jsx("div",{className:"nice-model-inference__bar-fill",style:{height:`${Math.min(100,o.metrics.latencyP50*x/100)}px`}}),e.jsxs("span",{className:"nice-model-inference__percentile-label",children:["P",x]})]},x))})]})]}),m==="logs"&&r&&e.jsxs("div",{className:"nice-model-inference__logs-panel",children:[e.jsxs("div",{className:"nice-model-inference__logs-header",children:[e.jsx("h3",{children:s("modelInference.requestLogs","Request Logs")}),e.jsx("button",{className:"nice-model-inference__clear-logs-button",onClick:()=>c(x=>({...x,logs:[]})),children:s("modelInference.clearLogs","Clear Logs")})]}),e.jsx("div",{className:"nice-model-inference__logs-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:s("modelInference.time","Time")}),e.jsx("th",{children:s("modelInference.requestId","Request ID")}),e.jsx("th",{children:s("modelInference.duration","Duration")}),e.jsx("th",{children:s("modelInference.status","Status")}),e.jsx("th",{children:s("modelInference.inputSize","Input Size")}),e.jsx("th",{children:s("modelInference.outputSize","Output Size")})]})}),e.jsx("tbody",{children:o.logs.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"nice-model-inference__empty-logs",children:s("modelInference.noLogsYet","No logs yet")})}):o.logs.map((x,B)=>e.jsxs("tr",{className:`nice-model-inference__log-row nice-model-inference__log-row--${x.status}`,children:[e.jsx("td",{children:X(x.timestamp)}),e.jsx("td",{className:"nice-model-inference__request-id",children:x.requestId.slice(0,8)}),e.jsx("td",{children:H(x.duration)}),e.jsx("td",{children:e.jsx("span",{className:`nice-model-inference__status-badge nice-model-inference__status-badge--${x.status}`,children:x.status})}),e.jsxs("td",{children:[x.inputSize," B"]}),e.jsxs("td",{children:[x.outputSize," B"]})]},B))})]})})]})]})]})};class ne{constructor(a){this.abortController=null,this.config={timeout:3e4,maxRetries:3,retryDelay:1e3,...a}}async healthCheck(){try{return(await this.chat({messages:[{role:"user",content:"Hi"}],maxTokens:5})).choices.length>0}catch{return!1}}async fetchWithRetry(a,i,r=this.config.maxRetries){let n=null;for(let s=0;s<=r;s++)try{this.abortController=new AbortController;const o=setTimeout(()=>{var m;return(m=this.abortController)==null?void 0:m.abort()},this.config.timeout),c=await fetch(a,{...i,signal:this.abortController.signal});if(clearTimeout(o),c.ok)return c;if(c.status>=400&&c.status<500){const m=await c.text();throw new Error(`API Error ${c.status}: ${m}`)}n=new Error(`HTTP ${c.status}`)}catch(o){n=o,s<r&&await this.delay(this.config.retryDelay*(s+1))}throw n??new Error("Request failed after retries")}delay(a){return new Promise(i=>setTimeout(i,a))}async parseSSEStream(a,i,r,n){var m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){n==null||n(new Error("No response body"));return}const o=new TextDecoder;let c="";try{for(;;){const{done:p,value:u}=await s.read();if(p)break;c+=o.decode(u,{stream:!0});const v=c.split(`
16
- `);c=v.pop()||"";for(const w of v)if(w.startsWith("data: ")){const A=w.slice(6).trim();if(A==="[DONE]"){r==null||r();return}try{const R=JSON.parse(A);i(this.normalizeStreamChunk(R))}catch{}}}r==null||r()}catch(p){n==null||n(p)}finally{s.releaseLock()}}}class ke extends ne{constructor(a){super(a),this.type="openai",this.name="OpenAI",this.baseUrl=a.baseUrl||"https://api.openai.com/v1"}async chat(a){const r=await(await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify(this.buildRequestBody(a))})).json();return this.normalizeResponse(r,a)}async chatStream(a,i,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify({...this.buildRequestBody(a),stream:!0})});await this.parseSSEStream(s,i,r,n)}catch(s){n==null||n(s)}}async listModels(){return((await(await this.fetchWithRetry(`${this.baseUrl}/models`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers}})).json()).data||[]).filter(r=>r.id.includes("gpt")).map(r=>r.id)}buildRequestBody(a){return{model:a.model||this.config.model||"gpt-4o-mini",messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024,top_p:a.topP,frequency_penalty:a.frequencyPenalty,presence_penalty:a.presencePenalty,stop:a.stop,functions:a.functions,function_call:a.functionCall}}normalizeResponse(a,i){const r=a;return{id:r.id,model:r.model,choices:r.choices.map(n=>({index:n.index,message:n.message,finishReason:n.finish_reason})),usage:{promptTokens:r.usage.prompt_tokens,completionTokens:r.usage.completion_tokens,totalTokens:r.usage.total_tokens},estimatedCost:this.estimateCost(r.model,r.usage.prompt_tokens,r.usage.completion_tokens)}}normalizeStreamChunk(a){const i=a;return{id:i.id,choices:i.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}estimateCost(a,i,r){const n={"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4-turbo":{input:10,output:30},"gpt-4":{input:30,output:60},"gpt-3.5-turbo":{input:.5,output:1.5}},s=Object.keys(n).find(c=>a.includes(c)),o=s?n[s]:n["gpt-4o-mini"];return i/1e6*o.input+r/1e6*o.output}}class pa extends ne{constructor(a){super(a),this.type="anthropic",this.name="Anthropic Claude",this.baseUrl=a.baseUrl||"https://api.anthropic.com/v1"}async chat(a){const r=await(await this.fetchWithRetry(`${this.baseUrl}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01",...this.config.headers},body:JSON.stringify(this.buildRequestBody(a))})).json();return this.normalizeResponse(r)}async chatStream(a,i,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01",...this.config.headers},body:JSON.stringify({...this.buildRequestBody(a),stream:!0})});await this.parseAnthropicStream(s,i,r,n)}catch(s){n==null||n(s)}}buildRequestBody(a){const i=a.messages.find(n=>n.role==="system"),r=a.messages.filter(n=>n.role!=="system");return{model:a.model||this.config.model||"claude-3-5-sonnet-20241022",max_tokens:a.maxTokens??1024,system:i==null?void 0:i.content,messages:r.map(n=>({role:n.role==="assistant"?"assistant":"user",content:n.content})),temperature:a.temperature??.7}}normalizeResponse(a){const i=a,r=i.content.find(n=>n.type==="text");return{id:i.id,model:i.model,choices:[{index:0,message:{role:"assistant",content:(r==null?void 0:r.text)||""},finishReason:i.stop_reason==="end_turn"?"stop":"length"}],usage:{promptTokens:i.usage.input_tokens,completionTokens:i.usage.output_tokens,totalTokens:i.usage.input_tokens+i.usage.output_tokens},estimatedCost:this.estimateCost(i.model,i.usage.input_tokens,i.usage.output_tokens)}}normalizeStreamChunk(a){var r;const i=a;return{id:"",choices:[{index:i.index||0,delta:{content:((r=i.delta)==null?void 0:r.text)||""},finishReason:i.type==="message_stop"?"stop":null}]}}async parseAnthropicStream(a,i,r,n){var m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){n==null||n(new Error("No response body"));return}const o=new TextDecoder;let c="";try{for(;;){const{done:p,value:u}=await s.read();if(p)break;c+=o.decode(u,{stream:!0});const v=c.split(`
17
- `);c=v.pop()||"";for(const w of v)if(w.startsWith("data: "))try{const A=JSON.parse(w.slice(6));if(A.type==="content_block_delta")i(this.normalizeStreamChunk(A));else if(A.type==="message_stop"){r==null||r();return}}catch{}}r==null||r()}catch(p){n==null||n(p)}finally{s.releaseLock()}}estimateCost(a,i,r){const n={"claude-3-5-sonnet":{input:3,output:15},"claude-3-5-haiku":{input:.25,output:1.25},"claude-3-opus":{input:15,output:75},"claude-3-sonnet":{input:3,output:15},"claude-3-haiku":{input:.25,output:1.25}},s=Object.keys(n).find(c=>a.includes(c)),o=s?n[s]:n["claude-3-5-sonnet"];return i/1e6*o.input+r/1e6*o.output}}class ga extends ne{constructor(a){if(super(a),this.type="azure-openai",this.name="Azure OpenAI",!a.baseUrl||!a.deployment)throw new Error("Azure OpenAI requires baseUrl and deployment")}async chat(a){const i=`${this.config.baseUrl}/openai/deployments/${this.config.deployment}/chat/completions?api-version=${this.config.apiVersion||"2024-02-01"}`,n=await(await this.fetchWithRetry(i,{method:"POST",headers:{"Content-Type":"application/json","api-key":this.config.apiKey,...this.config.headers},body:JSON.stringify(this.buildRequestBody(a))})).json();return this.normalizeResponse(n)}async chatStream(a,i,r,n){const s=`${this.config.baseUrl}/openai/deployments/${this.config.deployment}/chat/completions?api-version=${this.config.apiVersion||"2024-02-01"}`;try{const o=await this.fetchWithRetry(s,{method:"POST",headers:{"Content-Type":"application/json","api-key":this.config.apiKey,...this.config.headers},body:JSON.stringify({...this.buildRequestBody(a),stream:!0})});await this.parseSSEStream(o,i,r,n)}catch(o){n==null||n(o)}}buildRequestBody(a){return{messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024,top_p:a.topP,frequency_penalty:a.frequencyPenalty,presence_penalty:a.presencePenalty,stop:a.stop}}normalizeResponse(a){const i=a;return{id:i.id,model:i.model,choices:i.choices.map(r=>({index:r.index,message:r.message,finishReason:r.finish_reason})),usage:{promptTokens:i.usage.prompt_tokens,completionTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens}}}normalizeStreamChunk(a){const i=a;return{id:i.id,choices:i.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}}class ha extends ne{constructor(a){super(a),this.type="ollama",this.name="Ollama (Local)",this.baseUrl=a.baseUrl||"http://localhost:11434"}async chat(a){const r=await(await this.fetchWithRetry(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json",...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama3",messages:a.messages,stream:!1,options:{temperature:a.temperature??.7,num_predict:a.maxTokens??1024}})})).json();return this.normalizeResponse(r)}async chatStream(a,i,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json",...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama3",messages:a.messages,stream:!0,options:{temperature:a.temperature??.7,num_predict:a.maxTokens??1024}})});await this.parseOllamaStream(s,i,r,n)}catch(s){n==null||n(s)}}async listModels(){try{return((await(await this.fetchWithRetry(`${this.baseUrl}/api/tags`,{method:"GET"})).json()).models||[]).map(r=>r.name)}catch{return[]}}normalizeResponse(a){const i=a;return{id:`ollama-${Date.now()}`,model:i.model,choices:[{index:0,message:i.message,finishReason:i.done?"stop":null}],usage:{promptTokens:i.prompt_eval_count||0,completionTokens:i.eval_count||0,totalTokens:(i.prompt_eval_count||0)+(i.eval_count||0)},estimatedCost:0}}normalizeStreamChunk(a){var r;const i=a;return{id:`ollama-${Date.now()}`,choices:[{index:0,delta:{content:((r=i.message)==null?void 0:r.content)||""},finishReason:i.done?"stop":null}]}}async parseOllamaStream(a,i,r,n){var m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){n==null||n(new Error("No response body"));return}const o=new TextDecoder;let c="";try{for(;;){const{done:p,value:u}=await s.read();if(p)break;c+=o.decode(u,{stream:!0});const v=c.split(`
18
- `);c=v.pop()||"";for(const w of v)if(w.trim())try{const A=JSON.parse(w);if(i(this.normalizeStreamChunk(A)),A.done){r==null||r();return}}catch{}}r==null||r()}catch(p){n==null||n(p)}finally{s.releaseLock()}}}class fa extends ne{constructor(a){super(a),this.type="groq",this.name="Groq",this.baseUrl=a.baseUrl||"https://api.groq.com/openai/v1"}async chat(a){const r=await(await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama-3.1-70b-versatile",messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024})})).json();return this.normalizeResponse(r)}async chatStream(a,i,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama-3.1-70b-versatile",messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024,stream:!0})});await this.parseSSEStream(s,i,r,n)}catch(s){n==null||n(s)}}normalizeResponse(a){const i=a;return{id:i.id,model:i.model,choices:i.choices.map(r=>({index:r.index,message:r.message,finishReason:r.finish_reason})),usage:{promptTokens:i.usage.prompt_tokens,completionTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens},estimatedCost:0}}normalizeStreamChunk(a){const i=a;return{id:i.id,choices:i.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}}function ae(t){switch(t.type){case"openai":return new ke(t);case"anthropic":return new pa(t);case"azure-openai":return new ga(t);case"ollama":return new ha(t);case"groq":return new fa(t);case"custom":return new ke(t);default:throw new Error(`Unsupported provider type: ${t.type}`)}}function V(t){const a=new URL(t.endpoint),i=a.host.toLowerCase(),r=a.pathname.replace(/\/+$/,""),n=m=>`${a.protocol}//${a.host}${r.endsWith(m)?r.slice(0,-m.length):r}`,s={apiKey:t.apiKey,model:t.model,headers:t.headers},o=/^(.*)\/openai\/deployments\/([^/]+)\/chat\/completions$/.exec(r);if(i.endsWith("azure.com")&&o)return ae({type:"azure-openai",...s,baseUrl:`${a.protocol}//${a.host}${o[1]}`,deployment:o[2],apiVersion:a.searchParams.get("api-version")??void 0});if(i.includes("anthropic.com"))return ae({type:"anthropic",...s,baseUrl:n("/messages")});if(i.endsWith(":11434")||i.includes("ollama"))return ae({type:"ollama",...s,baseUrl:n("/api/chat")});const c=i.includes("openai.com")?"openai":i.includes("groq.com")?"groq":"custom";return ae({type:c,...s,baseUrl:n("/chat/completions")})}function ie(t,a){for(const n of t.variables)if(n.required&&!(n.name in a)&&!n.default)throw new Error(`Missing required variable: ${n.name}`);const i={};for(const n of t.variables)i[n.name]=a[n.name]??n.default;const r=n=>n.replace(/\{\{#if (\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g,(o,c,m)=>{const p=i[c];return p==null||p===""||p===!1||Array.isArray(p)&&p.length===0?"":m}).replace(/\{\{(\w+)\}\}/g,(o,c)=>{const m=i[c];return m===void 0?`{{${c}}}`:typeof m=="object"?JSON.stringify(m,null,2):String(m)});return{system:r(t.system),user:r(t.user),metadata:{templateId:t.id,variables:i,timestamp:Date.now()}}}const oe={id:"data-grid-filter",name:"DataGrid Natural Language Filter",description:"Convert natural language queries to DataGrid filter configurations",category:"data-query",system:`You are a filter query generator for a data grid component.
15
+ ]`,rows:10,className:"nice-model-inference__json-input"})]}),e.jsxs("div",{className:"nice-model-inference__parameters-section",children:[e.jsx("h4",{children:s("modelInference.parameters","Parameters")}),e.jsxs("div",{className:"nice-model-inference__parameters-grid",children:[e.jsxs("label",{children:[s("modelInference.temperature","Temperature"),e.jsx("input",{type:"number",value:u.temperature,onChange:b=>y({...u,temperature:parseFloat(b.target.value)}),min:"0",max:"2",step:"0.1"})]}),e.jsxs("label",{children:[s("modelInference.topK","Top K"),e.jsx("input",{type:"number",value:u.topK,onChange:b=>y({...u,topK:parseInt(b.target.value)}),min:"1",max:"100"})]}),e.jsxs("label",{children:[s("modelInference.topP","Top P"),e.jsx("input",{type:"number",value:u.topP,onChange:b=>y({...u,topP:parseFloat(b.target.value)}),min:"0",max:"1",step:"0.05"})]}),e.jsxs("label",{children:[s("modelInference.threshold","Threshold"),e.jsx("input",{type:"number",value:u.threshold,onChange:b=>y({...u,threshold:parseFloat(b.target.value)}),min:"0",max:"1",step:"0.05"})]})]})]}),e.jsx("button",{className:"nice-model-inference__run-button",onClick:F,disabled:v||!N&&!M&&R==="{}",children:v?s("modelInference.running","Running..."):s("modelInference.runInference","Run Inference")})]}),e.jsxs("div",{className:"nice-model-inference__output-section",children:[e.jsx("h3",{children:s("modelInference.output","Output")}),w&&e.jsxs("div",{className:"nice-model-inference__error-message",children:[e.jsx("span",{className:"nice-model-inference__error-icon",children:e.jsx(T.NiceIcon,{name:"warning",size:16})}),w]}),_&&e.jsxs("div",{className:"nice-model-inference__result-container",children:[e.jsxs("div",{className:"nice-model-inference__result-meta",children:[e.jsx("span",{children:s("modelInference.requestId2","Request ID: {requestId}").replace("{requestId}",String(_.requestId))}),e.jsx("span",{children:s("modelInference.latency","Latency: {duration}").replace("{duration}",String(K(_.latency)))}),e.jsx("span",{children:s("modelInference.model","Model: {modelVersion}").replace("{modelVersion}",String(_.modelVersion))})]}),e.jsx("div",{className:"nice-model-inference__predictions-list",children:_.predictions.map((b,B)=>S(b,B))})]}),!w&&!_&&e.jsxs("div",{className:"nice-model-inference__empty-output",children:[e.jsx("span",{className:"nice-model-inference__icon",children:e.jsx(T.NiceIcon,{name:"upload",size:32})}),e.jsx("p",{children:s("modelInference.runInferenceToSeeResults","Run inference to see results")})]})]})]}),m==="batch"&&e.jsxs("div",{className:"nice-model-inference__batch-panel",children:[e.jsxs("div",{className:"nice-model-inference__batch-upload",children:[e.jsx("h3",{children:s("modelInference.batchInference","Batch Inference")}),e.jsx("p",{className:"nice-model-inference__hint",children:s("modelInference.uploadAFileWithMultiple","Upload a file with multiple inputs for batch processing")}),e.jsxs("label",{className:"nice-model-inference__upload-zone",children:[e.jsx("input",{type:"file",accept:".json,.csv,.txt",onChange:async b=>{var U;const B=(U=b.target.files)==null?void 0:U[0];if(B){const J=await B.text();try{const H=JSON.parse(J);if(Array.isArray(H)){const V=H.map(te=>({type:"json",data:te}));G(V)}}catch{f(s("modelInference.invalidBatchFileFormat","Invalid batch file format"))}}},hidden:!0}),e.jsx("span",{className:"nice-model-inference__upload-icon",children:e.jsx(T.NiceIcon,{name:"folder",size:32})}),e.jsx("span",{children:s("modelInference.uploadJsonArrayFile","Upload JSON array file")})]})]}),I!==null&&e.jsxs("div",{className:"nice-model-inference__batch-progress",children:[e.jsx("div",{className:"nice-model-inference__progress-bar",children:e.jsx("div",{className:"nice-model-inference__progress-fill",style:{width:`${I}%`}})}),e.jsxs("span",{children:[Math.round(I),"%"]})]}),j.length>0&&e.jsxs("div",{className:"nice-model-inference__batch-results",children:[e.jsx("h3",{children:s("modelInference.results","Results ({batchResults})").replace("{batchResults}",String(j.length))}),e.jsx("div",{className:"nice-model-inference__results-list",children:j.map((b,B)=>e.jsxs("div",{className:"nice-model-inference__batch-result-item",children:[e.jsxs("span",{className:"nice-model-inference__result-index",children:["#",B+1]}),b.predictions.map((U,J)=>e.jsxs("span",{className:"nice-model-inference__result-prediction",children:[U.label,": ",(U.confidence||U.score||0).toFixed(1),"%"]},J))]},B))})]})]}),m==="metrics"&&i&&e.jsxs("div",{className:"nice-model-inference__metrics-panel",children:[e.jsxs("div",{className:"nice-model-inference__metrics-grid",children:[e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:o.metrics.requestsTotal}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.totalRequests","Total Requests")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:o.metrics.requestsPerSecond.toFixed(1)}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.requestsSec","Requests/sec")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:K(o.metrics.latencyP50)}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.p50Latency","P50 Latency")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:K(o.metrics.latencyP95)}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.p95Latency","P95 Latency")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsx("span",{className:"nice-model-inference__metric-value",children:K(o.metrics.latencyP99)}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.p99Latency","P99 Latency")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsxs("span",{className:"nice-model-inference__metric-value",children:[o.metrics.successRate.toFixed(1),"%"]}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.successRate","Success Rate")})]}),e.jsxs("div",{className:"nice-model-inference__metric-card",children:[e.jsxs("span",{className:"nice-model-inference__metric-value",children:[(o.metrics.errorRate*100).toFixed(2),"%"]}),e.jsx("span",{className:"nice-model-inference__metric-label",children:s("modelInference.errorRate","Error Rate")})]})]}),e.jsxs("div",{className:"nice-model-inference__latency-histogram",children:[e.jsx("h3",{children:s("modelInference.latencyDistribution","Latency Distribution")}),e.jsx("div",{className:"nice-model-inference__histogram-bars",children:[10,25,50,75,90,95,99].map(b=>e.jsxs("div",{className:"nice-model-inference__histogram-bar",children:[e.jsx("div",{className:"nice-model-inference__bar-fill",style:{height:`${Math.min(100,o.metrics.latencyP50*b/100)}px`}}),e.jsxs("span",{className:"nice-model-inference__percentile-label",children:["P",b]})]},b))})]})]}),m==="logs"&&n&&e.jsxs("div",{className:"nice-model-inference__logs-panel",children:[e.jsxs("div",{className:"nice-model-inference__logs-header",children:[e.jsx("h3",{children:s("modelInference.requestLogs","Request Logs")}),e.jsx("button",{className:"nice-model-inference__clear-logs-button",onClick:()=>c(b=>({...b,logs:[]})),children:s("modelInference.clearLogs","Clear Logs")})]}),e.jsx("div",{className:"nice-model-inference__logs-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:s("modelInference.time","Time")}),e.jsx("th",{children:s("modelInference.requestId","Request ID")}),e.jsx("th",{children:s("modelInference.duration","Duration")}),e.jsx("th",{children:s("modelInference.status","Status")}),e.jsx("th",{children:s("modelInference.inputSize","Input Size")}),e.jsx("th",{children:s("modelInference.outputSize","Output Size")})]})}),e.jsx("tbody",{children:o.logs.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"nice-model-inference__empty-logs",children:s("modelInference.noLogsYet","No logs yet")})}):o.logs.map((b,B)=>e.jsxs("tr",{className:`nice-model-inference__log-row nice-model-inference__log-row--${b.status}`,children:[e.jsx("td",{children:X(b.timestamp)}),e.jsx("td",{className:"nice-model-inference__request-id",children:b.requestId.slice(0,8)}),e.jsx("td",{children:K(b.duration)}),e.jsx("td",{children:e.jsx("span",{className:`nice-model-inference__status-badge nice-model-inference__status-badge--${b.status}`,children:b.status})}),e.jsxs("td",{children:[b.inputSize," B"]}),e.jsxs("td",{children:[b.outputSize," B"]})]},B))})]})})]})]})]})};class re{constructor(a){this.abortController=null,this.config={timeout:3e4,maxRetries:3,retryDelay:1e3,...a}}async healthCheck(){try{return(await this.chat({messages:[{role:"user",content:"Hi"}],maxTokens:5})).choices.length>0}catch{return!1}}async fetchWithRetry(a,i,n=this.config.maxRetries){let r=null;for(let s=0;s<=n;s++)try{this.abortController=new AbortController;const o=setTimeout(()=>{var m;return(m=this.abortController)==null?void 0:m.abort()},this.config.timeout),c=await fetch(a,{...i,signal:this.abortController.signal});if(clearTimeout(o),c.ok)return c;if(c.status>=400&&c.status<500){const m=await c.text();throw new Error(`API Error ${c.status}: ${m}`)}r=new Error(`HTTP ${c.status}`)}catch(o){r=o,s<n&&await this.delay(this.config.retryDelay*(s+1))}throw r??new Error("Request failed after retries")}delay(a){return new Promise(i=>setTimeout(i,a))}async parseSSEStream(a,i,n,r){var m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){r==null||r(new Error("No response body"));return}const o=new TextDecoder;let c="";try{for(;;){const{done:p,value:d}=await s.read();if(p)break;c+=o.decode(d,{stream:!0});const x=c.split(`
16
+ `);c=x.pop()||"";for(const N of x)if(N.startsWith("data: ")){const A=N.slice(6).trim();if(A==="[DONE]"){n==null||n();return}try{const R=JSON.parse(A);i(this.normalizeStreamChunk(R))}catch{}}}n==null||n()}catch(p){r==null||r(p)}finally{s.releaseLock()}}}class ke extends re{constructor(a){super(a),this.type="openai",this.name="OpenAI",this.baseUrl=a.baseUrl||"https://api.openai.com/v1"}async chat(a){const n=await(await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify(this.buildRequestBody(a))})).json();return this.normalizeResponse(n,a)}async chatStream(a,i,n,r){try{const s=await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify({...this.buildRequestBody(a),stream:!0})});await this.parseSSEStream(s,i,n,r)}catch(s){r==null||r(s)}}async listModels(){return((await(await this.fetchWithRetry(`${this.baseUrl}/models`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers}})).json()).data||[]).filter(n=>n.id.includes("gpt")).map(n=>n.id)}buildRequestBody(a){return{model:a.model||this.config.model||"gpt-4o-mini",messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024,top_p:a.topP,frequency_penalty:a.frequencyPenalty,presence_penalty:a.presencePenalty,stop:a.stop,functions:a.functions,function_call:a.functionCall}}normalizeResponse(a,i){const n=a;return{id:n.id,model:n.model,choices:n.choices.map(r=>({index:r.index,message:r.message,finishReason:r.finish_reason})),usage:{promptTokens:n.usage.prompt_tokens,completionTokens:n.usage.completion_tokens,totalTokens:n.usage.total_tokens},estimatedCost:this.estimateCost(n.model,n.usage.prompt_tokens,n.usage.completion_tokens)}}normalizeStreamChunk(a){const i=a;return{id:i.id,choices:i.choices.map(n=>({index:n.index,delta:n.delta,finishReason:n.finish_reason}))}}estimateCost(a,i,n){const r={"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4-turbo":{input:10,output:30},"gpt-4":{input:30,output:60},"gpt-3.5-turbo":{input:.5,output:1.5}},s=Object.keys(r).find(c=>a.includes(c)),o=s?r[s]:r["gpt-4o-mini"];return i/1e6*o.input+n/1e6*o.output}}class pa extends re{constructor(a){super(a),this.type="anthropic",this.name="Anthropic Claude",this.baseUrl=a.baseUrl||"https://api.anthropic.com/v1"}async chat(a){const n=await(await this.fetchWithRetry(`${this.baseUrl}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01",...this.config.headers},body:JSON.stringify(this.buildRequestBody(a))})).json();return this.normalizeResponse(n)}async chatStream(a,i,n,r){try{const s=await this.fetchWithRetry(`${this.baseUrl}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01",...this.config.headers},body:JSON.stringify({...this.buildRequestBody(a),stream:!0})});await this.parseAnthropicStream(s,i,n,r)}catch(s){r==null||r(s)}}buildRequestBody(a){const i=a.messages.find(r=>r.role==="system"),n=a.messages.filter(r=>r.role!=="system");return{model:a.model||this.config.model||"claude-3-5-sonnet-20241022",max_tokens:a.maxTokens??1024,system:i==null?void 0:i.content,messages:n.map(r=>({role:r.role==="assistant"?"assistant":"user",content:r.content})),temperature:a.temperature??.7}}normalizeResponse(a){const i=a,n=i.content.find(r=>r.type==="text");return{id:i.id,model:i.model,choices:[{index:0,message:{role:"assistant",content:(n==null?void 0:n.text)||""},finishReason:i.stop_reason==="end_turn"?"stop":"length"}],usage:{promptTokens:i.usage.input_tokens,completionTokens:i.usage.output_tokens,totalTokens:i.usage.input_tokens+i.usage.output_tokens},estimatedCost:this.estimateCost(i.model,i.usage.input_tokens,i.usage.output_tokens)}}normalizeStreamChunk(a){var n;const i=a;return{id:"",choices:[{index:i.index||0,delta:{content:((n=i.delta)==null?void 0:n.text)||""},finishReason:i.type==="message_stop"?"stop":null}]}}async parseAnthropicStream(a,i,n,r){var m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){r==null||r(new Error("No response body"));return}const o=new TextDecoder;let c="";try{for(;;){const{done:p,value:d}=await s.read();if(p)break;c+=o.decode(d,{stream:!0});const x=c.split(`
17
+ `);c=x.pop()||"";for(const N of x)if(N.startsWith("data: "))try{const A=JSON.parse(N.slice(6));if(A.type==="content_block_delta")i(this.normalizeStreamChunk(A));else if(A.type==="message_stop"){n==null||n();return}}catch{}}n==null||n()}catch(p){r==null||r(p)}finally{s.releaseLock()}}estimateCost(a,i,n){const r={"claude-3-5-sonnet":{input:3,output:15},"claude-3-5-haiku":{input:.25,output:1.25},"claude-3-opus":{input:15,output:75},"claude-3-sonnet":{input:3,output:15},"claude-3-haiku":{input:.25,output:1.25}},s=Object.keys(r).find(c=>a.includes(c)),o=s?r[s]:r["claude-3-5-sonnet"];return i/1e6*o.input+n/1e6*o.output}}class ga extends re{constructor(a){if(super(a),this.type="azure-openai",this.name="Azure OpenAI",!a.baseUrl||!a.deployment)throw new Error("Azure OpenAI requires baseUrl and deployment")}async chat(a){const i=`${this.config.baseUrl}/openai/deployments/${this.config.deployment}/chat/completions?api-version=${this.config.apiVersion||"2024-02-01"}`,r=await(await this.fetchWithRetry(i,{method:"POST",headers:{"Content-Type":"application/json","api-key":this.config.apiKey,...this.config.headers},body:JSON.stringify(this.buildRequestBody(a))})).json();return this.normalizeResponse(r)}async chatStream(a,i,n,r){const s=`${this.config.baseUrl}/openai/deployments/${this.config.deployment}/chat/completions?api-version=${this.config.apiVersion||"2024-02-01"}`;try{const o=await this.fetchWithRetry(s,{method:"POST",headers:{"Content-Type":"application/json","api-key":this.config.apiKey,...this.config.headers},body:JSON.stringify({...this.buildRequestBody(a),stream:!0})});await this.parseSSEStream(o,i,n,r)}catch(o){r==null||r(o)}}buildRequestBody(a){return{messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024,top_p:a.topP,frequency_penalty:a.frequencyPenalty,presence_penalty:a.presencePenalty,stop:a.stop}}normalizeResponse(a){const i=a;return{id:i.id,model:i.model,choices:i.choices.map(n=>({index:n.index,message:n.message,finishReason:n.finish_reason})),usage:{promptTokens:i.usage.prompt_tokens,completionTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens}}}normalizeStreamChunk(a){const i=a;return{id:i.id,choices:i.choices.map(n=>({index:n.index,delta:n.delta,finishReason:n.finish_reason}))}}}class ha extends re{constructor(a){super(a),this.type="ollama",this.name="Ollama (Local)",this.baseUrl=a.baseUrl||"http://localhost:11434"}async chat(a){const n=await(await this.fetchWithRetry(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json",...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama3",messages:a.messages,stream:!1,options:{temperature:a.temperature??.7,num_predict:a.maxTokens??1024}})})).json();return this.normalizeResponse(n)}async chatStream(a,i,n,r){try{const s=await this.fetchWithRetry(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json",...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama3",messages:a.messages,stream:!0,options:{temperature:a.temperature??.7,num_predict:a.maxTokens??1024}})});await this.parseOllamaStream(s,i,n,r)}catch(s){r==null||r(s)}}async listModels(){try{return((await(await this.fetchWithRetry(`${this.baseUrl}/api/tags`,{method:"GET"})).json()).models||[]).map(n=>n.name)}catch{return[]}}normalizeResponse(a){const i=a;return{id:`ollama-${Date.now()}`,model:i.model,choices:[{index:0,message:i.message,finishReason:i.done?"stop":null}],usage:{promptTokens:i.prompt_eval_count||0,completionTokens:i.eval_count||0,totalTokens:(i.prompt_eval_count||0)+(i.eval_count||0)},estimatedCost:0}}normalizeStreamChunk(a){var n;const i=a;return{id:`ollama-${Date.now()}`,choices:[{index:0,delta:{content:((n=i.message)==null?void 0:n.content)||""},finishReason:i.done?"stop":null}]}}async parseOllamaStream(a,i,n,r){var m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){r==null||r(new Error("No response body"));return}const o=new TextDecoder;let c="";try{for(;;){const{done:p,value:d}=await s.read();if(p)break;c+=o.decode(d,{stream:!0});const x=c.split(`
18
+ `);c=x.pop()||"";for(const N of x)if(N.trim())try{const A=JSON.parse(N);if(i(this.normalizeStreamChunk(A)),A.done){n==null||n();return}}catch{}}n==null||n()}catch(p){r==null||r(p)}finally{s.releaseLock()}}}class fa extends re{constructor(a){super(a),this.type="groq",this.name="Groq",this.baseUrl=a.baseUrl||"https://api.groq.com/openai/v1"}async chat(a){const n=await(await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama-3.1-70b-versatile",messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024})})).json();return this.normalizeResponse(n)}async chatStream(a,i,n,r){try{const s=await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama-3.1-70b-versatile",messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024,stream:!0})});await this.parseSSEStream(s,i,n,r)}catch(s){r==null||r(s)}}normalizeResponse(a){const i=a;return{id:i.id,model:i.model,choices:i.choices.map(n=>({index:n.index,message:n.message,finishReason:n.finish_reason})),usage:{promptTokens:i.usage.prompt_tokens,completionTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens},estimatedCost:0}}normalizeStreamChunk(a){const i=a;return{id:i.id,choices:i.choices.map(n=>({index:n.index,delta:n.delta,finishReason:n.finish_reason}))}}}function ee(t){switch(t.type){case"openai":return new ke(t);case"anthropic":return new pa(t);case"azure-openai":return new ga(t);case"ollama":return new ha(t);case"groq":return new fa(t);case"custom":return new ke(t);default:throw new Error(`Unsupported provider type: ${t.type}`)}}function Y(t){const a=new URL(t.endpoint),i=a.host.toLowerCase(),n=a.pathname.replace(/\/+$/,""),r=m=>`${a.protocol}//${a.host}${n.endsWith(m)?n.slice(0,-m.length):n}`,s={apiKey:t.apiKey,model:t.model,headers:t.headers},o=/^(.*)\/openai\/deployments\/([^/]+)\/chat\/completions$/.exec(n);if(i.endsWith("azure.com")&&o)return ee({type:"azure-openai",...s,baseUrl:`${a.protocol}//${a.host}${o[1]}`,deployment:o[2],apiVersion:a.searchParams.get("api-version")??void 0});if(i.includes("anthropic.com"))return ee({type:"anthropic",...s,baseUrl:r("/messages")});if(i.endsWith(":11434")||i.includes("ollama"))return ee({type:"ollama",...s,baseUrl:r("/api/chat")});const c=i.includes("openai.com")?"openai":i.includes("groq.com")?"groq":"custom";return ee({type:c,...s,baseUrl:r("/chat/completions")})}function ae(t,a){for(const r of t.variables)if(r.required&&!(r.name in a)&&!r.default)throw new Error(`Missing required variable: ${r.name}`);const i={};for(const r of t.variables)i[r.name]=a[r.name]??r.default;const n=r=>r.replace(/\{\{#if (\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g,(o,c,m)=>{const p=i[c];return p==null||p===""||p===!1||Array.isArray(p)&&p.length===0?"":m}).replace(/\{\{(\w+)\}\}/g,(o,c)=>{const m=i[c];return m===void 0?`{{${c}}}`:typeof m=="object"?JSON.stringify(m,null,2):String(m)});return{system:n(t.system),user:n(t.user),metadata:{templateId:t.id,variables:i,timestamp:Date.now()}}}const oe={id:"data-grid-filter",name:"DataGrid Natural Language Filter",description:"Convert natural language queries to DataGrid filter configurations",category:"data-query",system:`You are a filter query generator for a data grid component.
19
19
  Given column definitions and a natural language query, generate a JSON filter configuration.
20
20
 
21
21
  Available filter operators:
@@ -366,7 +366,7 @@ Format output as structured JSON:
366
366
 
367
367
  {{#if context}}Context: {{context}}{{/if}}
368
368
 
369
- Provide summary and insights:`,variables:[{name:"data",description:"Data to summarize (JSON or CSV)",required:!0,type:"string"},{name:"context",description:"Business context",required:!1,type:"string"}],suggestedTemperature:.4,maxTokens:1024},xe={[oe.id]:oe,[le.id]:le,[de.id]:de,[ue.id]:ue,[me.id]:me,[pe.id]:pe,[ge.id]:ge,[Ne.id]:Ne,[Se.id]:Se,[Ce.id]:Ce,[Ie.id]:Ie};function Ci(t){return xe[t]}function Ii(t){return Object.values(xe).filter(a=>a.category===t)}function Ai(){return Object.keys(xe)}class Oe{constructor(){this.records=new Map}async save(a,i){const r=this.records.get(a)||[];this.records.set(a,[...r,...i])}async load(a,i,r){const n=this.records.get(a)||[];return!i&&!r?n:n.filter(s=>!(i&&s.timestamp<i.getTime()||r&&s.timestamp>r.getTime()))}async clear(a,i){if(!i)this.records.delete(a);else{const r=this.records.get(a)||[];this.records.set(a,r.filter(n=>n.timestamp>=i.getTime()))}}}class xa{constructor(){this.prefix="nice2dev-ai-cost:"}async save(a,i){if(typeof window>"u")return;const r=`${this.prefix}${a}`,s=[...JSON.parse(localStorage.getItem(r)||"[]"),...i],o=Date.now()-720*60*60*1e3,c=s.filter(m=>m.timestamp>o);localStorage.setItem(r,JSON.stringify(c))}async load(a,i,r){if(typeof window>"u")return[];const n=`${this.prefix}${a}`,s=JSON.parse(localStorage.getItem(n)||"[]");return!i&&!r?s:s.filter(o=>!(i&&o.timestamp<i.getTime()||r&&o.timestamp>r.getTime()))}async clear(a,i){if(typeof window>"u")return;const r=`${this.prefix}${a}`;if(!i)localStorage.removeItem(r);else{const n=JSON.parse(localStorage.getItem(r)||"[]");localStorage.setItem(r,JSON.stringify(n.filter(s=>s.timestamp>=i.getTime())))}}}class ba{constructor(a,i){this.pendingRecords=[],this.flushTimer=null,this.alertCallbacks=[],this.minuteCounter=new Map,this.dayCounter=new Map,this.storage=a||new Oe,this.budgetConfig={monthlyBudget:100,dailyBudget:10,maxTokensPerRequest:4096,maxRequestsPerMinute:30,maxRequestsPerDay:1e3,alertThresholds:[50,80,90,100],...i}}async recordUsage(a,i){const r={...i,id:this.generateId(),timestamp:Date.now()};this.pendingRecords.push(r),this.updateCounters(a),this.scheduleFlush(a);const n=await this.getBudgetStatus(a);this.checkAlerts(a,n)}async canMakeRequest(a){const i=await this.getBudgetStatus(a);return i.isOverBudget?{allowed:!1,reason:"Budget exceeded"}:this.budgetConfig.maxRequestsPerMinute&&i.requestsThisMinute>=this.budgetConfig.maxRequestsPerMinute?{allowed:!1,reason:"Rate limit exceeded (per minute)"}:this.budgetConfig.maxRequestsPerDay&&i.requestsToday>=this.budgetConfig.maxRequestsPerDay?{allowed:!1,reason:"Daily request limit exceeded"}:{allowed:!0}}async getBudgetStatus(a){const i=new Date,r=new Date(i.getFullYear(),i.getMonth(),i.getDate()),n=new Date(i.getFullYear(),i.getMonth(),1),s=await this.storage.load(a,r),o=await this.storage.load(a,n),c=s.reduce((R,M)=>R+M.estimatedCost,0),m=o.reduce((R,M)=>R+M.estimatedCost,0),p=this.budgetConfig.dailyBudget||1/0,u=this.budgetConfig.monthlyBudget||1/0,v=p?c/p*100:0,w=u?m/u*100:0,A=[];for(const R of this.budgetConfig.alertThresholds||[])v>=R&&A.push(`Daily budget ${R}% used`),w>=R&&A.push(`Monthly budget ${R}% used`);return{dailyUsed:c,dailyRemaining:Math.max(0,p-c),dailyPercent:v,monthlyUsed:m,monthlyRemaining:Math.max(0,u-m),monthlyPercent:w,requestsToday:s.length,requestsThisMinute:this.getMinuteCount(a),isOverBudget:c>=p||m>=u,alerts:A}}async getUsageStats(a,i,r){const n=await this.storage.load(a,i,r),s={totalRequests:n.length,totalTokens:0,totalPromptTokens:0,totalCompletionTokens:0,totalCost:0,averageLatency:0,errorCount:0,cacheHitRate:0,byModel:{},byFeature:{},byDay:{}};let o=0,c=0;for(const m of n){s.totalTokens+=m.totalTokens,s.totalPromptTokens+=m.promptTokens,s.totalCompletionTokens+=m.completionTokens,s.totalCost+=m.estimatedCost,o+=m.latencyMs,m.error&&s.errorCount++,m.cached&&c++,s.byModel[m.model]||(s.byModel[m.model]={requests:0,tokens:0,cost:0}),s.byModel[m.model].requests++,s.byModel[m.model].tokens+=m.totalTokens,s.byModel[m.model].cost+=m.estimatedCost;const p=m.feature||"unknown";s.byFeature[p]||(s.byFeature[p]={requests:0,tokens:0,cost:0}),s.byFeature[p].requests++,s.byFeature[p].tokens+=m.totalTokens,s.byFeature[p].cost+=m.estimatedCost;const u=new Date(m.timestamp).toISOString().split("T")[0];s.byDay[u]||(s.byDay[u]={requests:0,tokens:0,cost:0}),s.byDay[u].requests++,s.byDay[u].tokens+=m.totalTokens,s.byDay[u].cost+=m.estimatedCost}return n.length>0&&(s.averageLatency=o/n.length,s.cacheHitRate=c/n.length),s}onAlert(a){return this.alertCallbacks.push(a),()=>{const i=this.alertCallbacks.indexOf(a);i>=0&&this.alertCallbacks.splice(i,1)}}setBudgetConfig(a){this.budgetConfig={...this.budgetConfig,...a}}async clearUsage(a,i){await this.storage.clear(a,i)}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}updateCounters(a){const i=Date.now(),r=i-6e4,n=this.minuteCounter.get(a)||[];n.push(i),this.minuteCounter.set(a,n.filter(c=>c>r));const s=new Date().toISOString().split("T")[0],o=`${a}:${s}`;this.dayCounter.set(o,(this.dayCounter.get(o)||0)+1)}getMinuteCount(a){const r=Date.now()-6e4;return(this.minuteCounter.get(a)||[]).filter(s=>s>r).length}scheduleFlush(a){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,this.pendingRecords.length>0&&(await this.storage.save(a,this.pendingRecords),this.pendingRecords=[])},1e3))}checkAlerts(a,i){if(i.alerts.length!==0)for(const r of i.alerts)for(const n of this.alertCallbacks)try{n(r,i)}catch{}}}function Ti(t,a){const i=l.useRef(null),[r,n]=l.useState(null),[s,o]=l.useState(null),[c,m]=l.useState(!0);l.useEffect(()=>{const w=typeof window<"u"?new xa:new Oe;i.current=new ba(w,a);const A=i.current.onAlert(R=>{console.warn(`[AI Cost Alert] ${R}`)});return()=>{A()}},[]);const p=l.useCallback(async()=>{if(i.current){m(!0);try{const[w,A]=await Promise.all([i.current.getBudgetStatus(t),i.current.getUsageStats(t)]);n(w),o(A)}finally{m(!1)}}},[t]);l.useEffect(()=>{p()},[p]);const u=l.useCallback(async w=>{i.current&&(await i.current.recordUsage(t,w),await p())},[t,p]),v=l.useCallback(async()=>i.current?i.current.canMakeRequest(t):{allowed:!0},[t]);return{status:r,stats:s,loading:c,recordUsage:u,canMakeRequest:v,refresh:p}}class Ri{constructor(a=100,i=36e5){this.cache=new Map,this.maxSize=a,this.ttl=i}hashRequest(a){const i=JSON.stringify({messages:a.messages,model:a.model,temperature:a.temperature});let r=0;for(let n=0;n<i.length;n++){const s=i.charCodeAt(n);r=(r<<5)-r+s,r=r&r}return r.toString(36)}get(a){const i=this.hashRequest(a),r=this.cache.get(i);return r?Date.now()-r.timestamp>this.ttl?(this.cache.delete(i),null):r.response:null}set(a,i){const r=this.hashRequest(a);if(this.cache.size>=this.maxSize){const n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(r,{request:r,response:i,timestamp:Date.now()})}clear(){this.cache.clear()}}class ya{constructor(a,i){this.backupProviders=[],this.circuitBreakers=new Map,this.primaryProvider=a,this.config={strategies:["retry","failover","cache","graceful-degrade"],maxRetries:3,retryDelay:1e3,backoffMultiplier:2,backupProviders:[],cacheTTL:36e5,offlineConfig:void 0,circuitBreakerThreshold:5,circuitBreakerResetTime:6e4,onFallback:void 0,...i},this.cache=new Ri(100,this.config.cacheTTL);for(const r of this.config.backupProviders||[])this.backupProviders.push(ae(r));this.config.offlineConfig&&(this.offlineProvider=ae(this.config.offlineConfig))}async chat(a){if(this.isCircuitOpen(this.primaryProvider.type))return this.executeWithFallback(a,new Error("Circuit breaker open"));try{const i=await this.primaryProvider.chat(a);return this.cache.set(a,i),this.resetCircuitBreaker(this.primaryProvider.type),i}catch(i){return this.recordFailure(this.primaryProvider.type),this.executeWithFallback(a,i)}}async executeWithFallback(a,i){var r,n;for(const s of this.config.strategies)try{const o=await this.executeStrategy(s,a,i);if(o)return(n=(r=this.config).onFallback)==null||n.call(r,s,i),o}catch{}throw new Error(`All fallback strategies failed. Original error: ${i.message}`)}async executeStrategy(a,i,r){switch(a){case"retry":return this.retryStrategy(i);case"failover":return this.failoverStrategy(i);case"cache":return this.cacheStrategy(i);case"offline":return this.offlineStrategy(i);case"graceful-degrade":return this.gracefulDegradeStrategy(i,r);case"circuit-breaker":return this.openCircuitBreaker(this.primaryProvider.type),null;default:return null}}async retryStrategy(a){let i=this.config.retryDelay;for(let r=0;r<this.config.maxRetries;r++){await this.delay(i);try{const n=await this.primaryProvider.chat(a);return this.cache.set(a,n),n}catch{i*=this.config.backoffMultiplier}}return null}async failoverStrategy(a){for(const i of this.backupProviders)if(!this.isCircuitOpen(i.type))try{const r=await i.chat(a);return this.cache.set(a,r),r}catch{this.recordFailure(i.type)}return null}cacheStrategy(a){const i=this.cache.get(a);return i?{...i,id:`cached-${i.id}`}:null}async offlineStrategy(a){if(!this.offlineProvider)return null;try{return await this.offlineProvider.chat(a)}catch{return null}}gracefulDegradeStrategy(a,i){const r=[...a.messages].reverse().find(n=>n.role==="user");return{id:`degraded-${Date.now()}`,model:"fallback",choices:[{index:0,message:{role:"assistant",content:this.generateDegradedResponse((r==null?void 0:r.content)||"",i)},finishReason:"stop"}],usage:{promptTokens:0,completionTokens:0,totalTokens:0}}}generateDegradedResponse(a,i){return a.toLowerCase().includes("filter")||a.toLowerCase().includes("show")?JSON.stringify({filters:[],logic:"and"}):a.toLowerCase().includes("form")||a.toLowerCase().includes("create")?JSON.stringify({title:"Form",fields:[{id:"field1",type:"text",label:"Field 1"}]}):a.toLowerCase().includes("chart")||a.toLowerCase().includes("graph")?JSON.stringify({type:"bar",title:"Chart",data:{source:"data"}}):`I'm sorry, I couldn't process your request at this time. The service is temporarily unavailable. Please try again later or contact support. (Error: ${i.message.substring(0,50)})`}isCircuitOpen(a){const i=this.circuitBreakers.get(a);return i&&i.isOpen?Date.now()-i.lastFailure>this.config.circuitBreakerResetTime?(this.resetCircuitBreaker(a),!1):!0:!1}recordFailure(a){const i=this.circuitBreakers.get(a)||{failures:0,lastFailure:0,isOpen:!1};i.failures++,i.lastFailure=Date.now(),i.failures>=this.config.circuitBreakerThreshold&&(i.isOpen=!0),this.circuitBreakers.set(a,i)}openCircuitBreaker(a){this.circuitBreakers.set(a,{failures:this.config.circuitBreakerThreshold,lastFailure:Date.now(),isOpen:!0})}resetCircuitBreaker(a){this.circuitBreakers.delete(a)}delay(a){return new Promise(i=>setTimeout(i,a))}addBackupProvider(a){this.backupProviders.push(a)}setOfflineProvider(a){this.offlineProvider=a}clearCache(){this.cache.clear()}resetAllCircuitBreakers(){this.circuitBreakers.clear()}getCircuitBreakerStatus(){const a={};for(const[i,r]of this.circuitBreakers)a[i]={...r};return a}async healthCheck(){const a={};a[this.primaryProvider.type]=await this.primaryProvider.healthCheck();for(const i of this.backupProviders)a[`backup-${i.type}`]=await i.healthCheck();return this.offlineProvider&&(a.offline=await this.offlineProvider.healthCheck()),a}}function va(t,a){const i=ae(t);return new ya(i,a)}function Li(t,a){const i={strategies:["retry","failover","cache","graceful-degrade"],maxRetries:3,retryDelay:1e3,backoffMultiplier:2,backupProviders:a?[a]:[],circuitBreakerThreshold:5,circuitBreakerResetTime:6e4};return typeof window>"u"&&(i.offlineConfig={type:"ollama",model:"llama3"}),va(t,i)}const zi=[];function _a(t){const{columns:a,config:i,onFilterGenerated:r,onSortGenerated:n,onError:s}=t,o=ee(),{t:c,lang:m}=T.useNiceTranslation(),[p,u]=l.useState(!1),[v,w]=l.useState(null),[A,R]=l.useState(null),[M,P]=l.useState([]),g=l.useRef(null),d=i||(o==null?void 0:o.config),j=l.useMemo(()=>a.map(h=>({id:h.id,label:h.label,type:h.type,...h.options?{options:h.options}:{}})),[a]),y=l.useCallback(async h=>{var f;if(!d){const k="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(k),{type:"filter",error:k}}u(!0),w(h);const _=performance.now();(f=g.current)==null||f.abort(),g.current=new AbortController;try{const k=V(d),S=h.toLowerCase(),N=S.includes("sort")||S.includes("order")||S.includes("arrange")||S.includes("by highest")||S.includes("by lowest"),$=S.includes("show")||S.includes("find")||S.includes("filter")||S.includes("where")||S.includes("with")||S.includes("only"),E=m!=="en"&&!N&&!$,z=N||E,F=$||!N,U={type:"combined"};if(F){const H=ie(oe,{columns:j,query:h}),X=await k.chat({messages:[{role:"system",content:H.system},{role:"user",content:H.user}],temperature:.2,maxTokens:512}),C=Mi(X);C&&(!E||C.filters.length>0)&&(U.filterConfig=C,U.type="filter",r==null||r(C))}if(z){const H=ie(le,{columns:j,query:h}),X=await k.chat({messages:[{role:"system",content:H.system},{role:"user",content:H.user}],temperature:.1,maxTokens:256}),C=$i(X);C&&(!E||C.sort.length>0)&&(U.sortConfig=C,U.type=U.filterConfig?"combined":"sort",n==null||n(C))}return U.latencyMs=performance.now()-_,R(U),P(H=>[...H.slice(-9),{query:h,result:U}]),U}catch(k){const S=k instanceof Error?k.message:c("dataGridAI.requestFailed","AI request failed"),N={type:"filter",error:S,latencyMs:performance.now()-_};return R(N),s==null||s(S),N}finally{u(!1)}},[d,j,r,n,s,c,m]),I=l.useCallback(()=>{w(null),R(null)},[]),b=l.useCallback(()=>{var h;(h=g.current)==null||h.abort(),u(!1)},[]);return l.useEffect(()=>()=>{var h;(h=g.current)==null||h.abort()},[]),{processQuery:y,loading:p,lastQuery:v,lastResult:A,history:M,clearResults:I,abort:b,isConfigured:!!d}}function Mi(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.filters&&Array.isArray(c.filters))return{filters:c.filters,logic:c.logic||"and",confidence:c.confidence,explanation:c.explanation}}catch{}return null}function $i(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.sort&&Array.isArray(c.sort))return{sort:c.sort,confidence:c.confidence}}catch{}return null}function Pi({columns:t=zi,config:a,onFilter:i,onSort:r,placeholder:n,showHistory:s=!0,showSuggestions:o=!0,className:c,style:m}){const{t:p}=T.useNiceTranslation(),[u,v]=l.useState(""),[w,A]=l.useState(!1),R=l.useRef(null),{processQuery:M,loading:P,lastResult:g,history:d,isConfigured:j}=_a({columns:t,config:a,onFilterGenerated:i,onSortGenerated:r}),y=l.useMemo(()=>{if(!o||t.length===0)return[];const f=[],k=(z,F,U)=>p(z,F).replace("{column}",U.label),S=t.filter(z=>z.type==="string");S.length>0&&f.push(k("dataGridAI.suggest.contains",'Show rows where {column} contains "example"',S[0]));const N=t.filter(z=>z.type==="number");N.length>0&&(f.push(k("dataGridAI.suggest.greaterThan","{column} greater than 100",N[0])),f.push(k("dataGridAI.suggest.sortHighest","Sort by highest {column}",N[0])));const $=t.filter(z=>z.type==="date");$.length>0&&(f.push(k("dataGridAI.suggest.lastDays","{column} in the last 7 days",$[0])),f.push(k("dataGridAI.suggest.sortNewest","Sort by newest {column}",$[0])));const E=t.filter(z=>{var F;return z.type==="enum"&&((F=z.options)==null?void 0:F.length)});return E.length>0&&E[0].options&&f.push(k("dataGridAI.suggest.equals","Where {column} is {value}",E[0]).replace("{value}",E[0].options[0])),f.slice(0,5)},[t,o,p]),I=async()=>{!u.trim()||P||(await M(u.trim()),A(!1))},b=f=>{f.key==="Enter"?(f.preventDefault(),I()):f.key==="Escape"&&A(!1)},h=f=>{var k;v(f),A(!1),(k=R.current)==null||k.focus()},_=f=>{v(f),A(!1),M(f)};return j?e.jsxs("div",{className:`nice-datagrid-ai ${c||""}`,style:m,children:[e.jsxs("div",{className:"nice-datagrid-ai__input-wrapper",children:[e.jsx("span",{className:"nice-datagrid-ai__icon",children:e.jsx(T.NiceIcon,{name:"search",size:16})}),e.jsx("input",{ref:R,type:"text",value:u,onChange:f=>v(f.target.value),onKeyDown:b,onFocus:()=>A(!0),onBlur:()=>setTimeout(()=>A(!1),200),placeholder:n??p("dataGridAI.queryPlaceholder",'Ask AI to filter or sort data... (e.g., "show orders from last week")'),className:"nice-datagrid-ai__input",disabled:P,"aria-label":p("dataGridAI.queryInput","AI query input")}),P?e.jsx("span",{className:"nice-datagrid-ai__spinner"}):e.jsx("button",{type:"button",onClick:I,className:"nice-datagrid-ai__submit",disabled:!u.trim(),"aria-label":p("dataGridAI.submitQuery","Submit query"),children:e.jsx(T.NiceIcon,{name:"send",size:16})})]}),w&&(y.length>0||s&&d.length>0)&&e.jsxs("div",{className:"nice-datagrid-ai__dropdown",children:[o&&y.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:p("dataGridAI.suggestions","Suggestions")}),y.map((f,k)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>h(f),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(T.NiceIcon,{name:"lightbulb",size:14})}),f]},k))]}),s&&d.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:p("dataGridAI.recent","Recent")}),d.slice(-5).reverse().map((f,k)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>_(f.query),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(T.NiceIcon,{name:"clock",size:14})}),f.query,f.result.error&&e.jsx("span",{className:"nice-datagrid-ai__item-error",children:e.jsx(T.NiceIcon,{name:"warning",size:14})})]},k))]})]}),g&&!g.error&&e.jsxs("div",{className:"nice-datagrid-ai__result",children:[g.filterConfig&&e.jsx("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--filter",children:g.filterConfig.filters.length===1?p("dataGridAI.filterApplied","1 filter applied"):p("dataGridAI.filtersApplied","{count} filters applied").replace("{count}",String(g.filterConfig.filters.length))}),g.sortConfig&&e.jsx("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--sort",children:p("dataGridAI.sortedBy","Sorted by {columns}").replace("{columns}",g.sortConfig.sort.map(f=>{var k;return((k=t.find(S=>S.id===f.column))==null?void 0:k.label)??f.column}).join(", "))}),g.latencyMs&&e.jsxs("span",{className:"nice-datagrid-ai__latency",children:[Math.round(g.latencyMs),"ms"]})]}),(g==null?void 0:g.error)&&e.jsx("div",{className:"nice-datagrid-ai__error",children:g.error}),e.jsx("style",{children:`
369
+ Provide summary and insights:`,variables:[{name:"data",description:"Data to summarize (JSON or CSV)",required:!0,type:"string"},{name:"context",description:"Business context",required:!1,type:"string"}],suggestedTemperature:.4,maxTokens:1024},xe={[oe.id]:oe,[le.id]:le,[de.id]:de,[ue.id]:ue,[me.id]:me,[pe.id]:pe,[ge.id]:ge,[Ne.id]:Ne,[Se.id]:Se,[Ce.id]:Ce,[Ie.id]:Ie};function Ci(t){return xe[t]}function Ii(t){return Object.values(xe).filter(a=>a.category===t)}function Ai(){return Object.keys(xe)}class Oe{constructor(){this.records=new Map}async save(a,i){const n=this.records.get(a)||[];this.records.set(a,[...n,...i])}async load(a,i,n){const r=this.records.get(a)||[];return!i&&!n?r:r.filter(s=>!(i&&s.timestamp<i.getTime()||n&&s.timestamp>n.getTime()))}async clear(a,i){if(!i)this.records.delete(a);else{const n=this.records.get(a)||[];this.records.set(a,n.filter(r=>r.timestamp>=i.getTime()))}}}class xa{constructor(){this.prefix="nice2dev-ai-cost:"}async save(a,i){if(typeof window>"u")return;const n=`${this.prefix}${a}`,s=[...JSON.parse(localStorage.getItem(n)||"[]"),...i],o=Date.now()-720*60*60*1e3,c=s.filter(m=>m.timestamp>o);localStorage.setItem(n,JSON.stringify(c))}async load(a,i,n){if(typeof window>"u")return[];const r=`${this.prefix}${a}`,s=JSON.parse(localStorage.getItem(r)||"[]");return!i&&!n?s:s.filter(o=>!(i&&o.timestamp<i.getTime()||n&&o.timestamp>n.getTime()))}async clear(a,i){if(typeof window>"u")return;const n=`${this.prefix}${a}`;if(!i)localStorage.removeItem(n);else{const r=JSON.parse(localStorage.getItem(n)||"[]");localStorage.setItem(n,JSON.stringify(r.filter(s=>s.timestamp>=i.getTime())))}}}class ba{constructor(a,i){this.pendingRecords=[],this.flushTimer=null,this.alertCallbacks=[],this.minuteCounter=new Map,this.dayCounter=new Map,this.storage=a||new Oe,this.budgetConfig={monthlyBudget:100,dailyBudget:10,maxTokensPerRequest:4096,maxRequestsPerMinute:30,maxRequestsPerDay:1e3,alertThresholds:[50,80,90,100],...i}}async recordUsage(a,i){const n={...i,id:this.generateId(),timestamp:Date.now()};this.pendingRecords.push(n),this.updateCounters(a),this.scheduleFlush(a);const r=await this.getBudgetStatus(a);this.checkAlerts(a,r)}async canMakeRequest(a){const i=await this.getBudgetStatus(a);return i.isOverBudget?{allowed:!1,reason:"Budget exceeded"}:this.budgetConfig.maxRequestsPerMinute&&i.requestsThisMinute>=this.budgetConfig.maxRequestsPerMinute?{allowed:!1,reason:"Rate limit exceeded (per minute)"}:this.budgetConfig.maxRequestsPerDay&&i.requestsToday>=this.budgetConfig.maxRequestsPerDay?{allowed:!1,reason:"Daily request limit exceeded"}:{allowed:!0}}async getBudgetStatus(a){const i=new Date,n=new Date(i.getFullYear(),i.getMonth(),i.getDate()),r=new Date(i.getFullYear(),i.getMonth(),1),s=await this.storage.load(a,n),o=await this.storage.load(a,r),c=s.reduce((R,$)=>R+$.estimatedCost,0),m=o.reduce((R,$)=>R+$.estimatedCost,0),p=this.budgetConfig.dailyBudget||1/0,d=this.budgetConfig.monthlyBudget||1/0,x=p?c/p*100:0,N=d?m/d*100:0,A=[];for(const R of this.budgetConfig.alertThresholds||[])x>=R&&A.push(`Daily budget ${R}% used`),N>=R&&A.push(`Monthly budget ${R}% used`);return{dailyUsed:c,dailyRemaining:Math.max(0,p-c),dailyPercent:x,monthlyUsed:m,monthlyRemaining:Math.max(0,d-m),monthlyPercent:N,requestsToday:s.length,requestsThisMinute:this.getMinuteCount(a),isOverBudget:c>=p||m>=d,alerts:A}}async getUsageStats(a,i,n){const r=await this.storage.load(a,i,n),s={totalRequests:r.length,totalTokens:0,totalPromptTokens:0,totalCompletionTokens:0,totalCost:0,averageLatency:0,errorCount:0,cacheHitRate:0,byModel:{},byFeature:{},byDay:{}};let o=0,c=0;for(const m of r){s.totalTokens+=m.totalTokens,s.totalPromptTokens+=m.promptTokens,s.totalCompletionTokens+=m.completionTokens,s.totalCost+=m.estimatedCost,o+=m.latencyMs,m.error&&s.errorCount++,m.cached&&c++,s.byModel[m.model]||(s.byModel[m.model]={requests:0,tokens:0,cost:0}),s.byModel[m.model].requests++,s.byModel[m.model].tokens+=m.totalTokens,s.byModel[m.model].cost+=m.estimatedCost;const p=m.feature||"unknown";s.byFeature[p]||(s.byFeature[p]={requests:0,tokens:0,cost:0}),s.byFeature[p].requests++,s.byFeature[p].tokens+=m.totalTokens,s.byFeature[p].cost+=m.estimatedCost;const d=new Date(m.timestamp).toISOString().split("T")[0];s.byDay[d]||(s.byDay[d]={requests:0,tokens:0,cost:0}),s.byDay[d].requests++,s.byDay[d].tokens+=m.totalTokens,s.byDay[d].cost+=m.estimatedCost}return r.length>0&&(s.averageLatency=o/r.length,s.cacheHitRate=c/r.length),s}onAlert(a){return this.alertCallbacks.push(a),()=>{const i=this.alertCallbacks.indexOf(a);i>=0&&this.alertCallbacks.splice(i,1)}}setBudgetConfig(a){this.budgetConfig={...this.budgetConfig,...a}}async clearUsage(a,i){await this.storage.clear(a,i)}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}updateCounters(a){const i=Date.now(),n=i-6e4,r=this.minuteCounter.get(a)||[];r.push(i),this.minuteCounter.set(a,r.filter(c=>c>n));const s=new Date().toISOString().split("T")[0],o=`${a}:${s}`;this.dayCounter.set(o,(this.dayCounter.get(o)||0)+1)}getMinuteCount(a){const n=Date.now()-6e4;return(this.minuteCounter.get(a)||[]).filter(s=>s>n).length}scheduleFlush(a){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,this.pendingRecords.length>0&&(await this.storage.save(a,this.pendingRecords),this.pendingRecords=[])},1e3))}checkAlerts(a,i){if(i.alerts.length!==0)for(const n of i.alerts)for(const r of this.alertCallbacks)try{r(n,i)}catch{}}}function Ti(t,a){const i=l.useRef(null),[n,r]=l.useState(null),[s,o]=l.useState(null),[c,m]=l.useState(!0);l.useEffect(()=>{const N=typeof window<"u"?new xa:new Oe;i.current=new ba(N,a);const A=i.current.onAlert(R=>{console.warn(`[AI Cost Alert] ${R}`)});return()=>{A()}},[]);const p=l.useCallback(async()=>{if(i.current){m(!0);try{const[N,A]=await Promise.all([i.current.getBudgetStatus(t),i.current.getUsageStats(t)]);r(N),o(A)}finally{m(!1)}}},[t]);l.useEffect(()=>{p()},[p]);const d=l.useCallback(async N=>{i.current&&(await i.current.recordUsage(t,N),await p())},[t,p]),x=l.useCallback(async()=>i.current?i.current.canMakeRequest(t):{allowed:!0},[t]);return{status:n,stats:s,loading:c,recordUsage:d,canMakeRequest:x,refresh:p}}class Ri{constructor(a=100,i=36e5){this.cache=new Map,this.maxSize=a,this.ttl=i}hashRequest(a){const i=JSON.stringify({messages:a.messages,model:a.model,temperature:a.temperature});let n=0;for(let r=0;r<i.length;r++){const s=i.charCodeAt(r);n=(n<<5)-n+s,n=n&n}return n.toString(36)}get(a){const i=this.hashRequest(a),n=this.cache.get(i);return n?Date.now()-n.timestamp>this.ttl?(this.cache.delete(i),null):n.response:null}set(a,i){const n=this.hashRequest(a);if(this.cache.size>=this.maxSize){const r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(n,{request:n,response:i,timestamp:Date.now()})}clear(){this.cache.clear()}}class ya{constructor(a,i){this.backupProviders=[],this.circuitBreakers=new Map,this.primaryProvider=a,this.config={strategies:["retry","failover","cache","graceful-degrade"],maxRetries:3,retryDelay:1e3,backoffMultiplier:2,backupProviders:[],cacheTTL:36e5,offlineConfig:void 0,circuitBreakerThreshold:5,circuitBreakerResetTime:6e4,onFallback:void 0,...i},this.cache=new Ri(100,this.config.cacheTTL);for(const n of this.config.backupProviders||[])this.backupProviders.push(ee(n));this.config.offlineConfig&&(this.offlineProvider=ee(this.config.offlineConfig))}async chat(a){if(this.isCircuitOpen(this.primaryProvider.type))return this.executeWithFallback(a,new Error("Circuit breaker open"));try{const i=await this.primaryProvider.chat(a);return this.cache.set(a,i),this.resetCircuitBreaker(this.primaryProvider.type),i}catch(i){return this.recordFailure(this.primaryProvider.type),this.executeWithFallback(a,i)}}async executeWithFallback(a,i){var n,r;for(const s of this.config.strategies)try{const o=await this.executeStrategy(s,a,i);if(o)return(r=(n=this.config).onFallback)==null||r.call(n,s,i),o}catch{}throw new Error(`All fallback strategies failed. Original error: ${i.message}`)}async executeStrategy(a,i,n){switch(a){case"retry":return this.retryStrategy(i);case"failover":return this.failoverStrategy(i);case"cache":return this.cacheStrategy(i);case"offline":return this.offlineStrategy(i);case"graceful-degrade":return this.gracefulDegradeStrategy(i,n);case"circuit-breaker":return this.openCircuitBreaker(this.primaryProvider.type),null;default:return null}}async retryStrategy(a){let i=this.config.retryDelay;for(let n=0;n<this.config.maxRetries;n++){await this.delay(i);try{const r=await this.primaryProvider.chat(a);return this.cache.set(a,r),r}catch{i*=this.config.backoffMultiplier}}return null}async failoverStrategy(a){for(const i of this.backupProviders)if(!this.isCircuitOpen(i.type))try{const n=await i.chat(a);return this.cache.set(a,n),n}catch{this.recordFailure(i.type)}return null}cacheStrategy(a){const i=this.cache.get(a);return i?{...i,id:`cached-${i.id}`}:null}async offlineStrategy(a){if(!this.offlineProvider)return null;try{return await this.offlineProvider.chat(a)}catch{return null}}gracefulDegradeStrategy(a,i){const n=[...a.messages].reverse().find(r=>r.role==="user");return{id:`degraded-${Date.now()}`,model:"fallback",choices:[{index:0,message:{role:"assistant",content:this.generateDegradedResponse((n==null?void 0:n.content)||"",i)},finishReason:"stop"}],usage:{promptTokens:0,completionTokens:0,totalTokens:0}}}generateDegradedResponse(a,i){return a.toLowerCase().includes("filter")||a.toLowerCase().includes("show")?JSON.stringify({filters:[],logic:"and"}):a.toLowerCase().includes("form")||a.toLowerCase().includes("create")?JSON.stringify({title:"Form",fields:[{id:"field1",type:"text",label:"Field 1"}]}):a.toLowerCase().includes("chart")||a.toLowerCase().includes("graph")?JSON.stringify({type:"bar",title:"Chart",data:{source:"data"}}):`I'm sorry, I couldn't process your request at this time. The service is temporarily unavailable. Please try again later or contact support. (Error: ${i.message.substring(0,50)})`}isCircuitOpen(a){const i=this.circuitBreakers.get(a);return i&&i.isOpen?Date.now()-i.lastFailure>this.config.circuitBreakerResetTime?(this.resetCircuitBreaker(a),!1):!0:!1}recordFailure(a){const i=this.circuitBreakers.get(a)||{failures:0,lastFailure:0,isOpen:!1};i.failures++,i.lastFailure=Date.now(),i.failures>=this.config.circuitBreakerThreshold&&(i.isOpen=!0),this.circuitBreakers.set(a,i)}openCircuitBreaker(a){this.circuitBreakers.set(a,{failures:this.config.circuitBreakerThreshold,lastFailure:Date.now(),isOpen:!0})}resetCircuitBreaker(a){this.circuitBreakers.delete(a)}delay(a){return new Promise(i=>setTimeout(i,a))}addBackupProvider(a){this.backupProviders.push(a)}setOfflineProvider(a){this.offlineProvider=a}clearCache(){this.cache.clear()}resetAllCircuitBreakers(){this.circuitBreakers.clear()}getCircuitBreakerStatus(){const a={};for(const[i,n]of this.circuitBreakers)a[i]={...n};return a}async healthCheck(){const a={};a[this.primaryProvider.type]=await this.primaryProvider.healthCheck();for(const i of this.backupProviders)a[`backup-${i.type}`]=await i.healthCheck();return this.offlineProvider&&(a.offline=await this.offlineProvider.healthCheck()),a}}function va(t,a){const i=ee(t);return new ya(i,a)}function Li(t,a){const i={strategies:["retry","failover","cache","graceful-degrade"],maxRetries:3,retryDelay:1e3,backoffMultiplier:2,backupProviders:a?[a]:[],circuitBreakerThreshold:5,circuitBreakerResetTime:6e4};return typeof window>"u"&&(i.offlineConfig={type:"ollama",model:"llama3"}),va(t,i)}const zi=[];function _a(t){const{columns:a,config:i,onFilterGenerated:n,onSortGenerated:r,onError:s}=t,o=Z(),{t:c,lang:m}=T.useNiceTranslation(),[p,d]=l.useState(!1),[x,N]=l.useState(null),[A,R]=l.useState(null),[$,M]=l.useState([]),g=l.useRef(null),u=i||(o==null?void 0:o.config),y=l.useMemo(()=>a.map(h=>({id:h.id,label:h.label,type:h.type,...h.options?{options:h.options}:{}})),[a]),_=l.useCallback(async h=>{var f;if(!u){const j="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(j),{type:"filter",error:j}}d(!0),N(h);const w=performance.now();(f=g.current)==null||f.abort(),g.current=new AbortController;try{const j=Y(u),k=h.toLowerCase(),I=k.includes("sort")||k.includes("order")||k.includes("arrange")||k.includes("by highest")||k.includes("by lowest"),z=k.includes("show")||k.includes("find")||k.includes("filter")||k.includes("where")||k.includes("with")||k.includes("only"),E=m!=="en"&&!I&&!z,P=I||E,F=z||!I,G={type:"combined"};if(F){const K=ae(oe,{columns:y,query:h}),X=await j.chat({messages:[{role:"system",content:K.system},{role:"user",content:K.user}],temperature:.2,maxTokens:512}),S=Mi(X);S&&(!E||S.filters.length>0)&&(G.filterConfig=S,G.type="filter",n==null||n(S))}if(P){const K=ae(le,{columns:y,query:h}),X=await j.chat({messages:[{role:"system",content:K.system},{role:"user",content:K.user}],temperature:.1,maxTokens:256}),S=$i(X);S&&(!E||S.sort.length>0)&&(G.sortConfig=S,G.type=G.filterConfig?"combined":"sort",r==null||r(S))}return G.latencyMs=performance.now()-w,R(G),M(K=>[...K.slice(-9),{query:h,result:G}]),G}catch(j){const k=j instanceof Error?j.message:c("dataGridAI.requestFailed","AI request failed"),I={type:"filter",error:k,latencyMs:performance.now()-w};return R(I),s==null||s(k),I}finally{d(!1)}},[u,y,n,r,s,c,m]),C=l.useCallback(()=>{N(null),R(null)},[]),v=l.useCallback(()=>{var h;(h=g.current)==null||h.abort(),d(!1)},[]);return l.useEffect(()=>()=>{var h;(h=g.current)==null||h.abort()},[]),{processQuery:_,loading:p,lastQuery:x,lastResult:A,history:$,clearResults:C,abort:v,isConfigured:!!u}}function Mi(t){var a,i,n;try{const r=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((n=(r.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,r])[1])==null?void 0:n.trim())||r,c=JSON.parse(o);if(c.filters&&Array.isArray(c.filters))return{filters:c.filters,logic:c.logic||"and",confidence:c.confidence,explanation:c.explanation}}catch{}return null}function $i(t){var a,i,n;try{const r=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((n=(r.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,r])[1])==null?void 0:n.trim())||r,c=JSON.parse(o);if(c.sort&&Array.isArray(c.sort))return{sort:c.sort,confidence:c.confidence}}catch{}return null}function Pi({columns:t=zi,config:a,onFilter:i,onSort:n,placeholder:r,showHistory:s=!0,showSuggestions:o=!0,className:c,style:m}){const{t:p}=T.useNiceTranslation(),[d,x]=l.useState(""),[N,A]=l.useState(!1),R=l.useRef(null),{processQuery:$,loading:M,lastResult:g,history:u,isConfigured:y}=_a({columns:t,config:a,onFilterGenerated:i,onSortGenerated:n}),_=l.useMemo(()=>{if(!o||t.length===0)return[];const f=[],j=(P,F,G)=>p(P,F).replace("{column}",G.label),k=t.filter(P=>P.type==="string");k.length>0&&f.push(j("dataGridAI.suggest.contains",'Show rows where {column} contains "example"',k[0]));const I=t.filter(P=>P.type==="number");I.length>0&&(f.push(j("dataGridAI.suggest.greaterThan","{column} greater than 100",I[0])),f.push(j("dataGridAI.suggest.sortHighest","Sort by highest {column}",I[0])));const z=t.filter(P=>P.type==="date");z.length>0&&(f.push(j("dataGridAI.suggest.lastDays","{column} in the last 7 days",z[0])),f.push(j("dataGridAI.suggest.sortNewest","Sort by newest {column}",z[0])));const E=t.filter(P=>{var F;return P.type==="enum"&&((F=P.options)==null?void 0:F.length)});return E.length>0&&E[0].options&&f.push(j("dataGridAI.suggest.equals","Where {column} is {value}",E[0]).replace("{value}",E[0].options[0])),f.slice(0,5)},[t,o,p]),C=async()=>{!d.trim()||M||(await $(d.trim()),A(!1))},v=f=>{f.key==="Enter"?(f.preventDefault(),C()):f.key==="Escape"&&A(!1)},h=f=>{var j;x(f),A(!1),(j=R.current)==null||j.focus()},w=f=>{x(f),A(!1),$(f)};return y?e.jsxs("div",{className:`nice-datagrid-ai ${c||""}`,style:m,children:[e.jsxs("div",{className:"nice-datagrid-ai__input-wrapper",children:[e.jsx("span",{className:"nice-datagrid-ai__icon",children:e.jsx(T.NiceIcon,{name:"search",size:16})}),e.jsx("input",{ref:R,type:"text",value:d,onChange:f=>x(f.target.value),onKeyDown:v,onFocus:()=>A(!0),onBlur:()=>setTimeout(()=>A(!1),200),placeholder:r??p("dataGridAI.queryPlaceholder",'Ask AI to filter or sort data... (e.g., "show orders from last week")'),className:"nice-datagrid-ai__input",disabled:M,"aria-label":p("dataGridAI.queryInput","AI query input")}),M?e.jsx("span",{className:"nice-datagrid-ai__spinner"}):e.jsx("button",{type:"button",onClick:C,className:"nice-datagrid-ai__submit",disabled:!d.trim(),"aria-label":p("dataGridAI.submitQuery","Submit query"),children:e.jsx(T.NiceIcon,{name:"send",size:16})})]}),N&&(_.length>0||s&&u.length>0)&&e.jsxs("div",{className:"nice-datagrid-ai__dropdown",children:[o&&_.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:p("dataGridAI.suggestions","Suggestions")}),_.map((f,j)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>h(f),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(T.NiceIcon,{name:"lightbulb",size:14})}),f]},j))]}),s&&u.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:p("dataGridAI.recent","Recent")}),u.slice(-5).reverse().map((f,j)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>w(f.query),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(T.NiceIcon,{name:"clock",size:14})}),f.query,f.result.error&&e.jsx("span",{className:"nice-datagrid-ai__item-error",children:e.jsx(T.NiceIcon,{name:"warning",size:14})})]},j))]})]}),g&&!g.error&&e.jsxs("div",{className:"nice-datagrid-ai__result",children:[g.filterConfig&&e.jsx("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--filter",children:g.filterConfig.filters.length===1?p("dataGridAI.filterApplied","1 filter applied"):p("dataGridAI.filtersApplied","{count} filters applied").replace("{count}",String(g.filterConfig.filters.length))}),g.sortConfig&&e.jsx("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--sort",children:p("dataGridAI.sortedBy","Sorted by {columns}").replace("{columns}",g.sortConfig.sort.map(f=>{var j;return((j=t.find(k=>k.id===f.column))==null?void 0:j.label)??f.column}).join(", "))}),g.latencyMs&&e.jsxs("span",{className:"nice-datagrid-ai__latency",children:[Math.round(g.latencyMs),"ms"]})]}),(g==null?void 0:g.error)&&e.jsx("div",{className:"nice-datagrid-ai__error",children:g.error}),e.jsx("style",{children:`
370
370
  .nice-datagrid-ai {
371
371
  position: relative;
372
372
  font-family: var(--nice-font-family, system-ui, sans-serif);
@@ -548,13 +548,13 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
548
548
  border-radius: var(--nice-radius-sm, 4px);
549
549
  font-size: 13px;
550
550
  }
551
- `})]}):e.jsx("div",{className:`nice-datagrid-ai nice-datagrid-ai--disabled ${c||""}`,style:m,children:e.jsx("input",{type:"text",placeholder:p("dataGridAI.notConfigured","AI not configured"),disabled:!0,className:"nice-datagrid-ai__input"})})}function wa(t={}){const{config:a,schema:i,context:r,onFormGenerated:n,onError:s}=t,o=ee(),{t:c}=T.useNiceTranslation(),[m,p]=l.useState(!1),[u,v]=l.useState(null),[w,A]=l.useState(null),[R,M]=l.useState([]),P=l.useRef(null),g=a||(o==null?void 0:o.config),d=l.useCallback(async b=>{var _,f,k;if(!g){const S="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(S),{error:S}}p(!0),v(b);const h=performance.now();(_=P.current)==null||_.abort(),P.current=new AbortController;try{const S=V(g),N=ie(de,{description:b,schema:i?JSON.stringify(i,null,2):void 0,context:r}),$=await S.chat({messages:[{role:"system",content:N.system},{role:"user",content:N.user}],temperature:.5,maxTokens:2048}),E=Oi($),z={config:E||void 0,rawResponse:(k=(f=$.choices[0])==null?void 0:f.message)==null?void 0:k.content,latencyMs:performance.now()-h,error:E?void 0:c("formBuilderAI.parseFailed","Failed to parse form configuration")};return E&&(n==null||n(E)),A(z),M(F=>[...F.slice(-9),{description:b,result:z}]),z}catch(S){const N=S instanceof Error?S.message:c("formBuilderAI.requestFailed","AI request failed"),$={error:N,latencyMs:performance.now()-h};return A($),s==null||s(N),$}finally{p(!1)}},[g,i,r,n,s,c]),j=l.useCallback(async b=>{if(!(w!=null&&w.config))return{error:c("formBuilderAI.nothingToRefine","No form to refine. Generate a form first.")};const h=`
551
+ `})]}):e.jsx("div",{className:`nice-datagrid-ai nice-datagrid-ai--disabled ${c||""}`,style:m,children:e.jsx("input",{type:"text",placeholder:p("dataGridAI.notConfigured","AI not configured"),disabled:!0,className:"nice-datagrid-ai__input"})})}function wa(t={}){const{config:a,schema:i,context:n,onFormGenerated:r,onError:s}=t,o=Z(),{t:c}=T.useNiceTranslation(),[m,p]=l.useState(!1),[d,x]=l.useState(null),[N,A]=l.useState(null),[R,$]=l.useState([]),M=l.useRef(null),g=a||(o==null?void 0:o.config),u=l.useCallback(async v=>{var w,f,j;if(!g){const k="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(k),{error:k}}p(!0),x(v);const h=performance.now();(w=M.current)==null||w.abort(),M.current=new AbortController;try{const k=Y(g),I=ae(de,{description:v,schema:i?JSON.stringify(i,null,2):void 0,context:n}),z=await k.chat({messages:[{role:"system",content:I.system},{role:"user",content:I.user}],temperature:.5,maxTokens:2048}),E=Oi(z),P={config:E||void 0,rawResponse:(j=(f=z.choices[0])==null?void 0:f.message)==null?void 0:j.content,latencyMs:performance.now()-h,error:E?void 0:c("formBuilderAI.parseFailed","Failed to parse form configuration")};return E&&(r==null||r(E)),A(P),$(F=>[...F.slice(-9),{description:v,result:P}]),P}catch(k){const I=k instanceof Error?k.message:c("formBuilderAI.requestFailed","AI request failed"),z={error:I,latencyMs:performance.now()-h};return A(z),s==null||s(I),z}finally{p(!1)}},[g,i,n,r,s,c]),y=l.useCallback(async v=>{if(!(N!=null&&N.config))return{error:c("formBuilderAI.nothingToRefine","No form to refine. Generate a form first.")};const h=`
552
552
  Modify this existing form based on the following instructions:
553
553
 
554
- Current form: ${JSON.stringify(w.config,null,2)}
554
+ Current form: ${JSON.stringify(N.config,null,2)}
555
555
 
556
- Instructions: ${b}
557
- `;return d(h)},[w,d,c]),y=l.useCallback(()=>{v(null),A(null)},[]),I=l.useCallback(()=>{var b;(b=P.current)==null||b.abort(),p(!1)},[]);return l.useEffect(()=>()=>{var b;(b=P.current)==null||b.abort()},[]),{generateForm:d,refineForm:j,loading:m,lastDescription:u,lastResult:w,history:R,clearResults:y,abort:I,isConfigured:!!g}}function Oi(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.fields&&Array.isArray(c.fields))return{title:c.title,description:c.description,fields:c.fields,layout:c.layout,submitLabel:c.submitLabel,validation:c.validation}}catch{}return null}function Ei({config:t,schema:a,context:i,onGenerate:r,placeholder:n,showExamples:s=!0,showPreview:o=!0,className:c,style:m,renderForm:p}){const{t:u}=T.useNiceTranslation(),[v,w]=l.useState(""),[A,R]=l.useState(!1),M=l.useRef(null),{generateForm:P,loading:g,lastResult:d,isConfigured:j}=wa({config:t,schema:a,context:i,onFormGenerated:r}),y=[u("formBuilderAI.example.contact","Simple contact form with name, email, and message"),u("formBuilderAI.example.registration","User registration with email validation and password confirmation"),u("formBuilderAI.example.feedback","Product feedback survey with rating scale and comments"),u("formBuilderAI.example.rsvp","Event RSVP with name, attending status, and dietary restrictions"),u("formBuilderAI.example.jobApplication","Job application with personal info, experience, and file upload"),u("formBuilderAI.example.newsletter","Newsletter subscription with email and preferences")],[I,b=""]=u("formBuilderAI.shortcutHint","Press {keys} to generate").split("{keys}"),h=async()=>{!v.trim()||g||await P(v.trim())},_=S=>{var N;w(S),R(!1),(N=M.current)==null||N.focus()},f=S=>{S.key==="Enter"&&(S.ctrlKey||S.metaKey)&&(S.preventDefault(),h())},k=S=>{w(S.target.value),S.target.style.height="auto",S.target.style.height=Math.min(S.target.scrollHeight,200)+"px"};return j?e.jsxs("div",{className:`nice-form-builder-ai ${c||""}`,style:m,children:[e.jsxs("div",{className:"nice-form-builder-ai__input-section",children:[e.jsxs("label",{className:"nice-form-builder-ai__label",children:[e.jsx("span",{className:"nice-form-builder-ai__label-icon",children:e.jsx(T.NiceIcon,{name:"wand",size:16})}),u("formBuilderAI.describeYourForm","Describe your form")]}),e.jsxs("div",{className:"nice-form-builder-ai__input-wrapper",children:[e.jsx("textarea",{"aria-label":u("formBuilderAI.describeYourForm","Describe your form"),ref:M,value:v,onChange:k,onKeyDown:f,placeholder:n??u("formBuilderAI.placeholder",'Describe the form you want to create... (e.g., "Contact form with name, email, subject, and message")'),className:"nice-form-builder-ai__textarea",disabled:g,rows:2}),e.jsxs("div",{className:"nice-form-builder-ai__actions",children:[s&&e.jsxs("div",{className:"nice-form-builder-ai__examples-wrapper",children:[e.jsx("button",{type:"button",onClick:()=>R(!A),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--secondary",children:u("formBuilderAI.examples","Examples")}),A&&e.jsx("div",{className:"nice-form-builder-ai__dropdown",children:y.map((S,N)=>e.jsx("button",{type:"button",className:"nice-form-builder-ai__dropdown-item",onClick:()=>_(S),children:S},N))})]}),e.jsx("button",{type:"button",onClick:h,disabled:!v.trim()||g,className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--primary",children:g?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"nice-form-builder-ai__spinner"}),u("formBuilderAI.generating","Generating...")]}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"rocket",size:14}),u("formBuilderAI.generateForm","Generate Form")]})})]})]}),e.jsxs("p",{className:"nice-form-builder-ai__hint",children:[I,e.jsx("kbd",{children:u("formBuilderAI.ctrl","Ctrl")}),"+",e.jsx("kbd",{children:u("formBuilderAI.enter","Enter")}),b]})]}),d&&e.jsx("div",{className:"nice-form-builder-ai__result",children:d.error?e.jsxs("div",{className:"nice-form-builder-ai__error",children:[e.jsx("strong",{children:u("formBuilderAI.errorLabel","Error:")})," ",d.error]}):d.config&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-form-builder-ai__result-header",children:[e.jsx("h3",{className:"nice-form-builder-ai__result-title",children:u("formBuilderAI.generatedForm","Generated Form: {title}").replace("{title}",d.config.title||u("formBuilderAI.untitled","Untitled"))}),d.latencyMs&&e.jsxs("span",{className:"nice-form-builder-ai__latency",children:[Math.round(d.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(d.config),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--success",children:u("formBuilderAI.useForm","Use This Form")})]}),d.config.description&&e.jsx("p",{className:"nice-form-builder-ai__result-description",children:d.config.description}),o&&e.jsx("div",{className:"nice-form-builder-ai__preview",children:p?p(d.config):e.jsx(Di,{config:d.config})}),e.jsxs("details",{className:"nice-form-builder-ai__json",children:[e.jsx("summary",{children:u("formBuilderAI.viewJson","View JSON Configuration")}),e.jsx("pre",{children:JSON.stringify(d.config,null,2)})]})]})}),e.jsx("style",{children:`
556
+ Instructions: ${v}
557
+ `;return u(h)},[N,u,c]),_=l.useCallback(()=>{x(null),A(null)},[]),C=l.useCallback(()=>{var v;(v=M.current)==null||v.abort(),p(!1)},[]);return l.useEffect(()=>()=>{var v;(v=M.current)==null||v.abort()},[]),{generateForm:u,refineForm:y,loading:m,lastDescription:d,lastResult:N,history:R,clearResults:_,abort:C,isConfigured:!!g}}function Oi(t){var a,i,n;try{const r=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((n=(r.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,r])[1])==null?void 0:n.trim())||r,c=JSON.parse(o);if(c.fields&&Array.isArray(c.fields))return{title:c.title,description:c.description,fields:c.fields,layout:c.layout,submitLabel:c.submitLabel,validation:c.validation}}catch{}return null}function Ei({config:t,schema:a,context:i,onGenerate:n,placeholder:r,showExamples:s=!0,showPreview:o=!0,className:c,style:m,renderForm:p}){const{t:d}=T.useNiceTranslation(),[x,N]=l.useState(""),[A,R]=l.useState(!1),$=l.useRef(null),{generateForm:M,loading:g,lastResult:u,isConfigured:y}=wa({config:t,schema:a,context:i,onFormGenerated:n}),_=[d("formBuilderAI.example.contact","Simple contact form with name, email, and message"),d("formBuilderAI.example.registration","User registration with email validation and password confirmation"),d("formBuilderAI.example.feedback","Product feedback survey with rating scale and comments"),d("formBuilderAI.example.rsvp","Event RSVP with name, attending status, and dietary restrictions"),d("formBuilderAI.example.jobApplication","Job application with personal info, experience, and file upload"),d("formBuilderAI.example.newsletter","Newsletter subscription with email and preferences")],[C,v=""]=d("formBuilderAI.shortcutHint","Press {keys} to generate").split("{keys}"),h=async()=>{!x.trim()||g||await M(x.trim())},w=k=>{var I;N(k),R(!1),(I=$.current)==null||I.focus()},f=k=>{k.key==="Enter"&&(k.ctrlKey||k.metaKey)&&(k.preventDefault(),h())},j=k=>{N(k.target.value),k.target.style.height="auto",k.target.style.height=Math.min(k.target.scrollHeight,200)+"px"};return y?e.jsxs("div",{className:`nice-form-builder-ai ${c||""}`,style:m,children:[e.jsxs("div",{className:"nice-form-builder-ai__input-section",children:[e.jsxs("label",{className:"nice-form-builder-ai__label",children:[e.jsx("span",{className:"nice-form-builder-ai__label-icon",children:e.jsx(T.NiceIcon,{name:"wand",size:16})}),d("formBuilderAI.describeYourForm","Describe your form")]}),e.jsxs("div",{className:"nice-form-builder-ai__input-wrapper",children:[e.jsx("textarea",{"aria-label":d("formBuilderAI.describeYourForm","Describe your form"),ref:$,value:x,onChange:j,onKeyDown:f,placeholder:r??d("formBuilderAI.placeholder",'Describe the form you want to create... (e.g., "Contact form with name, email, subject, and message")'),className:"nice-form-builder-ai__textarea",disabled:g,rows:2}),e.jsxs("div",{className:"nice-form-builder-ai__actions",children:[s&&e.jsxs("div",{className:"nice-form-builder-ai__examples-wrapper",children:[e.jsx("button",{type:"button",onClick:()=>R(!A),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--secondary",children:d("formBuilderAI.examples","Examples")}),A&&e.jsx("div",{className:"nice-form-builder-ai__dropdown",children:_.map((k,I)=>e.jsx("button",{type:"button",className:"nice-form-builder-ai__dropdown-item",onClick:()=>w(k),children:k},I))})]}),e.jsx("button",{type:"button",onClick:h,disabled:!x.trim()||g,className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--primary",children:g?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"nice-form-builder-ai__spinner"}),d("formBuilderAI.generating","Generating...")]}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"rocket",size:14}),d("formBuilderAI.generateForm","Generate Form")]})})]})]}),e.jsxs("p",{className:"nice-form-builder-ai__hint",children:[C,e.jsx("kbd",{children:d("formBuilderAI.ctrl","Ctrl")}),"+",e.jsx("kbd",{children:d("formBuilderAI.enter","Enter")}),v]})]}),u&&e.jsx("div",{className:"nice-form-builder-ai__result",children:u.error?e.jsxs("div",{className:"nice-form-builder-ai__error",children:[e.jsx("strong",{children:d("formBuilderAI.errorLabel","Error:")})," ",u.error]}):u.config&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-form-builder-ai__result-header",children:[e.jsx("h3",{className:"nice-form-builder-ai__result-title",children:d("formBuilderAI.generatedForm","Generated Form: {title}").replace("{title}",u.config.title||d("formBuilderAI.untitled","Untitled"))}),u.latencyMs&&e.jsxs("span",{className:"nice-form-builder-ai__latency",children:[Math.round(u.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>n==null?void 0:n(u.config),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--success",children:d("formBuilderAI.useForm","Use This Form")})]}),u.config.description&&e.jsx("p",{className:"nice-form-builder-ai__result-description",children:u.config.description}),o&&e.jsx("div",{className:"nice-form-builder-ai__preview",children:p?p(u.config):e.jsx(Di,{config:u.config})}),e.jsxs("details",{className:"nice-form-builder-ai__json",children:[e.jsx("summary",{children:d("formBuilderAI.viewJson","View JSON Configuration")}),e.jsx("pre",{children:JSON.stringify(u.config,null,2)})]})]})}),e.jsx("style",{children:`
558
558
  .nice-form-builder-ai {
559
559
  font-family: var(--nice-font-family, system-ui, sans-serif);
560
560
  }
@@ -775,7 +775,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
775
775
  color: var(--nice-error, #c62828);
776
776
  border-radius: var(--nice-radius-md, 6px);
777
777
  }
778
- `})]}):e.jsx("div",{className:`nice-form-builder-ai nice-form-builder-ai--disabled ${c||""}`,style:m,children:e.jsx("p",{children:u("formBuilderAI.notConfigured","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function Di({config:t}){var n,s;const{t:a}=T.useNiceTranslation(),i=o=>{var m,p;const c={id:o.id,placeholder:o.placeholder,required:o.required,disabled:!0};switch(o.type){case"textarea":case"richtext":case"markdown":return e.jsx("textarea",{...c,rows:3,className:"nice-form-preview__input nice-form-preview__textarea"});case"select":case"multiselect":return e.jsxs("select",{...c,className:"nice-form-preview__input nice-form-preview__select",children:[e.jsx("option",{value:"",children:a("formBuilderAI.selectField","Select {label}...").replace("{label}",o.label)}),(m=o.options)==null?void 0:m.map(u=>e.jsx("option",{value:u.value,children:u.label},u.value))]});case"radio":return e.jsx("div",{className:"nice-form-preview__radio-group",children:(p=o.options)==null?void 0:p.map(u=>e.jsxs("label",{className:"nice-form-preview__radio",children:[e.jsx("input",{type:"radio",name:o.id,value:u.value,disabled:!0}),u.label]},u.value))});case"checkbox":return e.jsxs("label",{className:"nice-form-preview__checkbox",children:[e.jsx("input",{type:"checkbox",disabled:!0}),o.label]});case"file":case"image":return e.jsx("input",{type:"file",...c,className:"nice-form-preview__input"});case"date":return e.jsx("input",{type:"date",...c,className:"nice-form-preview__input"});case"time":return e.jsx("input",{type:"time",...c,className:"nice-form-preview__input"});case"datetime":return e.jsx("input",{type:"datetime-local",...c,className:"nice-form-preview__input"});case"number":case"currency":case"percentage":return e.jsx("input",{type:"number",...c,className:"nice-form-preview__input"});case"email":return e.jsx("input",{type:"email",...c,className:"nice-form-preview__input"});case"phone":return e.jsx("input",{type:"tel",...c,className:"nice-form-preview__input"});case"url":return e.jsx("input",{type:"url",...c,className:"nice-form-preview__input"});case"password":return e.jsx("input",{type:"password",...c,className:"nice-form-preview__input"});case"color":return e.jsx("input",{type:"color",...c,className:"nice-form-preview__input nice-form-preview__color"});case"slider":case"rating":return e.jsx("input",{type:"range",...c,className:"nice-form-preview__input"});default:return e.jsx("input",{type:"text",...c,className:"nice-form-preview__input"})}},r=((n=t.layout)==null?void 0:n.columns)||1;return e.jsxs("form",{className:"nice-form-preview",style:{"--columns":r},children:[(s=t.layout)!=null&&s.sections?t.layout.sections.map((o,c)=>e.jsxs("fieldset",{className:"nice-form-preview__section",children:[o.title&&e.jsx("legend",{children:o.title}),o.description&&e.jsx("p",{className:"nice-form-preview__section-desc",children:o.description}),e.jsx("div",{className:"nice-form-preview__grid",children:o.fields.map(m=>{const p=t.fields.find(u=>u.id===m);return p?e.jsxs("div",{className:"nice-form-preview__field",children:[p.type!=="checkbox"&&e.jsxs("label",{className:"nice-form-preview__label",children:[p.label,p.required&&e.jsx("span",{className:"nice-form-preview__required",children:"*"})]}),i(p)]},p.id):null})})]},c)):e.jsx("div",{className:"nice-form-preview__grid",children:t.fields.map(o=>e.jsxs("div",{className:"nice-form-preview__field",children:[o.type!=="checkbox"&&e.jsxs("label",{className:"nice-form-preview__label",children:[o.label,o.required&&e.jsx("span",{className:"nice-form-preview__required",children:"*"})]}),i(o)]},o.id))}),e.jsx("div",{className:"nice-form-preview__submit",children:e.jsx("button",{type:"button",disabled:!0,className:"nice-form-preview__submit-btn",children:t.submitLabel||a("submit","Submit")})}),e.jsx("style",{children:`
778
+ `})]}):e.jsx("div",{className:`nice-form-builder-ai nice-form-builder-ai--disabled ${c||""}`,style:m,children:e.jsx("p",{children:d("formBuilderAI.notConfigured","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function Di({config:t}){var r,s;const{t:a}=T.useNiceTranslation(),i=o=>{var m,p;const c={id:o.id,placeholder:o.placeholder,required:o.required,disabled:!0};switch(o.type){case"textarea":case"richtext":case"markdown":return e.jsx("textarea",{...c,rows:3,className:"nice-form-preview__input nice-form-preview__textarea"});case"select":case"multiselect":return e.jsxs("select",{...c,className:"nice-form-preview__input nice-form-preview__select",children:[e.jsx("option",{value:"",children:a("formBuilderAI.selectField","Select {label}...").replace("{label}",o.label)}),(m=o.options)==null?void 0:m.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))]});case"radio":return e.jsx("div",{className:"nice-form-preview__radio-group",children:(p=o.options)==null?void 0:p.map(d=>e.jsxs("label",{className:"nice-form-preview__radio",children:[e.jsx("input",{type:"radio",name:o.id,value:d.value,disabled:!0}),d.label]},d.value))});case"checkbox":return e.jsxs("label",{className:"nice-form-preview__checkbox",children:[e.jsx("input",{type:"checkbox",disabled:!0}),o.label]});case"file":case"image":return e.jsx("input",{type:"file",...c,className:"nice-form-preview__input"});case"date":return e.jsx("input",{type:"date",...c,className:"nice-form-preview__input"});case"time":return e.jsx("input",{type:"time",...c,className:"nice-form-preview__input"});case"datetime":return e.jsx("input",{type:"datetime-local",...c,className:"nice-form-preview__input"});case"number":case"currency":case"percentage":return e.jsx("input",{type:"number",...c,className:"nice-form-preview__input"});case"email":return e.jsx("input",{type:"email",...c,className:"nice-form-preview__input"});case"phone":return e.jsx("input",{type:"tel",...c,className:"nice-form-preview__input"});case"url":return e.jsx("input",{type:"url",...c,className:"nice-form-preview__input"});case"password":return e.jsx("input",{type:"password",...c,className:"nice-form-preview__input"});case"color":return e.jsx("input",{type:"color",...c,className:"nice-form-preview__input nice-form-preview__color"});case"slider":case"rating":return e.jsx("input",{type:"range",...c,className:"nice-form-preview__input"});default:return e.jsx("input",{type:"text",...c,className:"nice-form-preview__input"})}},n=((r=t.layout)==null?void 0:r.columns)||1;return e.jsxs("form",{className:"nice-form-preview",style:{"--columns":n},children:[(s=t.layout)!=null&&s.sections?t.layout.sections.map((o,c)=>e.jsxs("fieldset",{className:"nice-form-preview__section",children:[o.title&&e.jsx("legend",{children:o.title}),o.description&&e.jsx("p",{className:"nice-form-preview__section-desc",children:o.description}),e.jsx("div",{className:"nice-form-preview__grid",children:o.fields.map(m=>{const p=t.fields.find(d=>d.id===m);return p?e.jsxs("div",{className:"nice-form-preview__field",children:[p.type!=="checkbox"&&e.jsxs("label",{className:"nice-form-preview__label",children:[p.label,p.required&&e.jsx("span",{className:"nice-form-preview__required",children:"*"})]}),i(p)]},p.id):null})})]},c)):e.jsx("div",{className:"nice-form-preview__grid",children:t.fields.map(o=>e.jsxs("div",{className:"nice-form-preview__field",children:[o.type!=="checkbox"&&e.jsxs("label",{className:"nice-form-preview__label",children:[o.label,o.required&&e.jsx("span",{className:"nice-form-preview__required",children:"*"})]}),i(o)]},o.id))}),e.jsx("div",{className:"nice-form-preview__submit",children:e.jsx("button",{type:"button",disabled:!0,className:"nice-form-preview__submit-btn",children:t.submitLabel||a("submit","Submit")})}),e.jsx("style",{children:`
779
779
  .nice-form-preview {
780
780
  --columns: 1;
781
781
  }
@@ -880,7 +880,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
880
880
  cursor: not-allowed;
881
881
  opacity: 0.7;
882
882
  }
883
- `})]})}function ja(t={}){const{config:a,dataFields:i,context:r,onChartGenerated:n,onError:s}=t,o=ee(),{t:c}=T.useNiceTranslation(),[m,p]=l.useState(!1),[u,v]=l.useState(null),[w,A]=l.useState(null),[R,M]=l.useState([]),P=l.useRef(null),g=a||(o==null?void 0:o.config),d=l.useMemo(()=>{if(i)return i.map(h=>{var _;return{name:h.name,type:h.type,label:h.label||h.name,...(_=h.sampleValues)!=null&&_.length?{samples:h.sampleValues.slice(0,3)}:{}}})},[i]),j=l.useCallback(async h=>{var f,k,S;if(!g){const N="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(N),{error:N}}p(!0),v(h);const _=performance.now();(f=P.current)==null||f.abort(),P.current=new AbortController;try{const N=V(g),$=ie(ue,{request:h,data:d?JSON.stringify(d,null,2):void 0,context:r}),E=await N.chat({messages:[{role:"system",content:$.system},{role:"user",content:$.user}],temperature:.4,maxTokens:1024}),z=Bi(E),F={config:z||void 0,rawResponse:(S=(k=E.choices[0])==null?void 0:k.message)==null?void 0:S.content,latencyMs:performance.now()-_,error:z?void 0:c("chartAI.parseFailed","Failed to parse chart configuration"),suggestions:Fi(z,c)};return z&&(n==null||n(z)),A(F),M(U=>[...U.slice(-9),{request:h,result:F}]),F}catch(N){const $=N instanceof Error?N.message:c("chartAI.requestFailed","AI request failed"),E={error:$,latencyMs:performance.now()-_};return A(E),s==null||s($),E}finally{p(!1)}},[g,d,r,n,s,c]),y=l.useCallback(async()=>w!=null&&w.config?{line:["area","bar","scatter"],area:["line","bar","column"],bar:["column","line","pie"],column:["bar","line","area"],pie:["donut","bar","treemap"],donut:["pie","funnel","gauge"],scatter:["bubble","line","heatmap"],bubble:["scatter","treemap"],heatmap:["treemap","bar"],treemap:["pie","heatmap","bar"],funnel:["bar","donut"],radar:["bar","polar"],polar:["radar","pie"],gauge:["donut","bar"],candlestick:["line","area"],sankey:["funnel","bar"]}[w.config.type]||[]:[],[w]),I=l.useCallback(()=>{v(null),A(null)},[]),b=l.useCallback(()=>{var h;(h=P.current)==null||h.abort(),p(!1)},[]);return l.useEffect(()=>()=>{var h;(h=P.current)==null||h.abort()},[]),{generateChart:j,suggestAlternatives:y,loading:m,lastRequest:u,lastResult:w,history:R,clearResults:I,abort:b,isConfigured:!!g}}function Bi(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.type)return{type:c.type,title:c.title,subtitle:c.subtitle,data:c.data||{},xAxis:c.xAxis,yAxis:c.yAxis,options:c.options}}catch{}return null}function Fi(t,a){var r;if(!t)return[];const i=[];return(t.type==="line"||t.type==="bar")&&(i.push(a("chartAI.suggest.trendLine","Add trend line for forecasting")),i.push(a("chartAI.suggest.stack","Stack series for comparison"))),(t.type==="pie"||t.type==="donut")&&(i.push(a("chartAI.suggest.toBar","Convert to bar chart for better comparison")),i.push(a("chartAI.suggest.percentLabels","Add data labels for percentages"))),(r=t.options)!=null&&r.animation||i.push(a("chartAI.suggest.animate","Enable animations for better UX")),i.slice(0,3)}const Ji={line:["chartAI.type.line","Line"],area:["chartAI.type.area","Area"],bar:["chartAI.type.bar","Bar"],column:["chartAI.type.column","Column"],pie:["chartAI.type.pie","Pie"],donut:["chartAI.type.donut","Donut"],scatter:["chartAI.type.scatter","Scatter"],bubble:["chartAI.type.bubble","Bubble"],heatmap:["chartAI.type.heatmap","Heatmap"],treemap:["chartAI.type.treemap","Treemap"],funnel:["chartAI.type.funnel","Funnel"],radar:["chartAI.type.radar","Radar"],polar:["chartAI.type.polar","Polar"],gauge:["chartAI.type.gauge","Gauge"],candlestick:["chartAI.type.candlestick","Candlestick"],sankey:["chartAI.type.sankey","Sankey"]},Ae=(t,a)=>{const i=Ji[t];return i?a(i[0],i[1]):t.charAt(0).toUpperCase()+t.slice(1)};function qi({config:t,dataFields:a,context:i,onGenerate:r,placeholder:n,showTypeSelector:s=!0,showPreview:o=!0,className:c,style:m,renderChart:p}){const{t:u}=T.useNiceTranslation(),[v,w]=l.useState(""),[A,R]=l.useState(null),M=l.useRef(null),{generateChart:P,suggestAlternatives:g,loading:d,lastResult:j,isConfigured:y}=ja({config:t,dataFields:a,context:i,onChartGenerated:r}),I=[["line","line"],["bar","bar-chart"],["pie","circle"],["area","bar-chart"],["scatter","grid"],["donut","circle"],["heatmap","grid"],["funnel","filter"],["gauge","target"],["radar","target"]].map(([k,S])=>({type:k,icon:S,label:Ae(k,u)})),b=async()=>{if(!v.trim()||d)return;const k=A?`Create a ${A} chart: ${v}`:v;await P(k)},h=k=>{k.key==="Enter"&&(k.preventDefault(),b())},_=k=>{R(A===k?null:k)},f=async k=>{if(!(j!=null&&j.config))return;const S={...j.config,type:k};r==null||r(S)};return y?e.jsxs("div",{className:`nice-chart-ai ${c||""}`,style:m,children:[s&&e.jsx("div",{className:"nice-chart-ai__types",children:I.map(({type:k,icon:S,label:N})=>e.jsxs("button",{type:"button",className:`nice-chart-ai__type ${A===k?"nice-chart-ai__type--selected":""}`,onClick:()=>_(k),title:N,children:[e.jsx("span",{className:"nice-chart-ai__type-icon",children:e.jsx(T.NiceIcon,{name:S,size:20})}),e.jsx("span",{className:"nice-chart-ai__type-label",children:N})]},k))}),e.jsxs("div",{className:"nice-chart-ai__input-wrapper",children:[e.jsx("span",{className:"nice-chart-ai__icon",children:e.jsx(T.NiceIcon,{name:"bar-chart",size:18})}),e.jsx("input",{ref:M,type:"text",value:v,onChange:k=>w(k.target.value),onKeyDown:h,placeholder:n??u("chartAI.placeholder",'Describe the chart you want... (e.g., "Show monthly sales as a line chart")'),className:"nice-chart-ai__input",disabled:d}),d?e.jsx("span",{className:"nice-chart-ai__spinner"}):e.jsx("button",{type:"button",onClick:b,className:"nice-chart-ai__submit",disabled:!v.trim(),children:u("chartAI.generate","Generate")})]}),a&&a.length>0&&e.jsxs("div",{className:"nice-chart-ai__fields",children:[e.jsx("span",{className:"nice-chart-ai__fields-label",children:u("chartAI.availableFields","Available fields:")}),a.map(k=>e.jsx("span",{className:"nice-chart-ai__field-badge",title:k.type,children:k.label||k.name},k.name))]}),j&&e.jsx("div",{className:"nice-chart-ai__result",children:j.error?e.jsx("div",{className:"nice-chart-ai__error",children:j.error}):j.config&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-chart-ai__result-header",children:[e.jsxs("div",{className:"nice-chart-ai__result-info",children:[e.jsxs("span",{className:"nice-chart-ai__chart-type",children:[(()=>{var S;const k=(S=I.find(N=>N.type===j.config.type))==null?void 0:S.icon;return k?e.jsx(T.NiceIcon,{name:k,size:16}):null})(),u("chartAI.chartOfType","{type} Chart").replace("{type}",Ae(j.config.type,u))]}),j.config.title&&e.jsx("span",{className:"nice-chart-ai__chart-title",children:j.config.title})]}),j.latencyMs&&e.jsxs("span",{className:"nice-chart-ai__latency",children:[Math.round(j.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(j.config),className:"nice-chart-ai__use-btn",children:u("chartAI.useChart","Use This Chart")})]}),e.jsxs("div",{className:"nice-chart-ai__alternatives",children:[e.jsx("span",{children:u("chartAI.tryAlso","Try also:")}),I.filter(k=>k.type!==j.config.type).slice(0,4).map(({type:k,icon:S,label:N})=>e.jsx("button",{type:"button",className:"nice-chart-ai__alternative",onClick:()=>f(k),title:u("chartAI.convertTo","Convert to {type}").replace("{type}",N),"aria-label":u("chartAI.convertTo","Convert to {type}").replace("{type}",N),children:e.jsx(T.NiceIcon,{name:S,size:16})},k))]}),o&&e.jsx("div",{className:"nice-chart-ai__preview",children:p?p(j.config):e.jsx(Gi,{config:j.config})}),e.jsxs("details",{className:"nice-chart-ai__json",children:[e.jsx("summary",{children:u("chartAI.viewConfig","View Configuration")}),e.jsx("pre",{children:JSON.stringify(j.config,null,2)})]})]})}),e.jsx("style",{children:`
883
+ `})]})}function ja(t={}){const{config:a,dataFields:i,context:n,onChartGenerated:r,onError:s}=t,o=Z(),{t:c}=T.useNiceTranslation(),[m,p]=l.useState(!1),[d,x]=l.useState(null),[N,A]=l.useState(null),[R,$]=l.useState([]),M=l.useRef(null),g=a||(o==null?void 0:o.config),u=l.useMemo(()=>{if(i)return i.map(h=>{var w;return{name:h.name,type:h.type,label:h.label||h.name,...(w=h.sampleValues)!=null&&w.length?{samples:h.sampleValues.slice(0,3)}:{}}})},[i]),y=l.useCallback(async h=>{var f,j,k;if(!g){const I="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(I),{error:I}}p(!0),x(h);const w=performance.now();(f=M.current)==null||f.abort(),M.current=new AbortController;try{const I=Y(g),z=ae(ue,{request:h,data:u?JSON.stringify(u,null,2):void 0,context:n}),E=await I.chat({messages:[{role:"system",content:z.system},{role:"user",content:z.user}],temperature:.4,maxTokens:1024}),P=Bi(E),F={config:P||void 0,rawResponse:(k=(j=E.choices[0])==null?void 0:j.message)==null?void 0:k.content,latencyMs:performance.now()-w,error:P?void 0:c("chartAI.parseFailed","Failed to parse chart configuration"),suggestions:Fi(P,c)};return P&&(r==null||r(P)),A(F),$(G=>[...G.slice(-9),{request:h,result:F}]),F}catch(I){const z=I instanceof Error?I.message:c("chartAI.requestFailed","AI request failed"),E={error:z,latencyMs:performance.now()-w};return A(E),s==null||s(z),E}finally{p(!1)}},[g,u,n,r,s,c]),_=l.useCallback(async()=>N!=null&&N.config?{line:["area","bar","scatter"],area:["line","bar","column"],bar:["column","line","pie"],column:["bar","line","area"],pie:["donut","bar","treemap"],donut:["pie","funnel","gauge"],scatter:["bubble","line","heatmap"],bubble:["scatter","treemap"],heatmap:["treemap","bar"],treemap:["pie","heatmap","bar"],funnel:["bar","donut"],radar:["bar","polar"],polar:["radar","pie"],gauge:["donut","bar"],candlestick:["line","area"],sankey:["funnel","bar"]}[N.config.type]||[]:[],[N]),C=l.useCallback(()=>{x(null),A(null)},[]),v=l.useCallback(()=>{var h;(h=M.current)==null||h.abort(),p(!1)},[]);return l.useEffect(()=>()=>{var h;(h=M.current)==null||h.abort()},[]),{generateChart:y,suggestAlternatives:_,loading:m,lastRequest:d,lastResult:N,history:R,clearResults:C,abort:v,isConfigured:!!g}}function Bi(t){var a,i,n;try{const r=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((n=(r.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,r])[1])==null?void 0:n.trim())||r,c=JSON.parse(o);if(c.type)return{type:c.type,title:c.title,subtitle:c.subtitle,data:c.data||{},xAxis:c.xAxis,yAxis:c.yAxis,options:c.options}}catch{}return null}function Fi(t,a){var n;if(!t)return[];const i=[];return(t.type==="line"||t.type==="bar")&&(i.push(a("chartAI.suggest.trendLine","Add trend line for forecasting")),i.push(a("chartAI.suggest.stack","Stack series for comparison"))),(t.type==="pie"||t.type==="donut")&&(i.push(a("chartAI.suggest.toBar","Convert to bar chart for better comparison")),i.push(a("chartAI.suggest.percentLabels","Add data labels for percentages"))),(n=t.options)!=null&&n.animation||i.push(a("chartAI.suggest.animate","Enable animations for better UX")),i.slice(0,3)}const Ji={line:["chartAI.type.line","Line"],area:["chartAI.type.area","Area"],bar:["chartAI.type.bar","Bar"],column:["chartAI.type.column","Column"],pie:["chartAI.type.pie","Pie"],donut:["chartAI.type.donut","Donut"],scatter:["chartAI.type.scatter","Scatter"],bubble:["chartAI.type.bubble","Bubble"],heatmap:["chartAI.type.heatmap","Heatmap"],treemap:["chartAI.type.treemap","Treemap"],funnel:["chartAI.type.funnel","Funnel"],radar:["chartAI.type.radar","Radar"],polar:["chartAI.type.polar","Polar"],gauge:["chartAI.type.gauge","Gauge"],candlestick:["chartAI.type.candlestick","Candlestick"],sankey:["chartAI.type.sankey","Sankey"]},Ae=(t,a)=>{const i=Ji[t];return i?a(i[0],i[1]):t.charAt(0).toUpperCase()+t.slice(1)};function qi({config:t,dataFields:a,context:i,onGenerate:n,placeholder:r,showTypeSelector:s=!0,showPreview:o=!0,className:c,style:m,renderChart:p}){const{t:d}=T.useNiceTranslation(),[x,N]=l.useState(""),[A,R]=l.useState(null),$=l.useRef(null),{generateChart:M,suggestAlternatives:g,loading:u,lastResult:y,isConfigured:_}=ja({config:t,dataFields:a,context:i,onChartGenerated:n}),C=[["line","line"],["bar","bar-chart"],["pie","circle"],["area","bar-chart"],["scatter","grid"],["donut","circle"],["heatmap","grid"],["funnel","filter"],["gauge","target"],["radar","target"]].map(([j,k])=>({type:j,icon:k,label:Ae(j,d)})),v=async()=>{if(!x.trim()||u)return;const j=A?`Create a ${A} chart: ${x}`:x;await M(j)},h=j=>{j.key==="Enter"&&(j.preventDefault(),v())},w=j=>{R(A===j?null:j)},f=async j=>{if(!(y!=null&&y.config))return;const k={...y.config,type:j};n==null||n(k)};return _?e.jsxs("div",{className:`nice-chart-ai ${c||""}`,style:m,children:[s&&e.jsx("div",{className:"nice-chart-ai__types",children:C.map(({type:j,icon:k,label:I})=>e.jsxs("button",{type:"button",className:`nice-chart-ai__type ${A===j?"nice-chart-ai__type--selected":""}`,onClick:()=>w(j),title:I,children:[e.jsx("span",{className:"nice-chart-ai__type-icon",children:e.jsx(T.NiceIcon,{name:k,size:20})}),e.jsx("span",{className:"nice-chart-ai__type-label",children:I})]},j))}),e.jsxs("div",{className:"nice-chart-ai__input-wrapper",children:[e.jsx("span",{className:"nice-chart-ai__icon",children:e.jsx(T.NiceIcon,{name:"bar-chart",size:18})}),e.jsx("input",{ref:$,type:"text",value:x,onChange:j=>N(j.target.value),onKeyDown:h,placeholder:r??d("chartAI.placeholder",'Describe the chart you want... (e.g., "Show monthly sales as a line chart")'),className:"nice-chart-ai__input",disabled:u}),u?e.jsx("span",{className:"nice-chart-ai__spinner"}):e.jsx("button",{type:"button",onClick:v,className:"nice-chart-ai__submit",disabled:!x.trim(),children:d("chartAI.generate","Generate")})]}),a&&a.length>0&&e.jsxs("div",{className:"nice-chart-ai__fields",children:[e.jsx("span",{className:"nice-chart-ai__fields-label",children:d("chartAI.availableFields","Available fields:")}),a.map(j=>e.jsx("span",{className:"nice-chart-ai__field-badge",title:j.type,children:j.label||j.name},j.name))]}),y&&e.jsx("div",{className:"nice-chart-ai__result",children:y.error?e.jsx("div",{className:"nice-chart-ai__error",children:y.error}):y.config&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-chart-ai__result-header",children:[e.jsxs("div",{className:"nice-chart-ai__result-info",children:[e.jsxs("span",{className:"nice-chart-ai__chart-type",children:[(()=>{var k;const j=(k=C.find(I=>I.type===y.config.type))==null?void 0:k.icon;return j?e.jsx(T.NiceIcon,{name:j,size:16}):null})(),d("chartAI.chartOfType","{type} Chart").replace("{type}",Ae(y.config.type,d))]}),y.config.title&&e.jsx("span",{className:"nice-chart-ai__chart-title",children:y.config.title})]}),y.latencyMs&&e.jsxs("span",{className:"nice-chart-ai__latency",children:[Math.round(y.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>n==null?void 0:n(y.config),className:"nice-chart-ai__use-btn",children:d("chartAI.useChart","Use This Chart")})]}),e.jsxs("div",{className:"nice-chart-ai__alternatives",children:[e.jsx("span",{children:d("chartAI.tryAlso","Try also:")}),C.filter(j=>j.type!==y.config.type).slice(0,4).map(({type:j,icon:k,label:I})=>e.jsx("button",{type:"button",className:"nice-chart-ai__alternative",onClick:()=>f(j),title:d("chartAI.convertTo","Convert to {type}").replace("{type}",I),"aria-label":d("chartAI.convertTo","Convert to {type}").replace("{type}",I),children:e.jsx(T.NiceIcon,{name:k,size:16})},j))]}),o&&e.jsx("div",{className:"nice-chart-ai__preview",children:p?p(y.config):e.jsx(Gi,{config:y.config})}),e.jsxs("details",{className:"nice-chart-ai__json",children:[e.jsx("summary",{children:d("chartAI.viewConfig","View Configuration")}),e.jsx("pre",{children:JSON.stringify(y.config,null,2)})]})]})}),e.jsx("style",{children:`
884
884
  .nice-chart-ai {
885
885
  font-family: var(--nice-font-family, system-ui, sans-serif);
886
886
  }
@@ -1124,7 +1124,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
1124
1124
  color: var(--nice-error, #c62828);
1125
1125
  border-radius: var(--nice-radius-md, 6px);
1126
1126
  }
1127
- `})]}):e.jsx("div",{className:`nice-chart-ai nice-chart-ai--disabled ${c||""}`,style:m,children:e.jsx("p",{children:u("chartAI.notConfigured","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function Gi({config:t}){var n;const{t:a}=T.useNiceTranslation(),i=s=>a("chartAI.series","Series {n}").replace("{n}",String(s)),r=()=>{switch(t.type){case"bar":case"column":return e.jsxs("svg",{viewBox:"0 0 200 100",className:"nice-chart-preview__svg",children:[e.jsx("rect",{x:"20",y:"60",width:"25",height:"30",fill:"var(--nice-success, #4caf50)",rx:"2"}),e.jsx("rect",{x:"55",y:"40",width:"25",height:"50",fill:"var(--nice-primary, #2196f3)",rx:"2"}),e.jsx("rect",{x:"90",y:"20",width:"25",height:"70",fill:"var(--nice-warning, #ff9800)",rx:"2"}),e.jsx("rect",{x:"125",y:"50",width:"25",height:"40",fill:"var(--nice-accent, #9c27b0)",rx:"2"}),e.jsx("rect",{x:"160",y:"30",width:"25",height:"60",fill:"var(--nice-color-accent-pink, #e91e63)",rx:"2"})]});case"line":case"area":return e.jsxs("svg",{viewBox:"0 0 200 100",className:"nice-chart-preview__svg",children:[e.jsx("path",{d:"M 20 70 Q 50 30, 80 50 T 140 40 T 180 60",fill:"none",stroke:"var(--nice-primary, #2196f3)",strokeWidth:"3",strokeLinecap:"round"}),t.type==="area"&&e.jsx("path",{d:"M 20 70 Q 50 30, 80 50 T 140 40 T 180 60 V 90 H 20 Z",fill:"color-mix(in srgb, var(--nice-primary, #2196f3) 20%, transparent)"}),e.jsx("circle",{cx:"20",cy:"70",r:"4",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"80",cy:"50",r:"4",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"140",cy:"40",r:"4",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"180",cy:"60",r:"4",fill:"var(--nice-primary, #2196f3)"})]});case"pie":case"donut":{const s=t.type==="donut"?35:40,o=t.type==="donut"?20:0;return e.jsxs("svg",{viewBox:"0 0 100 100",className:"nice-chart-preview__svg",children:[e.jsx("circle",{cx:"50",cy:"50",r:s,fill:"var(--nice-success, #4caf50)"}),e.jsx("path",{d:"M 50 50 L 50 10 A 40 40 0 0 1 90 50 Z",fill:"var(--nice-primary, #2196f3)"}),e.jsx("path",{d:"M 50 50 L 90 50 A 40 40 0 0 1 70 85 Z",fill:"var(--nice-warning, #ff9800)"}),e.jsx("path",{d:"M 50 50 L 70 85 A 40 40 0 0 1 30 85 Z",fill:"var(--nice-accent, #9c27b0)"}),t.type==="donut"&&e.jsx("circle",{cx:"50",cy:"50",r:o,fill:"white"})]})}case"scatter":return e.jsxs("svg",{viewBox:"0 0 200 100",className:"nice-chart-preview__svg",children:[e.jsx("circle",{cx:"30",cy:"70",r:"5",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"50",cy:"40",r:"7",fill:"var(--nice-success, #4caf50)"}),e.jsx("circle",{cx:"80",cy:"60",r:"4",fill:"var(--nice-warning, #ff9800)"}),e.jsx("circle",{cx:"110",cy:"30",r:"6",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"140",cy:"50",r:"5",fill:"var(--nice-accent, #9c27b0)"}),e.jsx("circle",{cx:"170",cy:"45",r:"8",fill:"var(--nice-success, #4caf50)"})]});case"gauge":return e.jsxs("svg",{viewBox:"0 0 100 60",className:"nice-chart-preview__svg",children:[e.jsx("path",{d:"M 10 50 A 40 40 0 0 1 90 50",fill:"none",stroke:"var(--nice-border, #e0e0e0)",strokeWidth:"8",strokeLinecap:"round"}),e.jsx("path",{d:"M 10 50 A 40 40 0 0 1 60 15",fill:"none",stroke:"var(--nice-success, #4caf50)",strokeWidth:"8",strokeLinecap:"round"}),e.jsx("text",{x:"50",y:"50",textAnchor:"middle",fontSize:"14",fontWeight:"bold",children:"75%"})]});default:return e.jsxs("div",{className:"nice-chart-preview__placeholder",children:[e.jsx("span",{className:"nice-chart-preview__icon",children:e.jsx(T.NiceIcon,{name:"bar-chart",size:32})}),e.jsx("span",{children:a("chartAI.chartOfType","{type} Chart").replace("{type}",Ae(t.type,a))})]})}};return e.jsxs("div",{className:"nice-chart-preview",children:[t.title&&e.jsx("div",{className:"nice-chart-preview__title",children:t.title}),t.subtitle&&e.jsx("div",{className:"nice-chart-preview__subtitle",children:t.subtitle}),e.jsx("div",{className:"nice-chart-preview__chart",children:r()}),((n=t.options)==null?void 0:n.legend)&&e.jsxs("div",{className:"nice-chart-preview__legend",children:[e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-success, #4caf50)"}}),i(1)]}),e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-primary, #2196f3)"}}),i(2)]}),e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-warning, #ff9800)"}}),i(3)]})]}),e.jsx("style",{children:`
1127
+ `})]}):e.jsx("div",{className:`nice-chart-ai nice-chart-ai--disabled ${c||""}`,style:m,children:e.jsx("p",{children:d("chartAI.notConfigured","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function Gi({config:t}){var r;const{t:a}=T.useNiceTranslation(),i=s=>a("chartAI.series","Series {n}").replace("{n}",String(s)),n=()=>{switch(t.type){case"bar":case"column":return e.jsxs("svg",{viewBox:"0 0 200 100",className:"nice-chart-preview__svg",children:[e.jsx("rect",{x:"20",y:"60",width:"25",height:"30",fill:"var(--nice-success, #4caf50)",rx:"2"}),e.jsx("rect",{x:"55",y:"40",width:"25",height:"50",fill:"var(--nice-primary, #2196f3)",rx:"2"}),e.jsx("rect",{x:"90",y:"20",width:"25",height:"70",fill:"var(--nice-warning, #ff9800)",rx:"2"}),e.jsx("rect",{x:"125",y:"50",width:"25",height:"40",fill:"var(--nice-accent, #9c27b0)",rx:"2"}),e.jsx("rect",{x:"160",y:"30",width:"25",height:"60",fill:"var(--nice-color-accent-pink, #e91e63)",rx:"2"})]});case"line":case"area":return e.jsxs("svg",{viewBox:"0 0 200 100",className:"nice-chart-preview__svg",children:[e.jsx("path",{d:"M 20 70 Q 50 30, 80 50 T 140 40 T 180 60",fill:"none",stroke:"var(--nice-primary, #2196f3)",strokeWidth:"3",strokeLinecap:"round"}),t.type==="area"&&e.jsx("path",{d:"M 20 70 Q 50 30, 80 50 T 140 40 T 180 60 V 90 H 20 Z",fill:"color-mix(in srgb, var(--nice-primary, #2196f3) 20%, transparent)"}),e.jsx("circle",{cx:"20",cy:"70",r:"4",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"80",cy:"50",r:"4",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"140",cy:"40",r:"4",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"180",cy:"60",r:"4",fill:"var(--nice-primary, #2196f3)"})]});case"pie":case"donut":{const s=t.type==="donut"?35:40,o=t.type==="donut"?20:0;return e.jsxs("svg",{viewBox:"0 0 100 100",className:"nice-chart-preview__svg",children:[e.jsx("circle",{cx:"50",cy:"50",r:s,fill:"var(--nice-success, #4caf50)"}),e.jsx("path",{d:"M 50 50 L 50 10 A 40 40 0 0 1 90 50 Z",fill:"var(--nice-primary, #2196f3)"}),e.jsx("path",{d:"M 50 50 L 90 50 A 40 40 0 0 1 70 85 Z",fill:"var(--nice-warning, #ff9800)"}),e.jsx("path",{d:"M 50 50 L 70 85 A 40 40 0 0 1 30 85 Z",fill:"var(--nice-accent, #9c27b0)"}),t.type==="donut"&&e.jsx("circle",{cx:"50",cy:"50",r:o,fill:"white"})]})}case"scatter":return e.jsxs("svg",{viewBox:"0 0 200 100",className:"nice-chart-preview__svg",children:[e.jsx("circle",{cx:"30",cy:"70",r:"5",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"50",cy:"40",r:"7",fill:"var(--nice-success, #4caf50)"}),e.jsx("circle",{cx:"80",cy:"60",r:"4",fill:"var(--nice-warning, #ff9800)"}),e.jsx("circle",{cx:"110",cy:"30",r:"6",fill:"var(--nice-primary, #2196f3)"}),e.jsx("circle",{cx:"140",cy:"50",r:"5",fill:"var(--nice-accent, #9c27b0)"}),e.jsx("circle",{cx:"170",cy:"45",r:"8",fill:"var(--nice-success, #4caf50)"})]});case"gauge":return e.jsxs("svg",{viewBox:"0 0 100 60",className:"nice-chart-preview__svg",children:[e.jsx("path",{d:"M 10 50 A 40 40 0 0 1 90 50",fill:"none",stroke:"var(--nice-border, #e0e0e0)",strokeWidth:"8",strokeLinecap:"round"}),e.jsx("path",{d:"M 10 50 A 40 40 0 0 1 60 15",fill:"none",stroke:"var(--nice-success, #4caf50)",strokeWidth:"8",strokeLinecap:"round"}),e.jsx("text",{x:"50",y:"50",textAnchor:"middle",fontSize:"14",fontWeight:"bold",children:"75%"})]});default:return e.jsxs("div",{className:"nice-chart-preview__placeholder",children:[e.jsx("span",{className:"nice-chart-preview__icon",children:e.jsx(T.NiceIcon,{name:"bar-chart",size:32})}),e.jsx("span",{children:a("chartAI.chartOfType","{type} Chart").replace("{type}",Ae(t.type,a))})]})}};return e.jsxs("div",{className:"nice-chart-preview",children:[t.title&&e.jsx("div",{className:"nice-chart-preview__title",children:t.title}),t.subtitle&&e.jsx("div",{className:"nice-chart-preview__subtitle",children:t.subtitle}),e.jsx("div",{className:"nice-chart-preview__chart",children:n()}),((r=t.options)==null?void 0:r.legend)&&e.jsxs("div",{className:"nice-chart-preview__legend",children:[e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-success, #4caf50)"}}),i(1)]}),e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-primary, #2196f3)"}}),i(2)]}),e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-warning, #ff9800)"}}),i(3)]})]}),e.jsx("style",{children:`
1128
1128
  .nice-chart-preview {
1129
1129
  text-align: center;
1130
1130
  }
@@ -1185,12 +1185,12 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
1185
1185
  height: 12px;
1186
1186
  border-radius: var(--nice-radius-sm, 2px);
1187
1187
  }
1188
- `})]})}function ka(t={}){const{config:a,language:i="typescript",context:r,maxSuggestions:n=3,debounceMs:s=300,onSuggestion:o,onError:c}=t,m=ee(),[p,u]=l.useState(!1),[v,w]=l.useState([]),[A,R]=l.useState(-1),M=l.useRef(null),P=l.useRef(null),g=a||(m==null?void 0:m.config),d=l.useCallback(async(N,$)=>{var z,F,U;if(!g)return{suggestions:[],error:"AI not configured"};u(!0),(z=M.current)==null||z.abort(),M.current=new AbortController;const E=performance.now();try{const H=V(g),X=N.split(`
1189
- `),C=X[$.line]||"",x=[...X.slice(Math.max(0,$.line-20),$.line),C.substring(0,$.column)].join(`
1190
- `),B=[C.substring($.column),...X.slice($.line+1,$.line+10)].join(`
1191
- `),G=ie(me,{language:i,prefix:x,suffix:B,context:r}),q=await H.chat({messages:[{role:"system",content:G.system},{role:"user",content:G.user}],temperature:.2,maxTokens:512}),W=Ui(q,$,n),Q={suggestions:W,rawResponse:(U=(F=q.choices[0])==null?void 0:F.message)==null?void 0:U.content,latencyMs:performance.now()-E};return w(W),R(W.length>0?0:-1),o==null||o(W),Q}catch(H){const X=H instanceof Error?H.message:"Completion failed";return c==null||c(X),{suggestions:[],error:X,latencyMs:performance.now()-E}}finally{u(!1)}},[g,i,r,n,o,c]),j=l.useCallback((N,$)=>{P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{d(N,$)},s)},[d,s]),y=l.useCallback(async N=>{if(!g)return null;u(!0);try{const E=await V(g).chat({messages:[{role:"system",content:`You are a code explanation assistant. Explain the following ${i} code clearly and concisely. Return JSON with: { "summary": string, "details": string, "complexity": "low"|"medium"|"high", "suggestions": string[] }`},{role:"user",content:N}],temperature:.3,maxTokens:1024});return Wi(E)}catch{return null}finally{u(!1)}},[g,i]),I=l.useCallback(async N=>{if(!g)return[];u(!0);try{const E=await V(g).chat({messages:[{role:"system",content:`You are a code refactoring assistant. Analyze the following ${i} code and suggest improvements. Return JSON array with: [{ "title": string, "description": string, "before": string, "after": string, "type": "extract-function"|"rename"|"simplify"|"optimize"|"security"|"style" }]`},{role:"user",content:N}],temperature:.4,maxTokens:2048});return Hi(E)}catch{return[]}finally{u(!1)}},[g,i]),b=l.useCallback(async(N,$)=>{var E,z;if(!g)return null;u(!0);try{const F=V(g),U=$||Ki(i);return((z=(E=(await F.chat({messages:[{role:"system",content:`You are a testing expert. Generate comprehensive unit tests for the following ${i} code using ${U}. Include edge cases and error scenarios. Return only the test code.`},{role:"user",content:N}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:E.message)==null?void 0:z.content)||null}catch{return null}finally{u(!1)}},[g,i]),h=l.useCallback(async(N,$)=>{var E,z;if(!g)return null;u(!0);try{const F=V(g),U=$||Yi(i);return((z=(E=(await F.chat({messages:[{role:"system",content:`Generate ${U} documentation for the following ${i} code. Include descriptions for parameters, return values, and examples where appropriate. Return only the documented code.`},{role:"user",content:N}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:E.message)==null?void 0:z.content)||null}catch{return null}finally{u(!1)}},[g,i]),_=l.useCallback((N=A)=>{const $=v[N];return w([]),R(-1),$},[v,A]),f=l.useCallback(()=>{w([]),R(-1)},[]),k=l.useCallback(N=>{v.length!==0&&R($=>N==="up"?$<=0?v.length-1:$-1:$>=v.length-1?0:$+1)},[v.length]),S=l.useCallback(()=>{var N;(N=M.current)==null||N.abort(),P.current&&clearTimeout(P.current),u(!1)},[]);return l.useEffect(()=>()=>{var N;(N=M.current)==null||N.abort(),P.current&&clearTimeout(P.current)},[]),{getCompletions:d,getCompletionsDebounced:j,suggestions:v,activeSuggestion:A,acceptSuggestion:_,dismissSuggestions:f,navigateSuggestions:k,explainCode:y,suggestRefactoring:I,generateTests:b,generateDocs:h,loading:p,abort:S,isConfigured:!!g}}function Ui(t,a,i){var o,c;const r=((c=(o=t.choices[0])==null?void 0:o.message)==null?void 0:c.content)||"",n=/^\s*```[\w+#.-]*\n([\s\S]*?)\n?```\s*$/.exec(r),s=(n?n[1]:r).replace(/^\n+/,"").replace(/\s+$/,"");return!s.trim()||i<1?[]:[{id:`suggestion-${Date.now()}-0`,text:s,type:s.includes(`
1188
+ `})]})}function ka(t={}){const{config:a,language:i="typescript",context:n,maxSuggestions:r=3,debounceMs:s=300,onSuggestion:o,onError:c}=t,m=Z(),[p,d]=l.useState(!1),[x,N]=l.useState([]),[A,R]=l.useState(-1),$=l.useRef(null),M=l.useRef(null),g=a||(m==null?void 0:m.config),u=l.useCallback(async(I,z)=>{var P,F,G;if(!g)return{suggestions:[],error:"AI not configured"};d(!0),(P=$.current)==null||P.abort(),$.current=new AbortController;const E=performance.now();try{const K=Y(g),X=I.split(`
1189
+ `),S=X[z.line]||"",b=[...X.slice(Math.max(0,z.line-20),z.line),S.substring(0,z.column)].join(`
1190
+ `),B=[S.substring(z.column),...X.slice(z.line+1,z.line+10)].join(`
1191
+ `),U=ae(me,{language:i,prefix:b,suffix:B,context:n}),J=await K.chat({messages:[{role:"system",content:U.system},{role:"user",content:U.user}],temperature:.2,maxTokens:512}),H=Ui(J,z,r),V={suggestions:H,rawResponse:(G=(F=J.choices[0])==null?void 0:F.message)==null?void 0:G.content,latencyMs:performance.now()-E};return N(H),R(H.length>0?0:-1),o==null||o(H),V}catch(K){const X=K instanceof Error?K.message:"Completion failed";return c==null||c(X),{suggestions:[],error:X,latencyMs:performance.now()-E}}finally{d(!1)}},[g,i,n,r,o,c]),y=l.useCallback((I,z)=>{M.current&&clearTimeout(M.current),M.current=setTimeout(()=>{u(I,z)},s)},[u,s]),_=l.useCallback(async I=>{if(!g)return null;d(!0);try{const E=await Y(g).chat({messages:[{role:"system",content:`You are a code explanation assistant. Explain the following ${i} code clearly and concisely. Return JSON with: { "summary": string, "details": string, "complexity": "low"|"medium"|"high", "suggestions": string[] }`},{role:"user",content:I}],temperature:.3,maxTokens:1024});return Wi(E)}catch{return null}finally{d(!1)}},[g,i]),C=l.useCallback(async I=>{if(!g)return[];d(!0);try{const E=await Y(g).chat({messages:[{role:"system",content:`You are a code refactoring assistant. Analyze the following ${i} code and suggest improvements. Return JSON array with: [{ "title": string, "description": string, "before": string, "after": string, "type": "extract-function"|"rename"|"simplify"|"optimize"|"security"|"style" }]`},{role:"user",content:I}],temperature:.4,maxTokens:2048});return Hi(E)}catch{return[]}finally{d(!1)}},[g,i]),v=l.useCallback(async(I,z)=>{var E,P;if(!g)return null;d(!0);try{const F=Y(g),G=z||Ki(i);return((P=(E=(await F.chat({messages:[{role:"system",content:`You are a testing expert. Generate comprehensive unit tests for the following ${i} code using ${G}. Include edge cases and error scenarios. Return only the test code.`},{role:"user",content:I}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:E.message)==null?void 0:P.content)||null}catch{return null}finally{d(!1)}},[g,i]),h=l.useCallback(async(I,z)=>{var E,P;if(!g)return null;d(!0);try{const F=Y(g),G=z||Vi(i);return((P=(E=(await F.chat({messages:[{role:"system",content:`Generate ${G} documentation for the following ${i} code. Include descriptions for parameters, return values, and examples where appropriate. Return only the documented code.`},{role:"user",content:I}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:E.message)==null?void 0:P.content)||null}catch{return null}finally{d(!1)}},[g,i]),w=l.useCallback((I=A)=>{const z=x[I];return N([]),R(-1),z},[x,A]),f=l.useCallback(()=>{N([]),R(-1)},[]),j=l.useCallback(I=>{x.length!==0&&R(z=>I==="up"?z<=0?x.length-1:z-1:z>=x.length-1?0:z+1)},[x.length]),k=l.useCallback(()=>{var I;(I=$.current)==null||I.abort(),M.current&&clearTimeout(M.current),d(!1)},[]);return l.useEffect(()=>()=>{var I;(I=$.current)==null||I.abort(),M.current&&clearTimeout(M.current)},[]),{getCompletions:u,getCompletionsDebounced:y,suggestions:x,activeSuggestion:A,acceptSuggestion:w,dismissSuggestions:f,navigateSuggestions:j,explainCode:_,suggestRefactoring:C,generateTests:v,generateDocs:h,loading:p,abort:k,isConfigured:!!g}}function Ui(t,a,i){var o,c;const n=((c=(o=t.choices[0])==null?void 0:o.message)==null?void 0:c.content)||"",r=/^\s*```[\w+#.-]*\n([\s\S]*?)\n?```\s*$/.exec(n),s=(r?r[1]:n).replace(/^\n+/,"").replace(/\s+$/,"");return!s.trim()||i<1?[]:[{id:`suggestion-${Date.now()}-0`,text:s,type:s.includes(`
1192
1192
  `)?"block":"inline",preview:s.trim().split(`
1193
- `)[0].slice(0,50),confidence:.8,insertPosition:a}]}function Wi(t){var a,i;try{const r=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",n=r.match(/\{[\s\S]*\}/);return n?JSON.parse(n[0]):{summary:r}}catch{return null}}function Hi(t){var a,i;try{const n=(((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"").match(/\[[\s\S]*\]/);if(n)return JSON.parse(n[0])}catch{}return[]}function Ki(t){return{javascript:"Jest",typescript:"Jest",python:"pytest",java:"JUnit 5",csharp:"xUnit",go:"testing",rust:"cargo test",ruby:"RSpec",php:"PHPUnit",swift:"XCTest",kotlin:"JUnit 5",dart:"flutter_test"}[t]||"unit test"}function Yi(t){return{javascript:"jsdoc",typescript:"tsdoc",python:"docstring",java:"javadoc",kotlin:"javadoc"}[t]||"jsdoc"}function Vi({code:t="",language:a="typescript",config:i,onChange:r,onAcceptSuggestion:n,showToolbar:s=!0,enableInlineSuggestions:o=!0,placeholder:c,className:m,style:p,renderEditor:u}){const{t:v}=T.useNiceTranslation(),w=c??v("codeEditorAI.startTypingCode","Start typing code..."),[A,R]=l.useState(t),[M,P]=l.useState(null),[g,d]=l.useState(null),[j,y]=l.useState([]),[I,b]=l.useState(null),[h,_]=l.useState(null),f=l.useRef(null),{getCompletionsDebounced:k,suggestions:S,activeSuggestion:N,acceptSuggestion:$,dismissSuggestions:E,navigateSuggestions:z,explainCode:F,suggestRefactoring:U,generateTests:H,generateDocs:X,loading:C,isConfigured:x}=ka({config:i,language:a}),B=D=>{if(R(D),r==null||r(D),o&&f.current){const K=Xi(f.current);k(D,K)}},G=D=>{if(S.length>0)if(D.key==="ArrowUp")D.preventDefault(),z("up");else if(D.key==="ArrowDown")D.preventDefault(),z("down");else if(D.key==="Tab"||D.key==="Enter"){if(N>=0){D.preventDefault();const K=$(N);K&&(q(K),n==null||n(K))}}else D.key==="Escape"&&E()},q=D=>{if(!f.current)return;const K=f.current,te=K.selectionStart,Ee=A.slice(0,te)+D.text+A.slice(te);R(Ee),r==null||r(Ee);const De=te+D.text.length;setTimeout(()=>{K.focus(),K.setSelectionRange(De,De)},0)},W=async()=>{const D=M||A;if(!D.trim())return;_("explain");const K=await F(D);d(K)},Q=async()=>{const D=M||A;if(!D.trim())return;_("refactor");const K=await U(D);y(K)},re=async()=>{if(!A.trim())return;_("tests");const D=await H(A);b(D)},L=async()=>{if(!A.trim())return;_("docs");const D=await X(A);b(D)},O=D=>{const K=A.replace(D.before,D.after);R(K),r==null||r(K),_(null)},J=()=>{I&&navigator.clipboard.writeText(I)},Y=()=>{if(f.current){const D=f.current.selectionStart,K=f.current.selectionEnd;P(D!==K?A.slice(D,K):null)}};return x?u?e.jsx("div",{className:`nice-code-editor-ai ${m||""}`,style:p,children:u({code:A,onChange:B,suggestions:S,onAccept:D=>{const K=$(D);K&&(n==null||n(K))}})}):e.jsxs("div",{className:`nice-code-editor-ai ${m||""}`,style:p,children:[s&&e.jsxs("div",{className:"nice-code-editor-ai__toolbar",children:[e.jsx("span",{className:"nice-code-editor-ai__lang-badge",children:a}),e.jsxs("div",{className:"nice-code-editor-ai__actions",children:[e.jsxs("button",{type:"button",onClick:W,disabled:C||!A.trim(),title:v("codeEditorAI.explainCode","Explain code"),children:[e.jsx(T.NiceIcon,{name:"lightbulb",size:14})," ",v("codeEditorAI.explain","Explain")]}),e.jsxs("button",{type:"button",onClick:Q,disabled:C||!A.trim(),title:v("codeEditorAI.suggestRefactoring","Suggest refactoring"),children:[e.jsx(T.NiceIcon,{name:"settings",size:14})," ",v("codeEditorAI.refactor","Refactor")]}),e.jsxs("button",{type:"button",onClick:re,disabled:C||!A.trim(),title:v("codeEditorAI.generateTests","Generate tests"),children:[e.jsx(T.NiceIcon,{name:"flask",size:14})," ",v("codeEditorAI.tests","Tests")]}),e.jsxs("button",{type:"button",onClick:L,disabled:C||!A.trim(),title:v("codeEditorAI.generateDocs","Generate docs"),children:[e.jsx(T.NiceIcon,{name:"edit",size:14})," ",v("codeEditorAI.docs","Docs")]})]}),C&&e.jsx("span",{className:"nice-code-editor-ai__loading",children:v("codeEditorAI.processing","Processing...")})]}),e.jsxs("div",{className:"nice-code-editor-ai__editor-wrapper",children:[e.jsx("textarea",{ref:f,value:A,onChange:D=>B(D.target.value),onKeyDown:G,onSelect:Y,placeholder:w,className:"nice-code-editor-ai__textarea",spellCheck:!1}),S.length>0&&e.jsxs("div",{className:"nice-code-editor-ai__suggestions",children:[S.map((D,K)=>e.jsxs("div",{className:`nice-code-editor-ai__suggestion ${K===N?"nice-code-editor-ai__suggestion--active":""}`,onClick:()=>{const te=$(K);te&&(q(te),n==null||n(te))},children:[e.jsx("span",{className:"nice-code-editor-ai__suggestion-text",children:D.text}),e.jsxs("span",{className:"nice-code-editor-ai__suggestion-confidence",children:[Math.round(D.confidence*100),"%"]})]},D.id)),e.jsxs("div",{className:"nice-code-editor-ai__suggestions-hint",children:[e.jsx(T.NiceIcon,{name:"arrow-up",size:11}),e.jsx(T.NiceIcon,{name:"arrow-down",size:11})," navigate • Tab accept • Esc dismiss"]})]})]}),h&&e.jsxs("div",{className:"nice-code-editor-ai__panel",children:[e.jsxs("div",{className:"nice-code-editor-ai__panel-header",children:[e.jsxs("span",{children:[h==="explain"&&e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"lightbulb",size:14})," ",v("codeEditorAI.explanation","Explanation")]}),h==="refactor"&&e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"settings",size:14})," ",v("codeEditorAI.refactoringSuggestions","Refactoring Suggestions")]}),h==="tests"&&e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"flask",size:14})," ",v("codeEditorAI.generatedTests","Generated Tests")]}),h==="docs"&&e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"edit",size:14})," ",v("codeEditorAI.generatedDocumentation","Generated Documentation")]})]}),e.jsx("button",{type:"button",onClick:()=>_(null),"aria-label":v("codeEditorAI.closePanel","Close panel"),children:e.jsx(T.NiceIcon,{name:"close",size:16})})]}),e.jsxs("div",{className:"nice-code-editor-ai__panel-content",children:[h==="explain"&&g&&e.jsxs("div",{className:"nice-code-editor-ai__explanation",children:[e.jsx("div",{className:"nice-code-editor-ai__explanation-summary",children:g.summary}),g.details&&e.jsx("div",{className:"nice-code-editor-ai__explanation-details",children:g.details}),g.complexity&&e.jsxs("span",{className:`nice-code-editor-ai__complexity nice-code-editor-ai__complexity--${g.complexity}`,children:["Complexity: ",g.complexity]}),g.suggestions&&g.suggestions.length>0&&e.jsx("ul",{className:"nice-code-editor-ai__explanation-suggestions",children:g.suggestions.map((D,K)=>e.jsx("li",{children:D},K))})]}),h==="refactor"&&j.length>0&&e.jsx("div",{className:"nice-code-editor-ai__refactorings",children:j.map((D,K)=>e.jsxs("div",{className:"nice-code-editor-ai__refactoring",children:[e.jsxs("div",{className:"nice-code-editor-ai__refactoring-header",children:[e.jsx("span",{className:"nice-code-editor-ai__refactoring-title",children:D.title}),e.jsx("span",{className:`nice-code-editor-ai__refactoring-type nice-code-editor-ai__refactoring-type--${D.type}`,children:D.type})]}),e.jsx("p",{className:"nice-code-editor-ai__refactoring-desc",children:D.description}),e.jsxs("div",{className:"nice-code-editor-ai__refactoring-diff",children:[e.jsxs("div",{className:"nice-code-editor-ai__refactoring-before",children:[e.jsx("span",{children:"Before:"}),e.jsx("pre",{children:D.before})]}),e.jsxs("div",{className:"nice-code-editor-ai__refactoring-after",children:[e.jsx("span",{children:"After:"}),e.jsx("pre",{children:D.after})]})]}),e.jsx("button",{type:"button",className:"nice-code-editor-ai__refactoring-apply",onClick:()=>O(D),children:v("codeEditorAI.apply","Apply")})]},K))}),(h==="tests"||h==="docs")&&I&&e.jsxs("div",{className:"nice-code-editor-ai__generated",children:[e.jsx("pre",{children:I}),e.jsxs("button",{type:"button",onClick:J,children:[e.jsx(T.NiceIcon,{name:"clipboard",size:14})," ",v("codeEditorAI.copy","Copy")]})]})]})]}),e.jsx("style",{children:`
1193
+ `)[0].slice(0,50),confidence:.8,insertPosition:a}]}function Wi(t){var a,i;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",r=n.match(/\{[\s\S]*\}/);return r?JSON.parse(r[0]):{summary:n}}catch{return null}}function Hi(t){var a,i;try{const r=(((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"").match(/\[[\s\S]*\]/);if(r)return JSON.parse(r[0])}catch{}return[]}function Ki(t){return{javascript:"Jest",typescript:"Jest",python:"pytest",java:"JUnit 5",csharp:"xUnit",go:"testing",rust:"cargo test",ruby:"RSpec",php:"PHPUnit",swift:"XCTest",kotlin:"JUnit 5",dart:"flutter_test"}[t]||"unit test"}function Vi(t){return{javascript:"jsdoc",typescript:"tsdoc",python:"docstring",java:"javadoc",kotlin:"javadoc"}[t]||"jsdoc"}function Yi({code:t="",language:a="typescript",config:i,onChange:n,onAcceptSuggestion:r,showToolbar:s=!0,enableInlineSuggestions:o=!0,placeholder:c,className:m,style:p,renderEditor:d}){const{t:x}=T.useNiceTranslation(),N=c??x("codeEditorAI.startTypingCode","Start typing code..."),[A,R]=l.useState(t),[$,M]=l.useState(null),[g,u]=l.useState(null),[y,_]=l.useState([]),[C,v]=l.useState(null),[h,w]=l.useState(null),f=l.useRef(null),{getCompletionsDebounced:j,suggestions:k,activeSuggestion:I,acceptSuggestion:z,dismissSuggestions:E,navigateSuggestions:P,explainCode:F,suggestRefactoring:G,generateTests:K,generateDocs:X,loading:S,isConfigured:b}=ka({config:i,language:a}),B=D=>{if(R(D),n==null||n(D),o&&f.current){const W=Xi(f.current);j(D,W)}},U=D=>{if(k.length>0)if(D.key==="ArrowUp")D.preventDefault(),P("up");else if(D.key==="ArrowDown")D.preventDefault(),P("down");else if(D.key==="Tab"||D.key==="Enter"){if(I>=0){D.preventDefault();const W=z(I);W&&(J(W),r==null||r(W))}}else D.key==="Escape"&&E()},J=D=>{if(!f.current)return;const W=f.current,ie=W.selectionStart,Ee=A.slice(0,ie)+D.text+A.slice(ie);R(Ee),n==null||n(Ee);const De=ie+D.text.length;setTimeout(()=>{W.focus(),W.setSelectionRange(De,De)},0)},H=async()=>{const D=$||A;if(!D.trim())return;w("explain");const W=await F(D);u(W)},V=async()=>{const D=$||A;if(!D.trim())return;w("refactor");const W=await G(D);_(W)},te=async()=>{if(!A.trim())return;w("tests");const D=await K(A);v(D)},ne=async()=>{if(!A.trim())return;w("docs");const D=await X(A);v(D)},L=D=>{const W=A.replace(D.before,D.after);R(W),n==null||n(W),w(null)},O=()=>{C&&navigator.clipboard.writeText(C)},q=()=>{if(f.current){const D=f.current.selectionStart,W=f.current.selectionEnd;M(D!==W?A.slice(D,W):null)}};return b?d?e.jsx("div",{className:`nice-code-editor-ai ${m||""}`,style:p,children:d({code:A,onChange:B,suggestions:k,onAccept:D=>{const W=z(D);W&&(r==null||r(W))}})}):e.jsxs("div",{className:`nice-code-editor-ai ${m||""}`,style:p,children:[s&&e.jsxs("div",{className:"nice-code-editor-ai__toolbar",children:[e.jsx("span",{className:"nice-code-editor-ai__lang-badge",children:a}),e.jsxs("div",{className:"nice-code-editor-ai__actions",children:[e.jsxs("button",{type:"button",onClick:H,disabled:S||!A.trim(),title:x("codeEditorAI.explainCode","Explain code"),children:[e.jsx(T.NiceIcon,{name:"lightbulb",size:14})," ",x("codeEditorAI.explain","Explain")]}),e.jsxs("button",{type:"button",onClick:V,disabled:S||!A.trim(),title:x("codeEditorAI.suggestRefactoring","Suggest refactoring"),children:[e.jsx(T.NiceIcon,{name:"settings",size:14})," ",x("codeEditorAI.refactor","Refactor")]}),e.jsxs("button",{type:"button",onClick:te,disabled:S||!A.trim(),title:x("codeEditorAI.generateTests","Generate tests"),children:[e.jsx(T.NiceIcon,{name:"flask",size:14})," ",x("codeEditorAI.tests","Tests")]}),e.jsxs("button",{type:"button",onClick:ne,disabled:S||!A.trim(),title:x("codeEditorAI.generateDocs","Generate docs"),children:[e.jsx(T.NiceIcon,{name:"edit",size:14})," ",x("codeEditorAI.docs","Docs")]})]}),S&&e.jsx("span",{className:"nice-code-editor-ai__loading",children:x("codeEditorAI.processing","Processing...")})]}),e.jsxs("div",{className:"nice-code-editor-ai__editor-wrapper",children:[e.jsx("textarea",{ref:f,value:A,onChange:D=>B(D.target.value),onKeyDown:U,onSelect:q,placeholder:N,className:"nice-code-editor-ai__textarea",spellCheck:!1}),k.length>0&&e.jsxs("div",{className:"nice-code-editor-ai__suggestions",children:[k.map((D,W)=>e.jsxs("div",{className:`nice-code-editor-ai__suggestion ${W===I?"nice-code-editor-ai__suggestion--active":""}`,onClick:()=>{const ie=z(W);ie&&(J(ie),r==null||r(ie))},children:[e.jsx("span",{className:"nice-code-editor-ai__suggestion-text",children:D.text}),e.jsxs("span",{className:"nice-code-editor-ai__suggestion-confidence",children:[Math.round(D.confidence*100),"%"]})]},D.id)),e.jsxs("div",{className:"nice-code-editor-ai__suggestions-hint",children:[e.jsx(T.NiceIcon,{name:"arrow-up",size:11}),e.jsx(T.NiceIcon,{name:"arrow-down",size:11})," ",x("codeEditorAI.navigateTabAcceptEscDismiss","navigate • Tab accept • Esc dismiss")]})]})]}),h&&e.jsxs("div",{className:"nice-code-editor-ai__panel",children:[e.jsxs("div",{className:"nice-code-editor-ai__panel-header",children:[e.jsxs("span",{children:[h==="explain"&&e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"lightbulb",size:14})," ",x("codeEditorAI.explanation","Explanation")]}),h==="refactor"&&e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"settings",size:14})," ",x("codeEditorAI.refactoringSuggestions","Refactoring Suggestions")]}),h==="tests"&&e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"flask",size:14})," ",x("codeEditorAI.generatedTests","Generated Tests")]}),h==="docs"&&e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"edit",size:14})," ",x("codeEditorAI.generatedDocumentation","Generated Documentation")]})]}),e.jsx("button",{type:"button",onClick:()=>w(null),"aria-label":x("codeEditorAI.closePanel","Close panel"),children:e.jsx(T.NiceIcon,{name:"close",size:16})})]}),e.jsxs("div",{className:"nice-code-editor-ai__panel-content",children:[h==="explain"&&g&&e.jsxs("div",{className:"nice-code-editor-ai__explanation",children:[e.jsx("div",{className:"nice-code-editor-ai__explanation-summary",children:g.summary}),g.details&&e.jsx("div",{className:"nice-code-editor-ai__explanation-details",children:g.details}),g.complexity&&e.jsx("span",{className:`nice-code-editor-ai__complexity nice-code-editor-ai__complexity--${g.complexity}`,children:x("codeEditorAI.complexity","Complexity: {complexity}").replace("{complexity}",String(g.complexity))}),g.suggestions&&g.suggestions.length>0&&e.jsx("ul",{className:"nice-code-editor-ai__explanation-suggestions",children:g.suggestions.map((D,W)=>e.jsx("li",{children:D},W))})]}),h==="refactor"&&y.length>0&&e.jsx("div",{className:"nice-code-editor-ai__refactorings",children:y.map((D,W)=>e.jsxs("div",{className:"nice-code-editor-ai__refactoring",children:[e.jsxs("div",{className:"nice-code-editor-ai__refactoring-header",children:[e.jsx("span",{className:"nice-code-editor-ai__refactoring-title",children:D.title}),e.jsx("span",{className:`nice-code-editor-ai__refactoring-type nice-code-editor-ai__refactoring-type--${D.type}`,children:D.type})]}),e.jsx("p",{className:"nice-code-editor-ai__refactoring-desc",children:D.description}),e.jsxs("div",{className:"nice-code-editor-ai__refactoring-diff",children:[e.jsxs("div",{className:"nice-code-editor-ai__refactoring-before",children:[e.jsx("span",{children:x("codeEditorAI.before","Before:")}),e.jsx("pre",{children:D.before})]}),e.jsxs("div",{className:"nice-code-editor-ai__refactoring-after",children:[e.jsx("span",{children:x("codeEditorAI.after","After:")}),e.jsx("pre",{children:D.after})]})]}),e.jsx("button",{type:"button",className:"nice-code-editor-ai__refactoring-apply",onClick:()=>L(D),children:x("codeEditorAI.apply","Apply")})]},W))}),(h==="tests"||h==="docs")&&C&&e.jsxs("div",{className:"nice-code-editor-ai__generated",children:[e.jsx("pre",{children:C}),e.jsxs("button",{type:"button",onClick:O,children:[e.jsx(T.NiceIcon,{name:"clipboard",size:14})," ",x("codeEditorAI.copy","Copy")]})]})]})]}),e.jsx("style",{children:`
1194
1194
  .nice-code-editor-ai {
1195
1195
  font-family: var(--nice-font-family, system-ui, sans-serif);
1196
1196
  display: flex;
@@ -1496,13 +1496,13 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
1496
1496
  border-radius: var(--nice-radius-md, 6px);
1497
1497
  cursor: pointer;
1498
1498
  }
1499
- `})]}):e.jsxs("div",{className:`nice-code-editor-ai nice-code-editor-ai--disabled ${m||""}`,style:p,children:[e.jsx("p",{children:v("codeEditorAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")}),e.jsx("textarea",{value:A,onChange:D=>B(D.target.value),placeholder:w,className:"nice-code-editor-ai__textarea"})]})}function Xi(t){const i=t.value.substring(0,t.selectionStart).split(`
1500
- `);return{line:i.length-1,column:i[i.length-1].length}}function Na(t={}){const{config:a,context:i,existingRoles:r,existingVariables:n,onWorkflowGenerated:s,onError:o}=t,c=ee(),[m,p]=l.useState(!1),[u,v]=l.useState(null),[w,A]=l.useState([]),R=l.useRef(null),M=a||(c==null?void 0:c.config),P=l.useCallback(async b=>{var _,f,k;if(!M){const S="AI not configured";return o==null||o(S),{error:S}}p(!0);const h=performance.now();(_=R.current)==null||_.abort(),R.current=new AbortController;try{const S=V(M),N=[i,r!=null&&r.length?`Available roles: ${r.join(", ")}`:"",n!=null&&n.length?`Existing variables: ${n.join(", ")}`:""].filter(Boolean).join(`
1501
- `),$=ie(pe,{description:N?`${b}
1499
+ `})]}):e.jsxs("div",{className:`nice-code-editor-ai nice-code-editor-ai--disabled ${m||""}`,style:p,children:[e.jsx("p",{children:x("codeEditorAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")}),e.jsx("textarea",{value:A,onChange:D=>B(D.target.value),placeholder:N,className:"nice-code-editor-ai__textarea"})]})}function Xi(t){const i=t.value.substring(0,t.selectionStart).split(`
1500
+ `);return{line:i.length-1,column:i[i.length-1].length}}function Na(t={}){const{config:a,context:i,existingRoles:n,existingVariables:r,onWorkflowGenerated:s,onError:o}=t,c=Z(),[m,p]=l.useState(!1),[d,x]=l.useState(null),[N,A]=l.useState([]),R=l.useRef(null),$=a||(c==null?void 0:c.config),M=l.useCallback(async v=>{var w,f,j;if(!$){const k="AI not configured";return o==null||o(k),{error:k}}p(!0);const h=performance.now();(w=R.current)==null||w.abort(),R.current=new AbortController;try{const k=Y($),I=[i,n!=null&&n.length?`Available roles: ${n.join(", ")}`:"",r!=null&&r.length?`Existing variables: ${r.join(", ")}`:""].filter(Boolean).join(`
1501
+ `),z=ae(pe,{description:I?`${v}
1502
1502
 
1503
- ${N}`:b}),E=await S.chat({messages:[{role:"system",content:$.system},{role:"user",content:$.user}],temperature:.5,maxTokens:2048}),z=Ge(E),F={workflow:z||void 0,rawResponse:(k=(f=E.choices[0])==null?void 0:f.message)==null?void 0:k.content,latencyMs:performance.now()-h,error:z?void 0:"Failed to generate workflow",suggestions:Zi(z)};return z&&(s==null||s(z)),v(F),A(U=>[...U.slice(-9),{request:b,result:F}]),F}catch(S){const N=S instanceof Error?S.message:"Workflow generation failed",$={error:N,latencyMs:performance.now()-h};return v($),o==null||o(N),$}finally{p(!1)}},[M,i,r,n,s,o]),g=l.useCallback(async b=>{if(!M)return{error:"AI not configured"};p(!0);const h=performance.now();try{const f=await V(M).chat({messages:[{role:"system",content:"You are a workflow optimization expert. Analyze the following BPMN workflow and suggest improvements for efficiency, clarity, and error handling. Return the optimized workflow in JSON format with the same structure."},{role:"user",content:JSON.stringify(b,null,2)}],temperature:.4,maxTokens:2048});return{workflow:Ge(f)||void 0,latencyMs:performance.now()-h}}catch(_){return{error:_ instanceof Error?_.message:"Optimization failed"}}finally{p(!1)}},[M]),d=l.useCallback(async(b,h)=>{var _,f;if(!M)return[];p(!0);try{const k=V(M),S=b.nodes.find(z=>z.id===h),E=(((f=(_=(await k.chat({messages:[{role:"system",content:'Given the current workflow state, suggest 2-3 possible next steps after the specified node. Return JSON array of nodes: [{ "id": string, "type": string, "label": string, "description": string }]'},{role:"user",content:`Workflow: ${b.name}
1504
- Current node: ${(S==null?void 0:S.label)||h}
1505
- Existing nodes: ${b.nodes.map(z=>z.label).join(", ")}`}],temperature:.6,maxTokens:512})).choices[0])==null?void 0:_.message)==null?void 0:f.content)||"").match(/\[[\s\S]*\]/);if(E)return JSON.parse(E[0])}catch{}finally{p(!1)}return[]},[M]),j=l.useCallback(async b=>{var h,_;if(!M)return[];p(!0);try{const N=(((_=(h=(await V(M).chat({messages:[{role:"system",content:'Analyze the BPMN workflow for potential issues. Check for: dead ends, unreachable nodes, missing error handling, infinite loops, unclear conditions, missing assignments. Return JSON array of issues: [{ "severity": "error"|"warning"|"info", "message": string, "nodeId": string? }]'},{role:"user",content:JSON.stringify(b,null,2)}],temperature:.3,maxTokens:1024})).choices[0])==null?void 0:h.message)==null?void 0:_.content)||"").match(/\[[\s\S]*\]/);if(N)return JSON.parse(N[0]).map(E=>`[${E.severity}] ${E.message}`)}catch{}finally{p(!1)}return[]},[M]),y=l.useCallback(()=>{v(null)},[]),I=l.useCallback(()=>{var b;(b=R.current)==null||b.abort(),p(!1)},[]);return l.useEffect(()=>()=>{var b;(b=R.current)==null||b.abort()},[]),{generateWorkflow:P,optimizeWorkflow:g,suggestNextStep:d,validateWorkflow:j,loading:m,lastResult:u,history:w,clearResults:y,abort:I,isConfigured:!!M}}function Ge(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.nodes&&Array.isArray(c.nodes)){const m={gateway:"gateway-exclusive",event:"event-intermediate"},p=c.nodes.map((w,A)=>({...w,id:w.id||`node_${A}`,label:w.label??w.name??w.id??`Step ${A+1}`,type:m[w.type]??w.type})),u=Qi(p),v=p.map((w,A)=>({...w,position:w.position||u[A]}));return{id:c.id||`workflow_${Date.now()}`,name:c.name||"Generated Workflow",description:c.description,version:c.version||"1.0",nodes:v,edges:c.edges||[],lanes:c.lanes??c.swimlanes,variables:c.variables,metadata:c.metadata}}}catch{}return null}function Sa(t){return t.type==="start"||t.type==="end"||t.type.startsWith("gateway")?40:Math.round((t.label??"").length*7.2+64)}function Qi(t){let n=20,s=40;return t.map(o=>{const c=Sa(o);n>20&&n+c>640&&(n=20,s+=110);const m={x:n,y:s};return n+=c+48,m})}function Zi(t){if(!t)return[];const a=[];return t.nodes.some(s=>s.type==="event-error")||a.push("Add error boundary events for critical tasks"),!t.nodes.some(s=>s.type==="gateway-parallel")&&t.nodes.length>5&&a.push("Consider parallel gateways for independent tasks"),(!t.lanes||t.lanes.length===0)&&a.push("Add swimlanes to clarify responsibilities"),t.nodes.some(s=>s.type==="event-timer")||a.push("Add timer events for SLA monitoring"),a.slice(0,3)}const et=["Employee onboarding process with HR approval","Purchase order approval with budget check","Customer support ticket escalation workflow","Document review and approval process","Leave request with manager and HR approval"];function at({config:t,context:a,roles:i,onGenerate:r,placeholder:n,showExamples:s=!0,showPreview:o=!0,className:c,style:m,renderWorkflow:p}){const{t:u}=T.useNiceTranslation(),v=n??u("workflowDesignerAI.describeTheWorkflow",'Describe the workflow process... (e.g., "Leave request with manager approval")'),[w,A]=l.useState(""),[R,M]=l.useState([]),P=l.useRef(null),{generateWorkflow:g,validateWorkflow:d,loading:j,lastResult:y,isConfigured:I}=Na({config:t,context:a,existingRoles:i,onWorkflowGenerated:r}),b=async()=>{!w.trim()||j||await g(w)},h=k=>{var S;A(k),(S=P.current)==null||S.focus()},_=async()=>{if(!(y!=null&&y.workflow))return;const k=await d(y.workflow);M(k)},f=()=>{if(!(y!=null&&y.workflow))return;const k=tt(y.workflow),S=new Blob([k],{type:"application/xml"}),N=URL.createObjectURL(S),$=document.createElement("a");$.href=N,$.download=`${y.workflow.name.replace(/\s+/g,"_")}.bpmn`,$.click(),URL.revokeObjectURL(N)};return I?e.jsxs("div",{className:`nice-workflow-ai ${c||""}`,style:m,children:[e.jsxs("div",{className:"nice-workflow-ai__input-section",children:[e.jsx("textarea",{ref:P,value:w,onChange:k=>A(k.target.value),placeholder:v,className:"nice-workflow-ai__input",rows:3,disabled:j}),e.jsx("button",{type:"button",onClick:b,className:"nice-workflow-ai__submit",disabled:j||!w.trim(),children:j?e.jsx("span",{className:"nice-workflow-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"refresh",size:14})," ",u("workflowDesignerAI.generateWorkflow","Generate Workflow")]})})]}),s&&e.jsxs("div",{className:"nice-workflow-ai__examples",children:[e.jsx("span",{className:"nice-workflow-ai__examples-label",children:"Try:"}),et.slice(0,3).map((k,S)=>e.jsx("button",{type:"button",className:"nice-workflow-ai__example",onClick:()=>h(k),children:k},S))]}),y&&e.jsx("div",{className:"nice-workflow-ai__result",children:y.error?e.jsx("div",{className:"nice-workflow-ai__error",children:y.error}):y.workflow&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-workflow-ai__result-header",children:[e.jsxs("div",{className:"nice-workflow-ai__workflow-info",children:[e.jsx("span",{className:"nice-workflow-ai__workflow-name",children:y.workflow.name}),y.workflow.description&&e.jsx("span",{className:"nice-workflow-ai__workflow-desc",children:y.workflow.description})]}),e.jsxs("div",{className:"nice-workflow-ai__result-meta",children:[e.jsxs("span",{className:"nice-workflow-ai__stat",children:[y.workflow.nodes.length," nodes"]}),e.jsxs("span",{className:"nice-workflow-ai__stat",children:[y.workflow.edges.length," connections"]}),y.latencyMs&&e.jsxs("span",{className:"nice-workflow-ai__latency",children:[Math.round(y.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-workflow-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>r==null?void 0:r(y.workflow),children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",u("workflowDesignerAI.useWorkflow","Use Workflow")]}),e.jsxs("button",{type:"button",onClick:_,children:[e.jsx(T.NiceIcon,{name:"search",size:14})," ",u("workflowDesignerAI.validate","Validate")]}),e.jsxs("button",{type:"button",onClick:f,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," ",u("workflowDesignerAI.exportBpmn","Export BPMN")]})]}),R.length>0&&e.jsxs("div",{className:"nice-workflow-ai__validation",children:[e.jsx("div",{className:"nice-workflow-ai__validation-title",children:"Validation Issues:"}),e.jsx("ul",{children:R.map((k,S)=>e.jsx("li",{className:`nice-workflow-ai__issue nice-workflow-ai__issue--${k.startsWith("[error]")?"error":k.startsWith("[warning]")?"warning":"info"}`,children:k},S))})]}),o&&e.jsx("div",{className:"nice-workflow-ai__preview",children:p?p(y.workflow):e.jsx(it,{workflow:y.workflow})}),y.suggestions&&y.suggestions.length>0&&e.jsxs("div",{className:"nice-workflow-ai__suggestions",children:[e.jsxs("span",{className:"nice-workflow-ai__suggestions-title",children:[e.jsx(T.NiceIcon,{name:"lightbulb",size:14})," Suggestions:"]}),e.jsx("ul",{children:y.suggestions.map((k,S)=>e.jsx("li",{children:k},S))})]}),e.jsxs("details",{className:"nice-workflow-ai__json",children:[e.jsx("summary",{children:u("workflowDesignerAI.viewJsonDefinition","View JSON Definition")}),e.jsx("pre",{children:JSON.stringify(y.workflow,null,2)})]})]})}),e.jsx("style",{children:`
1503
+ ${I}`:v}),E=await k.chat({messages:[{role:"system",content:z.system},{role:"user",content:z.user}],temperature:.5,maxTokens:2048}),P=Ge(E),F={workflow:P||void 0,rawResponse:(j=(f=E.choices[0])==null?void 0:f.message)==null?void 0:j.content,latencyMs:performance.now()-h,error:P?void 0:"Failed to generate workflow",suggestions:Zi(P)};return P&&(s==null||s(P)),x(F),A(G=>[...G.slice(-9),{request:v,result:F}]),F}catch(k){const I=k instanceof Error?k.message:"Workflow generation failed",z={error:I,latencyMs:performance.now()-h};return x(z),o==null||o(I),z}finally{p(!1)}},[$,i,n,r,s,o]),g=l.useCallback(async v=>{if(!$)return{error:"AI not configured"};p(!0);const h=performance.now();try{const f=await Y($).chat({messages:[{role:"system",content:"You are a workflow optimization expert. Analyze the following BPMN workflow and suggest improvements for efficiency, clarity, and error handling. Return the optimized workflow in JSON format with the same structure."},{role:"user",content:JSON.stringify(v,null,2)}],temperature:.4,maxTokens:2048});return{workflow:Ge(f)||void 0,latencyMs:performance.now()-h}}catch(w){return{error:w instanceof Error?w.message:"Optimization failed"}}finally{p(!1)}},[$]),u=l.useCallback(async(v,h)=>{var w,f;if(!$)return[];p(!0);try{const j=Y($),k=v.nodes.find(P=>P.id===h),E=(((f=(w=(await j.chat({messages:[{role:"system",content:'Given the current workflow state, suggest 2-3 possible next steps after the specified node. Return JSON array of nodes: [{ "id": string, "type": string, "label": string, "description": string }]'},{role:"user",content:`Workflow: ${v.name}
1504
+ Current node: ${(k==null?void 0:k.label)||h}
1505
+ Existing nodes: ${v.nodes.map(P=>P.label).join(", ")}`}],temperature:.6,maxTokens:512})).choices[0])==null?void 0:w.message)==null?void 0:f.content)||"").match(/\[[\s\S]*\]/);if(E)return JSON.parse(E[0])}catch{}finally{p(!1)}return[]},[$]),y=l.useCallback(async v=>{var h,w;if(!$)return[];p(!0);try{const I=(((w=(h=(await Y($).chat({messages:[{role:"system",content:'Analyze the BPMN workflow for potential issues. Check for: dead ends, unreachable nodes, missing error handling, infinite loops, unclear conditions, missing assignments. Return JSON array of issues: [{ "severity": "error"|"warning"|"info", "message": string, "nodeId": string? }]'},{role:"user",content:JSON.stringify(v,null,2)}],temperature:.3,maxTokens:1024})).choices[0])==null?void 0:h.message)==null?void 0:w.content)||"").match(/\[[\s\S]*\]/);if(I)return JSON.parse(I[0]).map(E=>`[${E.severity}] ${E.message}`)}catch{}finally{p(!1)}return[]},[$]),_=l.useCallback(()=>{x(null)},[]),C=l.useCallback(()=>{var v;(v=R.current)==null||v.abort(),p(!1)},[]);return l.useEffect(()=>()=>{var v;(v=R.current)==null||v.abort()},[]),{generateWorkflow:M,optimizeWorkflow:g,suggestNextStep:u,validateWorkflow:y,loading:m,lastResult:d,history:N,clearResults:_,abort:C,isConfigured:!!$}}function Ge(t){var a,i,n;try{const r=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((n=(r.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,r])[1])==null?void 0:n.trim())||r,c=JSON.parse(o);if(c.nodes&&Array.isArray(c.nodes)){const m={gateway:"gateway-exclusive",event:"event-intermediate"},p=c.nodes.map((N,A)=>({...N,id:N.id||`node_${A}`,label:N.label??N.name??N.id??`Step ${A+1}`,type:m[N.type]??N.type})),d=Qi(p),x=p.map((N,A)=>({...N,position:N.position||d[A]}));return{id:c.id||`workflow_${Date.now()}`,name:c.name||"Generated Workflow",description:c.description,version:c.version||"1.0",nodes:x,edges:c.edges||[],lanes:c.lanes??c.swimlanes,variables:c.variables,metadata:c.metadata}}}catch{}return null}function Sa(t){return t.type==="start"||t.type==="end"||t.type.startsWith("gateway")?40:Math.round((t.label??"").length*7.2+64)}function Qi(t){let r=20,s=40;return t.map(o=>{const c=Sa(o);r>20&&r+c>640&&(r=20,s+=110);const m={x:r,y:s};return r+=c+48,m})}function Zi(t){if(!t)return[];const a=[];return t.nodes.some(s=>s.type==="event-error")||a.push("Add error boundary events for critical tasks"),!t.nodes.some(s=>s.type==="gateway-parallel")&&t.nodes.length>5&&a.push("Consider parallel gateways for independent tasks"),(!t.lanes||t.lanes.length===0)&&a.push("Add swimlanes to clarify responsibilities"),t.nodes.some(s=>s.type==="event-timer")||a.push("Add timer events for SLA monitoring"),a.slice(0,3)}const et=["Employee onboarding process with HR approval","Purchase order approval with budget check","Customer support ticket escalation workflow","Document review and approval process","Leave request with manager and HR approval"];function at({config:t,context:a,roles:i,onGenerate:n,placeholder:r,showExamples:s=!0,showPreview:o=!0,className:c,style:m,renderWorkflow:p}){const{t:d}=T.useNiceTranslation(),x=r??d("workflowDesignerAI.describeTheWorkflow",'Describe the workflow process... (e.g., "Leave request with manager approval")'),[N,A]=l.useState(""),[R,$]=l.useState([]),M=l.useRef(null),{generateWorkflow:g,validateWorkflow:u,loading:y,lastResult:_,isConfigured:C}=Na({config:t,context:a,existingRoles:i,onWorkflowGenerated:n}),v=async()=>{!N.trim()||y||await g(N)},h=j=>{var k;A(j),(k=M.current)==null||k.focus()},w=async()=>{if(!(_!=null&&_.workflow))return;const j=await u(_.workflow);$(j)},f=()=>{if(!(_!=null&&_.workflow))return;const j=tt(_.workflow),k=new Blob([j],{type:"application/xml"}),I=URL.createObjectURL(k),z=document.createElement("a");z.href=I,z.download=`${_.workflow.name.replace(/\s+/g,"_")}.bpmn`,z.click(),URL.revokeObjectURL(I)};return C?e.jsxs("div",{className:`nice-workflow-ai ${c||""}`,style:m,children:[e.jsxs("div",{className:"nice-workflow-ai__input-section",children:[e.jsx("textarea",{ref:M,value:N,onChange:j=>A(j.target.value),placeholder:x,className:"nice-workflow-ai__input",rows:3,disabled:y}),e.jsx("button",{type:"button",onClick:v,className:"nice-workflow-ai__submit",disabled:y||!N.trim(),children:y?e.jsx("span",{className:"nice-workflow-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"refresh",size:14})," ",d("workflowDesignerAI.generateWorkflow","Generate Workflow")]})})]}),s&&e.jsxs("div",{className:"nice-workflow-ai__examples",children:[e.jsx("span",{className:"nice-workflow-ai__examples-label",children:d("workflowDesignerAI.try","Try:")}),et.slice(0,3).map((j,k)=>e.jsx("button",{type:"button",className:"nice-workflow-ai__example",onClick:()=>h(j),children:j},k))]}),_&&e.jsx("div",{className:"nice-workflow-ai__result",children:_.error?e.jsx("div",{className:"nice-workflow-ai__error",children:_.error}):_.workflow&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-workflow-ai__result-header",children:[e.jsxs("div",{className:"nice-workflow-ai__workflow-info",children:[e.jsx("span",{className:"nice-workflow-ai__workflow-name",children:_.workflow.name}),_.workflow.description&&e.jsx("span",{className:"nice-workflow-ai__workflow-desc",children:_.workflow.description})]}),e.jsxs("div",{className:"nice-workflow-ai__result-meta",children:[e.jsx("span",{className:"nice-workflow-ai__stat",children:d("workflowDesignerAI.nodes","{nodes} nodes").replace("{nodes}",String(_.workflow.nodes.length))}),e.jsx("span",{className:"nice-workflow-ai__stat",children:d("workflowDesignerAI.connections","{edges} connections").replace("{edges}",String(_.workflow.edges.length))}),_.latencyMs&&e.jsxs("span",{className:"nice-workflow-ai__latency",children:[Math.round(_.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-workflow-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>n==null?void 0:n(_.workflow),children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",d("workflowDesignerAI.useWorkflow","Use Workflow")]}),e.jsxs("button",{type:"button",onClick:w,children:[e.jsx(T.NiceIcon,{name:"search",size:14})," ",d("workflowDesignerAI.validate","Validate")]}),e.jsxs("button",{type:"button",onClick:f,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," ",d("workflowDesignerAI.exportBpmn","Export BPMN")]})]}),R.length>0&&e.jsxs("div",{className:"nice-workflow-ai__validation",children:[e.jsx("div",{className:"nice-workflow-ai__validation-title",children:d("workflowDesignerAI.validationIssues","Validation Issues:")}),e.jsx("ul",{children:R.map((j,k)=>e.jsx("li",{className:`nice-workflow-ai__issue nice-workflow-ai__issue--${j.startsWith("[error]")?"error":j.startsWith("[warning]")?"warning":"info"}`,children:j},k))})]}),o&&e.jsx("div",{className:"nice-workflow-ai__preview",children:p?p(_.workflow):e.jsx(it,{workflow:_.workflow})}),_.suggestions&&_.suggestions.length>0&&e.jsxs("div",{className:"nice-workflow-ai__suggestions",children:[e.jsxs("span",{className:"nice-workflow-ai__suggestions-title",children:[e.jsx(T.NiceIcon,{name:"lightbulb",size:14})," ",d("workflowDesignerAI.suggestions","Suggestions:")]}),e.jsx("ul",{children:_.suggestions.map((j,k)=>e.jsx("li",{children:j},k))})]}),e.jsxs("details",{className:"nice-workflow-ai__json",children:[e.jsx("summary",{children:d("workflowDesignerAI.viewJsonDefinition","View JSON Definition")}),e.jsx("pre",{children:JSON.stringify(_.workflow,null,2)})]})]})}),e.jsx("style",{children:`
1506
1506
  .nice-workflow-ai {
1507
1507
  font-family: var(--nice-font-family, system-ui, sans-serif);
1508
1508
  }
@@ -1766,7 +1766,7 @@ Existing nodes: ${b.nodes.map(z=>z.label).join(", ")}`}],temperature:.6,maxToken
1766
1766
  color: var(--nice-error, #c62828);
1767
1767
  border-radius: var(--nice-radius-md, 6px);
1768
1768
  }
1769
- `})]}):e.jsx("div",{className:`nice-workflow-ai nice-workflow-ai--disabled ${c||""}`,style:m,children:e.jsx("p",{children:u("workflowDesignerAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function it({workflow:t}){const a=r=>({start:"play",end:"stop",task:"clipboard",userTask:"user",serviceTask:"settings",scriptTask:"file","gateway-exclusive":"hexagon","gateway-parallel":"plus","gateway-inclusive":"circle","event-timer":"clock","event-message":"mail","event-error":"warning"})[r]||"clipboard",i=r=>r==="start"?"var(--nice-success, #4caf50)":r==="end"?"var(--nice-danger, #f44336)":r.startsWith("gateway")?"var(--nice-warning, #ff9800)":r.startsWith("event")?"var(--nice-accent, #9c27b0)":"var(--nice-primary, #2196f3)";return e.jsxs("div",{className:"workflow-preview",children:[e.jsxs("div",{className:"workflow-preview__diagram",children:[t.nodes.map(r=>{var n,s;return e.jsxs("div",{className:`workflow-preview__node workflow-preview__node--${r.type.split("-")[0]}`,style:{left:(n=r.position)==null?void 0:n.x,top:(s=r.position)==null?void 0:s.y,borderColor:i(r.type)},children:[e.jsx("span",{className:"workflow-preview__node-icon",children:e.jsx(T.NiceIcon,{name:a(r.type),size:16})}),e.jsx("span",{className:"workflow-preview__node-label",children:r.label})]},r.id)}),e.jsxs("svg",{className:"workflow-preview__connections",children:[t.edges.map(r=>{const n=t.nodes.find(u=>u.id===r.source),s=t.nodes.find(u=>u.id===r.target);if(!(n!=null&&n.position)||!(s!=null&&s.position))return null;const o=n.position.x+Sa(n),c=n.position.y+20,m=s.position.x,p=s.position.y+20;return e.jsxs("g",{children:[e.jsx("line",{x1:o,y1:c,x2:m,y2:p,stroke:"var(--nice-text-secondary, #666)",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),r.label&&e.jsx("text",{x:(o+m)/2,y:(c+p)/2-5,fontSize:"10",fill:"var(--nice-text-secondary, #666)",textAnchor:"middle",children:r.label})]},r.id)}),e.jsx("defs",{children:e.jsx("marker",{id:"arrowhead",markerWidth:"10",markerHeight:"7",refX:"9",refY:"3.5",orient:"auto",children:e.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"var(--nice-text-secondary, #666)"})})})]})]}),t.lanes&&t.lanes.length>0&&e.jsxs("div",{className:"workflow-preview__lanes",children:[e.jsx("span",{className:"workflow-preview__lanes-title",children:"Swimlanes:"}),t.lanes.map(r=>e.jsx("span",{className:"workflow-preview__lane",children:r.name},r.id))]}),e.jsx("style",{children:`
1769
+ `})]}):e.jsx("div",{className:`nice-workflow-ai nice-workflow-ai--disabled ${c||""}`,style:m,children:e.jsx("p",{children:d("workflowDesignerAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function it({workflow:t}){const{t:a}=T.useNiceTranslation(),i=r=>({start:"play",end:"stop",task:"clipboard",userTask:"user",serviceTask:"settings",scriptTask:"file","gateway-exclusive":"hexagon","gateway-parallel":"plus","gateway-inclusive":"circle","event-timer":"clock","event-message":"mail","event-error":"warning"})[r]||"clipboard",n=r=>r==="start"?"var(--nice-success, #4caf50)":r==="end"?"var(--nice-danger, #f44336)":r.startsWith("gateway")?"var(--nice-warning, #ff9800)":r.startsWith("event")?"var(--nice-accent, #9c27b0)":"var(--nice-primary, #2196f3)";return e.jsxs("div",{className:"workflow-preview",children:[e.jsxs("div",{className:"workflow-preview__diagram",children:[t.nodes.map(r=>{var s,o;return e.jsxs("div",{className:`workflow-preview__node workflow-preview__node--${r.type.split("-")[0]}`,style:{left:(s=r.position)==null?void 0:s.x,top:(o=r.position)==null?void 0:o.y,borderColor:n(r.type)},children:[e.jsx("span",{className:"workflow-preview__node-icon",children:e.jsx(T.NiceIcon,{name:i(r.type),size:16})}),e.jsx("span",{className:"workflow-preview__node-label",children:r.label})]},r.id)}),e.jsxs("svg",{className:"workflow-preview__connections",children:[t.edges.map(r=>{const s=t.nodes.find(x=>x.id===r.source),o=t.nodes.find(x=>x.id===r.target);if(!(s!=null&&s.position)||!(o!=null&&o.position))return null;const c=s.position.x+Sa(s),m=s.position.y+20,p=o.position.x,d=o.position.y+20;return e.jsxs("g",{children:[e.jsx("line",{x1:c,y1:m,x2:p,y2:d,stroke:"var(--nice-text-secondary, #666)",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),r.label&&e.jsx("text",{x:(c+p)/2,y:(m+d)/2-5,fontSize:"10",fill:"var(--nice-text-secondary, #666)",textAnchor:"middle",children:r.label})]},r.id)}),e.jsx("defs",{children:e.jsx("marker",{id:"arrowhead",markerWidth:"10",markerHeight:"7",refX:"9",refY:"3.5",orient:"auto",children:e.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"var(--nice-text-secondary, #666)"})})})]})]}),t.lanes&&t.lanes.length>0&&e.jsxs("div",{className:"workflow-preview__lanes",children:[e.jsx("span",{className:"workflow-preview__lanes-title",children:a("workflowDesignerAI.swimlanes","Swimlanes:")}),t.lanes.map(r=>e.jsx("span",{className:"workflow-preview__lane",children:r.name},r.id))]}),e.jsx("style",{children:`
1770
1770
  .workflow-preview {
1771
1771
  min-height: 200px;
1772
1772
  }
@@ -1871,8 +1871,8 @@ Existing nodes: ${b.nodes.map(z=>z.label).join(", ")}`}],temperature:.6,maxToken
1871
1871
  border-radius: var(--nice-radius-sm, 4px);
1872
1872
  font-size: 12px;
1873
1873
  }
1874
- `})]})}function tt(t){const a={start:"bpmn:startEvent",end:"bpmn:endEvent",task:"bpmn:task",userTask:"bpmn:userTask",serviceTask:"bpmn:serviceTask",scriptTask:"bpmn:scriptTask","gateway-exclusive":"bpmn:exclusiveGateway","gateway-parallel":"bpmn:parallelGateway","gateway-inclusive":"bpmn:inclusiveGateway"},i=t.nodes.map(n=>` <${a[n.type]||"bpmn:task"} id="${n.id}" name="${be(n.label)}" />`).join(`
1875
- `),r=t.edges.map(n=>` <bpmn:sequenceFlow id="${n.id}" sourceRef="${n.source}" targetRef="${n.target}"${n.label?` name="${be(n.label)}"`:""} />`).join(`
1874
+ `})]})}function tt(t){const a={start:"bpmn:startEvent",end:"bpmn:endEvent",task:"bpmn:task",userTask:"bpmn:userTask",serviceTask:"bpmn:serviceTask",scriptTask:"bpmn:scriptTask","gateway-exclusive":"bpmn:exclusiveGateway","gateway-parallel":"bpmn:parallelGateway","gateway-inclusive":"bpmn:inclusiveGateway"},i=t.nodes.map(r=>` <${a[r.type]||"bpmn:task"} id="${r.id}" name="${be(r.label)}" />`).join(`
1875
+ `),n=t.edges.map(r=>` <bpmn:sequenceFlow id="${r.id}" sourceRef="${r.source}" targetRef="${r.target}"${r.label?` name="${be(r.label)}"`:""} />`).join(`
1876
1876
  `);return`<?xml version="1.0" encoding="UTF-8"?>
1877
1877
  <bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL"
1878
1878
  xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
@@ -1880,14 +1880,14 @@ Existing nodes: ${b.nodes.map(z=>z.label).join(", ")}`}],temperature:.6,maxToken
1880
1880
  targetNamespace="http://nice2dev.com/bpmn">
1881
1881
  <bpmn:process id="Process_${t.id}" name="${be(t.name)}" isExecutable="true">
1882
1882
  ${i}
1883
- ${r}
1883
+ ${n}
1884
1884
  </bpmn:process>
1885
- </bpmn:definitions>`}function be(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Ca(t={}){const{config:a,dataSources:i,context:r,onReportGenerated:n,onError:s}=t,o=ee(),[c,m]=l.useState(!1),[p,u]=l.useState(null),[v,w]=l.useState([]),A=l.useRef(null),R=a||(o==null?void 0:o.config),M=l.useCallback(async I=>{var h,_,f;if(!R){const k="AI not configured";return s==null||s(k),{error:k}}m(!0);const b=performance.now();(h=A.current)==null||h.abort(),A.current=new AbortController;try{const k=V(R),S=i?i.map(F=>`- ${F.name} (${F.id}): ${F.fields.join(", ")}`).join(`
1886
- `):void 0,N=ie(ge,{description:r?`${I}
1885
+ </bpmn:definitions>`}function be(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Ca(t={}){const{config:a,dataSources:i,context:n,onReportGenerated:r,onError:s}=t,o=Z(),[c,m]=l.useState(!1),[p,d]=l.useState(null),[x,N]=l.useState([]),A=l.useRef(null),R=a||(o==null?void 0:o.config),$=l.useCallback(async C=>{var h,w,f;if(!R){const j="AI not configured";return s==null||s(j),{error:j}}m(!0);const v=performance.now();(h=A.current)==null||h.abort(),A.current=new AbortController;try{const j=Y(R),k=i?i.map(F=>`- ${F.name} (${F.id}): ${F.fields.join(", ")}`).join(`
1886
+ `):void 0,I=ae(ge,{description:n?`${C}
1887
1887
 
1888
- Context: ${r}`:I,dataSources:S}),$=await k.chat({messages:[{role:"system",content:N.system},{role:"user",content:N.user}],temperature:.5,maxTokens:2048}),E=st($),z={layout:E||void 0,rawResponse:(f=(_=$.choices[0])==null?void 0:_.message)==null?void 0:f.content,latencyMs:performance.now()-b,error:E?void 0:"Failed to generate report layout",suggestions:ct(E)};return E&&(n==null||n(E)),u(z),w(F=>[...F.slice(-9),{request:I,result:z}]),z}catch(k){const S=k instanceof Error?k.message:"Report generation failed",N={error:S,latencyMs:performance.now()-b};return u(N),s==null||s(S),N}finally{m(!1)}},[R,i,r,n,s]),P=l.useCallback(async I=>{var b,h;if(!R)return[];m(!0);try{const S=(((h=(b=(await V(R).chat({messages:[{role:"system",content:"Given the existing report layout, suggest 2-3 additional sections that would enhance it. Return JSON array of sections with: id, type, title, order, config."},{role:"user",content:`Report: ${I.name}
1889
- Existing sections: ${I.sections.map(N=>N.type).join(", ")}`}],temperature:.6,maxTokens:1024})).choices[0])==null?void 0:b.message)==null?void 0:h.content)||"").match(/\[[\s\S]*\]/);if(S)return JSON.parse(S[0])}catch{}finally{m(!1)}return[]},[R]),g=l.useCallback(async I=>{var b,h;if(!R)return null;m(!0);try{return((h=(b=(await V(R).chat({messages:[{role:"system",content:"Generate a concise executive summary (2-3 paragraphs) based on the provided data. Highlight key metrics, trends, and actionable insights."},{role:"user",content:JSON.stringify(I,null,2)}],temperature:.5,maxTokens:512})).choices[0])==null?void 0:b.message)==null?void 0:h.content)||null}catch{return null}finally{m(!1)}},[R]),d=l.useCallback(async(I,b)=>{var h,_,f;if(!R)return"bar";try{const k=V(R),S=I.slice(0,5),$=(f=(_=(h=(await k.chat({messages:[{role:"system",content:"Based on the data sample and description, recommend the best chart type. Return only the chart type: line, bar, pie, donut, area, column, scatter, combo, gauge, or heatmap."},{role:"user",content:`Data: ${JSON.stringify(S)}
1890
- Purpose: ${b}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:h.message)==null?void 0:_.content)==null?void 0:f.toLowerCase().trim();return["line","bar","pie","donut","area","column","scatter","combo","gauge","heatmap"].find(z=>$==null?void 0:$.includes(z))||"bar"}catch{return"bar"}},[R]),j=l.useCallback(()=>{u(null)},[]),y=l.useCallback(()=>{var I;(I=A.current)==null||I.abort(),m(!1)},[]);return l.useEffect(()=>()=>{var I;(I=A.current)==null||I.abort()},[]),{generateReport:M,suggestSections:P,generateSummary:g,suggestChartType:d,loading:c,lastResult:p,history:v,clearResults:j,abort:y,isConfigured:!!R}}const rt=new Set(["header","summary","kpi","table","chart","text","image","divider","spacer","pageBreak","footer","toc","customBlock"]),nt={title:"header",subtitle:"text","kpi-card":"kpi",metric:"kpi","pivot-table":"table","page-break":"pageBreak","section-break":"divider",logo:"image"};function Ue(t){const a=typeof t=="string"?t:"";return nt[a]??(rt.has(a)?a:"customBlock")}function st(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.sections&&Array.isArray(c.sections)){const m=c.sections.flatMap(u=>Array.isArray(u.elements)&&!u.type?u.elements.map((v,w)=>({type:Ue(v.type),title:w===0?u.title:void 0,config:v.config??{}})):[{...u,type:Ue(u.type)}]);c.header&&!m.some(u=>u.type==="header")&&m.unshift({type:"header",title:"Header",config:c.header}),c.footer&&!m.some(u=>u.type==="footer")&&m.push({type:"footer",title:"Footer",config:c.footer});const p=m.map((u,v)=>({...u,id:u.id||`section_${v}`,order:u.order??v,config:u.config||{}}));return{id:c.id||`report_${Date.now()}`,name:c.name||c.title||"Generated Report",description:c.description,orientation:c.orientation||"portrait",pageSize:c.pageSize||"A4",margins:c.margins||{top:20,right:20,bottom:20,left:20},sections:p,dataSources:c.dataSources,parameters:c.parameters,styles:c.styles}}}catch{}return null}function ct(t){if(!t)return[];const a=[],i=new Set(t.sections.map(r=>r.type));return i.has("summary")||a.push("Add an executive summary for quick insights"),i.has("kpi")||a.push("Include KPI cards for key metrics"),i.has("chart")||a.push("Add visualizations to make data more accessible"),i.has("footer")||a.push("Add a footer with page numbers and date"),t.sections.length>5&&!i.has("toc")&&a.push("Consider adding a table of contents"),a.slice(0,3)}const ot=[{icon:"bar-chart",name:"Sales Report",prompt:"Monthly sales report with revenue KPIs, sales by region chart, and top products table"},{icon:"bar-chart",name:"Financial Summary",prompt:"Quarterly financial summary with P&L, cash flow chart, and expense breakdown"},{icon:"users",name:"HR Dashboard",prompt:"Employee report with headcount KPIs, department breakdown, and turnover trends"},{icon:"box",name:"Inventory Report",prompt:"Inventory status report with stock levels, low stock alerts, and turnover analysis"},{icon:"target",name:"KPI Dashboard",prompt:"Executive KPI dashboard with performance metrics, trends, and target comparison"}];function lt({config:t,dataSources:a,context:i,onGenerate:r,placeholder:n,showTemplates:s=!0,showPreview:o=!0,className:c,style:m,renderReport:p}){const{t:u}=T.useNiceTranslation(),v=n??u("reportBuilderAI.describeTheReport",'Describe the report you need... (e.g., "Monthly sales report with KPIs and charts")'),[w,A]=l.useState(""),R=l.useRef(null),{generateReport:M,loading:P,lastResult:g,isConfigured:d}=Ca({config:t,dataSources:a,context:i,onReportGenerated:r}),j=async()=>{!w.trim()||P||await M(w)},y=b=>{var h;A(b.prompt),(h=R.current)==null||h.focus()},I=()=>{if(!(g!=null&&g.layout))return;const b=JSON.stringify(g.layout,null,2),h=new Blob([b],{type:"application/json"}),_=URL.createObjectURL(h),f=document.createElement("a");f.href=_,f.download=`${g.layout.name.replace(/\s+/g,"_")}.json`,f.click(),URL.revokeObjectURL(_)};return d?e.jsxs("div",{className:`nice-report-ai ${c||""}`,style:m,children:[s&&e.jsx("div",{className:"nice-report-ai__templates",children:ot.map((b,h)=>e.jsxs("button",{type:"button",className:"nice-report-ai__template",onClick:()=>y(b),children:[e.jsx("span",{className:"nice-report-ai__template-icon",children:e.jsx(T.NiceIcon,{name:b.icon,size:24})}),e.jsx("span",{className:"nice-report-ai__template-name",children:b.name})]},h))}),e.jsxs("div",{className:"nice-report-ai__input-section",children:[e.jsx("textarea",{ref:R,value:w,onChange:b=>A(b.target.value),placeholder:v,className:"nice-report-ai__input",rows:3,disabled:P}),e.jsx("button",{type:"button",onClick:j,className:"nice-report-ai__submit",disabled:P||!w.trim(),children:P?e.jsx("span",{className:"nice-report-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"file",size:14})," ",u("reportBuilderAI.generateReport","Generate Report")]})})]}),a&&a.length>0&&e.jsxs("div",{className:"nice-report-ai__datasources",children:[e.jsx("span",{className:"nice-report-ai__datasources-label",children:"Available data:"}),a.map(b=>e.jsx("span",{className:"nice-report-ai__datasource",children:b.name},b.id))]}),g&&e.jsx("div",{className:"nice-report-ai__result",children:g.error?e.jsx("div",{className:"nice-report-ai__error",children:g.error}):g.layout&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-report-ai__result-header",children:[e.jsxs("div",{className:"nice-report-ai__report-info",children:[e.jsx("span",{className:"nice-report-ai__report-name",children:g.layout.name}),g.layout.description&&e.jsx("span",{className:"nice-report-ai__report-desc",children:g.layout.description})]}),e.jsxs("div",{className:"nice-report-ai__result-meta",children:[e.jsxs("span",{className:"nice-report-ai__stat",children:[g.layout.sections.length," sections"]}),e.jsxs("span",{className:"nice-report-ai__stat",children:[g.layout.pageSize," ",g.layout.orientation]}),g.latencyMs&&e.jsxs("span",{className:"nice-report-ai__latency",children:[Math.round(g.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-report-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>r==null?void 0:r(g.layout),children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",u("reportBuilderAI.useReport","Use Report")]}),e.jsxs("button",{type:"button",onClick:I,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," ",u("reportBuilderAI.exportJson","Export JSON")]})]}),e.jsxs("div",{className:"nice-report-ai__sections",children:[e.jsx("div",{className:"nice-report-ai__sections-title",children:"Report Structure:"}),e.jsx("div",{className:"nice-report-ai__sections-list",children:g.layout.sections.map((b,h)=>e.jsxs("div",{className:"nice-report-ai__section",children:[e.jsx("span",{className:"nice-report-ai__section-number",children:h+1}),e.jsx("span",{className:"nice-report-ai__section-icon",children:e.jsx(T.NiceIcon,{name:Ia(b.type),size:16})}),e.jsx("span",{className:"nice-report-ai__section-type",children:b.type}),b.title&&e.jsx("span",{className:"nice-report-ai__section-title",children:b.title})]},b.id))})]}),o&&e.jsx("div",{className:"nice-report-ai__preview",children:p?p(g.layout):e.jsx(dt,{layout:g.layout})}),g.suggestions&&g.suggestions.length>0&&e.jsxs("div",{className:"nice-report-ai__suggestions",children:[e.jsxs("span",{className:"nice-report-ai__suggestions-title",children:[e.jsx(T.NiceIcon,{name:"lightbulb",size:14})," Suggestions:"]}),e.jsx("ul",{children:g.suggestions.map((b,h)=>e.jsx("li",{children:b},h))})]}),e.jsxs("details",{className:"nice-report-ai__json",children:[e.jsx("summary",{children:u("reportBuilderAI.viewJsonDefinition","View JSON Definition")}),e.jsx("pre",{children:JSON.stringify(g.layout,null,2)})]})]})}),e.jsx("style",{children:`
1888
+ Context: ${n}`:C,dataSources:k}),z=await j.chat({messages:[{role:"system",content:I.system},{role:"user",content:I.user}],temperature:.5,maxTokens:2048}),E=st(z),P={layout:E||void 0,rawResponse:(f=(w=z.choices[0])==null?void 0:w.message)==null?void 0:f.content,latencyMs:performance.now()-v,error:E?void 0:"Failed to generate report layout",suggestions:ct(E)};return E&&(r==null||r(E)),d(P),N(F=>[...F.slice(-9),{request:C,result:P}]),P}catch(j){const k=j instanceof Error?j.message:"Report generation failed",I={error:k,latencyMs:performance.now()-v};return d(I),s==null||s(k),I}finally{m(!1)}},[R,i,n,r,s]),M=l.useCallback(async C=>{var v,h;if(!R)return[];m(!0);try{const k=(((h=(v=(await Y(R).chat({messages:[{role:"system",content:"Given the existing report layout, suggest 2-3 additional sections that would enhance it. Return JSON array of sections with: id, type, title, order, config."},{role:"user",content:`Report: ${C.name}
1889
+ Existing sections: ${C.sections.map(I=>I.type).join(", ")}`}],temperature:.6,maxTokens:1024})).choices[0])==null?void 0:v.message)==null?void 0:h.content)||"").match(/\[[\s\S]*\]/);if(k)return JSON.parse(k[0])}catch{}finally{m(!1)}return[]},[R]),g=l.useCallback(async C=>{var v,h;if(!R)return null;m(!0);try{return((h=(v=(await Y(R).chat({messages:[{role:"system",content:"Generate a concise executive summary (2-3 paragraphs) based on the provided data. Highlight key metrics, trends, and actionable insights."},{role:"user",content:JSON.stringify(C,null,2)}],temperature:.5,maxTokens:512})).choices[0])==null?void 0:v.message)==null?void 0:h.content)||null}catch{return null}finally{m(!1)}},[R]),u=l.useCallback(async(C,v)=>{var h,w,f;if(!R)return"bar";try{const j=Y(R),k=C.slice(0,5),z=(f=(w=(h=(await j.chat({messages:[{role:"system",content:"Based on the data sample and description, recommend the best chart type. Return only the chart type: line, bar, pie, donut, area, column, scatter, combo, gauge, or heatmap."},{role:"user",content:`Data: ${JSON.stringify(k)}
1890
+ Purpose: ${v}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:h.message)==null?void 0:w.content)==null?void 0:f.toLowerCase().trim();return["line","bar","pie","donut","area","column","scatter","combo","gauge","heatmap"].find(P=>z==null?void 0:z.includes(P))||"bar"}catch{return"bar"}},[R]),y=l.useCallback(()=>{d(null)},[]),_=l.useCallback(()=>{var C;(C=A.current)==null||C.abort(),m(!1)},[]);return l.useEffect(()=>()=>{var C;(C=A.current)==null||C.abort()},[]),{generateReport:$,suggestSections:M,generateSummary:g,suggestChartType:u,loading:c,lastResult:p,history:x,clearResults:y,abort:_,isConfigured:!!R}}const rt=new Set(["header","summary","kpi","table","chart","text","image","divider","spacer","pageBreak","footer","toc","customBlock"]),nt={title:"header",subtitle:"text","kpi-card":"kpi",metric:"kpi","pivot-table":"table","page-break":"pageBreak","section-break":"divider",logo:"image"};function Ue(t){const a=typeof t=="string"?t:"";return nt[a]??(rt.has(a)?a:"customBlock")}function st(t){var a,i,n;try{const r=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((n=(r.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,r])[1])==null?void 0:n.trim())||r,c=JSON.parse(o);if(c.sections&&Array.isArray(c.sections)){const m=c.sections.flatMap(d=>Array.isArray(d.elements)&&!d.type?d.elements.map((x,N)=>({type:Ue(x.type),title:N===0?d.title:void 0,config:x.config??{}})):[{...d,type:Ue(d.type)}]);c.header&&!m.some(d=>d.type==="header")&&m.unshift({type:"header",title:"Header",config:c.header}),c.footer&&!m.some(d=>d.type==="footer")&&m.push({type:"footer",title:"Footer",config:c.footer});const p=m.map((d,x)=>({...d,id:d.id||`section_${x}`,order:d.order??x,config:d.config||{}}));return{id:c.id||`report_${Date.now()}`,name:c.name||c.title||"Generated Report",description:c.description,orientation:c.orientation||"portrait",pageSize:c.pageSize||"A4",margins:c.margins||{top:20,right:20,bottom:20,left:20},sections:p,dataSources:c.dataSources,parameters:c.parameters,styles:c.styles}}}catch{}return null}function ct(t){if(!t)return[];const a=[],i=new Set(t.sections.map(n=>n.type));return i.has("summary")||a.push("Add an executive summary for quick insights"),i.has("kpi")||a.push("Include KPI cards for key metrics"),i.has("chart")||a.push("Add visualizations to make data more accessible"),i.has("footer")||a.push("Add a footer with page numbers and date"),t.sections.length>5&&!i.has("toc")&&a.push("Consider adding a table of contents"),a.slice(0,3)}const ot=[{icon:"bar-chart",name:"Sales Report",prompt:"Monthly sales report with revenue KPIs, sales by region chart, and top products table"},{icon:"bar-chart",name:"Financial Summary",prompt:"Quarterly financial summary with P&L, cash flow chart, and expense breakdown"},{icon:"users",name:"HR Dashboard",prompt:"Employee report with headcount KPIs, department breakdown, and turnover trends"},{icon:"box",name:"Inventory Report",prompt:"Inventory status report with stock levels, low stock alerts, and turnover analysis"},{icon:"target",name:"KPI Dashboard",prompt:"Executive KPI dashboard with performance metrics, trends, and target comparison"}];function lt({config:t,dataSources:a,context:i,onGenerate:n,placeholder:r,showTemplates:s=!0,showPreview:o=!0,className:c,style:m,renderReport:p}){const{t:d}=T.useNiceTranslation(),x=r??d("reportBuilderAI.describeTheReport",'Describe the report you need... (e.g., "Monthly sales report with KPIs and charts")'),[N,A]=l.useState(""),R=l.useRef(null),{generateReport:$,loading:M,lastResult:g,isConfigured:u}=Ca({config:t,dataSources:a,context:i,onReportGenerated:n}),y=async()=>{!N.trim()||M||await $(N)},_=v=>{var h;A(v.prompt),(h=R.current)==null||h.focus()},C=()=>{if(!(g!=null&&g.layout))return;const v=JSON.stringify(g.layout,null,2),h=new Blob([v],{type:"application/json"}),w=URL.createObjectURL(h),f=document.createElement("a");f.href=w,f.download=`${g.layout.name.replace(/\s+/g,"_")}.json`,f.click(),URL.revokeObjectURL(w)};return u?e.jsxs("div",{className:`nice-report-ai ${c||""}`,style:m,children:[s&&e.jsx("div",{className:"nice-report-ai__templates",children:ot.map((v,h)=>e.jsxs("button",{type:"button",className:"nice-report-ai__template",onClick:()=>_(v),children:[e.jsx("span",{className:"nice-report-ai__template-icon",children:e.jsx(T.NiceIcon,{name:v.icon,size:24})}),e.jsx("span",{className:"nice-report-ai__template-name",children:v.name})]},h))}),e.jsxs("div",{className:"nice-report-ai__input-section",children:[e.jsx("textarea",{ref:R,value:N,onChange:v=>A(v.target.value),placeholder:x,className:"nice-report-ai__input",rows:3,disabled:M}),e.jsx("button",{type:"button",onClick:y,className:"nice-report-ai__submit",disabled:M||!N.trim(),children:M?e.jsx("span",{className:"nice-report-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"file",size:14})," ",d("reportBuilderAI.generateReport","Generate Report")]})})]}),a&&a.length>0&&e.jsxs("div",{className:"nice-report-ai__datasources",children:[e.jsx("span",{className:"nice-report-ai__datasources-label",children:d("reportBuilderAI.availableData","Available data:")}),a.map(v=>e.jsx("span",{className:"nice-report-ai__datasource",children:v.name},v.id))]}),g&&e.jsx("div",{className:"nice-report-ai__result",children:g.error?e.jsx("div",{className:"nice-report-ai__error",children:g.error}):g.layout&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-report-ai__result-header",children:[e.jsxs("div",{className:"nice-report-ai__report-info",children:[e.jsx("span",{className:"nice-report-ai__report-name",children:g.layout.name}),g.layout.description&&e.jsx("span",{className:"nice-report-ai__report-desc",children:g.layout.description})]}),e.jsxs("div",{className:"nice-report-ai__result-meta",children:[e.jsx("span",{className:"nice-report-ai__stat",children:d("reportBuilderAI.sections","{sections} sections").replace("{sections}",String(g.layout.sections.length))}),e.jsxs("span",{className:"nice-report-ai__stat",children:[g.layout.pageSize," ",g.layout.orientation]}),g.latencyMs&&e.jsxs("span",{className:"nice-report-ai__latency",children:[Math.round(g.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-report-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>n==null?void 0:n(g.layout),children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",d("reportBuilderAI.useReport","Use Report")]}),e.jsxs("button",{type:"button",onClick:C,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," ",d("reportBuilderAI.exportJson","Export JSON")]})]}),e.jsxs("div",{className:"nice-report-ai__sections",children:[e.jsx("div",{className:"nice-report-ai__sections-title",children:d("reportBuilderAI.reportStructure","Report Structure:")}),e.jsx("div",{className:"nice-report-ai__sections-list",children:g.layout.sections.map((v,h)=>e.jsxs("div",{className:"nice-report-ai__section",children:[e.jsx("span",{className:"nice-report-ai__section-number",children:h+1}),e.jsx("span",{className:"nice-report-ai__section-icon",children:e.jsx(T.NiceIcon,{name:Ia(v.type),size:16})}),e.jsx("span",{className:"nice-report-ai__section-type",children:v.type}),v.title&&e.jsx("span",{className:"nice-report-ai__section-title",children:v.title})]},v.id))})]}),o&&e.jsx("div",{className:"nice-report-ai__preview",children:p?p(g.layout):e.jsx(dt,{layout:g.layout})}),g.suggestions&&g.suggestions.length>0&&e.jsxs("div",{className:"nice-report-ai__suggestions",children:[e.jsxs("span",{className:"nice-report-ai__suggestions-title",children:[e.jsx(T.NiceIcon,{name:"lightbulb",size:14})," ",d("reportBuilderAI.suggestions","Suggestions:")]}),e.jsx("ul",{children:g.suggestions.map((v,h)=>e.jsx("li",{children:v},h))})]}),e.jsxs("details",{className:"nice-report-ai__json",children:[e.jsx("summary",{children:d("reportBuilderAI.viewJsonDefinition","View JSON Definition")}),e.jsx("pre",{children:JSON.stringify(g.layout,null,2)})]})]})}),e.jsx("style",{children:`
1891
1891
  .nice-report-ai {
1892
1892
  font-family: var(--nice-font-family, system-ui, sans-serif);
1893
1893
  }
@@ -2199,7 +2199,7 @@ Purpose: ${b}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:h.messa
2199
2199
  color: var(--nice-error, #c62828);
2200
2200
  border-radius: var(--nice-radius-md, 6px);
2201
2201
  }
2202
- `})]}):e.jsx("div",{className:`nice-report-ai nice-report-ai--disabled ${c||""}`,style:m,children:e.jsx("p",{children:u("reportBuilderAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function Ia(t){return{header:"file",summary:"edit",kpi:"bar-chart",table:"clipboard",chart:"bar-chart",text:"file",image:"image",divider:"minus",spacer:"square",pageBreak:"file",footer:"file",toc:"book",customBlock:"puzzle"}[t]||"file"}function dt({layout:t}){return e.jsxs("div",{className:"report-preview",style:{aspectRatio:t.orientation==="landscape"?"1.414":"0.707",maxWidth:t.orientation==="landscape"?"100%":"60%"},children:[e.jsx("div",{className:"report-preview__paper",children:t.sections.map(a=>e.jsxs("div",{className:`report-preview__section report-preview__section--${a.type}`,children:[e.jsx("span",{className:"report-preview__section-icon",children:e.jsx(T.NiceIcon,{name:Ia(a.type),size:14})}),e.jsx("span",{className:"report-preview__section-label",children:a.title||a.type})]},a.id))}),e.jsx("style",{children:`
2202
+ `})]}):e.jsx("div",{className:`nice-report-ai nice-report-ai--disabled ${c||""}`,style:m,children:e.jsx("p",{children:d("reportBuilderAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function Ia(t){return{header:"file",summary:"edit",kpi:"bar-chart",table:"clipboard",chart:"bar-chart",text:"file",image:"image",divider:"minus",spacer:"square",pageBreak:"file",footer:"file",toc:"book",customBlock:"puzzle"}[t]||"file"}function dt({layout:t}){return e.jsxs("div",{className:"report-preview",style:{aspectRatio:t.orientation==="landscape"?"1.414":"0.707",maxWidth:t.orientation==="landscape"?"100%":"60%"},children:[e.jsx("div",{className:"report-preview__paper",children:t.sections.map(a=>e.jsxs("div",{className:`report-preview__section report-preview__section--${a.type}`,children:[e.jsx("span",{className:"report-preview__section-icon",children:e.jsx(T.NiceIcon,{name:Ia(a.type),size:14})}),e.jsx("span",{className:"report-preview__section-label",children:a.title||a.type})]},a.id))}),e.jsx("style",{children:`
2203
2203
  .report-preview {
2204
2204
  display: flex;
2205
2205
  justify-content: center;
@@ -2294,19 +2294,19 @@ Return only JSON: ${a?'{ "light": THEME, "dark": THEME }, the dark one with "mod
2294
2294
  },
2295
2295
  "typography": { "fontFamily": "...", "fontFamilyMono": "..." },
2296
2296
  "borderRadius": { "sm": "4px", "md": "8px", "lg": "12px" }
2297
- }`,user:t}}function Aa(t={}){const{config:a,generateDarkMode:i=!0,onThemeGenerated:r,onError:n}=t,s=ee(),[o,c]=l.useState(!1),[m,p]=l.useState(null),u=l.useRef(null),v=a||(s==null?void 0:s.config),w=l.useCallback(async d=>{var y,I,b,h;if(!v){const _="AI not configured";return n==null||n(_),{error:_}}c(!0);const j=performance.now();(y=u.current)==null||y.abort(),u.current=new AbortController;try{const _=V(v);let f="";switch(d.type){case"description":f=d.value;break;case"brand":f=`Create a theme for "${d.value.name}"${d.value.industry?` in the ${d.value.industry} industry`:""}${(I=d.value.keywords)!=null&&I.length?`. Keywords: ${d.value.keywords.join(", ")}`:""}`;break;case"colors":f=`Create a theme based on primary color ${d.value.primary}${d.value.secondary?` and secondary color ${d.value.secondary}`:""}`;break;case"image":f="Extract colors and create a theme from the provided image palette";break}const k=ut(f,i),S=await _.chat({messages:[{role:"system",content:k.system},{role:"user",content:k.user}],temperature:.6,maxTokens:2048}),N=We(S),$={theme:N.light||void 0,darkTheme:N.dark||void 0,rawResponse:(h=(b=S.choices[0])==null?void 0:b.message)==null?void 0:h.content,latencyMs:performance.now()-j,error:N.light?void 0:"Failed to generate theme",suggestions:mt(N.light)};return N.light&&(r==null||r(N.light,N.dark??void 0)),p($),$}catch(_){const f=_ instanceof Error?_.message:"Theme generation failed",k={error:f,latencyMs:performance.now()-j};return p(k),n==null||n(f),k}finally{c(!1)}},[v,i,r,n]),A=l.useCallback(async(d,j)=>{if(!v)return null;c(!0);try{const I=await V(v).chat({messages:[{role:"system",content:"Adjust the theme based on the user's request. Return the complete adjusted theme in JSON format."},{role:"user",content:`Current theme:
2298
- ${JSON.stringify(d,null,2)}
2299
-
2300
- Adjustments: ${j}`}],temperature:.4,maxTokens:2048});return We(I).light||null}catch{return null}finally{c(!1)}},[v]),R=l.useCallback(d=>{const j=[];return j.push(" /* Colors */"),Object.entries(d.colors).forEach(([y,I])=>{j.push(` --nice-${ve(y)}: ${I};`)}),j.push(`
2301
- /* Typography */`),Object.entries(d.typography).forEach(([y,I])=>{j.push(` --nice-${ve(y)}: ${I};`)}),j.push(`
2302
- /* Spacing */`),Object.entries(d.spacing).forEach(([y,I])=>{j.push(` --nice-spacing-${y}: ${I};`)}),j.push(`
2303
- /* Border Radius */`),Object.entries(d.borderRadius).forEach(([y,I])=>{j.push(` --nice-radius-${y}: ${I};`)}),j.push(`
2304
- /* Shadows */`),Object.entries(d.shadows).forEach(([y,I])=>{j.push(` --nice-shadow-${y}: ${I};`)}),j.push(`
2305
- /* Animations */`),Object.entries(d.animations).forEach(([y,I])=>{j.push(` --nice-${ve(y)}: ${I};`)}),`:root {
2306
- ${j.join(`
2297
+ }`,user:t}}function Aa(t={}){const{config:a,generateDarkMode:i=!0,onThemeGenerated:n,onError:r}=t,s=Z(),[o,c]=l.useState(!1),[m,p]=l.useState(null),d=l.useRef(null),x=a||(s==null?void 0:s.config),N=l.useCallback(async u=>{var _,C,v,h;if(!x){const w="AI not configured";return r==null||r(w),{error:w}}c(!0);const y=performance.now();(_=d.current)==null||_.abort(),d.current=new AbortController;try{const w=Y(x);let f="";switch(u.type){case"description":f=u.value;break;case"brand":f=`Create a theme for "${u.value.name}"${u.value.industry?` in the ${u.value.industry} industry`:""}${(C=u.value.keywords)!=null&&C.length?`. Keywords: ${u.value.keywords.join(", ")}`:""}`;break;case"colors":f=`Create a theme based on primary color ${u.value.primary}${u.value.secondary?` and secondary color ${u.value.secondary}`:""}`;break;case"image":f="Extract colors and create a theme from the provided image palette";break}const j=ut(f,i),k=await w.chat({messages:[{role:"system",content:j.system},{role:"user",content:j.user}],temperature:.6,maxTokens:2048}),I=We(k),z={theme:I.light||void 0,darkTheme:I.dark||void 0,rawResponse:(h=(v=k.choices[0])==null?void 0:v.message)==null?void 0:h.content,latencyMs:performance.now()-y,error:I.light?void 0:"Failed to generate theme",suggestions:mt(I.light)};return I.light&&(n==null||n(I.light,I.dark??void 0)),p(z),z}catch(w){const f=w instanceof Error?w.message:"Theme generation failed",j={error:f,latencyMs:performance.now()-y};return p(j),r==null||r(f),j}finally{c(!1)}},[x,i,n,r]),A=l.useCallback(async(u,y)=>{if(!x)return null;c(!0);try{const C=await Y(x).chat({messages:[{role:"system",content:"Adjust the theme based on the user's request. Return the complete adjusted theme in JSON format."},{role:"user",content:`Current theme:
2298
+ ${JSON.stringify(u,null,2)}
2299
+
2300
+ Adjustments: ${y}`}],temperature:.4,maxTokens:2048});return We(C).light||null}catch{return null}finally{c(!1)}},[x]),R=l.useCallback(u=>{const y=[];return y.push(" /* Colors */"),Object.entries(u.colors).forEach(([_,C])=>{y.push(` --nice-${ve(_)}: ${C};`)}),y.push(`
2301
+ /* Typography */`),Object.entries(u.typography).forEach(([_,C])=>{y.push(` --nice-${ve(_)}: ${C};`)}),y.push(`
2302
+ /* Spacing */`),Object.entries(u.spacing).forEach(([_,C])=>{y.push(` --nice-spacing-${_}: ${C};`)}),y.push(`
2303
+ /* Border Radius */`),Object.entries(u.borderRadius).forEach(([_,C])=>{y.push(` --nice-radius-${_}: ${C};`)}),y.push(`
2304
+ /* Shadows */`),Object.entries(u.shadows).forEach(([_,C])=>{y.push(` --nice-shadow-${_}: ${C};`)}),y.push(`
2305
+ /* Animations */`),Object.entries(u.animations).forEach(([_,C])=>{y.push(` --nice-${ve(_)}: ${C};`)}),`:root {
2306
+ ${y.join(`
2307
2307
  `)}
2308
- }`},[]),M=l.useCallback(d=>{const j={theme:{extend:{colors:{primary:{DEFAULT:d.colors.primary,light:d.colors.primaryLight,dark:d.colors.primaryDark},secondary:{DEFAULT:d.colors.secondary,light:d.colors.secondaryLight,dark:d.colors.secondaryDark},accent:d.colors.accent,success:d.colors.success,warning:d.colors.warning,error:d.colors.error,info:d.colors.info},fontFamily:{sans:[d.typography.fontFamily],mono:[d.typography.fontFamilyMono]},borderRadius:d.borderRadius,boxShadow:d.shadows}}};return`// tailwind.config.js
2309
- module.exports = ${JSON.stringify(j,null,2)}`},[]),P=l.useCallback(()=>{p(null)},[]),g=l.useCallback(()=>{var d;(d=u.current)==null||d.abort(),c(!1)},[]);return l.useEffect(()=>()=>{var d;(d=u.current)==null||d.abort()},[]),{generateTheme:w,adjustTheme:A,toCSSVariables:R,toTailwindConfig:M,loading:o,lastResult:m,clearResults:P,abort:g,isConfigured:!!v}}function We(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.light||c.theme)return{light:ye(c.light||c.theme),dark:c.dark?ye(c.dark):null};if(c.colors)return{light:ye(c),dark:null}}catch{}return{light:null,dark:null}}function ye(t){return{id:t.id||`theme_${Date.now()}`,name:t.name||"Generated Theme",description:t.description,mode:t.mode||"light",colors:{primary:"#0066cc",primaryLight:"#4d94db",primaryDark:"#004499",secondary:"#6c757d",secondaryLight:"#9ca3af",secondaryDark:"#4b5563",accent:"#ff6b35",background:"#ffffff",surface:"#f8f9fa",text:"#212529",textMuted:"#6c757d",textInverse:"#ffffff",border:"#dee2e6",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",...t.colors},typography:{fontFamily:"system-ui, -apple-system, sans-serif",fontFamilyMono:"ui-monospace, monospace",fontSizeBase:"16px",fontSizeXs:"12px",fontSizeSm:"14px",fontSizeMd:"16px",fontSizeLg:"18px",fontSizeXl:"20px",fontSize2xl:"24px",fontSize3xl:"30px",fontWeightLight:300,fontWeightNormal:400,fontWeightMedium:500,fontWeightSemibold:600,fontWeightBold:700,lineHeightTight:1.25,lineHeightNormal:1.5,lineHeightRelaxed:1.75,letterSpacing:"normal",...t.typography},spacing:{xs:"4px",sm:"8px",md:"16px",lg:"24px",xl:"32px","2xl":"48px","3xl":"64px","4xl":"80px",...t.spacing},borderRadius:{none:"0",sm:"4px",md:"8px",lg:"12px",xl:"16px",full:"9999px",...t.borderRadius},shadows:{none:"none",sm:"0 1px 2px rgba(0, 0, 0, 0.05)",md:"0 4px 6px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px rgba(0, 0, 0, 0.1)",xl:"0 20px 25px rgba(0, 0, 0, 0.1)",...t.shadows},animations:{durationFast:"150ms",durationNormal:"300ms",durationSlow:"500ms",easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)",...t.animations},components:t.components,cssVariables:t.cssVariables}}function mt(t){if(!t)return[];const a=[];return a.push("Verify WCAG contrast ratios for text on background"),a.push("Test the theme in both light and dark environments"),a.push("Ensure button and input styles are consistent"),a.slice(0,3)}function ve(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}const pt=[{icon:"building",name:"Corporate",prompt:"Professional corporate theme with blue and gray tones"},{icon:"palette",name:"Creative",prompt:"Vibrant creative agency theme with bold colors"},{icon:"tree",name:"Natural",prompt:"Organic natural theme with earth tones and greens"},{icon:"moon",name:"Dark Pro",prompt:"Modern dark theme for developer tools"},{icon:"gift",name:"Playful",prompt:"Fun playful theme with candy colors for kids"},{icon:"star",name:"Luxury",prompt:"Elegant luxury brand theme with gold accents"}];function gt({config:t,generateDarkMode:a=!0,onGenerate:i,showPresets:r=!0,showPreview:n=!0,className:s,style:o}){const{t:c}=T.useNiceTranslation(),[m,p]=l.useState("description"),[u,v]=l.useState(""),[w,A]=l.useState(""),[R,M]=l.useState(""),[P,g]=l.useState("#0066cc"),[d,j]=l.useState("light"),{generateTheme:y,toCSSVariables:I,toTailwindConfig:b,loading:h,lastResult:_,isConfigured:f}=Aa({config:t,generateDarkMode:a,onThemeGenerated:i}),k=async()=>{if(h)return;let z;switch(m){case"brand":if(!w.trim())return;z={type:"brand",value:{name:w,industry:R||void 0}};break;case"colors":z={type:"colors",value:{primary:P}};break;default:if(!u.trim())return;z={type:"description",value:u}}await y(z)},S=z=>{p("description"),v(z.prompt)},N=()=>{if(!(_!=null&&_.theme))return;const z=I(_.theme),F=new Blob([z],{type:"text/css"}),U=URL.createObjectURL(F),H=document.createElement("a");H.href=U,H.download=`${_.theme.name.replace(/\s+/g,"-").toLowerCase()}.css`,H.click(),URL.revokeObjectURL(U)},$=()=>{if(!(_!=null&&_.theme))return;const z=b(_.theme),F=new Blob([z],{type:"text/javascript"}),U=URL.createObjectURL(F),H=document.createElement("a");H.href=U,H.download="tailwind.config.js",H.click(),URL.revokeObjectURL(U)},E=d==="dark"&&(_!=null&&_.darkTheme)?_.darkTheme:_==null?void 0:_.theme;return f?e.jsxs("div",{className:`nice-theme-ai ${s||""}`,style:o,children:[r&&e.jsx("div",{className:"nice-theme-ai__presets",children:pt.map((z,F)=>e.jsxs("button",{type:"button",className:"nice-theme-ai__preset",onClick:()=>S(z),children:[e.jsx("span",{className:"nice-theme-ai__preset-icon",children:e.jsx(T.NiceIcon,{name:z.icon,size:24})}),e.jsx("span",{className:"nice-theme-ai__preset-name",children:z.name})]},F))}),e.jsxs("div",{className:"nice-theme-ai__tabs",children:[e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${m==="description"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("description"),children:[e.jsx(T.NiceIcon,{name:"edit",size:14})," ",c("themeGeneratorAI.description","Description")]}),e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${m==="brand"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("brand"),children:[e.jsx(T.NiceIcon,{name:"tag",size:14})," ",c("themeGeneratorAI.brand","Brand")]}),e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${m==="colors"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("colors"),children:[e.jsx(T.NiceIcon,{name:"palette",size:14})," ",c("themeGeneratorAI.colors","Colors")]})]}),e.jsxs("div",{className:"nice-theme-ai__input-section",children:[m==="description"&&e.jsx("textarea",{value:u,onChange:z=>v(z.target.value),placeholder:c("themeGeneratorAI.describeTheThemeYouWant","Describe the theme you want... (e.g., 'Modern tech startup with blue and green')"),className:"nice-theme-ai__textarea",rows:3,disabled:h}),m==="brand"&&e.jsxs("div",{className:"nice-theme-ai__brand-inputs",children:[e.jsx("input",{type:"text",value:w,onChange:z=>A(z.target.value),placeholder:c("themeGeneratorAI.brandName","Brand name"),className:"nice-theme-ai__input",disabled:h}),e.jsx("input",{type:"text",value:R,onChange:z=>M(z.target.value),placeholder:c("themeGeneratorAI.industryOptional","Industry (optional)"),className:"nice-theme-ai__input",disabled:h})]}),m==="colors"&&e.jsx("div",{className:"nice-theme-ai__color-input",children:e.jsxs("label",{children:["Primary Color:",e.jsx("input",{type:"color",value:P,onChange:z=>g(z.target.value),className:"nice-theme-ai__color-picker",disabled:h}),e.jsx("span",{className:"nice-theme-ai__color-value",children:P})]})}),e.jsx("button",{type:"button",onClick:k,className:"nice-theme-ai__submit",disabled:h,children:h?e.jsx("span",{className:"nice-theme-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"wand",size:14})," ",c("themeGeneratorAI.generateTheme","Generate Theme")]})})]}),(_==null?void 0:_.error)&&e.jsx("div",{className:"nice-theme-ai__error",role:"alert",children:_.error}),_&&E&&e.jsxs("div",{className:"nice-theme-ai__result",children:[e.jsxs("div",{className:"nice-theme-ai__result-header",children:[e.jsxs("div",{className:"nice-theme-ai__theme-info",children:[e.jsx("span",{className:"nice-theme-ai__theme-name",children:E.name}),E.description&&e.jsx("span",{className:"nice-theme-ai__theme-desc",children:E.description})]}),e.jsxs("div",{className:"nice-theme-ai__actions",children:[_.darkTheme&&e.jsxs("div",{className:"nice-theme-ai__mode-toggle",children:[e.jsx("button",{type:"button","aria-label":c("themeGeneratorAI.lightMode","Light mode"),className:d==="light"?"active":"",onClick:()=>j("light"),children:e.jsx(T.NiceIcon,{name:"sun",size:16})}),e.jsx("button",{type:"button","aria-label":c("themeGeneratorAI.darkMode","Dark mode"),className:d==="dark"?"active":"",onClick:()=>j("dark"),children:e.jsx(T.NiceIcon,{name:"moon",size:16})})]}),e.jsxs("button",{type:"button",onClick:N,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:$,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," ",c("themeGeneratorAI.tailwind","Tailwind")]})]})]}),n&&e.jsx(ht,{theme:E}),e.jsxs("div",{className:"nice-theme-ai__palette",children:[e.jsx("div",{className:"nice-theme-ai__palette-title",children:c("themeGeneratorAI.colorPalette","Color Palette")}),e.jsx("div",{className:"nice-theme-ai__colors",children:Object.entries(E.colors).map(([z,F])=>e.jsxs("div",{className:"nice-theme-ai__color",children:[e.jsx("div",{className:"nice-theme-ai__color-swatch",style:{backgroundColor:F}}),e.jsx("span",{className:"nice-theme-ai__color-name",children:z}),e.jsx("span",{className:"nice-theme-ai__color-hex",children:F})]},z))})]}),e.jsxs("div",{className:"nice-theme-ai__typography",children:[e.jsx("div",{className:"nice-theme-ai__typography-title",children:c("themeGeneratorAI.typography","Typography")}),e.jsxs("div",{style:{fontFamily:E.typography.fontFamily},children:[e.jsx("p",{style:{fontSize:E.typography.fontSize3xl,fontWeight:E.typography.fontWeightBold},children:c("themeGeneratorAI.heading1","Heading 1")}),e.jsx("p",{style:{fontSize:E.typography.fontSizeLg},children:"Body text: The quick brown fox jumps over the lazy dog."}),e.jsx("p",{style:{fontFamily:E.typography.fontFamilyMono,fontSize:E.typography.fontSizeSm},children:'const code = "Monospace font"'})]})]})]}),e.jsx("style",{children:`
2308
+ }`},[]),$=l.useCallback(u=>{const y={theme:{extend:{colors:{primary:{DEFAULT:u.colors.primary,light:u.colors.primaryLight,dark:u.colors.primaryDark},secondary:{DEFAULT:u.colors.secondary,light:u.colors.secondaryLight,dark:u.colors.secondaryDark},accent:u.colors.accent,success:u.colors.success,warning:u.colors.warning,error:u.colors.error,info:u.colors.info},fontFamily:{sans:[u.typography.fontFamily],mono:[u.typography.fontFamilyMono]},borderRadius:u.borderRadius,boxShadow:u.shadows}}};return`// tailwind.config.js
2309
+ module.exports = ${JSON.stringify(y,null,2)}`},[]),M=l.useCallback(()=>{p(null)},[]),g=l.useCallback(()=>{var u;(u=d.current)==null||u.abort(),c(!1)},[]);return l.useEffect(()=>()=>{var u;(u=d.current)==null||u.abort()},[]),{generateTheme:N,adjustTheme:A,toCSSVariables:R,toTailwindConfig:$,loading:o,lastResult:m,clearResults:M,abort:g,isConfigured:!!x}}function We(t){var a,i,n;try{const r=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((n=(r.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,r])[1])==null?void 0:n.trim())||r,c=JSON.parse(o);if(c.light||c.theme)return{light:ye(c.light||c.theme),dark:c.dark?ye(c.dark):null};if(c.colors)return{light:ye(c),dark:null}}catch{}return{light:null,dark:null}}function ye(t){return{id:t.id||`theme_${Date.now()}`,name:t.name||"Generated Theme",description:t.description,mode:t.mode||"light",colors:{primary:"#0066cc",primaryLight:"#4d94db",primaryDark:"#004499",secondary:"#6c757d",secondaryLight:"#9ca3af",secondaryDark:"#4b5563",accent:"#ff6b35",background:"#ffffff",surface:"#f8f9fa",text:"#212529",textMuted:"#6c757d",textInverse:"#ffffff",border:"#dee2e6",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",...t.colors},typography:{fontFamily:"system-ui, -apple-system, sans-serif",fontFamilyMono:"ui-monospace, monospace",fontSizeBase:"16px",fontSizeXs:"12px",fontSizeSm:"14px",fontSizeMd:"16px",fontSizeLg:"18px",fontSizeXl:"20px",fontSize2xl:"24px",fontSize3xl:"30px",fontWeightLight:300,fontWeightNormal:400,fontWeightMedium:500,fontWeightSemibold:600,fontWeightBold:700,lineHeightTight:1.25,lineHeightNormal:1.5,lineHeightRelaxed:1.75,letterSpacing:"normal",...t.typography},spacing:{xs:"4px",sm:"8px",md:"16px",lg:"24px",xl:"32px","2xl":"48px","3xl":"64px","4xl":"80px",...t.spacing},borderRadius:{none:"0",sm:"4px",md:"8px",lg:"12px",xl:"16px",full:"9999px",...t.borderRadius},shadows:{none:"none",sm:"0 1px 2px rgba(0, 0, 0, 0.05)",md:"0 4px 6px rgba(0, 0, 0, 0.1)",lg:"0 10px 15px rgba(0, 0, 0, 0.1)",xl:"0 20px 25px rgba(0, 0, 0, 0.1)",...t.shadows},animations:{durationFast:"150ms",durationNormal:"300ms",durationSlow:"500ms",easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)",...t.animations},components:t.components,cssVariables:t.cssVariables}}function mt(t){if(!t)return[];const a=[];return a.push("Verify WCAG contrast ratios for text on background"),a.push("Test the theme in both light and dark environments"),a.push("Ensure button and input styles are consistent"),a.slice(0,3)}function ve(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}const pt=[{icon:"building",name:"Corporate",prompt:"Professional corporate theme with blue and gray tones"},{icon:"palette",name:"Creative",prompt:"Vibrant creative agency theme with bold colors"},{icon:"tree",name:"Natural",prompt:"Organic natural theme with earth tones and greens"},{icon:"moon",name:"Dark Pro",prompt:"Modern dark theme for developer tools"},{icon:"gift",name:"Playful",prompt:"Fun playful theme with candy colors for kids"},{icon:"star",name:"Luxury",prompt:"Elegant luxury brand theme with gold accents"}];function gt({config:t,generateDarkMode:a=!0,onGenerate:i,showPresets:n=!0,showPreview:r=!0,className:s,style:o}){const{t:c}=T.useNiceTranslation(),[m,p]=l.useState("description"),[d,x]=l.useState(""),[N,A]=l.useState(""),[R,$]=l.useState(""),[M,g]=l.useState("#0066cc"),[u,y]=l.useState("light"),{generateTheme:_,toCSSVariables:C,toTailwindConfig:v,loading:h,lastResult:w,isConfigured:f}=Aa({config:t,generateDarkMode:a,onThemeGenerated:i}),j=async()=>{if(h)return;let P;switch(m){case"brand":if(!N.trim())return;P={type:"brand",value:{name:N,industry:R||void 0}};break;case"colors":P={type:"colors",value:{primary:M}};break;default:if(!d.trim())return;P={type:"description",value:d}}await _(P)},k=P=>{p("description"),x(P.prompt)},I=()=>{if(!(w!=null&&w.theme))return;const P=C(w.theme),F=new Blob([P],{type:"text/css"}),G=URL.createObjectURL(F),K=document.createElement("a");K.href=G,K.download=`${w.theme.name.replace(/\s+/g,"-").toLowerCase()}.css`,K.click(),URL.revokeObjectURL(G)},z=()=>{if(!(w!=null&&w.theme))return;const P=v(w.theme),F=new Blob([P],{type:"text/javascript"}),G=URL.createObjectURL(F),K=document.createElement("a");K.href=G,K.download="tailwind.config.js",K.click(),URL.revokeObjectURL(G)},E=u==="dark"&&(w!=null&&w.darkTheme)?w.darkTheme:w==null?void 0:w.theme;return f?e.jsxs("div",{className:`nice-theme-ai ${s||""}`,style:o,children:[n&&e.jsx("div",{className:"nice-theme-ai__presets",children:pt.map((P,F)=>e.jsxs("button",{type:"button",className:"nice-theme-ai__preset",onClick:()=>k(P),children:[e.jsx("span",{className:"nice-theme-ai__preset-icon",children:e.jsx(T.NiceIcon,{name:P.icon,size:24})}),e.jsx("span",{className:"nice-theme-ai__preset-name",children:P.name})]},F))}),e.jsxs("div",{className:"nice-theme-ai__tabs",children:[e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${m==="description"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("description"),children:[e.jsx(T.NiceIcon,{name:"edit",size:14})," ",c("themeGeneratorAI.description","Description")]}),e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${m==="brand"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("brand"),children:[e.jsx(T.NiceIcon,{name:"tag",size:14})," ",c("themeGeneratorAI.brand","Brand")]}),e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${m==="colors"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("colors"),children:[e.jsx(T.NiceIcon,{name:"palette",size:14})," ",c("themeGeneratorAI.colors","Colors")]})]}),e.jsxs("div",{className:"nice-theme-ai__input-section",children:[m==="description"&&e.jsx("textarea",{value:d,onChange:P=>x(P.target.value),placeholder:c("themeGeneratorAI.describeTheThemeYouWant","Describe the theme you want... (e.g., 'Modern tech startup with blue and green')"),className:"nice-theme-ai__textarea",rows:3,disabled:h}),m==="brand"&&e.jsxs("div",{className:"nice-theme-ai__brand-inputs",children:[e.jsx("input",{type:"text",value:N,onChange:P=>A(P.target.value),placeholder:c("themeGeneratorAI.brandName","Brand name"),className:"nice-theme-ai__input",disabled:h}),e.jsx("input",{type:"text",value:R,onChange:P=>$(P.target.value),placeholder:c("themeGeneratorAI.industryOptional","Industry (optional)"),className:"nice-theme-ai__input",disabled:h})]}),m==="colors"&&e.jsx("div",{className:"nice-theme-ai__color-input",children:e.jsxs("label",{children:[c("themeGeneratorAI.primaryColor","Primary Color:"),e.jsx("input",{type:"color",value:M,onChange:P=>g(P.target.value),className:"nice-theme-ai__color-picker",disabled:h}),e.jsx("span",{className:"nice-theme-ai__color-value",children:M})]})}),e.jsx("button",{type:"button",onClick:j,className:"nice-theme-ai__submit",disabled:h,children:h?e.jsx("span",{className:"nice-theme-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"wand",size:14})," ",c("themeGeneratorAI.generateTheme","Generate Theme")]})})]}),(w==null?void 0:w.error)&&e.jsx("div",{className:"nice-theme-ai__error",role:"alert",children:w.error}),w&&E&&e.jsxs("div",{className:"nice-theme-ai__result",children:[e.jsxs("div",{className:"nice-theme-ai__result-header",children:[e.jsxs("div",{className:"nice-theme-ai__theme-info",children:[e.jsx("span",{className:"nice-theme-ai__theme-name",children:E.name}),E.description&&e.jsx("span",{className:"nice-theme-ai__theme-desc",children:E.description})]}),e.jsxs("div",{className:"nice-theme-ai__actions",children:[w.darkTheme&&e.jsxs("div",{className:"nice-theme-ai__mode-toggle",children:[e.jsx("button",{type:"button","aria-label":c("themeGeneratorAI.lightMode","Light mode"),className:u==="light"?"active":"",onClick:()=>y("light"),children:e.jsx(T.NiceIcon,{name:"sun",size:16})}),e.jsx("button",{type:"button","aria-label":c("themeGeneratorAI.darkMode","Dark mode"),className:u==="dark"?"active":"",onClick:()=>y("dark"),children:e.jsx(T.NiceIcon,{name:"moon",size:16})})]}),e.jsxs("button",{type:"button",onClick:I,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:z,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," ",c("themeGeneratorAI.tailwind","Tailwind")]})]})]}),r&&e.jsx(ht,{theme:E}),e.jsxs("div",{className:"nice-theme-ai__palette",children:[e.jsx("div",{className:"nice-theme-ai__palette-title",children:c("themeGeneratorAI.colorPalette","Color Palette")}),e.jsx("div",{className:"nice-theme-ai__colors",children:Object.entries(E.colors).map(([P,F])=>e.jsxs("div",{className:"nice-theme-ai__color",children:[e.jsx("div",{className:"nice-theme-ai__color-swatch",style:{backgroundColor:F}}),e.jsx("span",{className:"nice-theme-ai__color-name",children:P}),e.jsx("span",{className:"nice-theme-ai__color-hex",children:F})]},P))})]}),e.jsxs("div",{className:"nice-theme-ai__typography",children:[e.jsx("div",{className:"nice-theme-ai__typography-title",children:c("themeGeneratorAI.typography","Typography")}),e.jsxs("div",{style:{fontFamily:E.typography.fontFamily},children:[e.jsx("p",{style:{fontSize:E.typography.fontSize3xl,fontWeight:E.typography.fontWeightBold},children:c("themeGeneratorAI.heading1","Heading 1")}),e.jsx("p",{style:{fontSize:E.typography.fontSizeLg},children:c("themeGeneratorAI.bodyTextTheQuickBrown","Body text: The quick brown fox jumps over the lazy dog.")}),e.jsx("p",{style:{fontFamily:E.typography.fontFamilyMono,fontSize:E.typography.fontSizeSm},children:'const code = "Monospace font"'})]})]})]}),e.jsx("style",{children:`
2310
2310
  .nice-theme-ai {
2311
2311
  font-family: var(--nice-font-family, system-ui, sans-serif);
2312
2312
  }
@@ -2633,13 +2633,13 @@ module.exports = ${JSON.stringify(j,null,2)}`},[]),P=l.useCallback(()=>{p(null)}
2633
2633
  cursor: text;
2634
2634
  width: 150px;
2635
2635
  }
2636
- `})]})}function Ta(t={}){const{config:a,targetDevice:i="responsive",onLayoutGenerated:r,onError:n}=t,s=ee(),[o,c]=l.useState(!1),[m,p]=l.useState(null),u=l.useRef(null),v=a||(s==null?void 0:s.config),w=l.useCallback(async(g,d)=>{var y,I,b;if(!v){const h="AI not configured";return n==null||n(h),{error:h}}c(!0);const j=performance.now();(y=u.current)==null||y.abort(),u.current=new AbortController;try{const h=V(v),_=`You are a UI layout expert. Generate a responsive layout based on the description.
2636
+ `})]})}function Ta(t={}){const{config:a,targetDevice:i="responsive",onLayoutGenerated:n,onError:r}=t,s=Z(),[o,c]=l.useState(!1),[m,p]=l.useState(null),d=l.useRef(null),x=a||(s==null?void 0:s.config),N=l.useCallback(async(g,u)=>{var _,C,v;if(!x){const h="AI not configured";return r==null||r(h),{error:h}}c(!0);const y=performance.now();(_=d.current)==null||_.abort(),d.current=new AbortController;try{const h=Y(x),w=`You are a UI layout expert. Generate a responsive layout based on the description.
2637
2637
  Return JSON with this structure:
2638
2638
  {
2639
2639
  "id": "unique_id",
2640
2640
  "name": "Layout Name",
2641
2641
  "description": "Description",
2642
- "type": "${d||"dashboard"}",
2642
+ "type": "${u||"dashboard"}",
2643
2643
  "container": {
2644
2644
  "direction": "row|column|grid",
2645
2645
  "gap": "16px",
@@ -2668,45 +2668,45 @@ Return JSON with this structure:
2668
2668
  "xl": "1280px",
2669
2669
  "2xl": "1536px"
2670
2670
  }
2671
- }`,f=await h.chat({messages:[{role:"system",content:_},{role:"user",content:`Create a ${i} layout: ${g}${d?` (type: ${d})`:""}`}],temperature:.5,maxTokens:2048}),k=ft(f),S={layout:k||void 0,rawResponse:(b=(I=f.choices[0])==null?void 0:I.message)==null?void 0:b.content,latencyMs:performance.now()-j,error:k?void 0:"Failed to generate layout",suggestions:xt(k)};return k&&(r==null||r(k)),p(S),S}catch(h){const _=h instanceof Error?h.message:"Layout generation failed",f={error:_,latencyMs:performance.now()-j};return p(f),n==null||n(_),f}finally{c(!1)}},[v,i,r,n]),A=l.useCallback(g=>{let d=`.${g.id} {
2672
- `;if(d+=` display: ${g.container.direction==="grid"?"grid":"flex"};
2673
- `,g.container.direction==="grid"){if(g.container.gridColumns){const j=typeof g.container.gridColumns=="number"?`repeat(${g.container.gridColumns}, 1fr)`:g.container.gridColumns;d+=` grid-template-columns: ${j};
2674
- `}g.container.gridRows&&(d+=` grid-template-rows: ${g.container.gridRows};
2675
- `)}else d+=` flex-direction: ${g.container.direction};
2676
- `,g.container.wrap&&(d+=` flex-wrap: wrap;
2677
- `);return g.container.gap&&(d+=` gap: ${g.container.gap};
2678
- `),g.container.padding&&(d+=` padding: ${g.container.padding};
2679
- `),g.container.align&&(d+=` align-items: ${g.container.align};
2680
- `),g.container.justify&&(d+=` justify-content: ${{start:"flex-start",end:"flex-end",center:"center",between:"space-between",around:"space-around",evenly:"space-evenly"}[g.container.justify]||g.container.justify};
2681
- `),d+=`}
2682
-
2683
- `,g.regions.forEach(j=>{var y,I,b,h,_,f;d+=`.${g.id}__${j.id} {
2684
- `,(y=j.position)!=null&&y.gridColumn&&(d+=` grid-column: ${j.position.gridColumn};
2685
- `),(I=j.position)!=null&&I.gridRow&&(d+=` grid-row: ${j.position.gridRow};
2686
- `),(b=j.size)!=null&&b.width&&(d+=` width: ${j.size.width};
2687
- `),(h=j.size)!=null&&h.height&&(d+=` height: ${j.size.height};
2688
- `),(_=j.size)!=null&&_.minWidth&&(d+=` min-width: ${j.size.minWidth};
2689
- `),(f=j.size)!=null&&f.maxWidth&&(d+=` max-width: ${j.size.maxWidth};
2690
- `),d+=`}
2691
-
2692
- `}),g.breakpoints&&Object.entries(g.breakpoints).forEach(([j,y])=>{const I=g.regions.filter(b=>{var h;return(h=b.responsive)==null?void 0:h[j]});I.length>0&&(d+=`@media (max-width: ${y}) {
2693
- `,I.forEach(b=>{var _,f;const h=b.responsive[j];d+=` .${g.id}__${b.id} {
2694
- `,(_=h.size)!=null&&_.width&&(d+=` width: ${h.size.width};
2695
- `),(f=h.size)!=null&&f.height&&(d+=` height: ${h.size.height};
2696
- `),d+=` }
2697
- `}),d+=`}
2698
-
2699
- `)}),d},[]),R=l.useCallback(g=>{const d=g.regions.map(j=>` <div className="${g.id}__${j.id}">{/* ${j.type} */}</div>`).join(`
2671
+ }`,f=await h.chat({messages:[{role:"system",content:w},{role:"user",content:`Create a ${i} layout: ${g}${u?` (type: ${u})`:""}`}],temperature:.5,maxTokens:2048}),j=ft(f),k={layout:j||void 0,rawResponse:(v=(C=f.choices[0])==null?void 0:C.message)==null?void 0:v.content,latencyMs:performance.now()-y,error:j?void 0:"Failed to generate layout",suggestions:xt(j)};return j&&(n==null||n(j)),p(k),k}catch(h){const w=h instanceof Error?h.message:"Layout generation failed",f={error:w,latencyMs:performance.now()-y};return p(f),r==null||r(w),f}finally{c(!1)}},[x,i,n,r]),A=l.useCallback(g=>{let u=`.${g.id} {
2672
+ `;if(u+=` display: ${g.container.direction==="grid"?"grid":"flex"};
2673
+ `,g.container.direction==="grid"){if(g.container.gridColumns){const y=typeof g.container.gridColumns=="number"?`repeat(${g.container.gridColumns}, 1fr)`:g.container.gridColumns;u+=` grid-template-columns: ${y};
2674
+ `}g.container.gridRows&&(u+=` grid-template-rows: ${g.container.gridRows};
2675
+ `)}else u+=` flex-direction: ${g.container.direction};
2676
+ `,g.container.wrap&&(u+=` flex-wrap: wrap;
2677
+ `);return g.container.gap&&(u+=` gap: ${g.container.gap};
2678
+ `),g.container.padding&&(u+=` padding: ${g.container.padding};
2679
+ `),g.container.align&&(u+=` align-items: ${g.container.align};
2680
+ `),g.container.justify&&(u+=` justify-content: ${{start:"flex-start",end:"flex-end",center:"center",between:"space-between",around:"space-around",evenly:"space-evenly"}[g.container.justify]||g.container.justify};
2681
+ `),u+=`}
2682
+
2683
+ `,g.regions.forEach(y=>{var _,C,v,h,w,f;u+=`.${g.id}__${y.id} {
2684
+ `,(_=y.position)!=null&&_.gridColumn&&(u+=` grid-column: ${y.position.gridColumn};
2685
+ `),(C=y.position)!=null&&C.gridRow&&(u+=` grid-row: ${y.position.gridRow};
2686
+ `),(v=y.size)!=null&&v.width&&(u+=` width: ${y.size.width};
2687
+ `),(h=y.size)!=null&&h.height&&(u+=` height: ${y.size.height};
2688
+ `),(w=y.size)!=null&&w.minWidth&&(u+=` min-width: ${y.size.minWidth};
2689
+ `),(f=y.size)!=null&&f.maxWidth&&(u+=` max-width: ${y.size.maxWidth};
2690
+ `),u+=`}
2691
+
2692
+ `}),g.breakpoints&&Object.entries(g.breakpoints).forEach(([y,_])=>{const C=g.regions.filter(v=>{var h;return(h=v.responsive)==null?void 0:h[y]});C.length>0&&(u+=`@media (max-width: ${_}) {
2693
+ `,C.forEach(v=>{var w,f;const h=v.responsive[y];u+=` .${g.id}__${v.id} {
2694
+ `,(w=h.size)!=null&&w.width&&(u+=` width: ${h.size.width};
2695
+ `),(f=h.size)!=null&&f.height&&(u+=` height: ${h.size.height};
2696
+ `),u+=` }
2697
+ `}),u+=`}
2698
+
2699
+ `)}),u},[]),R=l.useCallback(g=>{const u=g.regions.map(y=>` <div className="${g.id}__${y.id}">{/* ${y.type} */}</div>`).join(`
2700
2700
  `);return`import React from 'react';
2701
2701
  import './${g.id}.css';
2702
2702
 
2703
2703
  export function ${Ra(g.name)}() {
2704
2704
  return (
2705
2705
  <div className="${g.id}">
2706
- ${d}
2706
+ ${u}
2707
2707
  </div>
2708
2708
  );
2709
- }`},[]),M=l.useCallback(()=>{p(null)},[]),P=l.useCallback(()=>{var g;(g=u.current)==null||g.abort(),c(!1)},[]);return l.useEffect(()=>()=>{var g;(g=u.current)==null||g.abort()},[]),{generateLayout:w,toCSS:A,toReactComponent:R,loading:o,lastResult:m,clearResults:M,abort:P,isConfigured:!!v}}function ft(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(o);if(c.regions||c.container)return{id:c.id||`layout_${Date.now()}`,name:c.name||"Generated Layout",description:c.description,type:c.type||"dashboard",container:{direction:"grid",gap:"16px",padding:"20px",gridColumns:12,...c.container},regions:c.regions||[],breakpoints:c.breakpoints||{xs:"320px",sm:"640px",md:"768px",lg:"1024px",xl:"1280px","2xl":"1536px"},cssGrid:c.cssGrid,cssVariables:c.cssVariables}}catch{}return null}function xt(t){if(!t)return[];const a=[],i=new Set(t.regions.map(r=>r.type));return i.has("header")||a.push("Consider adding a header region for navigation"),!i.has("sidebar")&&t.type==="dashboard"&&a.push("Add a sidebar for dashboard navigation"),t.regions.some(r=>!r.responsive)&&a.push("Add responsive breakpoints for mobile compatibility"),a.slice(0,3)}function Ra(t){return t.replace(/[^a-zA-Z0-9]+(.)/g,(a,i)=>i.toUpperCase()).replace(/^./,a=>a.toUpperCase())}const bt=[{type:"dashboard",icon:"bar-chart",label:"Dashboard"},{type:"form",icon:"edit",label:"Form"},{type:"list",icon:"list",label:"List"},{type:"detail",icon:"file",label:"Detail"},{type:"landing",icon:"home",label:"Landing"},{type:"settings",icon:"settings",label:"Settings"},{type:"wizard",icon:"wand",label:"Wizard"},{type:"split",icon:"grid",label:"Split"},{type:"grid",icon:"grid",label:"Grid"},{type:"kanban",icon:"columns",label:"Kanban"}];function yt({config:t,targetDevice:a="responsive",onGenerate:i,showTypeSelector:r=!0,showPreview:n=!0,className:s,style:o,renderLayout:c}){const{t:m}=T.useNiceTranslation(),[p,u]=l.useState(""),[v,w]=l.useState(null),{generateLayout:A,toCSS:R,toReactComponent:M,loading:P,lastResult:g,isConfigured:d}=Ta({config:t,targetDevice:a,onLayoutGenerated:i}),j=async()=>{!p.trim()||P||await A(p,v||void 0)},y=()=>{if(!(g!=null&&g.layout))return;const b=R(g.layout),h=new Blob([b],{type:"text/css"}),_=URL.createObjectURL(h),f=document.createElement("a");f.href=_,f.download=`${g.layout.id}.css`,f.click(),URL.revokeObjectURL(_)},I=()=>{if(!(g!=null&&g.layout))return;const b=M(g.layout),h=new Blob([b],{type:"text/javascript"}),_=URL.createObjectURL(h),f=document.createElement("a");f.href=_,f.download=`${Ra(g.layout.name)}.tsx`,f.click(),URL.revokeObjectURL(_)};return d?e.jsxs("div",{className:`nice-layout-ai ${s||""}`,style:o,children:[r&&e.jsx("div",{className:"nice-layout-ai__types",children:bt.map(({type:b,icon:h,label:_})=>e.jsxs("button",{type:"button",className:`nice-layout-ai__type ${v===b?"nice-layout-ai__type--selected":""}`,onClick:()=>w(v===b?null:b),children:[e.jsx("span",{className:"nice-layout-ai__type-icon",children:e.jsx(T.NiceIcon,{name:h,size:20})}),e.jsx("span",{className:"nice-layout-ai__type-label",children:_})]},b))}),e.jsxs("div",{className:"nice-layout-ai__input-section",children:[e.jsx("textarea",{value:p,onChange:b=>u(b.target.value),placeholder:m("layoutAI.describeTheLayoutYouNeed","Describe the layout you need... (e.g., 'Admin dashboard with sidebar navigation and header')"),className:"nice-layout-ai__input",rows:3,disabled:P}),e.jsx("button",{type:"button",onClick:j,className:"nice-layout-ai__submit",disabled:P||!p.trim(),children:P?e.jsx("span",{className:"nice-layout-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"palette",size:14})," ",m("layoutAI.generateLayout","Generate Layout")]})})]}),(g==null?void 0:g.error)&&e.jsx("div",{className:"nice-layout-ai__error",role:"alert",children:g.error}),g&&g.layout&&e.jsxs("div",{className:"nice-layout-ai__result",children:[e.jsxs("div",{className:"nice-layout-ai__result-header",children:[e.jsxs("div",{className:"nice-layout-ai__layout-info",children:[e.jsx("span",{className:"nice-layout-ai__layout-name",children:g.layout.name}),e.jsx("span",{className:"nice-layout-ai__layout-type",children:g.layout.type})]}),e.jsxs("div",{className:"nice-layout-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>i==null?void 0:i(g.layout),children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",m("layoutAI.useLayout","Use Layout")]}),e.jsxs("button",{type:"button",onClick:y,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:I,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," ",m("layoutAI.react","React")]})]})]}),e.jsxs("div",{className:"nice-layout-ai__regions",children:[e.jsx("div",{className:"nice-layout-ai__regions-title",children:"Regions:"}),e.jsx("div",{className:"nice-layout-ai__regions-list",children:g.layout.regions.map(b=>e.jsx("span",{className:`nice-layout-ai__region nice-layout-ai__region--${b.type}`,children:b.type},b.id))})]}),n&&e.jsx("div",{className:"nice-layout-ai__preview",children:c?c(g.layout):e.jsx(vt,{layout:g.layout})}),e.jsxs("details",{className:"nice-layout-ai__json",children:[e.jsx("summary",{children:m("layoutAI.viewJsonDefinition","View JSON Definition")}),e.jsx("pre",{children:JSON.stringify(g.layout,null,2)})]})]}),e.jsx("style",{children:`
2709
+ }`},[]),$=l.useCallback(()=>{p(null)},[]),M=l.useCallback(()=>{var g;(g=d.current)==null||g.abort(),c(!1)},[]);return l.useEffect(()=>()=>{var g;(g=d.current)==null||g.abort()},[]),{generateLayout:N,toCSS:A,toReactComponent:R,loading:o,lastResult:m,clearResults:$,abort:M,isConfigured:!!x}}function ft(t){var a,i,n;try{const r=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",o=((n=(r.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,r])[1])==null?void 0:n.trim())||r,c=JSON.parse(o);if(c.regions||c.container)return{id:c.id||`layout_${Date.now()}`,name:c.name||"Generated Layout",description:c.description,type:c.type||"dashboard",container:{direction:"grid",gap:"16px",padding:"20px",gridColumns:12,...c.container},regions:c.regions||[],breakpoints:c.breakpoints||{xs:"320px",sm:"640px",md:"768px",lg:"1024px",xl:"1280px","2xl":"1536px"},cssGrid:c.cssGrid,cssVariables:c.cssVariables}}catch{}return null}function xt(t){if(!t)return[];const a=[],i=new Set(t.regions.map(n=>n.type));return i.has("header")||a.push("Consider adding a header region for navigation"),!i.has("sidebar")&&t.type==="dashboard"&&a.push("Add a sidebar for dashboard navigation"),t.regions.some(n=>!n.responsive)&&a.push("Add responsive breakpoints for mobile compatibility"),a.slice(0,3)}function Ra(t){return t.replace(/[^a-zA-Z0-9]+(.)/g,(a,i)=>i.toUpperCase()).replace(/^./,a=>a.toUpperCase())}const bt=[{type:"dashboard",icon:"bar-chart",label:"Dashboard"},{type:"form",icon:"edit",label:"Form"},{type:"list",icon:"list",label:"List"},{type:"detail",icon:"file",label:"Detail"},{type:"landing",icon:"home",label:"Landing"},{type:"settings",icon:"settings",label:"Settings"},{type:"wizard",icon:"wand",label:"Wizard"},{type:"split",icon:"grid",label:"Split"},{type:"grid",icon:"grid",label:"Grid"},{type:"kanban",icon:"columns",label:"Kanban"}];function yt({config:t,targetDevice:a="responsive",onGenerate:i,showTypeSelector:n=!0,showPreview:r=!0,className:s,style:o,renderLayout:c}){const{t:m}=T.useNiceTranslation(),[p,d]=l.useState(""),[x,N]=l.useState(null),{generateLayout:A,toCSS:R,toReactComponent:$,loading:M,lastResult:g,isConfigured:u}=Ta({config:t,targetDevice:a,onLayoutGenerated:i}),y=async()=>{!p.trim()||M||await A(p,x||void 0)},_=()=>{if(!(g!=null&&g.layout))return;const v=R(g.layout),h=new Blob([v],{type:"text/css"}),w=URL.createObjectURL(h),f=document.createElement("a");f.href=w,f.download=`${g.layout.id}.css`,f.click(),URL.revokeObjectURL(w)},C=()=>{if(!(g!=null&&g.layout))return;const v=$(g.layout),h=new Blob([v],{type:"text/javascript"}),w=URL.createObjectURL(h),f=document.createElement("a");f.href=w,f.download=`${Ra(g.layout.name)}.tsx`,f.click(),URL.revokeObjectURL(w)};return u?e.jsxs("div",{className:`nice-layout-ai ${s||""}`,style:o,children:[n&&e.jsx("div",{className:"nice-layout-ai__types",children:bt.map(({type:v,icon:h,label:w})=>e.jsxs("button",{type:"button",className:`nice-layout-ai__type ${x===v?"nice-layout-ai__type--selected":""}`,onClick:()=>N(x===v?null:v),children:[e.jsx("span",{className:"nice-layout-ai__type-icon",children:e.jsx(T.NiceIcon,{name:h,size:20})}),e.jsx("span",{className:"nice-layout-ai__type-label",children:w})]},v))}),e.jsxs("div",{className:"nice-layout-ai__input-section",children:[e.jsx("textarea",{value:p,onChange:v=>d(v.target.value),placeholder:m("layoutAI.describeTheLayoutYouNeed","Describe the layout you need... (e.g., 'Admin dashboard with sidebar navigation and header')"),className:"nice-layout-ai__input",rows:3,disabled:M}),e.jsx("button",{type:"button",onClick:y,className:"nice-layout-ai__submit",disabled:M||!p.trim(),children:M?e.jsx("span",{className:"nice-layout-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"palette",size:14})," ",m("layoutAI.generateLayout","Generate Layout")]})})]}),(g==null?void 0:g.error)&&e.jsx("div",{className:"nice-layout-ai__error",role:"alert",children:g.error}),g&&g.layout&&e.jsxs("div",{className:"nice-layout-ai__result",children:[e.jsxs("div",{className:"nice-layout-ai__result-header",children:[e.jsxs("div",{className:"nice-layout-ai__layout-info",children:[e.jsx("span",{className:"nice-layout-ai__layout-name",children:g.layout.name}),e.jsx("span",{className:"nice-layout-ai__layout-type",children:g.layout.type})]}),e.jsxs("div",{className:"nice-layout-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>i==null?void 0:i(g.layout),children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",m("layoutAI.useLayout","Use Layout")]}),e.jsxs("button",{type:"button",onClick:_,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:C,children:[e.jsx(T.NiceIcon,{name:"download",size:14})," ",m("layoutAI.react","React")]})]})]}),e.jsxs("div",{className:"nice-layout-ai__regions",children:[e.jsx("div",{className:"nice-layout-ai__regions-title",children:m("layoutAI.regions","Regions:")}),e.jsx("div",{className:"nice-layout-ai__regions-list",children:g.layout.regions.map(v=>e.jsx("span",{className:`nice-layout-ai__region nice-layout-ai__region--${v.type}`,children:v.type},v.id))})]}),r&&e.jsx("div",{className:"nice-layout-ai__preview",children:c?c(g.layout):e.jsx(vt,{layout:g.layout})}),e.jsxs("details",{className:"nice-layout-ai__json",children:[e.jsx("summary",{children:m("layoutAI.viewJsonDefinition","View JSON Definition")}),e.jsx("pre",{children:JSON.stringify(g.layout,null,2)})]})]}),e.jsx("style",{children:`
2710
2710
  .nice-layout-ai {
2711
2711
  font-family: var(--nice-font-family, system-ui, sans-serif);
2712
2712
  }
@@ -2941,7 +2941,7 @@ ${d}
2941
2941
  color: var(--nice-error, #c62828);
2942
2942
  border-radius: var(--nice-radius-md, 6px);
2943
2943
  }
2944
- `})]}):e.jsx("div",{className:`nice-layout-ai nice-layout-ai--disabled ${s||""}`,style:o,children:e.jsx("p",{children:m("layoutAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function vt({layout:t}){const a=i=>({header:"var(--nice-primary-bg, #e3f2fd)",sidebar:"var(--nice-success-bg, #e8f5e9)",aside:"var(--nice-success-bg, #e8f5e9)",main:"var(--nice-warning-bg, #fff3e0)",content:"var(--nice-warning-bg, #fff3e0)",footer:"var(--nice-bg-secondary, #f5f5f5)",nav:"var(--nice-accent-tint-10, #fce4ec)"})[i]||"var(--nice-bg-secondary, #f5f5f5)";return e.jsx("div",{className:"layout-preview",style:{display:t.container.direction==="grid"?"grid":"flex",flexDirection:t.container.direction==="column"?"column":"row",gridTemplateColumns:t.container.direction==="grid"&&t.container.gridColumns?typeof t.container.gridColumns=="number"?`repeat(${t.container.gridColumns}, 1fr)`:t.container.gridColumns:void 0,gap:t.container.gap||"8px",minHeight:"300px"},children:t.regions.map(i=>{var r,n,s,o,c,m;return e.jsx("div",{className:"layout-preview__region",style:{gridColumn:(r=i.position)==null?void 0:r.gridColumn,gridRow:(n=i.position)==null?void 0:n.gridRow,width:(s=i.size)==null?void 0:s.width,height:((o=i.size)==null?void 0:o.height)||"80px",minWidth:(c=i.size)==null?void 0:c.minWidth,maxWidth:(m=i.size)==null?void 0:m.maxWidth,background:a(i.type),borderRadius:"6px",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:500,color:"var(--nice-text-secondary, #666)",border:"1px dashed var(--nice-border, #ccc)"},children:i.type},i.id)})})}function La(t={}){const{config:a,wcagLevel:i="AA",onAuditComplete:r,onError:n}=t,s=ee(),[o,c]=l.useState(!1),[m,p]=l.useState(null),u=l.useRef(null),v=a||(s==null?void 0:s.config),w=l.useCallback(async(d,j)=>{var y;if(!v){const I="AI not configured";return n==null||n(I),Te("html",i,I)}c(!0),(y=u.current)==null||y.abort(),u.current=new AbortController;try{const I=V(v),b=`You are a WCAG accessibility expert. Analyze the provided HTML code for accessibility issues at WCAG ${i} level.
2944
+ `})]}):e.jsx("div",{className:`nice-layout-ai nice-layout-ai--disabled ${s||""}`,style:o,children:e.jsx("p",{children:m("layoutAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function vt({layout:t}){const a=i=>({header:"var(--nice-primary-bg, #e3f2fd)",sidebar:"var(--nice-success-bg, #e8f5e9)",aside:"var(--nice-success-bg, #e8f5e9)",main:"var(--nice-warning-bg, #fff3e0)",content:"var(--nice-warning-bg, #fff3e0)",footer:"var(--nice-bg-secondary, #f5f5f5)",nav:"var(--nice-accent-tint-10, #fce4ec)"})[i]||"var(--nice-bg-secondary, #f5f5f5)";return e.jsx("div",{className:"layout-preview",style:{display:t.container.direction==="grid"?"grid":"flex",flexDirection:t.container.direction==="column"?"column":"row",gridTemplateColumns:t.container.direction==="grid"&&t.container.gridColumns?typeof t.container.gridColumns=="number"?`repeat(${t.container.gridColumns}, 1fr)`:t.container.gridColumns:void 0,gap:t.container.gap||"8px",minHeight:"300px"},children:t.regions.map(i=>{var n,r,s,o,c,m;return e.jsx("div",{className:"layout-preview__region",style:{gridColumn:(n=i.position)==null?void 0:n.gridColumn,gridRow:(r=i.position)==null?void 0:r.gridRow,width:(s=i.size)==null?void 0:s.width,height:((o=i.size)==null?void 0:o.height)||"80px",minWidth:(c=i.size)==null?void 0:c.minWidth,maxWidth:(m=i.size)==null?void 0:m.maxWidth,background:a(i.type),borderRadius:"6px",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:500,color:"var(--nice-text-secondary, #666)",border:"1px dashed var(--nice-border, #ccc)"},children:i.type},i.id)})})}function La(t={}){const{config:a,wcagLevel:i="AA",onAuditComplete:n,onError:r}=t,s=Z(),[o,c]=l.useState(!1),[m,p]=l.useState(null),d=l.useRef(null),x=a||(s==null?void 0:s.config),N=l.useCallback(async(u,y)=>{var _;if(!x){const C="AI not configured";return r==null||r(C),Te("html",i,C)}c(!0),(_=d.current)==null||_.abort(),d.current=new AbortController;try{const C=Y(x),v=`You are a WCAG accessibility expert. Analyze the provided HTML code for accessibility issues at WCAG ${i} level.
2945
2945
 
2946
2946
  Return JSON with this exact structure:
2947
2947
  {
@@ -2975,10 +2975,10 @@ Focus on:
2975
2975
  7. Heading hierarchy
2976
2976
  8. Landmark regions
2977
2977
  9. Semantic HTML usage
2978
- 10. Language attributes`,h=await I.chat({messages:[{role:"system",content:b},{role:"user",content:`Analyze this HTML for accessibility:
2979
- ${j?`Context: ${j}
2978
+ 10. Language attributes`,h=await C.chat({messages:[{role:"system",content:v},{role:"user",content:`Analyze this HTML for accessibility:
2979
+ ${y?`Context: ${y}
2980
2980
 
2981
- `:""}${d}`}],temperature:.3,maxTokens:4096}),_=_t(h,"html",i);return p(_),r==null||r(_),_}catch(I){const b=I instanceof Error?I.message:"Audit failed";return n==null||n(b),Te("html",i,b)}finally{c(!1)}},[v,i,r,n]),A=l.useCallback((d,j)=>{const y=fe(he(d)),I=fe(he(j)),b=(Math.max(y,I)+.05)/(Math.min(y,I)+.05),h={foreground:d,background:j,ratio:Math.round(b*100)/100,passesAA:b>=4.5,passesAALarge:b>=3,passesAAA:b>=7,passesAAALarge:b>=4.5};return h.passesAA||(h.suggestions=jt(d,j,4.5)),h},[]),R=l.useCallback(async d=>{var j,y;if(!v)return n==null||n("AI not configured"),[];try{const f=(((y=(j=(await V(v).chat({messages:[{role:"system",content:`Analyze the HTML for ARIA attribute issues.
2981
+ `:""}${u}`}],temperature:.3,maxTokens:4096}),w=_t(h,"html",i);return p(w),n==null||n(w),w}catch(C){const v=C instanceof Error?C.message:"Audit failed";return r==null||r(v),Te("html",i,v)}finally{c(!1)}},[x,i,n,r]),A=l.useCallback((u,y)=>{const _=fe(he(u)),C=fe(he(y)),v=(Math.max(_,C)+.05)/(Math.min(_,C)+.05),h={foreground:u,background:y,ratio:Math.round(v*100)/100,passesAA:v>=4.5,passesAALarge:v>=3,passesAAA:v>=7,passesAAALarge:v>=4.5};return h.passesAA||(h.suggestions=jt(u,y,4.5)),h},[]),R=l.useCallback(async u=>{var y,_;if(!x)return r==null||r("AI not configured"),[];try{const f=(((_=(y=(await Y(x).chat({messages:[{role:"system",content:`Analyze the HTML for ARIA attribute issues.
2982
2982
  Return JSON array:
2983
2983
  [{
2984
2984
  "element": "<button>...",
@@ -2989,10 +2989,10 @@ Return JSON array:
2989
2989
  "issues": ["Missing aria-label"],
2990
2990
  "suggestions": ["Add aria-label='Submit form'"]
2991
2991
  }]`},{role:"user",content:`Validate ARIA in:
2992
- ${d}`}],temperature:.2,maxTokens:2048})).choices[0])==null?void 0:j.message)==null?void 0:y.content)||"").match(/\[[\s\S]*\]/);if(f)return JSON.parse(f[0])}catch{}return[]},[v,n]),M=l.useCallback(async d=>{var j,y;if(!v)return n==null||n("AI not configured"),d;try{const h=((y=(j=(await V(v).chat({messages:[{role:"system",content:`You are an accessibility expert. Improve the HTML to be fully WCAG ${i} compliant.
2992
+ ${u}`}],temperature:.2,maxTokens:2048})).choices[0])==null?void 0:y.message)==null?void 0:_.content)||"").match(/\[[\s\S]*\]/);if(f)return JSON.parse(f[0])}catch{}return[]},[x,r]),$=l.useCallback(async u=>{var y,_;if(!x)return r==null||r("AI not configured"),u;try{const h=((_=(y=(await Y(x).chat({messages:[{role:"system",content:`You are an accessibility expert. Improve the HTML to be fully WCAG ${i} compliant.
2993
2993
  Add proper ARIA attributes, semantic HTML, keyboard handlers, focus management.
2994
2994
  Return only the improved HTML code.`},{role:"user",content:`Make this accessible:
2995
- ${d}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:j.message)==null?void 0:y.content)||"",_=h.match(/```(?:html)?\s*([\s\S]*?)```/);return _?_[1].trim():h.trim()}catch{return d}},[v,i,n]),P=l.useCallback(()=>{p(null)},[]),g=l.useCallback(()=>{var d;(d=u.current)==null||d.abort(),c(!1)},[]);return l.useEffect(()=>()=>{var d;(d=u.current)==null||d.abort()},[]),{analyzeHTML:w,checkContrast:A,validateARIA:R,suggestAccessibleCode:M,loading:o,lastAudit:m,clearAudit:P,abort:g,isConfigured:!!v}}function Te(t,a,i){return{timestamp:new Date,target:t,wcagLevel:a,issues:i?[{id:"error",category:"semantic-html",severity:"critical",wcagCriteria:"N/A",wcagLevel:"A",title:"Audit Error",description:i,impact:"Audit could not complete",suggestion:"Try again or check configuration"}]:[],score:i?0:100,summary:{critical:i?1:0,serious:0,moderate:0,minor:0,passed:0},recommendations:[]}}function _t(t,a,i){var r,n,s;try{const o=((n=(r=t.choices[0])==null?void 0:r.message)==null?void 0:n.content)||"",m=((s=(o.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,o])[1])==null?void 0:s.trim())||o,p=JSON.parse(m),u=(p.issues||[]).map((w,A)=>({id:w.id||`issue_${A}`,category:w.category||"semantic-html",severity:w.severity||"moderate",wcagCriteria:w.wcagCriteria||"N/A",wcagLevel:w.wcagLevel||"A",title:w.title||"Unknown Issue",description:w.description||"",element:w.element,selector:w.selector,impact:w.impact||"",suggestion:w.suggestion||"",codeExample:w.codeExample})),v={critical:u.filter(w=>w.severity==="critical").length,serious:u.filter(w=>w.severity==="serious").length,moderate:u.filter(w=>w.severity==="moderate").length,minor:u.filter(w=>w.severity==="minor").length,passed:0};return{timestamp:new Date,target:a,wcagLevel:i,issues:u,score:p.score??wt(v),summary:v,recommendations:p.recommendations||[]}}catch{return Te(a,i,"Failed to parse audit results")}}function wt(t){const a=t.critical*25+t.serious*15+t.moderate*5+t.minor*2;return Math.max(0,100-a)}function he(t){const a=t.replace("#","");return a.length===3?{r:parseInt(a[0]+a[0],16),g:parseInt(a[1]+a[1],16),b:parseInt(a[2]+a[2],16)}:{r:parseInt(a.slice(0,2),16),g:parseInt(a.slice(2,4),16),b:parseInt(a.slice(4,6),16)}}function fe(t){const[a,i,r]=[t.r,t.g,t.b].map(n=>(n/=255,n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4)));return .2126*a+.7152*i+.0722*r}function jt(t,a,i){const r=[],n=he(t),s=he(a),o={r:Math.max(0,n.r-40),g:Math.max(0,n.g-40),b:Math.max(0,n.b-40)},c=`#${o.r.toString(16).padStart(2,"0")}${o.g.toString(16).padStart(2,"0")}${o.b.toString(16).padStart(2,"0")}`,m=fe(o),p=fe(s);(Math.max(m,p)+.05)/(Math.min(m,p)+.05)>=i&&r.push(`Try darker foreground: ${c}`);const v={r:Math.min(255,s.r+40),g:Math.min(255,s.g+40),b:Math.min(255,s.b+40)},w=`#${v.r.toString(16).padStart(2,"0")}${v.g.toString(16).padStart(2,"0")}${v.b.toString(16).padStart(2,"0")}`;return r.push(`Try lighter background: ${w}`),r}const _e={critical:{bg:"var(--nice-danger-bg, #ffebee)",color:"var(--nice-danger-dark, #c62828)",icon:"error"},serious:{bg:"var(--nice-warning-bg, #fff3e0)",color:"var(--nice-warning-dark, #e65100)",icon:"warning"},moderate:{bg:"var(--nice-warning-bg, #fff8e1)",color:"var(--nice-warning-dark, #f57f17)",icon:"zap"},minor:{bg:"var(--nice-primary-bg, #e3f2fd)",color:"var(--nice-primary-dark, #1565c0)",icon:"info"}};function kt({config:t,wcagLevel:a="AA",onAuditComplete:i,showContrastChecker:r=!0,className:n,style:s,renderIssue:o}){const{t:c}=T.useNiceTranslation(),[m,p]=l.useState(""),[u,v]=l.useState("#333333"),[w,A]=l.useState("#ffffff"),[R,M]=l.useState(null),{analyzeHTML:P,checkContrast:g,suggestAccessibleCode:d,loading:j,lastAudit:y,isConfigured:I}=La({config:t,wcagLevel:a,onAuditComplete:i}),b=async()=>{!m.trim()||j||await P(m)},h=()=>{const f=g(u,w);M(f)},_=async()=>{if(!m.trim())return;const f=await d(m);p(f)};return I?e.jsxs("div",{className:`nice-a11y-ai ${n||""}`,style:s,children:[r&&e.jsxs("div",{className:"nice-a11y-ai__contrast",children:[e.jsx("h3",{children:c("accessibilityAI.colorContrastChecker","Color Contrast Checker")}),e.jsxs("div",{className:"nice-a11y-ai__contrast-inputs",children:[e.jsxs("label",{children:[c("accessibilityAI.foreground","Foreground"),e.jsx("input",{type:"color",value:u,onChange:f=>v(f.target.value)}),e.jsx("input",{type:"text",value:u,onChange:f=>v(f.target.value)})]}),e.jsxs("label",{children:[c("accessibilityAI.background","Background"),e.jsx("input",{type:"color",value:w,onChange:f=>A(f.target.value)}),e.jsx("input",{type:"text",value:w,onChange:f=>A(f.target.value)})]}),e.jsx("button",{type:"button",onClick:h,children:c("accessibilityAI.check","Check")})]}),R&&e.jsxs("div",{className:"nice-a11y-ai__contrast-result",children:[e.jsx("div",{className:"nice-a11y-ai__contrast-preview",style:{color:u,background:w},children:c("accessibilityAI.sampleTextAa","Sample Text Aa")}),e.jsxs("div",{className:"nice-a11y-ai__contrast-ratio",children:[e.jsxs("span",{className:"nice-a11y-ai__ratio-value",children:[R.ratio,":1"]}),e.jsxs("div",{className:"nice-a11y-ai__passes",children:[e.jsxs("span",{className:R.passesAA?"pass":"fail",children:["AA: ",e.jsx(T.NiceIcon,{name:R.passesAA?"check":"close",size:14})]}),e.jsxs("span",{className:R.passesAALarge?"pass":"fail",children:["AA Large:"," ",e.jsx(T.NiceIcon,{name:R.passesAALarge?"check":"close",size:14})]}),e.jsxs("span",{className:R.passesAAA?"pass":"fail",children:["AAA: ",e.jsx(T.NiceIcon,{name:R.passesAAA?"check":"close",size:14})]})]})]}),R.suggestions&&R.suggestions.length>0&&e.jsx("div",{className:"nice-a11y-ai__suggestions",children:R.suggestions.map((f,k)=>e.jsx("div",{children:f},k))})]})]}),e.jsxs("div",{className:"nice-a11y-ai__analyzer",children:[e.jsxs("h3",{children:["HTML Accessibility Analyzer (WCAG ",a,")"]}),e.jsx("textarea",{value:m,onChange:f=>p(f.target.value),placeholder:c("accessibilityAI.pasteHtmlCodeToAnalyze","Paste HTML code to analyze..."),className:"nice-a11y-ai__input",rows:8,disabled:j}),e.jsxs("div",{className:"nice-a11y-ai__actions",children:[e.jsx("button",{type:"button",onClick:b,disabled:j||!m.trim(),children:j?e.jsx("span",{className:"nice-a11y-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"search",size:14})," ",c("accessibilityAI.analyze","Analyze")]})}),e.jsxs("button",{type:"button",onClick:_,disabled:j||!m.trim(),children:[e.jsx(T.NiceIcon,{name:"settings",size:14})," ",c("accessibilityAI.autoFix","Auto-Fix")]})]})]}),y&&e.jsxs("div",{className:"nice-a11y-ai__audit",children:[e.jsxs("div",{className:"nice-a11y-ai__audit-header",children:[e.jsxs("div",{className:"nice-a11y-ai__score",children:[e.jsx("span",{className:"nice-a11y-ai__score-value",children:y.score}),e.jsx("span",{className:"nice-a11y-ai__score-label",children:c("accessibilityAI.score","Score")})]}),e.jsxs("div",{className:"nice-a11y-ai__summary",children:[e.jsx("span",{className:"critical",children:c("accessibilityAI.critical","{critical} Critical").replace("{critical}",String(y.summary.critical))}),e.jsx("span",{className:"serious",children:c("accessibilityAI.serious","{serious} Serious").replace("{serious}",String(y.summary.serious))}),e.jsx("span",{className:"moderate",children:c("accessibilityAI.moderate","{moderate} Moderate").replace("{moderate}",String(y.summary.moderate))}),e.jsx("span",{className:"minor",children:c("accessibilityAI.minor","{minor} Minor").replace("{minor}",String(y.summary.minor))})]})]}),e.jsx("div",{className:"nice-a11y-ai__issues",children:y.issues.map(f=>o?o(f):e.jsxs("div",{className:"nice-a11y-ai__issue",style:{background:_e[f.severity].bg,borderLeftColor:_e[f.severity].color},children:[e.jsxs("div",{className:"nice-a11y-ai__issue-header",children:[e.jsx("span",{className:"nice-a11y-ai__issue-icon",children:e.jsx(T.NiceIcon,{name:_e[f.severity].icon,size:16})}),e.jsx("span",{className:"nice-a11y-ai__issue-title",children:f.title}),e.jsx("span",{className:"nice-a11y-ai__issue-wcag",children:c("accessibilityAI.wcag","WCAG {wcagCriteria} ({wcagLevel})").replace("{wcagCriteria}",String(f.wcagCriteria)).replace("{wcagLevel}",String(f.wcagLevel))})]}),e.jsx("p",{className:"nice-a11y-ai__issue-desc",children:f.description}),f.element&&e.jsx("code",{className:"nice-a11y-ai__issue-element",children:f.element}),e.jsxs("div",{className:"nice-a11y-ai__issue-suggestion",children:[e.jsx("strong",{children:"Fix:"})," ",f.suggestion]}),f.codeExample&&e.jsx("pre",{className:"nice-a11y-ai__issue-example",children:f.codeExample})]},f.id))}),y.recommendations.length>0&&e.jsxs("div",{className:"nice-a11y-ai__recommendations",children:[e.jsx("h4",{children:c("accessibilityAI.generalRecommendations","General Recommendations")}),e.jsx("ul",{children:y.recommendations.map((f,k)=>e.jsx("li",{children:f},k))})]})]}),e.jsx("style",{children:`
2995
+ ${u}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:y.message)==null?void 0:_.content)||"",w=h.match(/```(?:html)?\s*([\s\S]*?)```/);return w?w[1].trim():h.trim()}catch{return u}},[x,i,r]),M=l.useCallback(()=>{p(null)},[]),g=l.useCallback(()=>{var u;(u=d.current)==null||u.abort(),c(!1)},[]);return l.useEffect(()=>()=>{var u;(u=d.current)==null||u.abort()},[]),{analyzeHTML:N,checkContrast:A,validateARIA:R,suggestAccessibleCode:$,loading:o,lastAudit:m,clearAudit:M,abort:g,isConfigured:!!x}}function Te(t,a,i){return{timestamp:new Date,target:t,wcagLevel:a,issues:i?[{id:"error",category:"semantic-html",severity:"critical",wcagCriteria:"N/A",wcagLevel:"A",title:"Audit Error",description:i,impact:"Audit could not complete",suggestion:"Try again or check configuration"}]:[],score:i?0:100,summary:{critical:i?1:0,serious:0,moderate:0,minor:0,passed:0},recommendations:[]}}function _t(t,a,i){var n,r,s;try{const o=((r=(n=t.choices[0])==null?void 0:n.message)==null?void 0:r.content)||"",m=((s=(o.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,o])[1])==null?void 0:s.trim())||o,p=JSON.parse(m),d=(p.issues||[]).map((N,A)=>({id:N.id||`issue_${A}`,category:N.category||"semantic-html",severity:N.severity||"moderate",wcagCriteria:N.wcagCriteria||"N/A",wcagLevel:N.wcagLevel||"A",title:N.title||"Unknown Issue",description:N.description||"",element:N.element,selector:N.selector,impact:N.impact||"",suggestion:N.suggestion||"",codeExample:N.codeExample})),x={critical:d.filter(N=>N.severity==="critical").length,serious:d.filter(N=>N.severity==="serious").length,moderate:d.filter(N=>N.severity==="moderate").length,minor:d.filter(N=>N.severity==="minor").length,passed:0};return{timestamp:new Date,target:a,wcagLevel:i,issues:d,score:p.score??wt(x),summary:x,recommendations:p.recommendations||[]}}catch{return Te(a,i,"Failed to parse audit results")}}function wt(t){const a=t.critical*25+t.serious*15+t.moderate*5+t.minor*2;return Math.max(0,100-a)}function he(t){const a=t.replace("#","");return a.length===3?{r:parseInt(a[0]+a[0],16),g:parseInt(a[1]+a[1],16),b:parseInt(a[2]+a[2],16)}:{r:parseInt(a.slice(0,2),16),g:parseInt(a.slice(2,4),16),b:parseInt(a.slice(4,6),16)}}function fe(t){const[a,i,n]=[t.r,t.g,t.b].map(r=>(r/=255,r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4)));return .2126*a+.7152*i+.0722*n}function jt(t,a,i){const n=[],r=he(t),s=he(a),o={r:Math.max(0,r.r-40),g:Math.max(0,r.g-40),b:Math.max(0,r.b-40)},c=`#${o.r.toString(16).padStart(2,"0")}${o.g.toString(16).padStart(2,"0")}${o.b.toString(16).padStart(2,"0")}`,m=fe(o),p=fe(s);(Math.max(m,p)+.05)/(Math.min(m,p)+.05)>=i&&n.push(`Try darker foreground: ${c}`);const x={r:Math.min(255,s.r+40),g:Math.min(255,s.g+40),b:Math.min(255,s.b+40)},N=`#${x.r.toString(16).padStart(2,"0")}${x.g.toString(16).padStart(2,"0")}${x.b.toString(16).padStart(2,"0")}`;return n.push(`Try lighter background: ${N}`),n}const _e={critical:{bg:"var(--nice-danger-bg, #ffebee)",color:"var(--nice-danger-dark, #c62828)",icon:"error"},serious:{bg:"var(--nice-warning-bg, #fff3e0)",color:"var(--nice-warning-dark, #e65100)",icon:"warning"},moderate:{bg:"var(--nice-warning-bg, #fff8e1)",color:"var(--nice-warning-dark, #f57f17)",icon:"zap"},minor:{bg:"var(--nice-primary-bg, #e3f2fd)",color:"var(--nice-primary-dark, #1565c0)",icon:"info"}};function kt({config:t,wcagLevel:a="AA",onAuditComplete:i,showContrastChecker:n=!0,className:r,style:s,renderIssue:o}){const{t:c}=T.useNiceTranslation(),[m,p]=l.useState(""),[d,x]=l.useState("#333333"),[N,A]=l.useState("#ffffff"),[R,$]=l.useState(null),{analyzeHTML:M,checkContrast:g,suggestAccessibleCode:u,loading:y,lastAudit:_,isConfigured:C}=La({config:t,wcagLevel:a,onAuditComplete:i}),v=async()=>{!m.trim()||y||await M(m)},h=()=>{const f=g(d,N);$(f)},w=async()=>{if(!m.trim())return;const f=await u(m);p(f)};return C?e.jsxs("div",{className:`nice-a11y-ai ${r||""}`,style:s,children:[n&&e.jsxs("div",{className:"nice-a11y-ai__contrast",children:[e.jsx("h3",{children:c("accessibilityAI.colorContrastChecker","Color Contrast Checker")}),e.jsxs("div",{className:"nice-a11y-ai__contrast-inputs",children:[e.jsxs("label",{children:[c("accessibilityAI.foreground","Foreground"),e.jsx("input",{type:"color",value:d,onChange:f=>x(f.target.value)}),e.jsx("input",{type:"text",value:d,onChange:f=>x(f.target.value)})]}),e.jsxs("label",{children:[c("accessibilityAI.background","Background"),e.jsx("input",{type:"color",value:N,onChange:f=>A(f.target.value)}),e.jsx("input",{type:"text",value:N,onChange:f=>A(f.target.value)})]}),e.jsx("button",{type:"button",onClick:h,children:c("accessibilityAI.check","Check")})]}),R&&e.jsxs("div",{className:"nice-a11y-ai__contrast-result",children:[e.jsx("div",{className:"nice-a11y-ai__contrast-preview",style:{color:d,background:N},children:c("accessibilityAI.sampleTextAa","Sample Text Aa")}),e.jsxs("div",{className:"nice-a11y-ai__contrast-ratio",children:[e.jsxs("span",{className:"nice-a11y-ai__ratio-value",children:[R.ratio,":1"]}),e.jsxs("div",{className:"nice-a11y-ai__passes",children:[e.jsxs("span",{className:R.passesAA?"pass":"fail",children:[c("accessibilityAI.aa","AA:")," ",e.jsx(T.NiceIcon,{name:R.passesAA?"check":"close",size:14})]}),e.jsxs("span",{className:R.passesAALarge?"pass":"fail",children:[c("accessibilityAI.aaLarge","AA Large:")," ",e.jsx(T.NiceIcon,{name:R.passesAALarge?"check":"close",size:14})]}),e.jsxs("span",{className:R.passesAAA?"pass":"fail",children:[c("accessibilityAI.aaa","AAA:")," ",e.jsx(T.NiceIcon,{name:R.passesAAA?"check":"close",size:14})]})]})]}),R.suggestions&&R.suggestions.length>0&&e.jsx("div",{className:"nice-a11y-ai__suggestions",children:R.suggestions.map((f,j)=>e.jsx("div",{children:f},j))})]})]}),e.jsxs("div",{className:"nice-a11y-ai__analyzer",children:[e.jsx("h3",{children:c("accessibilityAI.htmlAccessibilityAnalyzerWcag","HTML Accessibility Analyzer (WCAG {wcagLevel})").replace("{wcagLevel}",String(a))}),e.jsx("textarea",{value:m,onChange:f=>p(f.target.value),placeholder:c("accessibilityAI.pasteHtmlCodeToAnalyze","Paste HTML code to analyze..."),className:"nice-a11y-ai__input",rows:8,disabled:y}),e.jsxs("div",{className:"nice-a11y-ai__actions",children:[e.jsx("button",{type:"button",onClick:v,disabled:y||!m.trim(),children:y?e.jsx("span",{className:"nice-a11y-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(T.NiceIcon,{name:"search",size:14})," ",c("accessibilityAI.analyze","Analyze")]})}),e.jsxs("button",{type:"button",onClick:w,disabled:y||!m.trim(),children:[e.jsx(T.NiceIcon,{name:"settings",size:14})," ",c("accessibilityAI.autoFix","Auto-Fix")]})]})]}),_&&e.jsxs("div",{className:"nice-a11y-ai__audit",children:[e.jsxs("div",{className:"nice-a11y-ai__audit-header",children:[e.jsxs("div",{className:"nice-a11y-ai__score",children:[e.jsx("span",{className:"nice-a11y-ai__score-value",children:_.score}),e.jsx("span",{className:"nice-a11y-ai__score-label",children:c("accessibilityAI.score","Score")})]}),e.jsxs("div",{className:"nice-a11y-ai__summary",children:[e.jsx("span",{className:"critical",children:c("accessibilityAI.critical","{critical} Critical").replace("{critical}",String(_.summary.critical))}),e.jsx("span",{className:"serious",children:c("accessibilityAI.serious","{serious} Serious").replace("{serious}",String(_.summary.serious))}),e.jsx("span",{className:"moderate",children:c("accessibilityAI.moderate","{moderate} Moderate").replace("{moderate}",String(_.summary.moderate))}),e.jsx("span",{className:"minor",children:c("accessibilityAI.minor","{minor} Minor").replace("{minor}",String(_.summary.minor))})]})]}),e.jsx("div",{className:"nice-a11y-ai__issues",children:_.issues.map(f=>o?o(f):e.jsxs("div",{className:"nice-a11y-ai__issue",style:{background:_e[f.severity].bg,borderLeftColor:_e[f.severity].color},children:[e.jsxs("div",{className:"nice-a11y-ai__issue-header",children:[e.jsx("span",{className:"nice-a11y-ai__issue-icon",children:e.jsx(T.NiceIcon,{name:_e[f.severity].icon,size:16})}),e.jsx("span",{className:"nice-a11y-ai__issue-title",children:f.title}),e.jsx("span",{className:"nice-a11y-ai__issue-wcag",children:c("accessibilityAI.wcag","WCAG {wcagCriteria} ({wcagLevel})").replace("{wcagCriteria}",String(f.wcagCriteria)).replace("{wcagLevel}",String(f.wcagLevel))})]}),e.jsx("p",{className:"nice-a11y-ai__issue-desc",children:f.description}),f.element&&e.jsx("code",{className:"nice-a11y-ai__issue-element",children:f.element}),e.jsxs("div",{className:"nice-a11y-ai__issue-suggestion",children:[e.jsx("strong",{children:c("accessibilityAI.fix","Fix:")})," ",f.suggestion]}),f.codeExample&&e.jsx("pre",{className:"nice-a11y-ai__issue-example",children:f.codeExample})]},f.id))}),_.recommendations.length>0&&e.jsxs("div",{className:"nice-a11y-ai__recommendations",children:[e.jsx("h4",{children:c("accessibilityAI.generalRecommendations","General Recommendations")}),e.jsx("ul",{children:_.recommendations.map((f,j)=>e.jsx("li",{children:f},j))})]})]}),e.jsx("style",{children:`
2996
2996
  .nice-a11y-ai {
2997
2997
  font-family: var(--nice-font-family, system-ui, sans-serif);
2998
2998
  }
@@ -3291,13 +3291,13 @@ ${d}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:j.message)==nu
3291
3291
  margin-bottom: var(--nice-space-1-5, 6px);
3292
3292
  font-size: 14px;
3293
3293
  }
3294
- `})]}):e.jsx("div",{className:`nice-a11y-ai nice-a11y-ai--disabled ${n||""}`,style:s,children:e.jsx("p",{children:c("accessibilityAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}const Re=[{name:"home",category:"navigation",keywords:["home","house","start","main"]},{name:"menu",category:"navigation",keywords:["menu","hamburger","nav","bars"]},{name:"arrow-left",category:"navigation",keywords:["back","previous","left","arrow"]},{name:"arrow-right",category:"navigation",keywords:["next","forward","right","arrow"]},{name:"chevron-down",category:"navigation",keywords:["expand","dropdown","down","chevron"]},{name:"chevron-up",category:"navigation",keywords:["collapse","up","chevron"]},{name:"plus",category:"action",keywords:["add","create","new","plus"]},{name:"minus",category:"action",keywords:["remove","subtract","minus"]},{name:"close",category:"action",keywords:["close","cancel","delete","remove","x"]},{name:"check",category:"action",keywords:["done","complete","success","check","tick"]},{name:"edit",category:"action",keywords:["edit","modify","pencil","write"]},{name:"trash",category:"action",keywords:["delete","remove","trash","bin"]},{name:"search",category:"action",keywords:["search","find","magnify","lookup"]},{name:"filter",category:"action",keywords:["filter","sort","funnel"]},{name:"download",category:"action",keywords:["download","save","export"]},{name:"upload",category:"action",keywords:["upload","import","send"]},{name:"refresh",category:"action",keywords:["refresh","reload","sync"]},{name:"copy",category:"action",keywords:["copy","duplicate","clone"]},{name:"mail",category:"communication",keywords:["email","mail","message","envelope"]},{name:"phone",category:"communication",keywords:["phone","call","telephone","contact"]},{name:"message",category:"communication",keywords:["chat","message","comment","bubble"]},{name:"bell",category:"notification",keywords:["notification","bell","alert","alarm"]},{name:"file",category:"file",keywords:["file","document","page"]},{name:"folder",category:"file",keywords:["folder","directory","category"]},{name:"image",category:"image",keywords:["image","photo","picture","gallery"]},{name:"video",category:"av",keywords:["video","movie","film","camera"]},{name:"user",category:"social",keywords:["user","person","account","profile"]},{name:"users",category:"social",keywords:["users","group","team","people"]},{name:"settings",category:"action",keywords:["settings","config","gear","cog","preferences"]},{name:"calendar",category:"business",keywords:["calendar","date","schedule","event"]},{name:"clock",category:"business",keywords:["time","clock","schedule","hour"]},{name:"card",category:"finance",keywords:["payment","card","credit","money","credit-card"]},{name:"bar-chart",category:"business",keywords:["chart","graph","analytics","statistics"]},{name:"lock",category:"security",keywords:["lock","secure","private","password"]},{name:"unlock",category:"security",keywords:["unlock","open","access"]},{name:"shield",category:"security",keywords:["shield","security","protect","safe"]},{name:"eye",category:"action",keywords:["view","show","visible","eye","visibility"]},{name:"eye-off",category:"action",keywords:["hide","invisible","hidden","eye-off"]},{name:"info",category:"alert",keywords:["info","information","help","about"]},{name:"warning",category:"alert",keywords:["warning","caution","alert","attention"]},{name:"error",category:"alert",keywords:["error","danger","fail","problem"]},{name:"success",category:"alert",keywords:["success","done","complete","check-circle"]},{name:"star",category:"action",keywords:["star","favorite","bookmark","rating"]},{name:"heart",category:"social",keywords:["heart","love","like","favorite"]},{name:"send",category:"social",keywords:["share","send","forward"]},{name:"link",category:"action",keywords:["link","url","chain","hyperlink"]},{name:"external-link",category:"action",keywords:["external","open","new-window"]}];let we=null,He=null;function Nt(){if(!we){const t=new Map(Re.map(a=>[a.name,a]));we=T.NICE_BUILTIN_ICONS.map(a=>t.get(a)??{name:a,category:"content",keywords:a.split("-")})}return we}function St(t){return He??(He=new Set(T.NICE_BUILTIN_ICONS)),He.has(t)}function za(t={}){const{config:a,defaultLibrary:i="nice",defaultStyle:r="outline",maxSuggestions:n=10,onSuggestion:s,onError:o}=t,c=ee(),[m,p]=l.useState(!1),[u,v]=l.useState(null),w=l.useRef(null),A=a||(c==null?void 0:c.config),R=l.useCallback(y=>{const I=y.toLowerCase(),b=I.split(/\s+/);return Nt().map(h=>{let _=0;return h.name===I?_+=100:h.name.includes(I)&&(_+=50),b.forEach(f=>{h.keywords.forEach(k=>{k===f?_+=30:k.length>=3&&f.length>=3&&(k.includes(f)||f.includes(k))&&(_+=15)})}),h.category===I&&(_+=20),{id:`icon_${h.name}`,name:h.name,displayName:h.name.replace(/-/g," ").replace(/\b\w/g,f=>f.toUpperCase()),category:h.category,style:r,library:i,relevanceScore:_,keywords:h.keywords}}).filter(h=>h.relevanceScore>0).sort((h,_)=>_.relevanceScore-h.relevanceScore).slice(0,n)},[i,r,n]),M=l.useCallback(async(y,I)=>{var _,f,k,S;const b=performance.now(),h=R(y);if(!A){const N={query:y,suggestions:h,latencyMs:performance.now()-b};return v(N),s==null||s(N),N}p(!0),(_=w.current)==null||_.abort(),w.current=new AbortController;try{const N=V(A),$=I?`
3294
+ `})]}):e.jsx("div",{className:`nice-a11y-ai nice-a11y-ai--disabled ${r||""}`,style:s,children:e.jsx("p",{children:c("accessibilityAI.aiNotConfiguredPleaseProvide","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}const Re=[{name:"home",category:"navigation",keywords:["home","house","start","main"]},{name:"menu",category:"navigation",keywords:["menu","hamburger","nav","bars"]},{name:"arrow-left",category:"navigation",keywords:["back","previous","left","arrow"]},{name:"arrow-right",category:"navigation",keywords:["next","forward","right","arrow"]},{name:"chevron-down",category:"navigation",keywords:["expand","dropdown","down","chevron"]},{name:"chevron-up",category:"navigation",keywords:["collapse","up","chevron"]},{name:"plus",category:"action",keywords:["add","create","new","plus"]},{name:"minus",category:"action",keywords:["remove","subtract","minus"]},{name:"close",category:"action",keywords:["close","cancel","delete","remove","x"]},{name:"check",category:"action",keywords:["done","complete","success","check","tick"]},{name:"edit",category:"action",keywords:["edit","modify","pencil","write"]},{name:"trash",category:"action",keywords:["delete","remove","trash","bin"]},{name:"search",category:"action",keywords:["search","find","magnify","lookup"]},{name:"filter",category:"action",keywords:["filter","sort","funnel"]},{name:"download",category:"action",keywords:["download","save","export"]},{name:"upload",category:"action",keywords:["upload","import","send"]},{name:"refresh",category:"action",keywords:["refresh","reload","sync"]},{name:"copy",category:"action",keywords:["copy","duplicate","clone"]},{name:"mail",category:"communication",keywords:["email","mail","message","envelope"]},{name:"phone",category:"communication",keywords:["phone","call","telephone","contact"]},{name:"message",category:"communication",keywords:["chat","message","comment","bubble"]},{name:"bell",category:"notification",keywords:["notification","bell","alert","alarm"]},{name:"file",category:"file",keywords:["file","document","page"]},{name:"folder",category:"file",keywords:["folder","directory","category"]},{name:"image",category:"image",keywords:["image","photo","picture","gallery"]},{name:"video",category:"av",keywords:["video","movie","film","camera"]},{name:"user",category:"social",keywords:["user","person","account","profile"]},{name:"users",category:"social",keywords:["users","group","team","people"]},{name:"settings",category:"action",keywords:["settings","config","gear","cog","preferences"]},{name:"calendar",category:"business",keywords:["calendar","date","schedule","event"]},{name:"clock",category:"business",keywords:["time","clock","schedule","hour"]},{name:"card",category:"finance",keywords:["payment","card","credit","money","credit-card"]},{name:"bar-chart",category:"business",keywords:["chart","graph","analytics","statistics"]},{name:"lock",category:"security",keywords:["lock","secure","private","password"]},{name:"unlock",category:"security",keywords:["unlock","open","access"]},{name:"shield",category:"security",keywords:["shield","security","protect","safe"]},{name:"eye",category:"action",keywords:["view","show","visible","eye","visibility"]},{name:"eye-off",category:"action",keywords:["hide","invisible","hidden","eye-off"]},{name:"info",category:"alert",keywords:["info","information","help","about"]},{name:"warning",category:"alert",keywords:["warning","caution","alert","attention"]},{name:"error",category:"alert",keywords:["error","danger","fail","problem"]},{name:"success",category:"alert",keywords:["success","done","complete","check-circle"]},{name:"star",category:"action",keywords:["star","favorite","bookmark","rating"]},{name:"heart",category:"social",keywords:["heart","love","like","favorite"]},{name:"send",category:"social",keywords:["share","send","forward"]},{name:"link",category:"action",keywords:["link","url","chain","hyperlink"]},{name:"external-link",category:"action",keywords:["external","open","new-window"]}];let we=null,He=null;function Nt(){if(!we){const t=new Map(Re.map(a=>[a.name,a]));we=T.NICE_BUILTIN_ICONS.map(a=>t.get(a)??{name:a,category:"content",keywords:a.split("-")})}return we}function St(t){return He??(He=new Set(T.NICE_BUILTIN_ICONS)),He.has(t)}function za(t={}){const{config:a,defaultLibrary:i="nice",defaultStyle:n="outline",maxSuggestions:r=10,onSuggestion:s,onError:o}=t,c=Z(),[m,p]=l.useState(!1),[d,x]=l.useState(null),N=l.useRef(null),A=a||(c==null?void 0:c.config),R=l.useCallback(_=>{const C=_.toLowerCase(),v=C.split(/\s+/);return Nt().map(h=>{let w=0;return h.name===C?w+=100:h.name.includes(C)&&(w+=50),v.forEach(f=>{h.keywords.forEach(j=>{j===f?w+=30:j.length>=3&&f.length>=3&&(j.includes(f)||f.includes(j))&&(w+=15)})}),h.category===C&&(w+=20),{id:`icon_${h.name}`,name:h.name,displayName:h.name.replace(/-/g," ").replace(/\b\w/g,f=>f.toUpperCase()),category:h.category,style:n,library:i,relevanceScore:w,keywords:h.keywords}}).filter(h=>h.relevanceScore>0).sort((h,w)=>w.relevanceScore-h.relevanceScore).slice(0,r)},[i,n,r]),$=l.useCallback(async(_,C)=>{var w,f,j,k;const v=performance.now(),h=R(_);if(!A){const I={query:_,suggestions:h,latencyMs:performance.now()-v};return x(I),s==null||s(I),I}p(!0),(w=N.current)==null||w.abort(),N.current=new AbortController;try{const I=Y(A),z=C?`
3295
3295
  Context:
3296
- - Component type: ${I.componentType||"any"}
3297
- - Purpose: ${I.purpose||"general"}
3298
- - Related icons: ${((f=I.relatedIcons)==null?void 0:f.join(", "))||"none"}
3299
- - Theme: ${I.theme||"light"}
3300
- - Preferred style: ${I.preferredStyle||r}`:"",F=(((S=(k=(await N.chat({messages:[{role:"system",content:`You are an icon recommendation expert. Suggest icons based on user query.
3296
+ - Component type: ${C.componentType||"any"}
3297
+ - Purpose: ${C.purpose||"general"}
3298
+ - Related icons: ${((f=C.relatedIcons)==null?void 0:f.join(", "))||"none"}
3299
+ - Theme: ${C.theme||"light"}
3300
+ - Preferred style: ${C.preferredStyle||n}`:"",F=(((k=(j=(await I.chat({messages:[{role:"system",content:`You are an icon recommendation expert. Suggest icons based on user query.
3301
3301
  Choose ONLY from this icon set (NiceIcon names), and use the names exactly as written:
3302
3302
  ${T.NICE_BUILTIN_ICONS.join(", ")}
3303
3303
 
@@ -3311,7 +3311,7 @@ Return JSON array of 5-10 icon suggestions:
3311
3311
  "usage": "Brief usage description"
3312
3312
  }]
3313
3313
 
3314
- Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Suggest icons for: "${y}"${$}`}],temperature:.5,maxTokens:1024})).choices[0])==null?void 0:k.message)==null?void 0:S.content)||"").match(/\[[\s\S]*\]/);let U=[];if(F)try{U=JSON.parse(F[0]).filter(x=>typeof x.name=="string"&&St(x.name)).map((x,B)=>({id:x.id||`ai_icon_${B}`,name:x.name,displayName:x.displayName||x.name,category:x.category||"action",style:(I==null?void 0:I.preferredStyle)||r,library:i,relevanceScore:x.relevanceScore||50,keywords:x.keywords||[],usage:x.usage}))}catch{}const H=Ct(h,U,n),X={query:y,suggestions:H,latencyMs:performance.now()-b};return v(X),s==null||s(X),X}catch(N){const $=N instanceof Error?N.message:"Suggestion failed",E={query:y,suggestions:h,latencyMs:performance.now()-b,error:$};return v(E),o==null||o($),E}finally{p(!1)}},[A,i,r,n,R,s,o]),P=l.useCallback(y=>Re.filter(I=>I.category===y).map(I=>({id:`icon_${I.name}`,name:I.name,displayName:I.name.replace(/-/g," ").replace(/\b\w/g,b=>b.toUpperCase()),category:I.category,style:r,library:i,relevanceScore:100,keywords:I.keywords})),[i,r]),g=l.useMemo(()=>{const y=new Set;return Re.forEach(I=>y.add(I.category)),Array.from(y)},[]),d=l.useCallback(()=>{v(null)},[]),j=l.useCallback(()=>{var y;(y=w.current)==null||y.abort(),p(!1)},[]);return l.useEffect(()=>()=>{var y;(y=w.current)==null||y.abort()},[]),{suggestIcons:M,localSearch:R,getByCategory:P,categories:g,loading:m,lastResult:u,clearResults:d,abort:j,isConfigured:!!A}}function Ct(t,a,i){const r=new Set,n=[];for(const s of t)r.has(s.name)||(r.add(s.name),n.push(s));for(const s of a)!r.has(s.name)&&n.length<i&&(r.add(s.name),n.push(s));return n.slice(0,i)}function It({config:t,defaultLibrary:a="nice",defaultStyle:i="outline",maxSuggestions:r=10,onSelect:n,showCategories:s=!0,showPreview:o=!0,className:c,style:m}){const{t:p}=T.useNiceTranslation(),u=S=>p(`iconSuggestor.category.${S}`,S.charAt(0).toUpperCase()+S.slice(1)),[v,w]=l.useState(""),[A,R]=l.useState(null),[M,P]=l.useState(null),{suggestIcons:g,getByCategory:d,categories:j,loading:y,lastResult:I}=za({config:t,defaultLibrary:a,defaultStyle:i,maxSuggestions:r}),b=async()=>{v.trim()&&(R(null),await g(v))},h=S=>{S.key==="Enter"&&b()},_=S=>{A===S?R(null):(R(S),w(""))},f=S=>{P(S),n==null||n(S)},k=A?d(A):(I==null?void 0:I.suggestions)||[];return e.jsxs("div",{className:`nice-icon-ai ${c||""}`,style:m,children:[e.jsxs("div",{className:"nice-icon-ai__search",children:[e.jsx("input",{type:"text",value:v,onChange:S=>w(S.target.value),onKeyDown:h,placeholder:p("iconSuggestor.placeholder","Search icons... (e.g., 'save', 'notification', 'user profile')"),"aria-label":p("iconSuggestor.query","Icon search"),className:"nice-icon-ai__input",disabled:y}),e.jsx("button",{type:"button",onClick:b,className:"nice-icon-ai__search-btn",disabled:y||!v.trim(),"aria-label":p("iconSuggestor.search","Search icons"),children:y?e.jsx("span",{className:"nice-icon-ai__spinner"}):e.jsx(T.NiceIcon,{name:"search",size:16})})]}),s&&e.jsx("div",{className:"nice-icon-ai__categories",children:j.map(S=>e.jsx("button",{type:"button",className:`nice-icon-ai__category ${A===S?"nice-icon-ai__category--selected":""}`,onClick:()=>_(S),children:u(S)},S))}),k.length>0&&e.jsx("div",{className:"nice-icon-ai__results",children:k.map(S=>e.jsxs("button",{type:"button",className:`nice-icon-ai__icon ${(M==null?void 0:M.id)===S.id?"nice-icon-ai__icon--selected":""}`,onClick:()=>f(S),title:S.displayName,children:[e.jsx(Ke,{icon:S}),e.jsx("span",{className:"nice-icon-ai__icon-name",children:S.displayName})]},S.id))}),o&&M&&e.jsxs("div",{className:"nice-icon-ai__preview",children:[e.jsx("div",{className:"nice-icon-ai__preview-icon",children:e.jsx(Ke,{icon:M,size:64})}),e.jsxs("div",{className:"nice-icon-ai__preview-info",children:[e.jsx("div",{className:"nice-icon-ai__preview-name",children:M.displayName}),e.jsxs("div",{className:"nice-icon-ai__preview-details",children:[e.jsx("span",{children:p("iconSuggestor.categoryLabel","Category: {category}").replace("{category}",u(M.category))}),e.jsx("code",{className:"nice-icon-ai__preview-code",children:Ye(M)})]}),e.jsx("div",{className:"nice-icon-ai__preview-keywords",children:M.keywords.map(S=>e.jsx("span",{className:"nice-icon-ai__keyword",children:S},S))}),M.usage&&e.jsx("div",{className:"nice-icon-ai__preview-usage",children:M.usage}),e.jsxs("div",{className:"nice-icon-ai__preview-actions",children:[e.jsxs("button",{type:"button",onClick:()=>n==null?void 0:n(M),children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",p("iconSuggestor.useIcon","Use Icon")]}),e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(M.name)},children:[e.jsx(T.NiceIcon,{name:"clipboard",size:14})," ",p("iconSuggestor.copyName","Copy Name")]}),e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(Ye(M))},children:[e.jsx(T.NiceIcon,{name:"code",size:14})," ",p("iconSuggestor.copyJsx","Copy JSX")]})]})]})]}),e.jsx("style",{children:`
3314
+ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Suggest icons for: "${_}"${z}`}],temperature:.5,maxTokens:1024})).choices[0])==null?void 0:j.message)==null?void 0:k.content)||"").match(/\[[\s\S]*\]/);let G=[];if(F)try{G=JSON.parse(F[0]).filter(b=>typeof b.name=="string"&&St(b.name)).map((b,B)=>({id:b.id||`ai_icon_${B}`,name:b.name,displayName:b.displayName||b.name,category:b.category||"action",style:(C==null?void 0:C.preferredStyle)||n,library:i,relevanceScore:b.relevanceScore||50,keywords:b.keywords||[],usage:b.usage}))}catch{}const K=Ct(h,G,r),X={query:_,suggestions:K,latencyMs:performance.now()-v};return x(X),s==null||s(X),X}catch(I){const z=I instanceof Error?I.message:"Suggestion failed",E={query:_,suggestions:h,latencyMs:performance.now()-v,error:z};return x(E),o==null||o(z),E}finally{p(!1)}},[A,i,n,r,R,s,o]),M=l.useCallback(_=>Re.filter(C=>C.category===_).map(C=>({id:`icon_${C.name}`,name:C.name,displayName:C.name.replace(/-/g," ").replace(/\b\w/g,v=>v.toUpperCase()),category:C.category,style:n,library:i,relevanceScore:100,keywords:C.keywords})),[i,n]),g=l.useMemo(()=>{const _=new Set;return Re.forEach(C=>_.add(C.category)),Array.from(_)},[]),u=l.useCallback(()=>{x(null)},[]),y=l.useCallback(()=>{var _;(_=N.current)==null||_.abort(),p(!1)},[]);return l.useEffect(()=>()=>{var _;(_=N.current)==null||_.abort()},[]),{suggestIcons:$,localSearch:R,getByCategory:M,categories:g,loading:m,lastResult:d,clearResults:u,abort:y,isConfigured:!!A}}function Ct(t,a,i){const n=new Set,r=[];for(const s of t)n.has(s.name)||(n.add(s.name),r.push(s));for(const s of a)!n.has(s.name)&&r.length<i&&(n.add(s.name),r.push(s));return r.slice(0,i)}function It({config:t,defaultLibrary:a="nice",defaultStyle:i="outline",maxSuggestions:n=10,onSelect:r,showCategories:s=!0,showPreview:o=!0,className:c,style:m}){const{t:p}=T.useNiceTranslation(),d=k=>p(`iconSuggestor.category.${k}`,k.charAt(0).toUpperCase()+k.slice(1)),[x,N]=l.useState(""),[A,R]=l.useState(null),[$,M]=l.useState(null),{suggestIcons:g,getByCategory:u,categories:y,loading:_,lastResult:C}=za({config:t,defaultLibrary:a,defaultStyle:i,maxSuggestions:n}),v=async()=>{x.trim()&&(R(null),await g(x))},h=k=>{k.key==="Enter"&&v()},w=k=>{A===k?R(null):(R(k),N(""))},f=k=>{M(k),r==null||r(k)},j=A?u(A):(C==null?void 0:C.suggestions)||[];return e.jsxs("div",{className:`nice-icon-ai ${c||""}`,style:m,children:[e.jsxs("div",{className:"nice-icon-ai__search",children:[e.jsx("input",{type:"text",value:x,onChange:k=>N(k.target.value),onKeyDown:h,placeholder:p("iconSuggestor.placeholder","Search icons... (e.g., 'save', 'notification', 'user profile')"),"aria-label":p("iconSuggestor.query","Icon search"),className:"nice-icon-ai__input",disabled:_}),e.jsx("button",{type:"button",onClick:v,className:"nice-icon-ai__search-btn",disabled:_||!x.trim(),"aria-label":p("iconSuggestor.search","Search icons"),children:_?e.jsx("span",{className:"nice-icon-ai__spinner"}):e.jsx(T.NiceIcon,{name:"search",size:16})})]}),s&&e.jsx("div",{className:"nice-icon-ai__categories",children:y.map(k=>e.jsx("button",{type:"button",className:`nice-icon-ai__category ${A===k?"nice-icon-ai__category--selected":""}`,onClick:()=>w(k),children:d(k)},k))}),j.length>0&&e.jsx("div",{className:"nice-icon-ai__results",children:j.map(k=>e.jsxs("button",{type:"button",className:`nice-icon-ai__icon ${($==null?void 0:$.id)===k.id?"nice-icon-ai__icon--selected":""}`,onClick:()=>f(k),title:k.displayName,children:[e.jsx(Ke,{icon:k}),e.jsx("span",{className:"nice-icon-ai__icon-name",children:k.displayName})]},k.id))}),o&&$&&e.jsxs("div",{className:"nice-icon-ai__preview",children:[e.jsx("div",{className:"nice-icon-ai__preview-icon",children:e.jsx(Ke,{icon:$,size:64})}),e.jsxs("div",{className:"nice-icon-ai__preview-info",children:[e.jsx("div",{className:"nice-icon-ai__preview-name",children:$.displayName}),e.jsxs("div",{className:"nice-icon-ai__preview-details",children:[e.jsx("span",{children:p("iconSuggestor.categoryLabel","Category: {category}").replace("{category}",d($.category))}),e.jsx("code",{className:"nice-icon-ai__preview-code",children:Ve($)})]}),e.jsx("div",{className:"nice-icon-ai__preview-keywords",children:$.keywords.map(k=>e.jsx("span",{className:"nice-icon-ai__keyword",children:k},k))}),$.usage&&e.jsx("div",{className:"nice-icon-ai__preview-usage",children:$.usage}),e.jsxs("div",{className:"nice-icon-ai__preview-actions",children:[e.jsxs("button",{type:"button",onClick:()=>r==null?void 0:r($),children:[e.jsx(T.NiceIcon,{name:"check",size:14})," ",p("iconSuggestor.useIcon","Use Icon")]}),e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText($.name)},children:[e.jsx(T.NiceIcon,{name:"clipboard",size:14})," ",p("iconSuggestor.copyName","Copy Name")]}),e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(Ve($))},children:[e.jsx(T.NiceIcon,{name:"code",size:14})," ",p("iconSuggestor.copyJsx","Copy JSX")]})]})]})]}),e.jsx("style",{children:`
3315
3315
  .nice-icon-ai {
3316
3316
  font-family: var(--nice-font-family, system-ui, sans-serif);
3317
3317
  }
@@ -3518,4 +3518,4 @@ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Sugges
3518
3518
  color: white;
3519
3519
  border: none;
3520
3520
  }
3521
- `})]})}function Ke({icon:t,size:a=32}){return e.jsx(T.NiceIcon,{name:t.name,size:a})}function Ye(t){return`<NiceIcon name="${t.name}" />`}exports.ACCESSIBILITY_CHECKER_TEMPLATE=Se;exports.AnthropicProvider=pa;exports.AzureOpenAIProvider=ga;exports.CHART_CONFIG_TEMPLATE=ue;exports.CODE_COMPLETION_TEMPLATE=me;exports.CostTracker=ba;exports.DATA_GRID_FILTER_TEMPLATE=oe;exports.DATA_GRID_SORT_TEMPLATE=le;exports.FORM_BUILDER_TEMPLATE=de;exports.GroqProvider=fa;exports.InMemoryCostStorage=Oe;exports.LocalStorageCostStorage=xa;exports.NiceAIHintBubble=ea;exports.NiceAIProvider=$a;exports.NiceAccessibilityAI=kt;exports.NiceChartAI=qi;exports.NiceCodeEditorAI=Vi;exports.NiceDataGridAI=Pi;exports.NiceDataLabeler=ki;exports.NiceFormBuilderAI=Ei;exports.NiceIconSuggestorAI=It;exports.NiceLayoutAI=yt;exports.NiceMLStudio=_i;exports.NiceModelInference=Si;exports.NiceReportBuilderAI=lt;exports.NiceThemeGeneratorAI=gt;exports.NiceWorkflowDesignerAI=at;exports.OllamaProvider=ha;exports.OpenAIProvider=ke;exports.PROMPT_TEMPLATES=xe;exports.REPORT_LAYOUT_TEMPLATE=ge;exports.RateLimiter=Ve;exports.ResilientLLMClient=ya;exports.SUMMARIZE_DATA_TEMPLATE=Ie;exports.THEME_GENERATOR_TEMPLATE=Ne;exports.TRANSLATION_TEMPLATE=Ce;exports.WORKFLOW_GENERATOR_TEMPLATE=pe;exports.build3DSceneContext=sa;exports.buildAudioContext=na;exports.buildChartContext=Ba;exports.buildCodeEditorContext=ta;exports.buildColorPickerContext=Pe;exports.buildDataGridContext=Da;exports.buildDatePickerContext=$e;exports.buildDiagramLayoutContext=da;exports.buildFormFillContext=aa;exports.buildGameEngineContext=la;exports.buildGraphicsContext=ca;exports.buildHtmlEditorContext=ra;exports.buildIconSearchContext=oa;exports.buildNumberInputContext=ze;exports.buildPresentationGenerateContext=ua;exports.buildSelectContext=Me;exports.buildSlideDesignContext=ma;exports.buildTextInputContext=Le;exports.buildValidationContext=ia;exports.colorControlContext=li;exports.compileTemplate=ie;exports.createLLMProvider=ae;exports.createProviderFromConfig=V;exports.createResilientClient=va;exports.createResilientClientWithDefaults=Li;exports.dateControlContext=oi;exports.getTemplate=Ci;exports.getTemplatesByCategory=Ii;exports.listTemplates=Ai;exports.numberControlContext=si;exports.parseJSONResponse=Ze;exports.parseSSEStream=Qe;exports.selectControlContext=ci;exports.textControlContext=ni;exports.useAI3DHint=Xa;exports.useAIAudioHint=Va;exports.useAICodeHint=Ka;exports.useAIColorHint=Ua;exports.useAIContext=ee;exports.useAIDateHint=Ga;exports.useAIDiagramLayout=ai;exports.useAIFormFill=Ha;exports.useAIGraphicsHint=Qa;exports.useAIHtmlHint=Ya;exports.useAIIconSearch=Za;exports.useAINpcHint=ei;exports.useAINumberHint=Ja;exports.useAIPresentationGenerate=ii;exports.useAISelectHint=qa;exports.useAISlideDesign=ti;exports.useAITextHint=Fa;exports.useAIValidation=Wa;exports.useAccessibilityAI=La;exports.useChartAI=ja;exports.useCodeEditorAI=ka;exports.useCostTracker=Ti;exports.useDataGridAI=_a;exports.useFormBuilderAI=wa;exports.useIconSuggestorAI=za;exports.useLayoutAI=Ta;exports.useNiceAIHint=Z;exports.useReportBuilderAI=Ca;exports.useThemeGeneratorAI=Aa;exports.useWorkflowDesignerAI=Na;exports.withAIHint=ri;
3521
+ `})]})}function Ke({icon:t,size:a=32}){return e.jsx(T.NiceIcon,{name:t.name,size:a})}function Ve(t){return`<NiceIcon name="${t.name}" />`}exports.ACCESSIBILITY_CHECKER_TEMPLATE=Se;exports.AnthropicProvider=pa;exports.AzureOpenAIProvider=ga;exports.CHART_CONFIG_TEMPLATE=ue;exports.CODE_COMPLETION_TEMPLATE=me;exports.CostTracker=ba;exports.DATA_GRID_FILTER_TEMPLATE=oe;exports.DATA_GRID_SORT_TEMPLATE=le;exports.FORM_BUILDER_TEMPLATE=de;exports.GroqProvider=fa;exports.InMemoryCostStorage=Oe;exports.LocalStorageCostStorage=xa;exports.NiceAIHintBubble=ea;exports.NiceAIProvider=$a;exports.NiceAccessibilityAI=kt;exports.NiceChartAI=qi;exports.NiceCodeEditorAI=Yi;exports.NiceDataGridAI=Pi;exports.NiceDataLabeler=ki;exports.NiceFormBuilderAI=Ei;exports.NiceIconSuggestorAI=It;exports.NiceLayoutAI=yt;exports.NiceMLStudio=_i;exports.NiceModelInference=Si;exports.NiceReportBuilderAI=lt;exports.NiceThemeGeneratorAI=gt;exports.NiceWorkflowDesignerAI=at;exports.OllamaProvider=ha;exports.OpenAIProvider=ke;exports.PROMPT_TEMPLATES=xe;exports.REPORT_LAYOUT_TEMPLATE=ge;exports.RateLimiter=Ye;exports.ResilientLLMClient=ya;exports.SUMMARIZE_DATA_TEMPLATE=Ie;exports.THEME_GENERATOR_TEMPLATE=Ne;exports.TRANSLATION_TEMPLATE=Ce;exports.WORKFLOW_GENERATOR_TEMPLATE=pe;exports.build3DSceneContext=sa;exports.buildAudioContext=na;exports.buildChartContext=Ba;exports.buildCodeEditorContext=ta;exports.buildColorPickerContext=Pe;exports.buildDataGridContext=Da;exports.buildDatePickerContext=$e;exports.buildDiagramLayoutContext=da;exports.buildFormFillContext=aa;exports.buildGameEngineContext=la;exports.buildGraphicsContext=ca;exports.buildHtmlEditorContext=ra;exports.buildIconSearchContext=oa;exports.buildNumberInputContext=ze;exports.buildPresentationGenerateContext=ua;exports.buildSelectContext=Me;exports.buildSlideDesignContext=ma;exports.buildTextInputContext=Le;exports.buildValidationContext=ia;exports.colorControlContext=li;exports.compileTemplate=ae;exports.createLLMProvider=ee;exports.createProviderFromConfig=Y;exports.createResilientClient=va;exports.createResilientClientWithDefaults=Li;exports.dateControlContext=oi;exports.getTemplate=Ci;exports.getTemplatesByCategory=Ii;exports.listTemplates=Ai;exports.numberControlContext=si;exports.parseJSONResponse=Ze;exports.parseSSEStream=Qe;exports.selectControlContext=ci;exports.textControlContext=ni;exports.useAI3DHint=Xa;exports.useAIAudioHint=Ya;exports.useAICodeHint=Ka;exports.useAIColorHint=Ua;exports.useAIContext=Z;exports.useAIDateHint=Ga;exports.useAIDiagramLayout=ai;exports.useAIFormFill=Ha;exports.useAIGraphicsHint=Qa;exports.useAIHtmlHint=Va;exports.useAIIconSearch=Za;exports.useAINpcHint=ei;exports.useAINumberHint=Ja;exports.useAIPresentationGenerate=ii;exports.useAISelectHint=qa;exports.useAISlideDesign=ti;exports.useAITextHint=Fa;exports.useAIValidation=Wa;exports.useAccessibilityAI=La;exports.useChartAI=ja;exports.useCodeEditorAI=ka;exports.useCostTracker=Ti;exports.useDataGridAI=_a;exports.useFormBuilderAI=wa;exports.useIconSuggestorAI=za;exports.useLayoutAI=Ta;exports.useNiceAIHint=Q;exports.useReportBuilderAI=Ca;exports.useThemeGeneratorAI=Aa;exports.useWorkflowDesignerAI=Na;exports.withAIHint=ri;