@nice2dev/ui-ai 1.1.10 → 1.2.0

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"),d=require("react"),L=require("@nice2dev/ui-core"),Ca=require("@nice2dev/ui");class Ue{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 qe=d.createContext(null);function Sa({config:t,rateLimits:a,enabled:i=!0,onRateLimitWarning:r,children:n}){const s=d.useRef(null);s.current||(s.current=new Ue(a,r));const c=d.useCallback(()=>s.current.getStatus(),[]),l=d.useMemo(()=>({config:t,enabled:i,rateLimiter:s.current,getRateLimitStatus:c}),[t,i,c]);return e.jsx(qe.Provider,{value:l,children:n})}function Z(){return d.useContext(qe)}async function*He(t,a){var s,c,l,p,f,g,y,w,S;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:z,value:k}=await i.read();if(z)break;n+=r.decode(k,{stream:!0});const I=n.split(`
2
- `);n=I.pop()??"";for(const j of I){const o=j.trim();if(!(!o||o===":")){if(o.startsWith("data:")){const N=o.slice(5).trim();if(N==="[DONE]"){yield{token:"",done:!0};return}try{const _=JSON.parse(N),m=((p=(l=(c=_.choices)==null?void 0:c[0])==null?void 0:l.delta)==null?void 0:p.content)??"",v=((g=(f=_.choices)==null?void 0:f[0])==null?void 0:g.finish_reason)==="stop";(m||v)&&(yield{token:m,done:v,usage:_.usage})}catch{N&&(yield{token:N,done:!1})}continue}try{const N=JSON.parse(o),_=N.text??N.content??N.token??"";_&&(yield{token:_,done:!1})}catch{o&&(yield{token:o,done:!1})}}}}if(n.trim()){const z=n.trim();if(z.startsWith("data:")){const k=z.slice(5).trim();if(k&&k!=="[DONE]")try{const j=((S=(w=(y=JSON.parse(k).choices)==null?void 0:y[0])==null?void 0:w.delta)==null?void 0:S.content)??"";j&&(yield{token:j,done:!0})}catch{yield{token:k,done:!0}}}}}finally{i.releaseLock()}}async function We(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 ne=new Map;function Pe(t,a){const i=a?{...t,fieldValue:void 0,formContext:void 0}:t;return JSON.stringify(i)}function Ta(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 c=typeof t.fieldValue=="string"?t.fieldValue:JSON.stringify(t.fieldValue);n.push(`Current value: ${c}`)}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:
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),d=require("react"),A=require("@nice2dev/ui-core"),Aa=require("@nice2dev/ui");class Ge{constructor(a={},t){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1,this.config={maxRequestsPerMinute:a.maxRequestsPerMinute??30,maxTokensPerSession:a.maxTokensPerSession??1e4,warnThresholdPercent:a.warnThresholdPercent??80},this.onWarning=t}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,t=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||t>=this.config.warnThresholdPercent}}reset(){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1}pruneOldTimestamps(){const a=Date.now()-6e4;this.timestamps=this.timestamps.filter(t=>t>a)}checkWarning(){var t;if(this.warningEmitted)return;this.getStatus().isWarning&&(this.warningEmitted=!0,(t=this.onWarning)==null||t.call(this))}}const We=d.createContext(null);function Ia({config:i,rateLimits:a,enabled:t=!0,onRateLimitWarning:r,children:n}){const s=d.useRef(null);s.current||(s.current=new Ge(a,r));const o=d.useCallback(()=>s.current.getStatus(),[]),c=d.useMemo(()=>({config:i,enabled:t,rateLimiter:s.current,getRateLimitStatus:o}),[i,t,o]);return e.jsx(We.Provider,{value:c,children:n})}function Z(){return d.useContext(We)}async function*Ve(i,a){var s,o,c,h,p,m,b,w,k;const t=(s=i.body)==null?void 0:s.getReader();if(!t)throw new Error("Response body is not readable");const r=new TextDecoder;let n="";try{for(;!(a!=null&&a.aborted);){const{done:M,value:C}=await t.read();if(M)break;n+=r.decode(C,{stream:!0});const O=n.split(`
2
+ `);n=O.pop()??"";for(const _ of O){const l=_.trim();if(!(!l||l===":")){if(l.startsWith("data:")){const y=l.slice(5).trim();if(y==="[DONE]"){yield{token:"",done:!0};return}try{const S=JSON.parse(y),f=((h=(c=(o=S.choices)==null?void 0:o[0])==null?void 0:c.delta)==null?void 0:h.content)??"",j=((m=(p=S.choices)==null?void 0:p[0])==null?void 0:m.finish_reason)==="stop";(f||j)&&(yield{token:f,done:j,usage:S.usage})}catch{y&&(yield{token:y,done:!1})}continue}try{const y=JSON.parse(l),S=y.text??y.content??y.token??"";S&&(yield{token:S,done:!1})}catch{l&&(yield{token:l,done:!1})}}}}if(n.trim()){const M=n.trim();if(M.startsWith("data:")){const C=M.slice(5).trim();if(C&&C!=="[DONE]")try{const _=((k=(w=(b=JSON.parse(C).choices)==null?void 0:b[0])==null?void 0:w.delta)==null?void 0:k.content)??"";_&&(yield{token:_,done:!0})}catch{yield{token:C,done:!0}}}}}finally{t.releaseLock()}}async function Ke(i){var t,r,n,s;const a=await i.json();if((n=(r=(t=a.choices)==null?void 0:t[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 ne=new Map;function Ee(i,a){const t=a?{...i,fieldValue:void 0,formContext:void 0}:i;return JSON.stringify(t)}function Ra(i,a){const t=[],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.";t.push({role:"system",content:r});const n=[];if(i.fieldLabel&&n.push(`Field: "${i.fieldLabel}"`),i.fieldType&&n.push(`Type: ${i.fieldType}`),!a.privacyMode&&i.fieldValue!==void 0){const o=typeof i.fieldValue=="string"?i.fieldValue:JSON.stringify(i.fieldValue);n.push(`Current value: ${o}`)}i.validationRules&&Object.keys(i.validationRules).length>0&&n.push(`Validation: ${JSON.stringify(i.validationRules)}`),i.schema&&Object.keys(i.schema).length>0&&n.push(`Schema: ${JSON.stringify(i.schema)}`),!a.privacyMode&&i.formContext&&Object.keys(i.formContext).length>0&&n.push(`Form context: ${JSON.stringify(i.formContext)}`),i.customPrompt&&n.push(i.customPrompt);const s=n.length>0?`Provide a helpful hint for this field:
3
3
  ${n.join(`
4
- `)}`:"Provide a helpful suggestion.";return i.push({role:"user",content:s}),i}function X(t={},a={}){t=t??{},a=a??{};const{debounceMs:i=500,disabled:r=!1}=a,n=Z(),[s,c]=d.useState(""),[l,p]=d.useState(!1),[f,g]=d.useState(null),[y,w]=d.useState(!1),S=d.useRef(null),z=d.useRef(0),k=d.useCallback(async()=>{var h,$,D;if(!n||!n.enabled||r)return;const{config:o,rateLimiter:N}=n;if(!N.recordRequest()){g("Rate limit exceeded. Please wait before requesting another hint.");return}const _=Pe(t,o.privacyMode??!1),m=ne.get(_);if(m){c(m),p(!1),g(null),w(!1);return}(h=S.current)==null||h.abort();const v=new AbortController;S.current=v,p(!0),g(null),c(""),w(!1);const x=Ta(t,o),u=o.stream!==!1;try{const C={"Content-Type":"application/json",...o.headers};o.apiKey&&(C.Authorization=`Bearer ${o.apiKey}`);const A=JSON.stringify({model:o.model??"gpt-3.5-turbo",messages:x,temperature:o.temperature??.7,max_tokens:o.maxTokens??256,stream:u}),O=await fetch(o.endpoint,{method:"POST",headers:C,body:A,signal:v.signal});if(!O.ok){const B=await O.text().catch(()=>O.statusText);throw new Error(`AI request failed (${O.status}): ${B}`)}if(u){w(!0);let B="";for await(const b of He(O,v.signal))if(v.signal.aborted||(B+=b.token,c(B),($=b.usage)!=null&&$.completion_tokens&&N.recordTokens(b.usage.completion_tokens),b.done))break;if(B.length>0){const b=Math.ceil(B.length/4);N.recordTokens(b)}ne.set(_,B)}else{const B=await We(O);c(B.text),ne.set(_,B.text),(D=B.usage)!=null&&D.completion_tokens?N.recordTokens(B.usage.completion_tokens):N.recordTokens(Math.ceil(B.text.length/4))}}catch(C){if(C instanceof DOMException&&C.name==="AbortError")return;g(C instanceof Error?C.message:"AI hint request failed")}finally{v.signal.aborted||(p(!1),w(!1))}},[n,t,r]);d.useEffect(()=>{if(!n||!n.enabled||r)return;const o=setTimeout(k,i);return()=>clearTimeout(o)},[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,z.current]),d.useEffect(()=>()=>{var o;(o=S.current)==null||o.abort()},[]);const I=d.useCallback(()=>{var o;(o=S.current)==null||o.abort(),p(!1),w(!1)},[]),j=d.useCallback(()=>{if(n){const o=Pe(t,n.config.privacyMode??!1);ne.delete(o)}z.current+=1,k()},[n,t,k]);return!n||!n.enabled?{text:"",loading:!1,error:null,streaming:!1,abort:()=>{},refresh:()=>{},hint:null,fetchHint:async()=>{}}:{text:s,loading:l,error:f,streaming:y,abort:I,refresh:j,hint:s?{content:s}:null,fetchHint:async()=>{await k()}}}function Aa(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,c=Math.max(i,r,n,s);return c===i?"top":c===r?"bottom":c===s?"right":"left"}function Ra(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 Se=d.forwardRef(({context:t,position:a="auto",debounceMs:i=500,showOnHover:r=!1,triggerIcon:n,className:s,style:c},l)=>{var _;const p=Z(),[f,g]=d.useState(!1),[y,w]=d.useState(!1),S=d.useRef(null),z=d.useRef(null),k=X(t,{debounceMs:i,disabled:!y});d.useEffect(()=>{if(!f)return;const m=v=>{var u,h;const x=v.target;(u=S.current)!=null&&u.contains(x)||(h=z.current)!=null&&h.contains(x)||(g(!1),w(!1))};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[f]),d.useEffect(()=>{if(!f)return;const m=v=>{v.key==="Escape"&&(g(!1),w(!1),k.abort())};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[f,k]);const I=d.useCallback(m=>{if(m.stopPropagation(),r)return;const v=!f;g(v),w(v)},[f,r]),j=d.useCallback(()=>{r&&(g(!0),w(!0))},[r]),o=d.useCallback(()=>{r&&(g(!1),w(!1))},[r]);if(!p||!p.enabled)return null;const N=Aa(a,((_=S.current)==null?void 0:_.getBoundingClientRect())??null);return e.jsxs("span",{ref:l,className:s,style:{position:"relative",display:"inline-flex",...c},onMouseEnter:j,onMouseLeave:o,children:[e.jsx("button",{ref:S,type:"button",onClick:I,"aria-label":"AI hint","aria-expanded":f,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(L.NiceIcon,{name:"wand",size:16})}),f&&e.jsxs("div",{ref:z,role:"tooltip",className:"ntd-ai-popover",style:Ra(N),children:[k.loading&&!k.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:"Thinking..."})]}),k.text&&e.jsxs("div",{className:"ntd-ai-content",children:[k.text,k.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"}})]}),k.error&&e.jsx("div",{className:"ntd-ai-error",style:{color:"var(--ntd-ai-error, #f38ba8)"},children:k.error}),k.text&&!k.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:()=>k.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(L.NiceIcon,{name:"refresh",size:12})," Refresh"]}),e.jsxs("button",{type:"button",onClick:()=>{var m;(m=navigator.clipboard)==null||m.writeText(k.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(L.NiceIcon,{name:"copy",size:12})," Copy"]})]})]})]})});Se.displayName="NiceAIHintBubble";function Te(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 Ae(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 Re(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 Ie(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 ze(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 Ia(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 za(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 Ge(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 Ve(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 Ma(t,a,i){const r=d.useMemo(()=>Te(t,a,i),[t,a,i==null?void 0:i.placeholder,i==null?void 0:i.maxLength,i==null?void 0:i.pattern]);return X(r,i)}function La(t,a,i){const r=d.useMemo(()=>Ae(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 X(r,i)}function Pa(t,a,i){const r=d.useMemo(()=>Re(t,a,i),[t,a,i==null?void 0:i.multiple]);return X(r,i)}function $a(t,a,i){const r=d.useMemo(()=>Ie(t,a,i),[t,a,i==null?void 0:i.min,i==null?void 0:i.max,i==null?void 0:i.disableWeekends]);return X(r,i)}function Oa(t,a,i){const r=d.useMemo(()=>ze(t,a,i),[t,a,i==null?void 0:i.industry]);return X(r,i)}function Ea(t,a,i,r,n){const s=d.useMemo(()=>r?Ve(t,a,i,r,n):{fieldLabel:t,fieldType:a},[t,a,i,r]);return X(s,{...n,disabled:!r||(n==null?void 0:n.disabled)})}function Da(t,a,i){const r=d.useMemo(()=>t?Ge(t,a):{fieldLabel:"Form"},[t,a]);return X(r,{...i,disabled:!t||(i==null?void 0:i.disabled)})}function Ke(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(`
4
+ `)}`:"Provide a helpful suggestion.";return t.push({role:"user",content:s}),t}function X(i={},a={}){i=i??{},a=a??{};const{debounceMs:t=500,disabled:r=!1}=a,n=Z(),[s,o]=d.useState(""),[c,h]=d.useState(!1),[p,m]=d.useState(null),[b,w]=d.useState(!1),k=d.useRef(null),M=d.useRef(0),C=d.useCallback(async()=>{var v,T,I;if(!n||!n.enabled||r)return;const{config:l,rateLimiter:y}=n;if(!y.recordRequest()){m("Rate limit exceeded. Please wait before requesting another hint.");return}const S=Ee(i,l.privacyMode??!1),f=ne.get(S);if(f){o(f),h(!1),m(null),w(!1);return}(v=k.current)==null||v.abort();const j=new AbortController;k.current=j,h(!0),m(null),o(""),w(!1);const g=Ra(i,l),x=l.stream!==!1;try{const N={"Content-Type":"application/json",...l.headers};l.apiKey&&(N.Authorization=`Bearer ${l.apiKey}`);const P=JSON.stringify({model:l.model??"gpt-3.5-turbo",messages:g,temperature:l.temperature??.7,max_tokens:l.maxTokens??256,stream:x}),$=await fetch(l.endpoint,{method:"POST",headers:N,body:P,signal:j.signal});if(!$.ok){const D=await $.text().catch(()=>$.statusText);throw new Error(`AI request failed (${$.status}): ${D}`)}if(x){w(!0);let D="";for await(const F of Ve($,j.signal))if(j.signal.aborted||(D+=F.token,o(D),(T=F.usage)!=null&&T.completion_tokens&&y.recordTokens(F.usage.completion_tokens),F.done))break;if(D.length>0){const F=Math.ceil(D.length/4);y.recordTokens(F)}ne.set(S,D)}else{const D=await Ke($);o(D.text),ne.set(S,D.text),(I=D.usage)!=null&&I.completion_tokens?y.recordTokens(D.usage.completion_tokens):y.recordTokens(Math.ceil(D.text.length/4))}}catch(N){if(N instanceof DOMException&&N.name==="AbortError")return;m(N instanceof Error?N.message:"AI hint request failed")}finally{j.signal.aborted||(h(!1),w(!1))}},[n,i,r]);d.useEffect(()=>{if(!n||!n.enabled||r)return;const l=setTimeout(C,t);return()=>clearTimeout(l)},[i==null?void 0:i.fieldLabel,i==null?void 0:i.fieldType,i==null?void 0:i.fieldValue,i==null?void 0:i.customPrompt,t,r,n==null?void 0:n.enabled,M.current]),d.useEffect(()=>()=>{var l;(l=k.current)==null||l.abort()},[]);const O=d.useCallback(()=>{var l;(l=k.current)==null||l.abort(),h(!1),w(!1)},[]),_=d.useCallback(()=>{if(n){const l=Ee(i,n.config.privacyMode??!1);ne.delete(l)}M.current+=1,C()},[n,i,C]);return!n||!n.enabled?{text:"",loading:!1,error:null,streaming:!1,abort:()=>{},refresh:()=>{},hint:null,fetchHint:async()=>{}}:{text:s,loading:c,error:p,streaming:b,abort:O,refresh:_,hint:s?{content:s}:null,fetchHint:async()=>{await C()}}}function za(i,a){if(i!=="auto"||!a)return i==="auto"?"top":i;const t=a.top,r=window.innerHeight-a.bottom,n=a.left,s=window.innerWidth-a.right,o=Math.max(t,r,n,s);return o===t?"top":o===r?"bottom":o===s?"right":"left"}function Ma(i){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(i){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 Ie=d.forwardRef(({context:i,position:a="auto",debounceMs:t=500,showOnHover:r=!1,triggerIcon:n,className:s,style:o},c)=>{var S;const h=Z(),[p,m]=d.useState(!1),[b,w]=d.useState(!1),k=d.useRef(null),M=d.useRef(null),C=X(i,{debounceMs:t,disabled:!b});d.useEffect(()=>{if(!p)return;const f=j=>{var x,v;const g=j.target;(x=k.current)!=null&&x.contains(g)||(v=M.current)!=null&&v.contains(g)||(m(!1),w(!1))};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[p]),d.useEffect(()=>{if(!p)return;const f=j=>{j.key==="Escape"&&(m(!1),w(!1),C.abort())};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[p,C]);const O=d.useCallback(f=>{if(f.stopPropagation(),r)return;const j=!p;m(j),w(j)},[p,r]),_=d.useCallback(()=>{r&&(m(!0),w(!0))},[r]),l=d.useCallback(()=>{r&&(m(!1),w(!1))},[r]);if(!h||!h.enabled)return null;const y=za(a,((S=k.current)==null?void 0:S.getBoundingClientRect())??null);return e.jsxs("span",{ref:c,className:s,style:{position:"relative",display:"inline-flex",...o},onMouseEnter:_,onMouseLeave:l,children:[e.jsx("button",{ref:k,type:"button",onClick:O,"aria-label":"AI hint","aria-expanded":p,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(A.NiceIcon,{name:"wand",size:16})}),p&&e.jsxs("div",{ref:M,role:"tooltip",className:"ntd-ai-popover",style:Ma(y),children:[C.loading&&!C.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:"Thinking..."})]}),C.text&&e.jsxs("div",{className:"ntd-ai-content",children:[C.text,C.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"}})]}),C.error&&e.jsx("div",{className:"ntd-ai-error",style:{color:"var(--ntd-ai-error, #f38ba8)"},children:C.error}),C.text&&!C.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:()=>C.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(A.NiceIcon,{name:"refresh",size:12})," Refresh"]}),e.jsxs("button",{type:"button",onClick:()=>{var f;(f=navigator.clipboard)==null||f.writeText(C.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(A.NiceIcon,{name:"copy",size:12})," Copy"]})]})]})]})});Ie.displayName="NiceAIHintBubble";function Re(i,a,t){return{fieldLabel:i,fieldType:"text",fieldValue:a,validationRules:{...(t==null?void 0:t.maxLength)!=null?{maxLength:t.maxLength}:{},...t!=null&&t.pattern?{pattern:t.pattern}:{}},customPrompt:t!=null&&t.placeholder?`Placeholder: "${t.placeholder}". Suggest content or correct grammar.`:"Suggest content, correct grammar, or auto-complete the text."}}function ze(i,a,t){return{fieldLabel:i,fieldType:"number",fieldValue:a,validationRules:{...(t==null?void 0:t.min)!=null?{min:t.min}:{},...(t==null?void 0:t.max)!=null?{max:t.max}:{},...(t==null?void 0:t.step)!=null?{step:t.step}:{}},customPrompt:t!=null&&t.unit?`Unit: ${t.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(i,a,t){return{fieldLabel:i,fieldType:t!=null&&t.multiple?"multi-select":"select",fieldValue:a,schema:t!=null&&t.options?{availableOptions:t.options.slice(0,20).map(r=>r.label)}:{},customPrompt:"Suggest the most likely selection. Explain why this option is recommended."}}function Le(i,a,t){const r=a instanceof Date?a.toISOString().split("T")[0]:a;return{fieldLabel:i,fieldType:"date",fieldValue:r,validationRules:{...t!=null&&t.min?{min:t.min}:{},...t!=null&&t.max?{max:t.max}:{},...t!=null&&t.disableWeekends?{noWeekends:!0}:{}},customPrompt:'Suggest a date. For example: "next business day", "end of month", "in 2 weeks". Explain your suggestion briefly.'}}function Pe(i,a,t){return{fieldLabel:i,fieldType:"color",fieldValue:a,schema:t!=null&&t.palette?{currentPalette:t.palette}:{},customPrompt:t!=null&&t.industry?`Industry: ${t.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 La(i,a){return{fieldLabel:i,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 Pa(i,a){return{fieldLabel:i,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 Ye(i,a){return{fieldLabel:"Form auto-fill",fieldType:"form",schema:{fields:a},customPrompt:`User description: "${i}"
5
+ Parse this description and return suggested values for each field as JSON: { ${a.map(t=>`"${t.label}": "value"`).join(", ")} }`}}function Xe(i,a,t,r,n){return{fieldLabel:i,fieldType:a,fieldValue:t,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 $a(i,a,t){const r=d.useMemo(()=>Re(i,a,t),[i,a,t==null?void 0:t.placeholder,t==null?void 0:t.maxLength,t==null?void 0:t.pattern]);return X(r,t)}function Oa(i,a,t){const r=d.useMemo(()=>ze(i,a,t),[i,a,t==null?void 0:t.min,t==null?void 0:t.max,t==null?void 0:t.step,t==null?void 0:t.unit]);return X(r,t)}function Ea(i,a,t){const r=d.useMemo(()=>Me(i,a,t),[i,a,t==null?void 0:t.multiple]);return X(r,t)}function Da(i,a,t){const r=d.useMemo(()=>Le(i,a,t),[i,a,t==null?void 0:t.min,t==null?void 0:t.max,t==null?void 0:t.disableWeekends]);return X(r,t)}function Ba(i,a,t){const r=d.useMemo(()=>Pe(i,a,t),[i,a,t==null?void 0:t.industry]);return X(r,t)}function Fa(i,a,t,r,n){const s=d.useMemo(()=>r?Xe(i,a,t,r,n):{fieldLabel:i,fieldType:a},[i,a,t,r]);return X(s,{...n,disabled:!r||(n==null?void 0:n.disabled)})}function qa(i,a,t){const r=d.useMemo(()=>i?Ye(i,a):{fieldLabel:"Form"},[i,a]);return X(r,{...t,disabled:!i||(t==null?void 0:t.disabled)})}function Qe(i,a,t){const n=(a==null?void 0:a.split(`
6
+ `))??[],s=(t==null?void 0:t.cursorLine)!=null?n.slice(Math.max(0,t.cursorLine-8),t.cursorLine+3).join(`
7
7
  `):n.slice(0,16).join(`
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 Ye(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 Xe(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 Ze(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 Qe(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 ea(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 Ba(t,a,i){const r=d.useMemo(()=>Ke(t,a,i),[t,a,i==null?void 0:i.cursorLine,i==null?void 0:i.cursorCol,i==null?void 0:i.framework]);return X(r,i)}function Fa(t,a,i){const r=d.useMemo(()=>Ye(t,a,i),[t,a,i==null?void 0:i.mode,i==null?void 0:i.locale]);return X(r,i)}function Ja(t,a){const i=d.useMemo(()=>Xe(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 X(i,a)}function Ua(t,a){const i=d.useMemo(()=>Ze(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 X(i,a)}function qa(t,a){const i=d.useMemo(()=>Qe(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 X(i,a)}function Ha(t,a){const i=d.useMemo(()=>ea(t,a),[t,a==null?void 0:a.limit,a==null?void 0:a.style]);return X(i,{...a,disabled:!t||(a==null?void 0:a.disabled)})}function aa(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(c=>c.node)}}}function Wa(t,a){const i=d.useMemo(()=>aa(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 X(i,a)}function ia(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 }] }`},c=t.map(p=>{var f;return{id:p.id,type:p.type,label:(f=p.label)==null?void 0:f.slice(0,30),pos:[Math.round(p.x),Math.round(p.y)]}}),l=a.map(p=>({id:p.id,src:p.source,tgt:p.target}));return{fieldLabel:`Diagram (${n})`,fieldType:`diagram:${r}`,fieldValue:JSON.stringify({nodes:c,edges:l}),schema:{diagramType:n,mode:r,nodeCount:t.length,edgeCount:a.length,containerSize:i==null?void 0:i.containerSize},customPrompt:s[r]}}function Ga(t,a,i){const r=d.useMemo(()=>ia(t,a,i),[JSON.stringify(t),JSON.stringify(a),i==null?void 0:i.mode,i==null?void 0:i.diagramType]);return X(r,{...i,disabled:t.length===0||(i==null?void 0:i.disabled)})}function ta(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),c={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:c[i]}}function Va(t,a){const i=d.useMemo(()=>ta(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 X(i,{...a,disabled:!t||(a==null?void 0:a.disabled)})}function ra(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 Ka(t,a){const i=d.useMemo(()=>ra(t,a),[JSON.stringify(t),a==null?void 0:a.mode,JSON.stringify(a==null?void 0:a.brandColors)]);return X(i,a)}function Ya(t,a,i){const r=d.forwardRef((n,s)=>{const{aiEnabled:c=!0,aiPosition:l="right",aiPrompt:p,aiDebounceMs:f=500,aiShowOnHover:g=!1,aiTriggerIcon:y,...w}=n,S=d.useMemo(()=>{const z=a(w);return p&&(z.customPrompt=p),z},[w,p]);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(t,{...w,ref:s}),c&&e.jsx(Se,{context:S,position:l,debounceMs:f,showOnHover:g,triggerIcon:y})]})});return r.displayName=i??`withAIHint(${t.displayName??t.name??"Component"})`,r}function Xa(t){return Te(t.label??"Text",t.value,{placeholder:t.placeholder,maxLength:t.maxLength})}function Za(t){return Ae(t.label??"Number",t.value,{min:t.min,max:t.max,step:t.step})}function Qa(t){return Re(t.label??"Select",t.value,{options:t.options,multiple:t.multiple})}function ei(t){return Ie(t.label??"Date",t.value,{min:t.min,max:t.max})}function ai(t){return ze(t.label??"Color",t.value)}const ii={id:crypto.randomUUID(),name:"New ML Project",type:"classification",status:"draft",datasets:[],experiments:[],models:[],createdAt:new Date,updatedAt:new Date},$e={classification:[{id:"logistic-regression",name:"Logistic Regression"},{id:"random-forest",name:"Random Forest"},{id:"gradient-boosting",name:"Gradient Boosting"},{id:"svm",name:"Support Vector Machine"},{id:"neural-network",name:"Neural Network"},{id:"xgboost",name:"XGBoost"}],regression:[{id:"linear-regression",name:"Linear Regression"},{id:"ridge",name:"Ridge Regression"},{id:"lasso",name:"Lasso Regression"},{id:"random-forest-reg",name:"Random Forest"},{id:"gradient-boosting-reg",name:"Gradient Boosting"}],clustering:[{id:"kmeans",name:"K-Means"},{id:"dbscan",name:"DBSCAN"},{id:"hierarchical",name:"Hierarchical Clustering"}]},Oe={classification:["accuracy","precision","recall","f1-score","auc-roc"],regression:["mse","rmse","mae","r2"],clustering:["silhouette","calinski-harabasz","davies-bouldin"]},ti=[{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"}],ri=({project:t,onProjectChange:a,onExperimentRun:i,onModelDeploy:r,className:n="",tutorial:s})=>{var B;const[c,l]=d.useState(t||ii),[p,f]=d.useState("data"),[g,y]=d.useState(null),[w,S]=d.useState(null),[z,k]=d.useState(null),[I,j]=d.useState(!1),[o,N]=d.useState({algorithm:"",hyperparameters:{},preprocessing:[]}),_=d.useCallback(b=>{const P={...c,...b,updatedAt:new Date};l(P),a==null||a(P)},[c,a]),m=async b=>{for(const P of Array.from(b)){const H={id:crypto.randomUUID(),name:P.name.replace(/\.[^.]+$/,""),type:"tabular",source:{type:"file",uri:P.name},size:P.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(P.name.endsWith(".csv")){const M=(await P.text()).split(`
11
- `),U=M[0].split(",").map(q=>q.trim());H.rowCount=M.length-1,H.columns=U.map(q=>({name:q,type:"text",nullable:!0,unique:0,missing:0})),H.splits=H.splits.map(q=>({...q,rowCount:Math.floor(H.rowCount*q.ratio)}))}_({datasets:[...c.datasets,H]})}},v=b=>{_({datasets:c.datasets.filter(P=>P.id!==b)}),g===b&&y(null)},x=async()=>{if(!o.algorithm||!g)return;const b={id:crypto.randomUUID(),name:`Experiment ${c.experiments.length+1}`,status:"pending",config:o,metrics:[],artifacts:[],logs:[]},P=[...c.experiments,b];if(_({experiments:P}),j(!1),i){const H=P.map(J=>J.id===b.id?{...J,status:"running",startedAt:new Date}:J);_({experiments:H});try{await i(b);const J=(Oe[c.type]||Oe.classification).map(M=>({name:M,value:Math.random()*.3+.7,split:"validation"}));_({experiments:H.map(M=>M.id===b.id?{...M,status:"completed",completedAt:new Date,metrics:J}:M)})}catch{_({experiments:H.map(J=>J.id===b.id?{...J,status:"failed"}:J)})}}},u=b=>{const P=c.experiments.find(J=>J.id===b);if(!P)return;const H={id:crypto.randomUUID(),name:`Model from ${P.name}`,version:"1.0.0",algorithm:P.config.algorithm,experimentId:b,status:"registered",metrics:P.metrics,size:Math.floor(Math.random()*100)*1024*1024,artifacts:[],deployments:[],createdAt:new Date};_({models:[...c.models,H]})},h=async b=>{const P=c.models.find(J=>J.id===b);if(!P||!r)return;const H=await r(P);_({models:c.models.map(J=>J.id===b?{...J,status:"production",deployments:[...J.deployments,H]}:J)})},$=b=>b<1024?`${b} B`:b<1024*1024?`${(b/1024).toFixed(1)} KB`:b<1024*1024*1024?`${(b/1024/1024).toFixed(1)} MB`:`${(b/1024/1024/1024).toFixed(1)} GB`,D=b=>{switch(b){case"completed":case"production":case"running":return"status-badge--success";case"pending":case"staging":return"status-badge--warning";case"failed":return"status-badge--error";default:return""}},C=e.jsxs("div",{className:"header__info",children:[e.jsx("input",{type:"text",value:c.name,onChange:b=>_({name:b.target.value}),className:"project-name-input"}),e.jsxs("select",{value:c.type,onChange:b=>_({type:b.target.value}),className:"project-type-select",children:[e.jsx("option",{value:"classification",children:"Classification"}),e.jsx("option",{value:"regression",children:"Regression"}),e.jsx("option",{value:"clustering",children:"Clustering"}),e.jsx("option",{value:"object-detection",children:"Object Detection"}),e.jsx("option",{value:"nlp",children:"NLP"}),e.jsx("option",{value:"time-series",children:"Time Series"})]})]}),A=e.jsx("div",{className:"header__tabs",children:["data","experiments","models","deploy"].map(b=>e.jsx("button",{className:`tab-button ${p===b?"tab-button--active":""}`,onClick:()=>f(b),children:b.charAt(0).toUpperCase()+b.slice(1)},b))}),O=e.jsxs("div",{className:"ml-studio__content",children:[p==="data"&&e.jsxs("div",{className:"data-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:"Datasets"}),e.jsxs("label",{className:"upload-button",children:[e.jsx("input",{type:"file",multiple:!0,accept:".csv,.json,.parquet",onChange:b=>b.target.files&&m(b.target.files),hidden:!0}),e.jsx(L.NiceIcon,{name:"plus",size:14})," Upload Dataset"]})]}),e.jsx("div",{className:"datasets-grid",children:c.datasets.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"bar-chart",size:32})}),e.jsx("p",{children:"No datasets uploaded yet"}),e.jsx("p",{className:"hint",children:"Upload CSV, JSON, or Parquet files to get started"})]}):c.datasets.map(b=>e.jsxs("div",{className:`dataset-card ${g===b.id?"dataset-card--selected":""}`,onClick:()=>y(b.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("span",{className:"dataset-icon",children:e.jsx(L.NiceIcon,{name:"folder",size:16})}),e.jsx("h3",{children:b.name}),e.jsx("button",{className:"remove-button","aria-label":"Remove dataset",onClick:P=>{P.stopPropagation(),v(b.id)},children:e.jsx(L.NiceIcon,{name:"close",size:14})})]}),e.jsxs("div",{className:"card-stats",children:[e.jsxs("span",{children:[b.rowCount.toLocaleString()," rows"]}),e.jsxs("span",{children:[b.columns.length," columns"]}),e.jsx("span",{children:$(b.size)})]}),e.jsx("div",{className:"splits-bar",children:b.splits.map(P=>e.jsx("div",{className:`split split--${P.name}`,style:{width:`${P.ratio*100}%`},title:`${P.name}: ${(P.ratio*100).toFixed(0)}%`},P.name))})]},b.id))}),g&&e.jsx("div",{className:"dataset-details",children:(()=>{const b=c.datasets.find(P=>P.id===g);return b?e.jsxs(e.Fragment,{children:[e.jsx("h3",{children:"Columns"}),e.jsxs("table",{className:"columns-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Name"}),e.jsx("th",{children:"Type"}),e.jsx("th",{children:"Missing"}),e.jsx("th",{children:"Unique"})]})}),e.jsx("tbody",{children:b.columns.map(P=>e.jsxs("tr",{children:[e.jsx("td",{children:P.name}),e.jsx("td",{children:e.jsxs("select",{value:P.type,onChange:H=>{_({datasets:c.datasets.map(J=>J.id===b.id?{...J,columns:J.columns.map(M=>M.name===P.name?{...M,type:H.target.value}:M)}:J)})},children:[e.jsx("option",{value:"numeric",children:"Numeric"}),e.jsx("option",{value:"categorical",children:"Categorical"}),e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"datetime",children:"DateTime"}),e.jsx("option",{value:"boolean",children:"Boolean"})]})}),e.jsx("td",{children:P.missing}),e.jsx("td",{children:P.unique})]},P.name))})]})]}):null})()})]}),p==="experiments"&&e.jsxs("div",{className:"experiments-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:"Experiments"}),e.jsxs("button",{className:"primary-button",onClick:()=>j(!0),disabled:c.datasets.length===0,children:[e.jsx(L.NiceIcon,{name:"plus",size:14})," New Experiment"]})]}),I&&e.jsxs("div",{className:"new-experiment-form",children:[e.jsx("h3",{children:"Configure Experiment"}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:["Dataset",e.jsxs("select",{value:g||"",onChange:b=>y(b.target.value),children:[e.jsx("option",{value:"",children:"Select dataset..."}),c.datasets.map(b=>e.jsx("option",{value:b.id,children:b.name},b.id))]})]}),e.jsxs("label",{children:["Algorithm",e.jsxs("select",{value:o.algorithm,onChange:b=>N({...o,algorithm:b.target.value}),children:[e.jsx("option",{value:"",children:"Select algorithm..."}),($e[c.type]||$e.classification).map(b=>e.jsx("option",{value:b.id,children:b.name},b.id))]})]}),g&&e.jsxs("label",{children:["Target Column",e.jsxs("select",{value:o.targetColumn||"",onChange:b=>N({...o,targetColumn:b.target.value}),children:[e.jsx("option",{value:"",children:"Select target..."}),(B=c.datasets.find(b=>b.id===g))==null?void 0:B.columns.map(b=>e.jsx("option",{value:b.name,children:b.name},b.name))]})]})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{className:"secondary-button",onClick:()=>j(!1),children:"Cancel"}),e.jsx("button",{className:"primary-button",onClick:x,disabled:!o.algorithm||!g,children:"Run Experiment"})]})]}),e.jsx("div",{className:"experiments-list",children:c.experiments.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"flask",size:32})}),e.jsx("p",{children:"No experiments yet"}),e.jsx("p",{className:"hint",children:"Create an experiment to train and evaluate models"})]}):c.experiments.map(b=>e.jsxs("div",{className:`experiment-card ${w===b.id?"experiment-card--selected":""}`,onClick:()=>S(b.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:b.name}),e.jsx("span",{className:`status-badge ${D(b.status)}`,children:b.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Algorithm: ",b.config.algorithm]}),b.duration&&e.jsxs("span",{children:["Duration: ",Math.round(b.duration),"s"]})]}),b.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:b.metrics.slice(0,3).map(P=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:P.name}),e.jsxs("span",{className:"metric-value",children:[(P.value*100).toFixed(1),"%"]})]},P.name))}),b.status==="completed"&&e.jsx("button",{className:"action-button",onClick:P=>{P.stopPropagation(),u(b.id)},children:"Register Model"})]},b.id))})]}),p==="models"&&e.jsxs("div",{className:"models-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:"Models"})}),e.jsx("div",{className:"models-list",children:c.models.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"wand",size:32})}),e.jsx("p",{children:"No models registered yet"}),e.jsx("p",{className:"hint",children:"Complete experiments and register models"})]}):c.models.map(b=>e.jsxs("div",{className:`model-card ${z===b.id?"model-card--selected":""}`,onClick:()=>k(b.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:b.name}),e.jsx("span",{className:`status-badge ${D(b.status)}`,children:b.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Algorithm: ",b.algorithm]}),e.jsxs("span",{children:["Version: ",b.version]}),e.jsxs("span",{children:["Size: ",$(b.size)]})]}),b.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:b.metrics.slice(0,3).map(P=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:P.name}),e.jsxs("span",{className:"metric-value",children:[(P.value*100).toFixed(1),"%"]})]},P.name))}),e.jsxs("div",{className:"card-actions",children:[e.jsx("button",{className:"action-button",children:"Download"}),e.jsx("button",{className:"action-button action-button--primary",onClick:P=>{P.stopPropagation(),h(b.id)},disabled:b.status==="production",children:b.status==="production"?"Deployed":"Deploy"})]})]},b.id))})]}),p==="deploy"&&e.jsxs("div",{className:"deploy-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:"Deployments"})}),e.jsx("div",{className:"deployments-list",children:c.models.filter(b=>b.deployments.length>0).length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"rocket",size:32})}),e.jsx("p",{children:"No deployments yet"}),e.jsx("p",{className:"hint",children:"Deploy a model to create inference endpoints"})]}):c.models.filter(b=>b.deployments.length>0).flatMap(b=>b.deployments.map(P=>({model:b,deployment:P}))).map(({model:b,deployment:P})=>e.jsxs("div",{className:"deployment-card",children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:P.name}),e.jsx("span",{className:`status-badge ${D(P.status)}`,children:P.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Model: ",b.name]}),e.jsxs("span",{children:["Endpoint: ",P.endpoint]})]}),e.jsxs("div",{className:"resources-info",children:[e.jsxs("span",{children:["CPU: ",P.resources.cpu," cores"]}),e.jsxs("span",{children:["Memory: ",P.resources.memory," GB"]}),e.jsxs("span",{children:["Replicas: ",P.resources.replicas]})]})]},P.id))})]})]});return e.jsxs("div",{className:`nice-ml-studio ${n}`,style:{position:"relative"},children:[e.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:e.jsx(L.NiceTutorialButton,{steps:L.resolveTutorial(s,ti)})}),e.jsx(Ca.NiceAppShell,{flush:!0,menubar:C,toolbar:A,children:O})]})},ni={id:crypto.randomUUID(),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},Ee=["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)"],si=({project:t,onProjectChange:a,onLabelSave:i,onExport:r,className:n=""})=>{var Q;const{t:s}=L.useNiceTranslation(),[c,l]=d.useState(t||ni),[p,f]=d.useState("label"),[g,y]=d.useState(0),[w,S]=d.useState(null),[z,k]=d.useState("select"),[I,j]=d.useState(!1),[o,N]=d.useState(null),[_,m]=d.useState(1),[v,x]=d.useState(!1),[u,h]=d.useState("all"),$=d.useRef(null),D=d.useRef(null),C=c.items[g];d.useEffect(()=>{t&&l(t)},[t]);const A=d.useCallback(T=>{const E={...c,...T};E.statistics={totalItems:E.items.length,labeled:E.items.filter(R=>R.status!=="pending").length,reviewed:E.items.filter(R=>R.status==="review"||R.status==="approved").length,approved:E.items.filter(R=>R.status==="approved").length,byClass:E.labelSchema.classes.map(R=>({classId:R.id,count:E.items.flatMap(F=>F.labels).filter(F=>F.classId===R.id).length}))},l(E),a==null||a(E)},[c,a]),O=()=>{const T={id:crypto.randomUUID(),name:`Class ${c.labelSchema.classes.length+1}`,color:Ee[c.labelSchema.classes.length%Ee.length],shortcut:String(c.labelSchema.classes.length+1)};A({labelSchema:{...c.labelSchema,classes:[...c.labelSchema.classes,T]}})},B=T=>{A({labelSchema:{...c.labelSchema,classes:c.labelSchema.classes.filter(E=>E.id!==T)},items:c.items.map(E=>({...E,labels:E.labels.filter(R=>R.classId!==T)}))})},b=(T,E)=>{A({labelSchema:{...c.labelSchema,classes:c.labelSchema.classes.map(R=>R.id===T?{...R,...E}:R)}})},P=(T,E)=>{if(!C)return;const R={id:crypto.randomUUID(),classId:T,type:c.type==="classification"?"class":c.type==="bounding-box"?"bbox":"class",data:E||{},createdBy:"current-user",createdAt:new Date},F={...C,labels:[...C.labels,R],status:"labeled"};A({items:c.items.map(V=>V.id===C.id?F:V)}),i==null||i(F)},H=T=>{if(!C)return;const E={...C,labels:C.labels.filter(R=>R.id!==T),status:C.labels.length<=1?"pending":"labeled"};A({items:c.items.map(R=>R.id===C.id?E:R)})},J=T=>{var V;if(z!=="bbox"||!w)return;const E=(V=$.current)==null?void 0:V.getBoundingClientRect();if(!E)return;const R=(T.clientX-E.left)/_,F=(T.clientY-E.top)/_;j(!0),N({x:R,y:F,width:0,height:0})},M=T=>{var V;if(!I||!o)return;const E=(V=$.current)==null?void 0:V.getBoundingClientRect();if(!E)return;const R=(T.clientX-E.left)/_,F=(T.clientY-E.top)/_;N({...o,width:R-o.x,height:F-o.y})},U=()=>{!I||!o||!w||(j(!1),Math.abs(o.width)>10&&Math.abs(o.height)>10&&P(w,{x:o.width<0?o.x+o.width:o.x,y:o.height<0?o.y+o.height:o.y,width:Math.abs(o.width),height:Math.abs(o.height)}),N(null))},q=T=>{const E=u==="all"?c.items:c.items.filter(F=>F.status===u),R=E.findIndex(F=>F.id===(C==null?void 0:C.id));if(T==="prev"&&R>0){const F=E[R-1];y(c.items.findIndex(V=>V.id===F.id))}else if(T==="next"&&R<E.length-1){const F=E[R+1];y(c.items.findIndex(V=>V.id===F.id))}},W=()=>{if(!C)return;const T={...C,status:"approved"};A({items:c.items.map(E=>E.id===C.id?T:E)}),q("next")},G=()=>{if(!C)return;const T={...C,status:"rejected"};A({items:c.items.map(E=>E.id===C.id?T:E)}),q("next")},Y=async T=>{r&&await r(T)};d.useEffect(()=>{const T=E=>{const R=E.target instanceof HTMLElement?E.target:null;if(p!=="label"||E.defaultPrevented||E.ctrlKey||E.metaKey||E.altKey||R!=null&&R.isContentEditable||R&&/^(INPUT|TEXTAREA|SELECT)$/.test(R.tagName)||E.key==="Enter"&&(R!=null&&R.closest("button, a")))return;const F=E.key,V=c.labelSchema.classes.find(re=>re.shortcut===F);V&&(c.type==="classification"?(P(V.id),q("next")):S(V.id)),E.key==="ArrowLeft"||E.key==="a"?q("prev"):(E.key==="ArrowRight"||E.key==="d")&&q("next"),E.key==="Enter"?W():E.key==="Backspace"&&G()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[p,C,c.labelSchema.classes,c.type]);const ee=T=>{switch(T){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:"labeler__header",children:[e.jsxs("div",{className:"header__info",children:[e.jsx("input",{type:"text",value:c.name,onChange:T=>A({name:T.target.value}),className:"project-name-input"}),e.jsxs("div",{className:"progress-bar",children:[e.jsx("div",{className:"progress-fill",style:{width:`${c.statistics.labeled/Math.max(c.statistics.totalItems,1)*100}%`}}),e.jsxs("span",{className:"progress-text",children:[c.statistics.labeled," / ",c.statistics.totalItems," labeled"]})]})]}),e.jsx("div",{className:"header__tabs",children:["label","schema","review","export"].map(T=>e.jsx("button",{className:`tab-button ${p===T?"tab-button--active":""}`,onClick:()=>f(T),children:T.charAt(0).toUpperCase()+T.slice(1)},T))}),e.jsx("button",{className:"shortcuts-button",onClick:()=>x(!v),children:s("dataLabeler.shortcuts","Shortcuts")})]}),e.jsxs("div",{className:"labeler__content",children:[p==="label"&&e.jsxs("div",{className:"label-panel",children:[e.jsxs("div",{className:"label-toolbar",children:[e.jsxs("div",{className:"tool-group",children:[e.jsxs("button",{className:`tool-button ${z==="select"?"tool-button--active":""}`,onClick:()=>k("select"),children:[e.jsx(L.NiceIcon,{name:"cursor",size:14})," ",s("dataLabeler.select","Select")]}),(c.type==="bounding-box"||c.type==="multi-label")&&e.jsxs("button",{className:`tool-button ${z==="bbox"?"tool-button--active":""}`,onClick:()=>k("bbox"),children:[e.jsx(L.NiceIcon,{name:"square",size:14})," Box"]}),c.type==="polygon"&&e.jsxs("button",{className:`tool-button ${z==="polygon"?"tool-button--active":""}`,onClick:()=>k("polygon"),children:[e.jsx(L.NiceIcon,{name:"hexagon",size:14})," ",s("dataLabeler.polygon","Polygon")]})]}),e.jsxs("div",{className:"zoom-group",children:[e.jsx("button",{"aria-label":s("dataLabeler.zoomOut","Zoom out"),onClick:()=>m(Math.max(.25,_-.25)),children:e.jsx(L.NiceIcon,{name:"minus",size:14})}),e.jsxs("span",{children:[Math.round(_*100),"%"]}),e.jsx("button",{"aria-label":s("dataLabeler.zoomIn","Zoom in"),onClick:()=>m(Math.min(4,_+.25)),children:e.jsx(L.NiceIcon,{name:"plus",size:14})})]}),e.jsxs("div",{className:"navigation-group",children:[e.jsxs("button",{onClick:()=>q("prev"),disabled:g===0,children:[e.jsx(L.NiceIcon,{name:"arrow-left",size:14})," ",s("dataLabeler.prev","Prev")]}),e.jsxs("span",{children:[g+1," / ",c.items.length]}),e.jsxs("button",{onClick:()=>q("next"),disabled:g>=c.items.length-1,children:[s("dataLabeler.next","Next")," ",e.jsx(L.NiceIcon,{name:"arrow-right",size:14})]})]})]}),e.jsxs("div",{className:"label-workspace",children:[e.jsx("div",{className:"canvas-container",ref:D,children:C?e.jsxs(e.Fragment,{children:[C.data.type==="image"&&e.jsxs(e.Fragment,{children:[e.jsx("img",{src:C.data.url,alt:s("dataLabeler.labelingItem","Labeling item"),className:"labeling-image",style:{transform:`scale(${_})`}}),e.jsx("canvas",{ref:$,className:"labeling-canvas",onMouseDown:J,onMouseMove:M,onMouseUp:U,onMouseLeave:U,style:{transform:`scale(${_})`,cursor:z==="bbox"?"crosshair":"default"}}),e.jsxs("div",{className:"annotations-overlay",style:{transform:`scale(${_})`},children:[C.labels.filter(T=>T.type==="bbox"&&T.data.x!==void 0).map(T=>{const E=c.labelSchema.classes.find(R=>R.id===T.classId);return e.jsxs("div",{className:"bbox-annotation",style:{left:T.data.x,top:T.data.y,width:T.data.width,height:T.data.height,borderColor:(E==null?void 0:E.color)||"var(--nice-danger, #ff0000)"},children:[e.jsx("span",{className:"bbox-label",style:{backgroundColor:(E==null?void 0:E.color)||"var(--nice-danger, #ff0000)"},children:E==null?void 0:E.name}),e.jsx("button",{className:"bbox-remove","aria-label":s("dataLabeler.removeLabel","Remove label"),onClick:()=>H(T.id),children:e.jsx(L.NiceIcon,{name:"close",size:12})})]},T.id)}),o&&e.jsx("div",{className:"bbox-drawing",style:{left:o.width<0?o.x+o.width:o.x,top:o.height<0?o.y+o.height:o.y,width:Math.abs(o.width),height:Math.abs(o.height),borderColor:(Q=c.labelSchema.classes.find(T=>T.id===w))==null?void 0:Q.color}})]})]}),C.data.type==="text"&&e.jsx("div",{className:"text-labeling",children:e.jsx("p",{className:"text-content",children:C.data.text})})]}):e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"clipboard",size:32})}),e.jsx("p",{children:s("dataLabeler.noItemsToLabel","No items to label")})]})}),e.jsxs("aside",{className:"class-sidebar",children:[e.jsx("h3",{children:s("dataLabeler.classes","Classes")}),e.jsx("div",{className:"class-list",children:c.labelSchema.classes.map(T=>e.jsxs("button",{className:`class-button ${w===T.id?"class-button--active":""}`,style:{borderLeftColor:T.color},onClick:()=>{c.type==="classification"?(P(T.id),q("next")):S(T.id)},children:[e.jsx("span",{className:"class-color",style:{backgroundColor:T.color}}),e.jsx("span",{className:"class-name",children:T.name}),T.shortcut&&e.jsx("span",{className:"class-shortcut",children:T.shortcut})]},T.id))}),C&&C.labels.length>0&&e.jsxs("div",{className:"current-labels",children:[e.jsx("h4",{children:s("dataLabeler.labels","Labels")}),C.labels.map(T=>{const E=c.labelSchema.classes.find(R=>R.id===T.classId);return e.jsxs("div",{className:"label-item",children:[e.jsx("span",{className:"label-color",style:{backgroundColor:E==null?void 0:E.color}}),e.jsx("span",{className:"label-name",children:E==null?void 0:E.name}),e.jsx("button",{"aria-label":s("dataLabeler.removeLabel","Remove label"),onClick:()=>H(T.id),children:e.jsx(L.NiceIcon,{name:"close",size:14})})]},T.id)})]}),p==="label"&&C&&e.jsxs("div",{className:"label-actions",children:[e.jsxs("button",{className:"approve-button",onClick:W,children:[e.jsx(L.NiceIcon,{name:"check",size:14})," ",s("dataLabeler.approve","Approve")]}),e.jsxs("button",{className:"reject-button",onClick:G,children:[e.jsx(L.NiceIcon,{name:"close",size:14})," ",s("dataLabeler.reject","Reject")]})]})]})]})]}),p==="schema"&&e.jsxs("div",{className:"schema-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:s("dataLabeler.labelSchema","Label Schema")}),e.jsxs("button",{className:"primary-button",onClick:O,children:[e.jsx(L.NiceIcon,{name:"plus",size:14})," ",s("dataLabeler.addClass","Add Class")]})]}),e.jsxs("div",{className:"schema-settings",children:[e.jsxs("label",{children:[s("dataLabeler.labelingType","Labeling Type"),e.jsxs("select",{value:c.type,onChange:T=>A({type:T.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:c.dataType,onChange:T=>A({dataType:T.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:"classes-list",children:c.labelSchema.classes.map((T,E)=>e.jsxs("div",{className:"class-editor",children:[e.jsx("input",{type:"color",value:T.color,onChange:R=>b(T.id,{color:R.target.value}),className:"color-picker"}),e.jsx("input",{type:"text",value:T.name,onChange:R=>b(T.id,{name:R.target.value}),className:"class-name-input",placeholder:s("dataLabeler.classNamePlaceholder","Class name")}),e.jsx("input",{type:"text",value:T.shortcut||"",onChange:R=>b(T.id,{shortcut:R.target.value}),className:"shortcut-input",placeholder:s("dataLabeler.shortcutKeyPlaceholder","Key"),maxLength:1}),e.jsx("button",{className:"remove-class-button","aria-label":s("dataLabeler.removeClass","Remove class"),onClick:()=>B(T.id),children:e.jsx(L.NiceIcon,{name:"trash",size:16})})]},T.id))}),e.jsxs("div",{className:"guidelines-section",children:[e.jsx("h3",{children:s("dataLabeler.labelingGuidelines","Labeling Guidelines")}),e.jsx("textarea",{value:c.guidelines||"",onChange:T=>A({guidelines:T.target.value}),placeholder:s("dataLabeler.guidelinesPlaceholder","Enter labeling guidelines for annotators..."),rows:6})]})]}),p==="review"&&e.jsxs("div",{className:"review-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:s("dataLabeler.reviewLabels","Review Labels")}),e.jsx("div",{className:"filter-group",children:e.jsxs("select",{value:u,onChange:T=>h(T.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:"items-grid",children:c.items.filter(T=>u==="all"||T.status===u).map((T,E)=>{var R;return e.jsxs("div",{className:`item-card ${g===c.items.indexOf(T)?"item-card--active":""}`,onClick:()=>{y(c.items.indexOf(T)),f("label")},children:[T.data.type==="image"&&e.jsx("img",{src:T.data.url,alt:`Item ${E+1}`,className:"item-thumbnail"}),T.data.type==="text"&&e.jsxs("p",{className:"item-text-preview",children:[(R=T.data.text)==null?void 0:R.slice(0,100),"..."]}),e.jsxs("div",{className:"item-footer",children:[e.jsx("span",{className:"status-dot",style:{backgroundColor:ee(T.status)}}),e.jsxs("span",{children:[T.labels.length," labels"]})]})]},T.id)})})]}),p==="export"&&e.jsxs("div",{className:"export-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:s("dataLabeler.exportLabels","Export Labels")})}),e.jsxs("div",{className:"export-stats",children:[e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:c.statistics.totalItems}),e.jsx("span",{className:"stat-label",children:s("dataLabeler.totalItems","Total Items")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:c.statistics.labeled}),e.jsx("span",{className:"stat-label",children:s("dataLabeler.labeled","Labeled")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:c.statistics.approved}),e.jsx("span",{className:"stat-label",children:s("dataLabeler.approved","Approved")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:c.labelSchema.classes.length}),e.jsx("span",{className:"stat-label",children:s("dataLabeler.classes","Classes")})]})]}),e.jsxs("div",{className:"export-formats",children:[e.jsx("h3",{children:s("dataLabeler.exportFormat","Export Format")}),e.jsxs("div",{className:"format-grid",children:[e.jsxs("button",{className:"format-button",onClick:()=>Y("coco"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(L.NiceIcon,{name:"box",size:24})}),e.jsx("span",{className:"format-name",children:s("dataLabeler.cocoJson","COCO JSON")}),e.jsx("span",{className:"format-desc",children:s("dataLabeler.cocoDesc","Common format for object detection")})]}),e.jsxs("button",{className:"format-button",onClick:()=>Y("voc"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(L.NiceIcon,{name:"file",size:24})}),e.jsx("span",{className:"format-name",children:s("dataLabeler.pascalVoc","Pascal VOC")}),e.jsx("span",{className:"format-desc",children:s("dataLabeler.vocDesc","XML format for bounding boxes")})]}),e.jsxs("button",{className:"format-button",onClick:()=>Y("yolo"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(L.NiceIcon,{name:"zap",size:24})}),e.jsx("span",{className:"format-name",children:s("dataLabeler.yolo","YOLO")}),e.jsx("span",{className:"format-desc",children:s("dataLabeler.yoloDesc","Text format for YOLO models")})]}),e.jsxs("button",{className:"format-button",onClick:()=>Y("csv"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(L.NiceIcon,{name:"bar-chart",size:24})}),e.jsx("span",{className:"format-name",children:"CSV"}),e.jsx("span",{className:"format-desc",children:s("dataLabeler.csvDesc","Tabular format for classification")})]})]})]}),e.jsxs("div",{className:"class-distribution",children:[e.jsx("h3",{children:s("dataLabeler.classDistribution","Class Distribution")}),e.jsx("div",{className:"distribution-bars",children:c.statistics.byClass.map(T=>{const E=c.labelSchema.classes.find(F=>F.id===T.classId),R=T.count/Math.max(c.statistics.labeled,1)*100;return e.jsxs("div",{className:"distribution-row",children:[e.jsx("span",{className:"class-name",style:{color:E==null?void 0:E.color},children:E==null?void 0:E.name}),e.jsx("div",{className:"bar-container",children:e.jsx("div",{className:"bar-fill",style:{width:`${R}%`,backgroundColor:E==null?void 0:E.color}})}),e.jsx("span",{className:"count",children:T.count})]},T.classId)})})]})]})]}),v&&e.jsx("div",{className:"shortcuts-modal",children:e.jsxs("div",{className:"modal-content",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:s("dataLabeler.keyboardShortcuts","Keyboard Shortcuts")}),e.jsx("button",{"aria-label":s("dataLabeler.close","Close"),onClick:()=>x(!1),children:e.jsx(L.NiceIcon,{name:"close",size:16})})]}),e.jsxs("div",{className:"shortcuts-list",children:[e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:"← / A"}),e.jsx("span",{className:"description",children:s("dataLabeler.previousItem","Previous item")})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:"→ / D"}),e.jsx("span",{className:"description",children:s("dataLabeler.nextItem","Next item")})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:s("dataLabeler.enterKey","Enter")}),e.jsx("span",{className:"description",children:s("dataLabeler.approveItem","Approve item")})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:s("dataLabeler.backspaceKey","Backspace")}),e.jsx("span",{className:"description",children:s("dataLabeler.rejectItem","Reject item")})]}),c.labelSchema.classes.map(T=>T.shortcut&&e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:T.shortcut}),e.jsxs("span",{className:"description",children:["Label as ",T.name]})]},T.id))]})]})})]})},ci={id:crypto.randomUUID(),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:[]},oi=({endpoint:t,onInference:a,showMetrics:i=!0,showLogs:r=!0,className:n=""})=>{const[s,c]=d.useState(t||ci),[l,p]=d.useState("test"),[f,g]=d.useState("text"),[y,w]=d.useState(""),[S,z]=d.useState("{}"),[k,I]=d.useState(null),[j,o]=d.useState({temperature:.7,topK:50,topP:.9,maxTokens:256,threshold:.5}),[N,_]=d.useState(null),[m,v]=d.useState(!1),[x,u]=d.useState(null),[h,$]=d.useState([]),[D,C]=d.useState(null),A=d.useRef(null),O=M=>{var q;const U=(q=M.target.files)==null?void 0:q[0];if(U){const W=new FileReader;W.onload=G=>{var Y;I((Y=G.target)==null?void 0:Y.result)},W.readAsDataURL(U)}},B=async()=>{if(!a){u("No inference handler provided");return}v(!0),u(null),_(null);const M=[];switch(f){case"text":M.push({type:"text",data:y});break;case"image":k&&M.push({type:"image",data:k});break;case"json":try{M.push({type:"json",data:JSON.parse(S)})}catch{u("Invalid JSON input"),v(!1);return}break;case"tabular":try{M.push({type:"tabular",data:JSON.parse(S)})}catch{u("Invalid tabular data"),v(!1);return}break}const U={inputs:M,parameters:j};try{const q=Date.now(),W=await a(U),G=Date.now()-q;_(W),c(Y=>({...Y,metrics:{...Y.metrics,requestsTotal:Y.metrics.requestsTotal+1,latencyP50:(Y.metrics.latencyP50+G)/2},logs:[{timestamp:new Date,requestId:W.requestId,duration:G,status:"success",inputSize:JSON.stringify(M).length,outputSize:JSON.stringify(W.predictions).length},...Y.logs.slice(0,99)]}))}catch(q){const W=q instanceof Error?q.message:"Inference failed";u(W),c(G=>({...G,metrics:{...G.metrics,requestsTotal:G.metrics.requestsTotal+1,errorRate:(G.metrics.errorRate*G.metrics.requestsTotal+1)/(G.metrics.requestsTotal+1)},logs:[{timestamp:new Date,requestId:crypto.randomUUID(),duration:0,status:"error",inputSize:JSON.stringify(M).length,outputSize:0,error:W},...G.logs.slice(0,99)]}))}finally{v(!1)}},b=async M=>{if(a){C(0),$([]);for(let U=0;U<M.length;U++){const q={inputs:[M[U]],parameters:j};try{const W=await a(q);$(G=>[...G,W])}catch(W){console.error("Batch item failed:",W)}C((U+1)/M.length*100)}C(null)}},P=M=>M<1e3?`${M.toFixed(0)}ms`:`${(M/1e3).toFixed(2)}s`,H=M=>M.toLocaleTimeString(),J=(M,U)=>e.jsxs("div",{className:"prediction-item",children:[M.label&&e.jsxs("div",{className:"prediction-label",children:[e.jsx("span",{className:"label-name",children:M.label}),M.confidence!==void 0&&e.jsxs("span",{className:"confidence-badge",style:{backgroundColor:`hsl(${M.confidence*120}, 70%, 40%)`},children:[(M.confidence*100).toFixed(1),"%"]})]}),M.score!==void 0&&e.jsxs("div",{className:"prediction-score",children:[e.jsx("span",{className:"score-label",children:"Score:"}),e.jsx("span",{className:"score-value",children:M.score.toFixed(4)})]}),M.text&&e.jsx("div",{className:"prediction-text",children:e.jsx("pre",{children:M.text})}),M.bbox&&e.jsx("div",{className:"prediction-bbox",children:e.jsxs("span",{children:["Box: (",M.bbox.x,", ",M.bbox.y,") - ",M.bbox.width,"×",M.bbox.height]})}),M.raw!==void 0&&M.raw!==null&&e.jsxs("details",{className:"raw-output",children:[e.jsx("summary",{children:"Raw Output"}),e.jsx("pre",{children:JSON.stringify(M.raw,null,2)})]})]},U);return e.jsxs("div",{className:`nice-model-inference ${n}`,children:[e.jsxs("header",{className:"inference__header",children:[e.jsxs("div",{className:"header__info",children:[e.jsx("h2",{children:s.name}),e.jsx("span",{className:`status-badge status-badge--${s.status}`,children:s.status})]}),e.jsxs("div",{className:"header__tabs",children:[e.jsx("button",{className:`tab-button ${l==="test"?"tab-button--active":""}`,onClick:()=>p("test"),children:"Test"}),e.jsx("button",{className:`tab-button ${l==="batch"?"tab-button--active":""}`,onClick:()=>p("batch"),children:"Batch"}),i&&e.jsx("button",{className:`tab-button ${l==="metrics"?"tab-button--active":""}`,onClick:()=>p("metrics"),children:"Metrics"}),r&&e.jsx("button",{className:`tab-button ${l==="logs"?"tab-button--active":""}`,onClick:()=>p("logs"),children:"Logs"})]})]}),e.jsxs("div",{className:"inference__content",children:[l==="test"&&e.jsxs("div",{className:"test-panel",children:[e.jsxs("div",{className:"input-section",children:[e.jsx("div",{className:"input-type-selector",children:["text","image","json","tabular"].map(M=>e.jsx("button",{className:`type-button ${f===M?"type-button--active":""}`,onClick:()=>g(M),children:M.charAt(0).toUpperCase()+M.slice(1)},M))}),e.jsxs("div",{className:"input-area",children:[f==="text"&&e.jsx("textarea",{value:y,onChange:M=>w(M.target.value),placeholder:"Enter text input...",rows:6,className:"text-input"}),f==="image"&&e.jsx("div",{className:"image-input",children:k?e.jsxs("div",{className:"image-preview",children:[e.jsx("img",{src:k,alt:"Input preview"}),e.jsx("button",{className:"clear-button",onClick:()=>I(null),children:"Clear"})]}):e.jsxs("label",{className:"upload-zone",children:[e.jsx("input",{ref:A,type:"file",accept:"image/*",onChange:O,hidden:!0}),e.jsx("span",{className:"upload-icon",children:e.jsx(L.NiceIcon,{name:"image",size:32})}),e.jsx("span",{children:"Click or drag to upload image"})]})}),(f==="json"||f==="tabular")&&e.jsx("textarea",{value:S,onChange:M=>z(M.target.value),placeholder:f==="json"?`{
8
+ `);return{fieldLabel:`Code editor (${i})`,fieldType:"code-editor",fieldValue:s||a,schema:{language:i,...t!=null&&t.framework?{framework:t.framework}:{},...(t==null?void 0:t.cursorLine)!=null?{cursorLine:t.cursorLine,cursorCol:t.cursorCol}:{}},customPrompt:`Language: ${i}${t!=null&&t.framework?`, framework: ${t.framework}`:""}.
9
+ Provide a concise inline completion or improvement hint for the code near the cursor. Limit response to ${(t==null?void 0:t.maxSuggestLines)??5} lines of code. If unsure, suggest the most idiomatic approach for this language/framework.`}}function Ze(i,a,t){var s;const r=(t==null?void 0:t.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:i,fieldType:"html-editor",fieldValue:a==null?void 0:a.slice(0,2e3),schema:{mode:r,...(s=t==null?void 0:t.targetKeywords)!=null&&s.length?{targetKeywords:t.targetKeywords}:{},...t!=null&&t.locale?{locale:t.locale}:{}},customPrompt:n[r]}}function ea(i,a){const t=(a==null?void 0:a.mode)??"tag",r=`"${i}"`+((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: ${i}`,fieldType:"audio",schema:{mode:t,...(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[t]}}function aa(i,a){var s;const t=(a==null?void 0:a.mode)??"material",r=(a==null?void 0:a.targetDevice)??"web",n={material:`Scene "${i}", ${(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 "${i}", triangles: ${(a==null?void 0:a.triangleCount)??"?"}, target: ${r}. Identify budget issues and suggest LOD levels, mesh merging, and texture atlas strategy.`,lighting:`Scene "${i}", target: ${r}. Suggest a complete lighting setup (types, intensity, color, shadow settings) for realistic rendering.`,animation:`Rig in scene "${i}". Suggest animation approach (FK/IK, bone count), keyframe timing and easing curves for natural movement.`};return{fieldLabel:`3D scene: ${i}`,fieldType:"3d-scene",schema:{mode:t,...(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[t]}}function ta(i,a){const t=(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 "${i}" (${r}). Suggest CSS/SVG filter parameters (brightness, contrast, saturate, hue-rotate, blur) as JSON: { brightness, contrast, saturate, hueRotate, blur }.`,palette:`Image "${i}". Extract or suggest a harmonious 5-color palette as JSON: { primary, secondary, accent, background, text }.`,upscale:`Image "${i}" at ${r}. Recommend upscaling strategy: model (ESRGAN/RealSR/SRCNN), scale factor, and expected quality gain.`,"style-transfer":`Image "${i}", target style: "${(a==null?void 0:a.targetStyle)??"artistic"}". Suggest style-transfer settings as JSON: { contentWeight, styleWeight, iterations, patchSize }.`};return{fieldLabel:`Graphics: ${i}`,fieldType:"graphics",schema:{mode:t,...(a==null?void 0:a.width)!=null?{width:a.width,height:a.height}:{},...a!=null&&a.targetStyle?{targetStyle:a.targetStyle}:{}},customPrompt:n[t]}}function ia(i,a){var t;return{fieldLabel:"Icon search",fieldType:"icon-picker",fieldValue:i,schema:{...a!=null&&a.style?{iconStyle:a.style}:{},...(a==null?void 0:a.limit)!=null?{maxResults:a.limit}:{},...(t=a==null?void 0:a.availableIcons)!=null&&t.length?{sampleIcons:a.availableIcons.slice(0,30)}:{}},customPrompt:`User query: "${i}"
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 Ja(i,a,t){const r=d.useMemo(()=>Qe(i,a,t),[i,a,t==null?void 0:t.cursorLine,t==null?void 0:t.cursorCol,t==null?void 0:t.framework]);return X(r,t)}function Ha(i,a,t){const r=d.useMemo(()=>Ze(i,a,t),[i,a,t==null?void 0:t.mode,t==null?void 0:t.locale]);return X(r,t)}function Ua(i,a){const t=d.useMemo(()=>ea(i,a),[i,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 X(t,a)}function Ga(i,a){const t=d.useMemo(()=>aa(i,a),[i,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 X(t,a)}function Wa(i,a){const t=d.useMemo(()=>ta(i,a),[i,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 X(t,a)}function Va(i,a){const t=d.useMemo(()=>ia(i,a),[i,a==null?void 0:a.limit,a==null?void 0:a.style]);return X(t,{...a,disabled:!i||(a==null?void 0:a.disabled)})}function ra(i,a){var s;const t=(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 "${i}" 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 "${i}". 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 "${i}". 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 "${i}". 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 "${i}". Include: item name, rarity, flavour text, and one special property. Keep it under 80 words.`};return{fieldLabel:i,fieldType:`game-engine:${t}`,fieldValue:a==null?void 0:a.gameState,customPrompt:n[t],schema:{genre:r,mode:t,btNodes:(s=a==null?void 0:a.btStatus)==null?void 0:s.map(o=>o.node)}}}function Ka(i,a){const t=d.useMemo(()=>ra(i,a),[i,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 X(t,a)}function na(i,a,t){const r=(t==null?void 0:t.mode)??"layout",n=(t==null?void 0:t.diagramType)??"flowchart",s={layout:`You are a diagram layout optimizer. Given this ${n} with ${i.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=i.map(h=>{var p;return{id:h.id,type:h.type,label:(p=h.label)==null?void 0:p.slice(0,30),pos:[Math.round(h.x),Math.round(h.y)]}}),c=a.map(h=>({id:h.id,src:h.source,tgt:h.target}));return{fieldLabel:`Diagram (${n})`,fieldType:`diagram:${r}`,fieldValue:JSON.stringify({nodes:o,edges:c}),schema:{diagramType:n,mode:r,nodeCount:i.length,edgeCount:a.length,containerSize:t==null?void 0:t.containerSize},customPrompt:s[r]}}function Ya(i,a,t){const r=d.useMemo(()=>na(i,a,t),[JSON.stringify(i),JSON.stringify(a),t==null?void 0:t.mode,t==null?void 0:t.diagramType]);return X(r,{...t,disabled:i.length===0||(t==null?void 0:t.disabled)})}function sa(i,a){const t=(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: "${i}". 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: "${i}". 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: "${i}". 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: "${i}". 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:${t}`,fieldValue:i,schema:{presentationType:r,mode:t,duration:n,slideCount:s,audience:a==null?void 0:a.audience,hasData:(a==null?void 0:a.dataContext)!=null},customPrompt:o[t]}}function Xa(i,a){const t=d.useMemo(()=>sa(i,a),[i,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 X(t,{...a,disabled:!i||(a==null?void 0:a.disabled)})}function ca(i,a){var n;const t=(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:i.title??"Slide Design",fieldType:`slide-design:${t}`,fieldValue:JSON.stringify(i),schema:{mode:t,hasElements:(((n=i.elements)==null?void 0:n.length)??0)>0,layout:i.layout,brandColors:a==null?void 0:a.brandColors},customPrompt:r[t]}}function Qa(i,a){const t=d.useMemo(()=>ca(i,a),[JSON.stringify(i),a==null?void 0:a.mode,JSON.stringify(a==null?void 0:a.brandColors)]);return X(t,a)}function Za(i,a,t){const r=d.forwardRef((n,s)=>{const{aiEnabled:o=!0,aiPosition:c="right",aiPrompt:h,aiDebounceMs:p=500,aiShowOnHover:m=!1,aiTriggerIcon:b,...w}=n,k=d.useMemo(()=>{const M=a(w);return h&&(M.customPrompt=h),M},[w,h]);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(i,{...w,ref:s}),o&&e.jsx(Ie,{context:k,position:c,debounceMs:p,showOnHover:m,triggerIcon:b})]})});return r.displayName=t??`withAIHint(${i.displayName??i.name??"Component"})`,r}function et(i){return Re(i.label??"Text",i.value,{placeholder:i.placeholder,maxLength:i.maxLength})}function at(i){return ze(i.label??"Number",i.value,{min:i.min,max:i.max,step:i.step})}function tt(i){return Me(i.label??"Select",i.value,{options:i.options,multiple:i.multiple})}function it(i){return Le(i.label??"Date",i.value,{min:i.min,max:i.max})}function rt(i){return Pe(i.label??"Color",i.value)}const nt=i=>({id:A.createId(),name:i,type:"classification",status:"draft",datasets:[],experiments:[],models:[],createdAt:new Date,updatedAt:new Date}),we={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"}]},st=Object.values(we).flat(),De=(i,a)=>{const t=st.find(r=>r.id===i);return t?a(t.key,t.name):i},ct=[["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"]],ot=[["data","mlStudio.tab.data","Data"],["experiments","mlStudio.tab.experiments","Experiments"],["models","mlStudio.tab.models","Models"],["deploy","mlStudio.tab.deploy","Deploy"]],lt=[["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"]],dt={train:["mlStudio.split.train","Train"],validation:["mlStudio.split.validation","Validation"],test:["mlStudio.split.test","Test"]},ut={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"]},pt={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"]},mt={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"]},se=(i,a,t)=>i?t(i[0],i[1]):a,gt=new Set(["accuracy","precision","recall","f1-score","auc-roc"]),Be=({name:i,value:a},t)=>gt.has(i)?`${(a*100).toLocaleString(t,{minimumFractionDigits:1,maximumFractionDigits:1})}%`:a.toLocaleString(t,{maximumFractionDigits:3}),ht=[{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"}],ft=({project:i,onProjectChange:a,onExperimentRun:t,onModelDeploy:r,onModelDownload:n,className:s="",tutorial:o})=>{var Y;const{t:c,lang:h}=A.useNiceTranslation(),[p,m]=d.useState(()=>i||nt(c("mlStudio.newProject","New ML Project"))),[b,w]=d.useState("data"),[k,M]=d.useState(null),[C,O]=d.useState(null),[_,l]=d.useState(null),[y,S]=d.useState(!1),[f,j]=d.useState({algorithm:"",hyperparameters:{},preprocessing:[]}),g=d.useRef(p),x=d.useCallback(u=>{const R=g.current,B={...R,...typeof u=="function"?u(R):u,updatedAt:new Date};g.current=B,m(B),a==null||a(B)},[a]),v=async u=>{for(const R of Array.from(u)){const B={id:A.createId(),name:R.name.replace(/\.[^.]+$/,""),type:"tabular",source:{type:"file",uri:R.name},size:R.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(R.name.endsWith(".csv")){const q=(await R.text()).split(`
11
+ `),G=q[0].split(",").map(Q=>Q.trim());B.rowCount=q.length-1,B.columns=G.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)}))}x(H=>({datasets:[...H.datasets,B]}))}},T=u=>{x({datasets:p.datasets.filter(R=>R.id!==u)}),k===u&&M(null)},I=async()=>{if(!f.algorithm||!k)return;const u={id:A.createId(),name:c("mlStudio.experimentName","Experiment {n}").replace("{n}",String(p.experiments.length+1)),status:"pending",config:f,metrics:[],artifacts:[],logs:[]},R=H=>x(q=>({experiments:q.experiments.map(G=>G.id===u.id?{...G,...H}:G)}));if(x(H=>({experiments:[...H.experiments,u]})),S(!1),!t)return;const B=new Date;R({status:"running",startedAt:B});try{const H=await t(u),q=typeof H=="object"&&H!==null?H:{},G=new Date;R({status:"completed",completedAt:G,duration:q.duration??(G.getTime()-B.getTime())/1e3,metrics:q.metrics??[],artifacts:q.artifacts??[],logs:q.logs??[]})}catch{R({status:"failed"})}},N=u=>{const R=p.experiments.find(q=>q.id===u);if(!R)return;const B=R.artifacts.filter(q=>q.type==="model"),H={id:A.createId(),name:c("mlStudio.modelFrom","Model from {name}").replace("{name}",R.name),version:"1.0.0",algorithm:R.config.algorithm,experimentId:u,status:"registered",metrics:R.metrics,size:B.reduce((q,G)=>q+G.size,0),artifacts:B,deployments:[],createdAt:new Date};x(q=>({models:[...q.models,H]}))},P=async u=>{const R=p.models.find(H=>H.id===u);if(!R||!r)return;const B=await r(R);x(H=>({models:H.models.map(q=>q.id===u?{...q,status:"production",deployments:[...q.deployments,B]}:q)}))},$=u=>u<1024?`${u} B`:u<1024*1024?`${(u/1024).toFixed(1)} KB`:u<1024*1024*1024?`${(u/1024/1024).toFixed(1)} MB`:`${(u/1024/1024/1024).toFixed(1)} GB`,D=u=>{switch(u){case"completed":case"production":case"running":return"status-badge--success";case"pending":case"staging":return"status-badge--pending";case"failed":return"status-badge--error";default:return""}},F=e.jsxs("div",{className:"header__info",children:[e.jsx("input",{type:"text",value:p.name,onChange:u=>x({name:u.target.value}),className:"project-name-input","aria-label":c("mlStudio.projectName","Project name")}),e.jsx("select",{value:p.type,onChange:u=>x({type:u.target.value}),className:"project-type-select","aria-label":c("mlStudio.projectType","Project type"),children:ct.map(([u,R,B])=>e.jsx("option",{value:u,children:c(R,B)},u))})]}),U=e.jsx("div",{className:"header__tabs",children:ot.map(([u,R,B])=>e.jsx("button",{className:`tab-button ${b===u?"tab-button--active":""}`,onClick:()=>w(u),children:c(R,B)},u))}),W=e.jsxs("div",{className:"ml-studio__content",children:[b==="data"&&e.jsxs("div",{className:"data-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:c("mlStudio.datasets","Datasets")}),e.jsxs("label",{className:"upload-button",children:[e.jsx("input",{type:"file",multiple:!0,accept:".csv,.json,.parquet",onChange:u=>u.target.files&&v(u.target.files),hidden:!0}),e.jsx(A.NiceIcon,{name:"plus",size:14})," ",c("mlStudio.uploadDataset","Upload Dataset")]})]}),e.jsx("div",{className:"datasets-grid",children:p.datasets.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(A.NiceIcon,{name:"bar-chart",size:32})}),e.jsx("p",{children:c("mlStudio.noDatasets","No datasets uploaded yet")}),e.jsx("p",{className:"hint",children:c("mlStudio.noDatasetsHint","Upload CSV, JSON, or Parquet files to get started")})]}):p.datasets.map(u=>e.jsxs("div",{className:`dataset-card ${k===u.id?"dataset-card--selected":""}`,onClick:()=>M(u.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("span",{className:"dataset-icon",children:e.jsx(A.NiceIcon,{name:"folder",size:16})}),e.jsx("h3",{children:u.name}),e.jsx("button",{className:"remove-button","aria-label":c("mlStudio.removeDataset","Remove dataset"),onClick:R=>{R.stopPropagation(),T(u.id)},children:e.jsx(A.NiceIcon,{name:"close",size:14})})]}),e.jsxs("div",{className:"card-stats",children:[e.jsx("span",{children:c("mlStudio.rows","{count} rows").replace("{count}",u.rowCount.toLocaleString(h))}),e.jsx("span",{children:c("mlStudio.columnCount","{count} columns").replace("{count}",String(u.columns.length))}),e.jsx("span",{children:$(u.size)})]}),e.jsx("div",{className:"splits-bar",children:u.splits.map(R=>e.jsx("div",{className:`split split--${R.name}`,style:{width:`${R.ratio*100}%`},title:`${se(dt[R.name],R.name,c)}: ${(R.ratio*100).toFixed(0)}%`},R.name))})]},u.id))}),k&&e.jsx("div",{className:"dataset-details",children:(()=>{const u=p.datasets.find(R=>R.id===k);return u?e.jsxs(e.Fragment,{children:[e.jsx("h3",{children:c("mlStudio.columns","Columns")}),e.jsxs("table",{className:"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:u.columns.map(R=>e.jsxs("tr",{children:[e.jsx("td",{children:R.name}),e.jsx("td",{children:e.jsx("select",{value:R.type,"aria-label":c("mlStudio.col.type","Type"),onChange:B=>{x({datasets:p.datasets.map(H=>H.id===u.id?{...H,columns:H.columns.map(q=>q.name===R.name?{...q,type:B.target.value}:q)}:H)})},children:lt.map(([B,H,q])=>e.jsx("option",{value:B,children:c(H,q)},B))})}),e.jsx("td",{children:R.missing}),e.jsx("td",{children:R.unique})]},R.name))})]})]}):null})()})]}),b==="experiments"&&e.jsxs("div",{className:"experiments-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:c("mlStudio.tab.experiments","Experiments")}),e.jsxs("button",{className:"primary-button",onClick:()=>S(!0),disabled:p.datasets.length===0,children:[e.jsx(A.NiceIcon,{name:"plus",size:14})," ",c("mlStudio.newExperiment","New Experiment")]})]}),y&&e.jsxs("div",{className:"new-experiment-form",children:[e.jsx("h3",{children:c("mlStudio.configureExperiment","Configure Experiment")}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{children:[c("mlStudio.dataset","Dataset"),e.jsxs("select",{value:k||"",onChange:u=>M(u.target.value),children:[e.jsx("option",{value:"",children:c("mlStudio.selectDataset","Select dataset...")}),p.datasets.map(u=>e.jsx("option",{value:u.id,children:u.name},u.id))]})]}),e.jsxs("label",{children:[c("mlStudio.algorithm","Algorithm"),e.jsxs("select",{value:f.algorithm,onChange:u=>j({...f,algorithm:u.target.value}),children:[e.jsx("option",{value:"",children:c("mlStudio.selectAlgorithm","Select algorithm...")}),(we[p.type]||we.classification).map(u=>e.jsx("option",{value:u.id,children:c(u.key,u.name)},u.id))]})]}),k&&e.jsxs("label",{children:[c("mlStudio.targetColumn","Target Column"),e.jsxs("select",{value:f.targetColumn||"",onChange:u=>j({...f,targetColumn:u.target.value}),children:[e.jsx("option",{value:"",children:c("mlStudio.selectTarget","Select target...")}),(Y=p.datasets.find(u=>u.id===k))==null?void 0:Y.columns.map(u=>e.jsx("option",{value:u.name,children:u.name},u.name))]})]})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{className:"secondary-button",onClick:()=>S(!1),children:c("cancel","Cancel")}),e.jsx("button",{className:"primary-button",onClick:I,disabled:!f.algorithm||!k,children:c("mlStudio.runExperiment","Run Experiment")})]})]}),e.jsx("div",{className:"experiments-list",children:p.experiments.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(A.NiceIcon,{name:"flask",size:32})}),e.jsx("p",{children:c("mlStudio.noExperiments","No experiments yet")}),e.jsx("p",{className:"hint",children:c("mlStudio.noExperimentsHint","Create an experiment to train and evaluate models")})]}):p.experiments.map(u=>e.jsxs("div",{className:`experiment-card ${C===u.id?"experiment-card--selected":""}`,onClick:()=>O(u.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:u.name}),e.jsx("span",{className:`status-badge ${D(u.status)}`,children:se(ut[u.status],u.status,c)})]}),e.jsxs("div",{className:"card-meta",children:[e.jsx("span",{children:c("mlStudio.algorithmValue","Algorithm: {name}").replace("{name}",De(u.config.algorithm,c))}),u.duration!==void 0&&e.jsx("span",{children:c("mlStudio.duration","Duration: {seconds}s").replace("{seconds}",String(Math.round(u.duration)))})]}),u.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:u.metrics.slice(0,3).map(R=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:R.name}),e.jsx("span",{className:"metric-value",children:Be(R,h)})]},R.name))}),u.status==="completed"&&e.jsx("button",{className:"action-button",onClick:R=>{R.stopPropagation(),N(u.id)},children:c("mlStudio.registerModel","Register Model")})]},u.id))})]}),b==="models"&&e.jsxs("div",{className:"models-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:c("mlStudio.tab.models","Models")})}),e.jsx("div",{className:"models-list",children:p.models.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(A.NiceIcon,{name:"wand",size:32})}),e.jsx("p",{children:c("mlStudio.noModels","No models registered yet")}),e.jsx("p",{className:"hint",children:c("mlStudio.noModelsHint","Complete experiments and register models")})]}):p.models.map(u=>e.jsxs("div",{className:`model-card ${_===u.id?"model-card--selected":""}`,onClick:()=>l(u.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:u.name}),e.jsx("span",{className:`status-badge ${D(u.status)}`,children:se(pt[u.status],u.status,c)})]}),e.jsxs("div",{className:"card-meta",children:[e.jsx("span",{children:c("mlStudio.algorithmValue","Algorithm: {name}").replace("{name}",De(u.algorithm,c))}),e.jsx("span",{children:c("mlStudio.version","Version: {version}").replace("{version}",u.version)}),u.size>0&&e.jsx("span",{children:c("mlStudio.size","Size: {size}").replace("{size}",$(u.size))})]}),u.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:u.metrics.slice(0,3).map(R=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:R.name}),e.jsx("span",{className:"metric-value",children:Be(R,h)})]},R.name))}),e.jsxs("div",{className:"card-actions",children:[e.jsx("button",{className:"action-button",onClick:R=>{R.stopPropagation(),n==null||n(u)},disabled:!n,title:n?void 0:c("mlStudio.downloadNotSetUp","Downloading models is not set up"),children:c("download","Download")}),e.jsx("button",{className:"action-button action-button--primary",onClick:R=>{R.stopPropagation(),P(u.id)},disabled:u.status==="production"||!r,title:r?void 0:c("mlStudio.deployNotSetUp","Deploying models is not set up"),children:u.status==="production"?c("mlStudio.deployed","Deployed"):c("mlStudio.deploy","Deploy")})]})]},u.id))})]}),b==="deploy"&&e.jsxs("div",{className:"deploy-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:c("mlStudio.deployments","Deployments")})}),e.jsx("div",{className:"deployments-list",children:p.models.filter(u=>u.deployments.length>0).length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(A.NiceIcon,{name:"rocket",size:32})}),e.jsx("p",{children:c("mlStudio.noDeployments","No deployments yet")}),e.jsx("p",{className:"hint",children:c("mlStudio.noDeploymentsHint","Deploy a model to create inference endpoints")})]}):p.models.filter(u=>u.deployments.length>0).flatMap(u=>u.deployments.map(R=>({model:u,deployment:R}))).map(({model:u,deployment:R})=>e.jsxs("div",{className:"deployment-card",children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:R.name}),e.jsx("span",{className:`status-badge ${D(R.status)}`,children:se(mt[R.status],R.status,c)})]}),e.jsxs("div",{className:"card-meta",children:[e.jsx("span",{children:c("mlStudio.modelValue","Model: {name}").replace("{name}",u.name)}),e.jsx("span",{children:c("mlStudio.endpoint","Endpoint: {url}").replace("{url}",R.endpoint)})]}),e.jsxs("div",{className:"resources-info",children:[e.jsx("span",{children:c("mlStudio.cpu","CPU: {count} cores").replace("{count}",String(R.resources.cpu))}),e.jsx("span",{children:c("mlStudio.memory","Memory: {gb} GB").replace("{gb}",String(R.resources.memory))}),e.jsx("span",{children:c("mlStudio.replicas","Replicas: {count}").replace("{count}",String(R.resources.replicas))})]})]},R.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(A.NiceTutorialButton,{steps:A.resolveTutorial(o,ht)})}),e.jsx(Aa.NiceAppShell,{flush:!0,menubar:F,toolbar:U,children:W})]})},xt={id:A.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},Fe=["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)"],bt={label:"Label",schema:"Schema",review:"Review",export:"Export"},yt=({project:i,onProjectChange:a,onLabelSave:t,onExport:r,className:n=""})=>{var ie;const{t:s}=A.useNiceTranslation(),[o,c]=d.useState(i||xt),[h,p]=d.useState("label"),[m,b]=d.useState(0),[w,k]=d.useState(null),[M,C]=d.useState("select"),[O,_]=d.useState(!1),[l,y]=d.useState(null),[S,f]=d.useState(1),[j,g]=d.useState(!1),[x,v]=d.useState("all"),T=d.useRef(null),I=d.useRef(null),N=o.items[m];d.useEffect(()=>{i&&c(i)},[i]);const P=d.useCallback(z=>{const E={...o,...z};E.statistics={totalItems:E.items.length,labeled:E.items.filter(L=>L.status!=="pending").length,reviewed:E.items.filter(L=>L.status==="review"||L.status==="approved").length,approved:E.items.filter(L=>L.status==="approved").length,byClass:E.labelSchema.classes.map(L=>({classId:L.id,count:E.items.flatMap(J=>J.labels).filter(J=>J.classId===L.id).length}))},c(E),a==null||a(E)},[o,a]),$=()=>{const z={id:A.createId(),name:`Class ${o.labelSchema.classes.length+1}`,color:Fe[o.labelSchema.classes.length%Fe.length],shortcut:String(o.labelSchema.classes.length+1)};P({labelSchema:{...o.labelSchema,classes:[...o.labelSchema.classes,z]}})},D=z=>{P({labelSchema:{...o.labelSchema,classes:o.labelSchema.classes.filter(E=>E.id!==z)},items:o.items.map(E=>({...E,labels:E.labels.filter(L=>L.classId!==z)}))})},F=(z,E)=>{P({labelSchema:{...o.labelSchema,classes:o.labelSchema.classes.map(L=>L.id===z?{...L,...E}:L)}})},U=(z,E)=>{if(!N)return;const L={id:A.createId(),classId:z,type:o.type==="classification"?"class":o.type==="bounding-box"?"bbox":"class",data:E||{},createdBy:"current-user",createdAt:new Date},J={...N,labels:[...N.labels,L],status:"labeled"};P({items:o.items.map(V=>V.id===N.id?J:V)}),t==null||t(J)},W=z=>{if(!N)return;const E={...N,labels:N.labels.filter(L=>L.id!==z),status:N.labels.length<=1?"pending":"labeled"};P({items:o.items.map(L=>L.id===N.id?E:L)})},Y=z=>{var V;if(M!=="bbox"||!w)return;const E=(V=T.current)==null?void 0:V.getBoundingClientRect();if(!E)return;const L=(z.clientX-E.left)/S,J=(z.clientY-E.top)/S;_(!0),y({x:L,y:J,width:0,height:0})},u=z=>{var V;if(!O||!l)return;const E=(V=T.current)==null?void 0:V.getBoundingClientRect();if(!E)return;const L=(z.clientX-E.left)/S,J=(z.clientY-E.top)/S;y({...l,width:L-l.x,height:J-l.y})},R=()=>{!O||!l||!w||(_(!1),Math.abs(l.width)>10&&Math.abs(l.height)>10&&U(w,{x:l.width<0?l.x+l.width:l.x,y:l.height<0?l.y+l.height:l.y,width:Math.abs(l.width),height:Math.abs(l.height)}),y(null))},B=z=>{const E=x==="all"?o.items:o.items.filter(J=>J.status===x),L=E.findIndex(J=>J.id===(N==null?void 0:N.id));if(z==="prev"&&L>0){const J=E[L-1];b(o.items.findIndex(V=>V.id===J.id))}else if(z==="next"&&L<E.length-1){const J=E[L+1];b(o.items.findIndex(V=>V.id===J.id))}},H=()=>{if(!N)return;const z={...N,status:"approved"};P({items:o.items.map(E=>E.id===N.id?z:E)}),B("next")},q=()=>{if(!N)return;const z={...N,status:"rejected"};P({items:o.items.map(E=>E.id===N.id?z:E)}),B("next")},G=async z=>{r&&await r(z)};d.useEffect(()=>{const z=E=>{const L=E.target instanceof HTMLElement?E.target:null;if(h!=="label"||E.defaultPrevented||E.ctrlKey||E.metaKey||E.altKey||L!=null&&L.isContentEditable||L&&/^(INPUT|TEXTAREA|SELECT)$/.test(L.tagName)||E.key==="Enter"&&(L!=null&&L.closest("button, a")))return;const J=E.key,V=o.labelSchema.classes.find(re=>re.shortcut===J);V&&(o.type==="classification"?(U(V.id),B("next")):k(V.id)),E.key==="ArrowLeft"||E.key==="a"?B("prev"):(E.key==="ArrowRight"||E.key==="d")&&B("next"),E.key==="Enter"?H():E.key==="Backspace"&&q()};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[h,N,o.labelSchema.classes,o.type]);const Q=z=>{switch(z){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:"labeler__header",children:[e.jsxs("div",{className:"header__info",children:[e.jsx("input",{type:"text",value:o.name,onChange:z=>P({name:z.target.value}),className:"project-name-input"}),e.jsxs("div",{className:"progress-bar",children:[e.jsx("div",{className:"progress-fill",style:{width:`${o.statistics.labeled/Math.max(o.statistics.totalItems,1)*100}%`}}),e.jsx("span",{className:"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:"header__tabs",children:["label","schema","review","export"].map(z=>e.jsx("button",{className:`tab-button ${h===z?"tab-button--active":""}`,onClick:()=>p(z),children:s(`dataLabeler.tab.${z}`,bt[z])},z))}),e.jsx("button",{className:"shortcuts-button",onClick:()=>g(!j),children:s("dataLabeler.shortcuts","Shortcuts")})]}),e.jsxs("div",{className:"labeler__content",children:[h==="label"&&e.jsxs("div",{className:"label-panel",children:[e.jsxs("div",{className:"label-toolbar",children:[e.jsxs("div",{className:"tool-group",children:[e.jsxs("button",{className:`tool-button ${M==="select"?"tool-button--active":""}`,onClick:()=>C("select"),children:[e.jsx(A.NiceIcon,{name:"cursor",size:14})," ",s("dataLabeler.select","Select")]}),(o.type==="bounding-box"||o.type==="multi-label")&&e.jsxs("button",{className:`tool-button ${M==="bbox"?"tool-button--active":""}`,onClick:()=>C("bbox"),children:[e.jsx(A.NiceIcon,{name:"square",size:14})," Box"]}),o.type==="polygon"&&e.jsxs("button",{className:`tool-button ${M==="polygon"?"tool-button--active":""}`,onClick:()=>C("polygon"),children:[e.jsx(A.NiceIcon,{name:"hexagon",size:14})," ",s("dataLabeler.polygon","Polygon")]})]}),e.jsxs("div",{className:"zoom-group",children:[e.jsx("button",{"aria-label":s("dataLabeler.zoomOut","Zoom out"),onClick:()=>f(Math.max(.25,S-.25)),children:e.jsx(A.NiceIcon,{name:"minus",size:14})}),e.jsxs("span",{children:[Math.round(S*100),"%"]}),e.jsx("button",{"aria-label":s("dataLabeler.zoomIn","Zoom in"),onClick:()=>f(Math.min(4,S+.25)),children:e.jsx(A.NiceIcon,{name:"plus",size:14})})]}),e.jsxs("div",{className:"navigation-group",children:[e.jsxs("button",{onClick:()=>B("prev"),disabled:m===0,children:[e.jsx(A.NiceIcon,{name:"arrow-left",size:14})," ",s("dataLabeler.prev","Prev")]}),e.jsxs("span",{children:[m+1," / ",o.items.length]}),e.jsxs("button",{onClick:()=>B("next"),disabled:m>=o.items.length-1,children:[s("dataLabeler.next","Next")," ",e.jsx(A.NiceIcon,{name:"arrow-right",size:14})]})]})]}),e.jsxs("div",{className:"label-workspace",children:[e.jsx("div",{className:"canvas-container",ref:I,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:"labeling-image",style:{transform:`scale(${S})`}}),e.jsx("canvas",{ref:T,className:"labeling-canvas",onMouseDown:Y,onMouseMove:u,onMouseUp:R,onMouseLeave:R,style:{transform:`scale(${S})`,cursor:M==="bbox"?"crosshair":"default"}}),e.jsxs("div",{className:"annotations-overlay",style:{transform:`scale(${S})`},children:[N.labels.filter(z=>z.type==="bbox"&&z.data.x!==void 0).map(z=>{const E=o.labelSchema.classes.find(L=>L.id===z.classId);return e.jsxs("div",{className:"bbox-annotation",style:{left:z.data.x,top:z.data.y,width:z.data.width,height:z.data.height,borderColor:(E==null?void 0:E.color)||"var(--nice-danger, #ff0000)"},children:[e.jsx("span",{className:"bbox-label",style:{backgroundColor:(E==null?void 0:E.color)||"var(--nice-danger, #ff0000)"},children:E==null?void 0:E.name}),e.jsx("button",{className:"bbox-remove","aria-label":s("dataLabeler.removeLabel","Remove label"),onClick:()=>W(z.id),children:e.jsx(A.NiceIcon,{name:"close",size:12})})]},z.id)}),l&&e.jsx("div",{className:"bbox-drawing",style:{left:l.width<0?l.x+l.width:l.x,top:l.height<0?l.y+l.height:l.y,width:Math.abs(l.width),height:Math.abs(l.height),borderColor:(ie=o.labelSchema.classes.find(z=>z.id===w))==null?void 0:ie.color}})]})]}),N.data.type==="text"&&e.jsx("div",{className:"text-labeling",children:e.jsx("p",{className:"text-content",children:N.data.text})})]}):e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:e.jsx(A.NiceIcon,{name:"clipboard",size:32})}),e.jsx("p",{children:s("dataLabeler.noItemsToLabel","No items to label")})]})}),e.jsxs("aside",{className:"class-sidebar",children:[e.jsx("h3",{children:s("dataLabeler.classes","Classes")}),e.jsx("div",{className:"class-list",children:o.labelSchema.classes.map(z=>e.jsxs("button",{className:`class-button ${w===z.id?"class-button--active":""}`,style:{borderLeftColor:z.color},onClick:()=>{o.type==="classification"?(U(z.id),B("next")):k(z.id)},children:[e.jsx("span",{className:"class-color",style:{backgroundColor:z.color}}),e.jsx("span",{className:"class-name",children:z.name}),z.shortcut&&e.jsx("span",{className:"class-shortcut",children:z.shortcut})]},z.id))}),N&&N.labels.length>0&&e.jsxs("div",{className:"current-labels",children:[e.jsx("h4",{children:s("dataLabeler.labels","Labels")}),N.labels.map(z=>{const E=o.labelSchema.classes.find(L=>L.id===z.classId);return e.jsxs("div",{className:"label-item",children:[e.jsx("span",{className:"label-color",style:{backgroundColor:E==null?void 0:E.color}}),e.jsx("span",{className:"label-name",children:E==null?void 0:E.name}),e.jsx("button",{"aria-label":s("dataLabeler.removeLabel","Remove label"),onClick:()=>W(z.id),children:e.jsx(A.NiceIcon,{name:"close",size:14})})]},z.id)})]}),h==="label"&&N&&e.jsxs("div",{className:"label-actions",children:[e.jsxs("button",{className:"approve-button",onClick:H,children:[e.jsx(A.NiceIcon,{name:"check",size:14})," ",s("dataLabeler.approve","Approve")]}),e.jsxs("button",{className:"reject-button",onClick:q,children:[e.jsx(A.NiceIcon,{name:"close",size:14})," ",s("dataLabeler.reject","Reject")]})]})]})]})]}),h==="schema"&&e.jsxs("div",{className:"schema-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:s("dataLabeler.labelSchema","Label Schema")}),e.jsxs("button",{className:"primary-button",onClick:$,children:[e.jsx(A.NiceIcon,{name:"plus",size:14})," ",s("dataLabeler.addClass","Add Class")]})]}),e.jsxs("div",{className:"schema-settings",children:[e.jsxs("label",{children:[s("dataLabeler.labelingType","Labeling Type"),e.jsxs("select",{value:o.type,onChange:z=>P({type:z.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:z=>P({dataType:z.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:"classes-list",children:o.labelSchema.classes.map((z,E)=>e.jsxs("div",{className:"class-editor",children:[e.jsx("input",{type:"color",value:z.color,onChange:L=>F(z.id,{color:L.target.value}),className:"color-picker"}),e.jsx("input",{type:"text",value:z.name,onChange:L=>F(z.id,{name:L.target.value}),className:"class-name-input",placeholder:s("dataLabeler.classNamePlaceholder","Class name")}),e.jsx("input",{type:"text",value:z.shortcut||"",onChange:L=>F(z.id,{shortcut:L.target.value}),className:"shortcut-input",placeholder:s("dataLabeler.shortcutKeyPlaceholder","Key"),maxLength:1}),e.jsx("button",{className:"remove-class-button","aria-label":s("dataLabeler.removeClass","Remove class"),onClick:()=>D(z.id),children:e.jsx(A.NiceIcon,{name:"trash",size:16})})]},z.id))}),e.jsxs("div",{className:"guidelines-section",children:[e.jsx("h3",{children:s("dataLabeler.labelingGuidelines","Labeling Guidelines")}),e.jsx("textarea",{value:o.guidelines||"",onChange:z=>P({guidelines:z.target.value}),placeholder:s("dataLabeler.guidelinesPlaceholder","Enter labeling guidelines for annotators..."),rows:6})]})]}),h==="review"&&e.jsxs("div",{className:"review-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:s("dataLabeler.reviewLabels","Review Labels")}),e.jsx("div",{className:"filter-group",children:e.jsxs("select",{value:x,onChange:z=>v(z.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:"items-grid",children:o.items.filter(z=>x==="all"||z.status===x).map((z,E)=>{var L;return e.jsxs("div",{className:`item-card ${m===o.items.indexOf(z)?"item-card--active":""}`,onClick:()=>{b(o.items.indexOf(z)),p("label")},children:[z.data.type==="image"&&e.jsx("img",{src:z.data.url,alt:`Item ${E+1}`,className:"item-thumbnail"}),z.data.type==="text"&&e.jsxs("p",{className:"item-text-preview",children:[(L=z.data.text)==null?void 0:L.slice(0,100),"..."]}),e.jsxs("div",{className:"item-footer",children:[e.jsx("span",{className:"status-dot",style:{backgroundColor:Q(z.status)}}),e.jsx("span",{children:s("dataLabeler.labelCount","{count} labels").replace("{count}",String(z.labels.length))})]})]},z.id)})})]}),h==="export"&&e.jsxs("div",{className:"export-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:s("dataLabeler.exportLabels","Export Labels")})}),e.jsxs("div",{className:"export-stats",children:[e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:o.statistics.totalItems}),e.jsx("span",{className:"stat-label",children:s("dataLabeler.totalItems","Total Items")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:o.statistics.labeled}),e.jsx("span",{className:"stat-label",children:s("dataLabeler.labeled","Labeled")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:o.statistics.approved}),e.jsx("span",{className:"stat-label",children:s("dataLabeler.approved","Approved")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:o.labelSchema.classes.length}),e.jsx("span",{className:"stat-label",children:s("dataLabeler.classes","Classes")})]})]}),e.jsxs("div",{className:"export-formats",children:[e.jsx("h3",{children:s("dataLabeler.exportFormat","Export Format")}),e.jsxs("div",{className:"format-grid",children:[e.jsxs("button",{className:"format-button",onClick:()=>G("coco"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(A.NiceIcon,{name:"box",size:24})}),e.jsx("span",{className:"format-name",children:s("dataLabeler.cocoJson","COCO JSON")}),e.jsx("span",{className:"format-desc",children:s("dataLabeler.cocoDesc","Common format for object detection")})]}),e.jsxs("button",{className:"format-button",onClick:()=>G("voc"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(A.NiceIcon,{name:"file",size:24})}),e.jsx("span",{className:"format-name",children:s("dataLabeler.pascalVoc","Pascal VOC")}),e.jsx("span",{className:"format-desc",children:s("dataLabeler.vocDesc","XML format for bounding boxes")})]}),e.jsxs("button",{className:"format-button",onClick:()=>G("yolo"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(A.NiceIcon,{name:"zap",size:24})}),e.jsx("span",{className:"format-name",children:s("dataLabeler.yolo","YOLO")}),e.jsx("span",{className:"format-desc",children:s("dataLabeler.yoloDesc","Text format for YOLO models")})]}),e.jsxs("button",{className:"format-button",onClick:()=>G("csv"),children:[e.jsx("span",{className:"format-icon",children:e.jsx(A.NiceIcon,{name:"bar-chart",size:24})}),e.jsx("span",{className:"format-name",children:"CSV"}),e.jsx("span",{className:"format-desc",children:s("dataLabeler.csvDesc","Tabular format for classification")})]})]})]}),e.jsxs("div",{className:"class-distribution",children:[e.jsx("h3",{children:s("dataLabeler.classDistribution","Class Distribution")}),e.jsx("div",{className:"distribution-bars",children:o.statistics.byClass.map(z=>{const E=o.labelSchema.classes.find(J=>J.id===z.classId),L=z.count/Math.max(o.statistics.labeled,1)*100;return e.jsxs("div",{className:"distribution-row",children:[e.jsx("span",{className:"class-name",style:{color:E==null?void 0:E.color},children:E==null?void 0:E.name}),e.jsx("div",{className:"bar-container",children:e.jsx("div",{className:"bar-fill",style:{width:`${L}%`,backgroundColor:E==null?void 0:E.color}})}),e.jsx("span",{className:"count",children:z.count})]},z.classId)})})]})]})]}),j&&e.jsx("div",{className:"shortcuts-modal",children:e.jsxs("div",{className:"modal-content",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:s("dataLabeler.keyboardShortcuts","Keyboard Shortcuts")}),e.jsx("button",{"aria-label":s("dataLabeler.close","Close"),onClick:()=>g(!1),children:e.jsx(A.NiceIcon,{name:"close",size:16})})]}),e.jsxs("div",{className:"shortcuts-list",children:[e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:"← / A"}),e.jsx("span",{className:"description",children:s("dataLabeler.previousItem","Previous item")})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:"→ / D"}),e.jsx("span",{className:"description",children:s("dataLabeler.nextItem","Next item")})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:s("dataLabeler.enterKey","Enter")}),e.jsx("span",{className:"description",children:s("dataLabeler.approveItem","Approve item")})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:s("dataLabeler.backspaceKey","Backspace")}),e.jsx("span",{className:"description",children:s("dataLabeler.rejectItem","Reject item")})]}),o.labelSchema.classes.map(z=>z.shortcut&&e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:z.shortcut}),e.jsx("span",{className:"description",children:s("dataLabeler.labelAs","Label as {name}").replace("{name}",z.name)})]},z.id))]})]})})]})},vt={id:A.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:[]},_t=({endpoint:i,onInference:a,showMetrics:t=!0,showLogs:r=!0,className:n=""})=>{const[s,o]=d.useState(i||vt),[c,h]=d.useState("test"),[p,m]=d.useState("text"),[b,w]=d.useState(""),[k,M]=d.useState("{}"),[C,O]=d.useState(null),[_,l]=d.useState({temperature:.7,topK:50,topP:.9,maxTokens:256,threshold:.5}),[y,S]=d.useState(null),[f,j]=d.useState(!1),[g,x]=d.useState(null),[v,T]=d.useState([]),[I,N]=d.useState(null),P=d.useRef(null),$=u=>{var B;const R=(B=u.target.files)==null?void 0:B[0];if(R){const H=new FileReader;H.onload=q=>{var G;O((G=q.target)==null?void 0:G.result)},H.readAsDataURL(R)}},D=async()=>{if(!a){x("No inference handler provided");return}j(!0),x(null),S(null);const u=[];switch(p){case"text":u.push({type:"text",data:b});break;case"image":C&&u.push({type:"image",data:C});break;case"json":try{u.push({type:"json",data:JSON.parse(k)})}catch{x("Invalid JSON input"),j(!1);return}break;case"tabular":try{u.push({type:"tabular",data:JSON.parse(k)})}catch{x("Invalid tabular data"),j(!1);return}break}const R={inputs:u,parameters:_};try{const B=Date.now(),H=await a(R),q=Date.now()-B;S(H),o(G=>({...G,metrics:{...G.metrics,requestsTotal:G.metrics.requestsTotal+1,latencyP50:(G.metrics.latencyP50+q)/2},logs:[{timestamp:new Date,requestId:H.requestId,duration:q,status:"success",inputSize:JSON.stringify(u).length,outputSize:JSON.stringify(H.predictions).length},...G.logs.slice(0,99)]}))}catch(B){const H=B instanceof Error?B.message:"Inference failed";x(H),o(q=>({...q,metrics:{...q.metrics,requestsTotal:q.metrics.requestsTotal+1,errorRate:(q.metrics.errorRate*q.metrics.requestsTotal+1)/(q.metrics.requestsTotal+1)},logs:[{timestamp:new Date,requestId:A.createId(),duration:0,status:"error",inputSize:JSON.stringify(u).length,outputSize:0,error:H},...q.logs.slice(0,99)]}))}finally{j(!1)}},F=async u=>{if(a){N(0),T([]);for(let R=0;R<u.length;R++){const B={inputs:[u[R]],parameters:_};try{const H=await a(B);T(q=>[...q,H])}catch(H){console.error("Batch item failed:",H)}N((R+1)/u.length*100)}N(null)}},U=u=>u<1e3?`${u.toFixed(0)}ms`:`${(u/1e3).toFixed(2)}s`,W=u=>u.toLocaleTimeString(),Y=(u,R)=>e.jsxs("div",{className:"prediction-item",children:[u.label&&e.jsxs("div",{className:"prediction-label",children:[e.jsx("span",{className:"label-name",children:u.label}),u.confidence!==void 0&&e.jsxs("span",{className:"confidence-badge",style:{backgroundColor:`hsl(${u.confidence*120}, 70%, 40%)`},children:[(u.confidence*100).toFixed(1),"%"]})]}),u.score!==void 0&&e.jsxs("div",{className:"prediction-score",children:[e.jsx("span",{className:"score-label",children:"Score:"}),e.jsx("span",{className:"score-value",children:u.score.toFixed(4)})]}),u.text&&e.jsx("div",{className:"prediction-text",children:e.jsx("pre",{children:u.text})}),u.bbox&&e.jsx("div",{className:"prediction-bbox",children:e.jsxs("span",{children:["Box: (",u.bbox.x,", ",u.bbox.y,") - ",u.bbox.width,"×",u.bbox.height]})}),u.raw!==void 0&&u.raw!==null&&e.jsxs("details",{className:"raw-output",children:[e.jsx("summary",{children:"Raw Output"}),e.jsx("pre",{children:JSON.stringify(u.raw,null,2)})]})]},R);return e.jsxs("div",{className:`nice-model-inference ${n}`,children:[e.jsxs("header",{className:"inference__header",children:[e.jsxs("div",{className:"header__info",children:[e.jsx("h2",{children:s.name}),e.jsx("span",{className:`status-badge status-badge--${s.status}`,children:s.status})]}),e.jsxs("div",{className:"header__tabs",children:[e.jsx("button",{className:`tab-button ${c==="test"?"tab-button--active":""}`,onClick:()=>h("test"),children:"Test"}),e.jsx("button",{className:`tab-button ${c==="batch"?"tab-button--active":""}`,onClick:()=>h("batch"),children:"Batch"}),t&&e.jsx("button",{className:`tab-button ${c==="metrics"?"tab-button--active":""}`,onClick:()=>h("metrics"),children:"Metrics"}),r&&e.jsx("button",{className:`tab-button ${c==="logs"?"tab-button--active":""}`,onClick:()=>h("logs"),children:"Logs"})]})]}),e.jsxs("div",{className:"inference__content",children:[c==="test"&&e.jsxs("div",{className:"test-panel",children:[e.jsxs("div",{className:"input-section",children:[e.jsx("div",{className:"input-type-selector",children:["text","image","json","tabular"].map(u=>e.jsx("button",{className:`type-button ${p===u?"type-button--active":""}`,onClick:()=>m(u),children:u.charAt(0).toUpperCase()+u.slice(1)},u))}),e.jsxs("div",{className:"input-area",children:[p==="text"&&e.jsx("textarea",{value:b,onChange:u=>w(u.target.value),placeholder:"Enter text input...",rows:6,className:"text-input"}),p==="image"&&e.jsx("div",{className:"image-input",children:C?e.jsxs("div",{className:"image-preview",children:[e.jsx("img",{src:C,alt:"Input preview"}),e.jsx("button",{className:"clear-button",onClick:()=>O(null),children:"Clear"})]}):e.jsxs("label",{className:"upload-zone",children:[e.jsx("input",{ref:P,type:"file",accept:"image/*",onChange:$,hidden:!0}),e.jsx("span",{className:"upload-icon",children:e.jsx(A.NiceIcon,{name:"image",size:32})}),e.jsx("span",{children:"Click or drag to upload image"})]})}),(p==="json"||p==="tabular")&&e.jsx("textarea",{value:k,onChange:u=>M(u.target.value),placeholder:p==="json"?`{
12
12
  "key": "value"
13
13
  }`:`[
14
14
  {"col1": "value1", "col2": "value2"}
15
- ]`,rows:10,className:"json-input"})]}),e.jsxs("div",{className:"parameters-section",children:[e.jsx("h4",{children:"Parameters"}),e.jsxs("div",{className:"parameters-grid",children:[e.jsxs("label",{children:["Temperature",e.jsx("input",{type:"number",value:j.temperature,onChange:M=>o({...j,temperature:parseFloat(M.target.value)}),min:"0",max:"2",step:"0.1"})]}),e.jsxs("label",{children:["Top K",e.jsx("input",{type:"number",value:j.topK,onChange:M=>o({...j,topK:parseInt(M.target.value)}),min:"1",max:"100"})]}),e.jsxs("label",{children:["Top P",e.jsx("input",{type:"number",value:j.topP,onChange:M=>o({...j,topP:parseFloat(M.target.value)}),min:"0",max:"1",step:"0.05"})]}),e.jsxs("label",{children:["Threshold",e.jsx("input",{type:"number",value:j.threshold,onChange:M=>o({...j,threshold:parseFloat(M.target.value)}),min:"0",max:"1",step:"0.05"})]})]})]}),e.jsx("button",{className:"run-button",onClick:B,disabled:m||!y&&!k&&S==="{}",children:m?"Running...":"Run Inference"})]}),e.jsxs("div",{className:"output-section",children:[e.jsx("h3",{children:"Output"}),x&&e.jsxs("div",{className:"error-message",children:[e.jsx("span",{className:"error-icon",children:e.jsx(L.NiceIcon,{name:"warning",size:16})}),x]}),N&&e.jsxs("div",{className:"result-container",children:[e.jsxs("div",{className:"result-meta",children:[e.jsxs("span",{children:["Request ID: ",N.requestId]}),e.jsxs("span",{children:["Latency: ",P(N.latency)]}),e.jsxs("span",{children:["Model: ",N.modelVersion]})]}),e.jsx("div",{className:"predictions-list",children:N.predictions.map((M,U)=>J(M,U))})]}),!x&&!N&&e.jsxs("div",{className:"empty-output",children:[e.jsx("span",{className:"icon",children:e.jsx(L.NiceIcon,{name:"upload",size:32})}),e.jsx("p",{children:"Run inference to see results"})]})]})]}),l==="batch"&&e.jsxs("div",{className:"batch-panel",children:[e.jsxs("div",{className:"batch-upload",children:[e.jsx("h3",{children:"Batch Inference"}),e.jsx("p",{className:"hint",children:"Upload a file with multiple inputs for batch processing"}),e.jsxs("label",{className:"upload-zone",children:[e.jsx("input",{type:"file",accept:".json,.csv,.txt",onChange:async M=>{var q;const U=(q=M.target.files)==null?void 0:q[0];if(U){const W=await U.text();try{const G=JSON.parse(W);if(Array.isArray(G)){const Y=G.map(ee=>({type:"json",data:ee}));b(Y)}}catch{u("Invalid batch file format")}}},hidden:!0}),e.jsx("span",{className:"upload-icon",children:e.jsx(L.NiceIcon,{name:"folder",size:32})}),e.jsx("span",{children:"Upload JSON array file"})]})]}),D!==null&&e.jsxs("div",{className:"batch-progress",children:[e.jsx("div",{className:"progress-bar",children:e.jsx("div",{className:"progress-fill",style:{width:`${D}%`}})}),e.jsxs("span",{children:[Math.round(D),"%"]})]}),h.length>0&&e.jsxs("div",{className:"batch-results",children:[e.jsxs("h3",{children:["Results (",h.length,")"]}),e.jsx("div",{className:"results-list",children:h.map((M,U)=>e.jsxs("div",{className:"batch-result-item",children:[e.jsxs("span",{className:"result-index",children:["#",U+1]}),M.predictions.map((q,W)=>e.jsxs("span",{className:"result-prediction",children:[q.label,": ",(q.confidence||q.score||0).toFixed(1),"%"]},W))]},U))})]})]}),l==="metrics"&&i&&e.jsxs("div",{className:"metrics-panel",children:[e.jsxs("div",{className:"metrics-grid",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:s.metrics.requestsTotal}),e.jsx("span",{className:"metric-label",children:"Total Requests"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:s.metrics.requestsPerSecond.toFixed(1)}),e.jsx("span",{className:"metric-label",children:"Requests/sec"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:P(s.metrics.latencyP50)}),e.jsx("span",{className:"metric-label",children:"P50 Latency"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:P(s.metrics.latencyP95)}),e.jsx("span",{className:"metric-label",children:"P95 Latency"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:P(s.metrics.latencyP99)}),e.jsx("span",{className:"metric-label",children:"P99 Latency"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("span",{className:"metric-value",children:[s.metrics.successRate.toFixed(1),"%"]}),e.jsx("span",{className:"metric-label",children:"Success Rate"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("span",{className:"metric-value",children:[(s.metrics.errorRate*100).toFixed(2),"%"]}),e.jsx("span",{className:"metric-label",children:"Error Rate"})]})]}),e.jsxs("div",{className:"latency-histogram",children:[e.jsx("h3",{children:"Latency Distribution"}),e.jsx("div",{className:"histogram-bars",children:[10,25,50,75,90,95,99].map(M=>e.jsxs("div",{className:"histogram-bar",children:[e.jsx("div",{className:"bar-fill",style:{height:`${Math.min(100,s.metrics.latencyP50*M/100)}px`}}),e.jsxs("span",{className:"percentile-label",children:["P",M]})]},M))})]})]}),l==="logs"&&r&&e.jsxs("div",{className:"logs-panel",children:[e.jsxs("div",{className:"logs-header",children:[e.jsx("h3",{children:"Request Logs"}),e.jsx("button",{className:"clear-logs-button",onClick:()=>c(M=>({...M,logs:[]})),children:"Clear Logs"})]}),e.jsx("div",{className:"logs-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Time"}),e.jsx("th",{children:"Request ID"}),e.jsx("th",{children:"Duration"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Input Size"}),e.jsx("th",{children:"Output Size"})]})}),e.jsx("tbody",{children:s.logs.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"empty-logs",children:"No logs yet"})}):s.logs.map((M,U)=>e.jsxs("tr",{className:`log-row log-row--${M.status}`,children:[e.jsx("td",{children:H(M.timestamp)}),e.jsx("td",{className:"request-id",children:M.requestId.slice(0,8)}),e.jsx("td",{children:P(M.duration)}),e.jsx("td",{children:e.jsx("span",{className:`status-badge status-badge--${M.status}`,children:M.status})}),e.jsxs("td",{children:[M.inputSize," B"]}),e.jsxs("td",{children:[M.outputSize," B"]})]},U))})]})})]})]})]})};class te{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 c=setTimeout(()=>{var p;return(p=this.abortController)==null?void 0:p.abort()},this.config.timeout),l=await fetch(a,{...i,signal:this.abortController.signal});if(clearTimeout(c),l.ok)return l;if(l.status>=400&&l.status<500){const p=await l.text();throw new Error(`API Error ${l.status}: ${p}`)}n=new Error(`HTTP ${l.status}`)}catch(c){n=c,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 p;const s=(p=a.body)==null?void 0:p.getReader();if(!s){n==null||n(new Error("No response body"));return}const c=new TextDecoder;let l="";try{for(;;){const{done:f,value:g}=await s.read();if(f)break;l+=c.decode(g,{stream:!0});const y=l.split(`
16
- `);l=y.pop()||"";for(const w of y)if(w.startsWith("data: ")){const S=w.slice(6).trim();if(S==="[DONE]"){r==null||r();return}try{const z=JSON.parse(S);i(this.normalizeStreamChunk(z))}catch{}}}r==null||r()}catch(f){n==null||n(f)}finally{s.releaseLock()}}}class _e extends te{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(l=>a.includes(l)),c=s?n[s]:n["gpt-4o-mini"];return i/1e6*c.input+r/1e6*c.output}}class na extends te{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 p;const s=(p=a.body)==null?void 0:p.getReader();if(!s){n==null||n(new Error("No response body"));return}const c=new TextDecoder;let l="";try{for(;;){const{done:f,value:g}=await s.read();if(f)break;l+=c.decode(g,{stream:!0});const y=l.split(`
17
- `);l=y.pop()||"";for(const w of y)if(w.startsWith("data: "))try{const S=JSON.parse(w.slice(6));if(S.type==="content_block_delta")i(this.normalizeStreamChunk(S));else if(S.type==="message_stop"){r==null||r();return}}catch{}}r==null||r()}catch(f){n==null||n(f)}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(l=>a.includes(l)),c=s?n[s]:n["claude-3-5-sonnet"];return i/1e6*c.input+r/1e6*c.output}}class sa extends te{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 c=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(c,i,r,n)}catch(c){n==null||n(c)}}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 ca extends te{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 p;const s=(p=a.body)==null?void 0:p.getReader();if(!s){n==null||n(new Error("No response body"));return}const c=new TextDecoder;let l="";try{for(;;){const{done:f,value:g}=await s.read();if(f)break;l+=c.decode(g,{stream:!0});const y=l.split(`
18
- `);l=y.pop()||"";for(const w of y)if(w.trim())try{const S=JSON.parse(w);if(i(this.normalizeStreamChunk(S)),S.done){r==null||r();return}}catch{}}r==null||r()}catch(f){n==null||n(f)}finally{s.releaseLock()}}}class oa extends te{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 _e(t);case"anthropic":return new na(t);case"azure-openai":return new sa(t);case"ollama":return new ca(t);case"groq":return new oa(t);case"custom":return new _e(t);default:throw new Error(`Unsupported provider type: ${t.type}`)}}function K(t){const a=new URL(t.endpoint),i=a.host.toLowerCase(),r=a.pathname.replace(/\/+$/,""),n=p=>`${a.protocol}//${a.host}${r.endsWith(p)?r.slice(0,-p.length):r}`,s={apiKey:t.apiKey,model:t.model,headers:t.headers},c=/^(.*)\/openai\/deployments\/([^/]+)\/chat\/completions$/.exec(r);if(i.endsWith("azure.com")&&c)return ae({type:"azure-openai",...s,baseUrl:`${a.protocol}//${a.host}${c[1]}`,deployment:c[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 l=i.includes("openai.com")?"openai":i.includes("groq.com")?"groq":"custom";return ae({type:l,...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,(c,l,p)=>{const f=i[l];return f==null||f===""||f===!1||Array.isArray(f)&&f.length===0?"":p}).replace(/\{\{(\w+)\}\}/g,(c,l)=>{const p=i[l];return p===void 0?`{{${l}}}`:typeof p=="object"?JSON.stringify(p,null,2):String(p)});return{system:r(t.system),user:r(t.user),metadata:{templateId:t.id,variables:i,timestamp:Date.now()}}}const se={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:"json-input"})]}),e.jsxs("div",{className:"parameters-section",children:[e.jsx("h4",{children:"Parameters"}),e.jsxs("div",{className:"parameters-grid",children:[e.jsxs("label",{children:["Temperature",e.jsx("input",{type:"number",value:_.temperature,onChange:u=>l({..._,temperature:parseFloat(u.target.value)}),min:"0",max:"2",step:"0.1"})]}),e.jsxs("label",{children:["Top K",e.jsx("input",{type:"number",value:_.topK,onChange:u=>l({..._,topK:parseInt(u.target.value)}),min:"1",max:"100"})]}),e.jsxs("label",{children:["Top P",e.jsx("input",{type:"number",value:_.topP,onChange:u=>l({..._,topP:parseFloat(u.target.value)}),min:"0",max:"1",step:"0.05"})]}),e.jsxs("label",{children:["Threshold",e.jsx("input",{type:"number",value:_.threshold,onChange:u=>l({..._,threshold:parseFloat(u.target.value)}),min:"0",max:"1",step:"0.05"})]})]})]}),e.jsx("button",{className:"run-button",onClick:D,disabled:f||!b&&!C&&k==="{}",children:f?"Running...":"Run Inference"})]}),e.jsxs("div",{className:"output-section",children:[e.jsx("h3",{children:"Output"}),g&&e.jsxs("div",{className:"error-message",children:[e.jsx("span",{className:"error-icon",children:e.jsx(A.NiceIcon,{name:"warning",size:16})}),g]}),y&&e.jsxs("div",{className:"result-container",children:[e.jsxs("div",{className:"result-meta",children:[e.jsxs("span",{children:["Request ID: ",y.requestId]}),e.jsxs("span",{children:["Latency: ",U(y.latency)]}),e.jsxs("span",{children:["Model: ",y.modelVersion]})]}),e.jsx("div",{className:"predictions-list",children:y.predictions.map((u,R)=>Y(u,R))})]}),!g&&!y&&e.jsxs("div",{className:"empty-output",children:[e.jsx("span",{className:"icon",children:e.jsx(A.NiceIcon,{name:"upload",size:32})}),e.jsx("p",{children:"Run inference to see results"})]})]})]}),c==="batch"&&e.jsxs("div",{className:"batch-panel",children:[e.jsxs("div",{className:"batch-upload",children:[e.jsx("h3",{children:"Batch Inference"}),e.jsx("p",{className:"hint",children:"Upload a file with multiple inputs for batch processing"}),e.jsxs("label",{className:"upload-zone",children:[e.jsx("input",{type:"file",accept:".json,.csv,.txt",onChange:async u=>{var B;const R=(B=u.target.files)==null?void 0:B[0];if(R){const H=await R.text();try{const q=JSON.parse(H);if(Array.isArray(q)){const G=q.map(Q=>({type:"json",data:Q}));F(G)}}catch{x("Invalid batch file format")}}},hidden:!0}),e.jsx("span",{className:"upload-icon",children:e.jsx(A.NiceIcon,{name:"folder",size:32})}),e.jsx("span",{children:"Upload JSON array file"})]})]}),I!==null&&e.jsxs("div",{className:"batch-progress",children:[e.jsx("div",{className:"progress-bar",children:e.jsx("div",{className:"progress-fill",style:{width:`${I}%`}})}),e.jsxs("span",{children:[Math.round(I),"%"]})]}),v.length>0&&e.jsxs("div",{className:"batch-results",children:[e.jsxs("h3",{children:["Results (",v.length,")"]}),e.jsx("div",{className:"results-list",children:v.map((u,R)=>e.jsxs("div",{className:"batch-result-item",children:[e.jsxs("span",{className:"result-index",children:["#",R+1]}),u.predictions.map((B,H)=>e.jsxs("span",{className:"result-prediction",children:[B.label,": ",(B.confidence||B.score||0).toFixed(1),"%"]},H))]},R))})]})]}),c==="metrics"&&t&&e.jsxs("div",{className:"metrics-panel",children:[e.jsxs("div",{className:"metrics-grid",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:s.metrics.requestsTotal}),e.jsx("span",{className:"metric-label",children:"Total Requests"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:s.metrics.requestsPerSecond.toFixed(1)}),e.jsx("span",{className:"metric-label",children:"Requests/sec"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:U(s.metrics.latencyP50)}),e.jsx("span",{className:"metric-label",children:"P50 Latency"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:U(s.metrics.latencyP95)}),e.jsx("span",{className:"metric-label",children:"P95 Latency"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:U(s.metrics.latencyP99)}),e.jsx("span",{className:"metric-label",children:"P99 Latency"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("span",{className:"metric-value",children:[s.metrics.successRate.toFixed(1),"%"]}),e.jsx("span",{className:"metric-label",children:"Success Rate"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("span",{className:"metric-value",children:[(s.metrics.errorRate*100).toFixed(2),"%"]}),e.jsx("span",{className:"metric-label",children:"Error Rate"})]})]}),e.jsxs("div",{className:"latency-histogram",children:[e.jsx("h3",{children:"Latency Distribution"}),e.jsx("div",{className:"histogram-bars",children:[10,25,50,75,90,95,99].map(u=>e.jsxs("div",{className:"histogram-bar",children:[e.jsx("div",{className:"bar-fill",style:{height:`${Math.min(100,s.metrics.latencyP50*u/100)}px`}}),e.jsxs("span",{className:"percentile-label",children:["P",u]})]},u))})]})]}),c==="logs"&&r&&e.jsxs("div",{className:"logs-panel",children:[e.jsxs("div",{className:"logs-header",children:[e.jsx("h3",{children:"Request Logs"}),e.jsx("button",{className:"clear-logs-button",onClick:()=>o(u=>({...u,logs:[]})),children:"Clear Logs"})]}),e.jsx("div",{className:"logs-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Time"}),e.jsx("th",{children:"Request ID"}),e.jsx("th",{children:"Duration"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Input Size"}),e.jsx("th",{children:"Output Size"})]})}),e.jsx("tbody",{children:s.logs.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"empty-logs",children:"No logs yet"})}):s.logs.map((u,R)=>e.jsxs("tr",{className:`log-row log-row--${u.status}`,children:[e.jsx("td",{children:W(u.timestamp)}),e.jsx("td",{className:"request-id",children:u.requestId.slice(0,8)}),e.jsx("td",{children:U(u.duration)}),e.jsx("td",{children:e.jsx("span",{className:`status-badge status-badge--${u.status}`,children:u.status})}),e.jsxs("td",{children:[u.inputSize," B"]}),e.jsxs("td",{children:[u.outputSize," B"]})]},R))})]})})]})]})]})};class te{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,t,r=this.config.maxRetries){let n=null;for(let s=0;s<=r;s++)try{this.abortController=new AbortController;const o=setTimeout(()=>{var h;return(h=this.abortController)==null?void 0:h.abort()},this.config.timeout),c=await fetch(a,{...t,signal:this.abortController.signal});if(clearTimeout(o),c.ok)return c;if(c.status>=400&&c.status<500){const h=await c.text();throw new Error(`API Error ${c.status}: ${h}`)}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(t=>setTimeout(t,a))}async parseSSEStream(a,t,r,n){var h;const s=(h=a.body)==null?void 0:h.getReader();if(!s){n==null||n(new Error("No response body"));return}const o=new TextDecoder;let c="";try{for(;;){const{done:p,value:m}=await s.read();if(p)break;c+=o.decode(m,{stream:!0});const b=c.split(`
16
+ `);c=b.pop()||"";for(const w of b)if(w.startsWith("data: ")){const k=w.slice(6).trim();if(k==="[DONE]"){r==null||r();return}try{const M=JSON.parse(k);t(this.normalizeStreamChunk(M))}catch{}}}r==null||r()}catch(p){n==null||n(p)}finally{s.releaseLock()}}}class je extends te{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,t,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,t,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,t){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 t=a;return{id:t.id,choices:t.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}estimateCost(a,t,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 t/1e6*o.input+r/1e6*o.output}}class oa extends te{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,t,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,t,r,n)}catch(s){n==null||n(s)}}buildRequestBody(a){const t=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:t==null?void 0:t.content,messages:r.map(n=>({role:n.role==="assistant"?"assistant":"user",content:n.content})),temperature:a.temperature??.7}}normalizeResponse(a){const t=a,r=t.content.find(n=>n.type==="text");return{id:t.id,model:t.model,choices:[{index:0,message:{role:"assistant",content:(r==null?void 0:r.text)||""},finishReason:t.stop_reason==="end_turn"?"stop":"length"}],usage:{promptTokens:t.usage.input_tokens,completionTokens:t.usage.output_tokens,totalTokens:t.usage.input_tokens+t.usage.output_tokens},estimatedCost:this.estimateCost(t.model,t.usage.input_tokens,t.usage.output_tokens)}}normalizeStreamChunk(a){var r;const t=a;return{id:"",choices:[{index:t.index||0,delta:{content:((r=t.delta)==null?void 0:r.text)||""},finishReason:t.type==="message_stop"?"stop":null}]}}async parseAnthropicStream(a,t,r,n){var h;const s=(h=a.body)==null?void 0:h.getReader();if(!s){n==null||n(new Error("No response body"));return}const o=new TextDecoder;let c="";try{for(;;){const{done:p,value:m}=await s.read();if(p)break;c+=o.decode(m,{stream:!0});const b=c.split(`
17
+ `);c=b.pop()||"";for(const w of b)if(w.startsWith("data: "))try{const k=JSON.parse(w.slice(6));if(k.type==="content_block_delta")t(this.normalizeStreamChunk(k));else if(k.type==="message_stop"){r==null||r();return}}catch{}}r==null||r()}catch(p){n==null||n(p)}finally{s.releaseLock()}}estimateCost(a,t,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 t/1e6*o.input+r/1e6*o.output}}class la extends te{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 t=`${this.config.baseUrl}/openai/deployments/${this.config.deployment}/chat/completions?api-version=${this.config.apiVersion||"2024-02-01"}`,n=await(await this.fetchWithRetry(t,{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,t,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,t,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 t=a;return{id:t.id,model:t.model,choices:t.choices.map(r=>({index:r.index,message:r.message,finishReason:r.finish_reason})),usage:{promptTokens:t.usage.prompt_tokens,completionTokens:t.usage.completion_tokens,totalTokens:t.usage.total_tokens}}}normalizeStreamChunk(a){const t=a;return{id:t.id,choices:t.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}}class da extends te{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,t,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,t,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 t=a;return{id:`ollama-${Date.now()}`,model:t.model,choices:[{index:0,message:t.message,finishReason:t.done?"stop":null}],usage:{promptTokens:t.prompt_eval_count||0,completionTokens:t.eval_count||0,totalTokens:(t.prompt_eval_count||0)+(t.eval_count||0)},estimatedCost:0}}normalizeStreamChunk(a){var r;const t=a;return{id:`ollama-${Date.now()}`,choices:[{index:0,delta:{content:((r=t.message)==null?void 0:r.content)||""},finishReason:t.done?"stop":null}]}}async parseOllamaStream(a,t,r,n){var h;const s=(h=a.body)==null?void 0:h.getReader();if(!s){n==null||n(new Error("No response body"));return}const o=new TextDecoder;let c="";try{for(;;){const{done:p,value:m}=await s.read();if(p)break;c+=o.decode(m,{stream:!0});const b=c.split(`
18
+ `);c=b.pop()||"";for(const w of b)if(w.trim())try{const k=JSON.parse(w);if(t(this.normalizeStreamChunk(k)),k.done){r==null||r();return}}catch{}}r==null||r()}catch(p){n==null||n(p)}finally{s.releaseLock()}}}class ua extends te{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,t,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,t,r,n)}catch(s){n==null||n(s)}}normalizeResponse(a){const t=a;return{id:t.id,model:t.model,choices:t.choices.map(r=>({index:r.index,message:r.message,finishReason:r.finish_reason})),usage:{promptTokens:t.usage.prompt_tokens,completionTokens:t.usage.completion_tokens,totalTokens:t.usage.total_tokens},estimatedCost:0}}normalizeStreamChunk(a){const t=a;return{id:t.id,choices:t.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}}function ee(i){switch(i.type){case"openai":return new je(i);case"anthropic":return new oa(i);case"azure-openai":return new la(i);case"ollama":return new da(i);case"groq":return new ua(i);case"custom":return new je(i);default:throw new Error(`Unsupported provider type: ${i.type}`)}}function K(i){const a=new URL(i.endpoint),t=a.host.toLowerCase(),r=a.pathname.replace(/\/+$/,""),n=h=>`${a.protocol}//${a.host}${r.endsWith(h)?r.slice(0,-h.length):r}`,s={apiKey:i.apiKey,model:i.model,headers:i.headers},o=/^(.*)\/openai\/deployments\/([^/]+)\/chat\/completions$/.exec(r);if(t.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(t.includes("anthropic.com"))return ee({type:"anthropic",...s,baseUrl:n("/messages")});if(t.endsWith(":11434")||t.includes("ollama"))return ee({type:"ollama",...s,baseUrl:n("/api/chat")});const c=t.includes("openai.com")?"openai":t.includes("groq.com")?"groq":"custom";return ee({type:c,...s,baseUrl:n("/chat/completions")})}function ae(i,a){for(const n of i.variables)if(n.required&&!(n.name in a)&&!n.default)throw new Error(`Missing required variable: ${n.name}`);const t={};for(const n of i.variables)t[n.name]=a[n.name]??n.default;const r=n=>n.replace(/\{\{#if (\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g,(o,c,h)=>{const p=t[c];return p==null||p===""||p===!1||Array.isArray(p)&&p.length===0?"":h}).replace(/\{\{(\w+)\}\}/g,(o,c)=>{const h=t[c];return h===void 0?`{{${c}}}`:typeof h=="object"?JSON.stringify(h,null,2):String(h)});return{system:r(i.system),user:r(i.user),metadata:{templateId:i.id,variables:t,timestamp:Date.now()}}}const ce={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:
@@ -48,7 +48,7 @@ Generate the filter configuration:`,variables:[{name:"columns",description:"JSON
48
48
  { "column": "city", "operator": "equals", "value": "New York" }
49
49
  ],
50
50
  "logic": "and"
51
- }`}],suggestedTemperature:.2,maxTokens:512},ce={id:"data-grid-sort",name:"DataGrid Natural Language Sort",description:"Convert natural language to sort configuration",category:"data-query",system:`You are a sort configuration generator for a data grid.
51
+ }`}],suggestedTemperature:.2,maxTokens:512},oe={id:"data-grid-sort",name:"DataGrid Natural Language Sort",description:"Convert natural language to sort configuration",category:"data-query",system:`You are a sort configuration generator for a data grid.
52
52
  Given columns and a natural language request, generate sort configuration.
53
53
 
54
54
  Output format:
@@ -66,7 +66,7 @@ Keywords mapping:
66
66
 
67
67
  Request: "{{query}}"
68
68
 
69
- Generate sort configuration:`,variables:[{name:"columns",description:"Column definitions",required:!0,type:"json"},{name:"query",description:"Natural language sort request",required:!0,type:"string"}],suggestedTemperature:.1,maxTokens:256},oe={id:"form-builder",name:"Form Generation from Description",description:"Generate form configuration from natural language description",category:"form-generation",system:`You are a form builder AI. Generate form configurations from descriptions.
69
+ Generate sort configuration:`,variables:[{name:"columns",description:"Column definitions",required:!0,type:"json"},{name:"query",description:"Natural language sort request",required:!0,type:"string"}],suggestedTemperature:.1,maxTokens:256},le={id:"form-builder",name:"Form Generation from Description",description:"Generate form configuration from natural language description",category:"form-generation",system:`You are a form builder AI. Generate form configurations from descriptions.
70
70
 
71
71
  Available field types:
72
72
  - text, email, phone, url, password
@@ -116,7 +116,7 @@ Generate the form configuration:`,variables:[{name:"description",description:"Na
116
116
  { "id": "message", "type": "textarea", "label": "Message", "required": true }
117
117
  ],
118
118
  "layout": { "columns": 1 }
119
- }`}],suggestedTemperature:.5,maxTokens:2048},le={id:"chart-config",name:"Chart Configuration Generator",description:"Generate chart configuration from data description",category:"chart-config",system:`You are a data visualization expert. Generate chart configurations from descriptions.
119
+ }`}],suggestedTemperature:.5,maxTokens:2048},de={id:"chart-config",name:"Chart Configuration Generator",description:"Generate chart configuration from data description",category:"chart-config",system:`You are a data visualization expert. Generate chart configurations from descriptions.
120
120
 
121
121
  Available chart types:
122
122
  - line, area, bar, column
@@ -156,14 +156,28 @@ Available data fields: {{data}}
156
156
  Context: {{context}}
157
157
  {{/if}}
158
158
 
159
- Generate the chart configuration:`,variables:[{name:"request",description:"Natural language chart request",required:!0,type:"string"},{name:"data",description:"Available data fields",required:!1,type:"json"},{name:"context",description:"Additional context",required:!1,type:"string"}],suggestedTemperature:.4,maxTokens:1024},de={id:"code-completion",name:"Code Completion",description:"Complete code based on context",category:"code-completion",system:`You are an expert programmer. Complete the code based on context.
159
+ Generate the chart configuration:`,variables:[{name:"request",description:"Natural language chart request",required:!0,type:"string"},{name:"data",description:"Available data fields",required:!1,type:"json"},{name:"context",description:"Additional context",required:!1,type:"string"}],suggestedTemperature:.4,maxTokens:1024},ue={id:"code-completion",name:"Code Completion",description:"Complete code based on context",category:"code-completion",system:`You are an expert programmer. Complete the code based on context.
160
160
 
161
161
  Rules:
162
162
  - Match the existing code style
163
163
  - Use the same language features and patterns
164
164
  - Keep completions concise and focused
165
165
  - Do not repeat existing code
166
- - Only output the completion, not the full code`,user:"Language: {{language}}\n\nContext (code before cursor):\n```{{language}}\n{{prefix}}\n```\n\nContext (code after cursor):\n```{{language}}\n{{suffix}}\n```\n\nComplete the code at the cursor position:",variables:[{name:"language",description:"Programming language",required:!0,type:"string"},{name:"prefix",description:"Code before cursor",required:!0,type:"string"},{name:"suffix",description:"Code after cursor",required:!1,type:"string",default:""}],suggestedModel:"gpt-4o",suggestedTemperature:.2,maxTokens:512},ue={id:"workflow-generator",name:"Workflow/BPMN Generator",description:"Generate workflow definition from process description",category:"workflow",system:`You are a business process expert. Generate workflow definitions from descriptions.
166
+ - Only output the completion, not the full code`,user:`Language: {{language}}
167
+ {{#if context}}
168
+ Project context: {{context}}
169
+ {{/if}}
170
+ Context (code before cursor):
171
+ \`\`\`{{language}}
172
+ {{prefix}}
173
+ \`\`\`
174
+
175
+ Context (code after cursor):
176
+ \`\`\`{{language}}
177
+ {{suffix}}
178
+ \`\`\`
179
+
180
+ Complete the code at the cursor position:`,variables:[{name:"language",description:"Programming language",required:!0,type:"string"},{name:"prefix",description:"Code before cursor",required:!0,type:"string"},{name:"suffix",description:"Code after cursor",required:!1,type:"string",default:""},{name:"context",description:"What the code is part of (framework, conventions)",required:!1,type:"string",default:""}],suggestedModel:"gpt-4o",suggestedTemperature:.2,maxTokens:512},pe={id:"workflow-generator",name:"Workflow/BPMN Generator",description:"Generate workflow definition from process description",category:"workflow",system:`You are a business process expert. Generate workflow definitions from descriptions.
167
181
 
168
182
  Output BPMN-compatible JSON:
169
183
  {
@@ -205,7 +219,7 @@ Available roles: {{roles}}
205
219
  Systems involved: {{systems}}
206
220
  {{/if}}
207
221
 
208
- Generate the workflow definition:`,variables:[{name:"description",description:"Process description",required:!0,type:"string"},{name:"roles",description:"Available roles/departments",required:!1,type:"array"},{name:"systems",description:"Systems involved",required:!1,type:"array"}],suggestedTemperature:.3,maxTokens:2048},pe={id:"report-layout",name:"Report Layout Generator",description:"Generate report layout from description",category:"report",system:`You are a report designer. Generate report layouts from descriptions.
222
+ Generate the workflow definition:`,variables:[{name:"description",description:"Process description",required:!0,type:"string"},{name:"roles",description:"Available roles/departments",required:!1,type:"array"},{name:"systems",description:"Systems involved",required:!1,type:"array"}],suggestedTemperature:.3,maxTokens:2048},me={id:"report-layout",name:"Report Layout Generator",description:"Generate report layout from description",category:"report",system:`You are a report designer. Generate report layouts from descriptions.
209
223
 
210
224
  Available report elements:
211
225
  - header, footer
@@ -243,7 +257,7 @@ Output JSON:
243
257
  Available data sources: {{dataSources}}
244
258
  {{/if}}
245
259
 
246
- Generate the report layout:`,variables:[{name:"description",description:"Report description",required:!0,type:"string"},{name:"dataSources",description:"Available data sources",required:!1,type:"json"}],suggestedTemperature:.4,maxTokens:2048},we={id:"theme-generator",name:"Theme Generator from Brand Colors",description:"Generate complete theme from brand colors",category:"theme",system:`You are a UI/UX designer specializing in design systems.
260
+ Generate the report layout:`,variables:[{name:"description",description:"Report description",required:!0,type:"string"},{name:"dataSources",description:"Available data sources",required:!1,type:"json"}],suggestedTemperature:.4,maxTokens:2048},ke={id:"theme-generator",name:"Theme Generator from Brand Colors",description:"Generate complete theme from brand colors",category:"theme",system:`You are a UI/UX designer specializing in design systems.
247
261
  Generate a complete theme from brand colors following accessibility guidelines.
248
262
 
249
263
  Rules:
@@ -283,7 +297,7 @@ Output JSON:
283
297
  {{#if industry}}Industry: {{industry}}{{/if}}
284
298
  {{#if style}}Style preference: {{style}}{{/if}}
285
299
 
286
- Generate the complete theme:`,variables:[{name:"primaryColor",description:"Primary brand color (hex)",required:!0,type:"string"},{name:"secondaryColor",description:"Secondary brand color (hex)",required:!1,type:"string"},{name:"accentColor",description:"Accent color (hex)",required:!1,type:"string"},{name:"industry",description:"Industry (healthcare, finance, etc.)",required:!1,type:"string"},{name:"style",description:"Style preference (modern, classic, playful)",required:!1,type:"string"}],suggestedTemperature:.5,maxTokens:2048},je={id:"accessibility-checker",name:"Accessibility Checker",description:"Check and fix accessibility issues in HTML/JSX",category:"accessibility",system:`You are a web accessibility expert (WCAG 2.1 AA/AAA certified).
300
+ Generate the complete theme:`,variables:[{name:"primaryColor",description:"Primary brand color (hex)",required:!0,type:"string"},{name:"secondaryColor",description:"Secondary brand color (hex)",required:!1,type:"string"},{name:"accentColor",description:"Accent color (hex)",required:!1,type:"string"},{name:"industry",description:"Industry (healthcare, finance, etc.)",required:!1,type:"string"},{name:"style",description:"Style preference (modern, classic, playful)",required:!1,type:"string"}],suggestedTemperature:.5,maxTokens:2048},Ne={id:"accessibility-checker",name:"Accessibility Checker",description:"Check and fix accessibility issues in HTML/JSX",category:"accessibility",system:`You are a web accessibility expert (WCAG 2.1 AA/AAA certified).
287
301
  Analyze code for accessibility issues and provide fixes.
288
302
 
289
303
  Check for:
@@ -310,7 +324,7 @@ Output JSON:
310
324
  ],
311
325
  "score": 0-100,
312
326
  "summary": "Brief summary of findings"
313
- }`,user:"Analyze this code for accessibility issues:\n\n```{{language}}\n{{code}}\n```\n\nReturn accessibility analysis:",variables:[{name:"code",description:"Code to analyze",required:!0,type:"string"},{name:"language",description:"Code language (html, jsx, tsx)",required:!1,type:"string",default:"jsx"}],suggestedTemperature:.2,maxTokens:2048},ke={id:"translation",name:"UI Translation",description:"Translate UI text maintaining context and formatting",category:"translation",system:`You are a professional UI translator.
327
+ }`,user:"Analyze this code for accessibility issues:\n\n```{{language}}\n{{code}}\n```\n\nReturn accessibility analysis:",variables:[{name:"code",description:"Code to analyze",required:!0,type:"string"},{name:"language",description:"Code language (html, jsx, tsx)",required:!1,type:"string",default:"jsx"}],suggestedTemperature:.2,maxTokens:2048},Se={id:"translation",name:"UI Translation",description:"Translate UI text maintaining context and formatting",category:"translation",system:`You are a professional UI translator.
314
328
  Translate text while:
315
329
  - Preserving placeholders like {name}, {{count}}, %s
316
330
  - Maintaining ICU message format syntax
@@ -328,7 +342,7 @@ Output JSON:
328
342
 
329
343
  {{texts}}
330
344
 
331
- Provide translations:`,variables:[{name:"sourceLanguage",description:"Source language",required:!0,type:"string"},{name:"targetLanguage",description:"Target language",required:!0,type:"string"},{name:"texts",description:"JSON object with keys and texts to translate",required:!0,type:"json"}],suggestedTemperature:.3,maxTokens:2048},Ne={id:"summarize-data",name:"Data Summarization",description:"Summarize tabular data into insights",category:"summarization",system:`You are a data analyst. Summarize data into actionable insights.
345
+ Provide translations:`,variables:[{name:"sourceLanguage",description:"Source language",required:!0,type:"string"},{name:"targetLanguage",description:"Target language",required:!0,type:"string"},{name:"texts",description:"JSON object with keys and texts to translate",required:!0,type:"json"}],suggestedTemperature:.3,maxTokens:2048},Ce={id:"summarize-data",name:"Data Summarization",description:"Summarize tabular data into insights",category:"summarization",system:`You are a data analyst. Summarize data into actionable insights.
332
346
 
333
347
  Provide:
334
348
  - Key statistics (min, max, mean, median)
@@ -352,7 +366,7 @@ Format output as structured JSON:
352
366
 
353
367
  {{#if context}}Context: {{context}}{{/if}}
354
368
 
355
- 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},ge={[se.id]:se,[ce.id]:ce,[oe.id]:oe,[le.id]:le,[de.id]:de,[ue.id]:ue,[pe.id]:pe,[we.id]:we,[je.id]:je,[ke.id]:ke,[Ne.id]:Ne};function li(t){return ge[t]}function di(t){return Object.values(ge).filter(a=>a.category===t)}function ui(){return Object.keys(ge)}class Me{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 la{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],c=Date.now()-720*60*60*1e3,l=s.filter(p=>p.timestamp>c);localStorage.setItem(r,JSON.stringify(l))}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(c=>!(i&&c.timestamp<i.getTime()||r&&c.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 da{constructor(a,i){this.pendingRecords=[],this.flushTimer=null,this.alertCallbacks=[],this.minuteCounter=new Map,this.dayCounter=new Map,this.storage=a||new Me,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),c=await this.storage.load(a,n),l=s.reduce((z,k)=>z+k.estimatedCost,0),p=c.reduce((z,k)=>z+k.estimatedCost,0),f=this.budgetConfig.dailyBudget||1/0,g=this.budgetConfig.monthlyBudget||1/0,y=f?l/f*100:0,w=g?p/g*100:0,S=[];for(const z of this.budgetConfig.alertThresholds||[])y>=z&&S.push(`Daily budget ${z}% used`),w>=z&&S.push(`Monthly budget ${z}% used`);return{dailyUsed:l,dailyRemaining:Math.max(0,f-l),dailyPercent:y,monthlyUsed:p,monthlyRemaining:Math.max(0,g-p),monthlyPercent:w,requestsToday:s.length,requestsThisMinute:this.getMinuteCount(a),isOverBudget:l>=f||p>=g,alerts:S}}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 c=0,l=0;for(const p of n){s.totalTokens+=p.totalTokens,s.totalPromptTokens+=p.promptTokens,s.totalCompletionTokens+=p.completionTokens,s.totalCost+=p.estimatedCost,c+=p.latencyMs,p.error&&s.errorCount++,p.cached&&l++,s.byModel[p.model]||(s.byModel[p.model]={requests:0,tokens:0,cost:0}),s.byModel[p.model].requests++,s.byModel[p.model].tokens+=p.totalTokens,s.byModel[p.model].cost+=p.estimatedCost;const f=p.feature||"unknown";s.byFeature[f]||(s.byFeature[f]={requests:0,tokens:0,cost:0}),s.byFeature[f].requests++,s.byFeature[f].tokens+=p.totalTokens,s.byFeature[f].cost+=p.estimatedCost;const g=new Date(p.timestamp).toISOString().split("T")[0];s.byDay[g]||(s.byDay[g]={requests:0,tokens:0,cost:0}),s.byDay[g].requests++,s.byDay[g].tokens+=p.totalTokens,s.byDay[g].cost+=p.estimatedCost}return n.length>0&&(s.averageLatency=c/n.length,s.cacheHitRate=l/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(l=>l>r));const s=new Date().toISOString().split("T")[0],c=`${a}:${s}`;this.dayCounter.set(c,(this.dayCounter.get(c)||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 pi(t,a){const i=d.useRef(null),[r,n]=d.useState(null),[s,c]=d.useState(null),[l,p]=d.useState(!0);d.useEffect(()=>{const w=typeof window<"u"?new la:new Me;i.current=new da(w,a);const S=i.current.onAlert(z=>{console.warn(`[AI Cost Alert] ${z}`)});return()=>{S()}},[]);const f=d.useCallback(async()=>{if(i.current){p(!0);try{const[w,S]=await Promise.all([i.current.getBudgetStatus(t),i.current.getUsageStats(t)]);n(w),c(S)}finally{p(!1)}}},[t]);d.useEffect(()=>{f()},[f]);const g=d.useCallback(async w=>{i.current&&(await i.current.recordUsage(t,w),await f())},[t,f]),y=d.useCallback(async()=>i.current?i.current.canMakeRequest(t):{allowed:!0},[t]);return{status:r,stats:s,loading:l,recordUsage:g,canMakeRequest:y,refresh:f}}class mi{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 ua{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 mi(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 c=await this.executeStrategy(s,a,i);if(c)return(n=(r=this.config).onFallback)==null||n.call(r,s,i),c}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 pa(t,a){const i=ae(t);return new ua(i,a)}function hi(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"}),pa(t,i)}function ma(t){const{columns:a,config:i,onFilterGenerated:r,onSortGenerated:n,onError:s}=t,c=Z(),[l,p]=d.useState(!1),[f,g]=d.useState(null),[y,w]=d.useState(null),[S,z]=d.useState([]),k=d.useRef(null),I=i||(c==null?void 0:c.config),j=d.useMemo(()=>a.map(m=>({id:m.id,label:m.label,type:m.type,...m.options?{options:m.options}:{}})),[a]),o=d.useCallback(async m=>{var x;if(!I){const u="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(u),{type:"filter",error:u}}p(!0),g(m);const v=performance.now();(x=k.current)==null||x.abort(),k.current=new AbortController;try{const u=K(I),h=m.toLowerCase(),$=h.includes("sort")||h.includes("order")||h.includes("arrange")||h.includes("by highest")||h.includes("by lowest"),D=h.includes("show")||h.includes("find")||h.includes("filter")||h.includes("where")||h.includes("with")||h.includes("only")||!$,C={type:"combined"};if(D){const A=ie(se,{columns:j,query:m}),O=await u.chat({messages:[{role:"system",content:A.system},{role:"user",content:A.user}],temperature:.2,maxTokens:512}),B=gi(O);B&&(C.filterConfig=B,C.type="filter",r==null||r(B))}if($){const A=ie(ce,{columns:j,query:m}),O=await u.chat({messages:[{role:"system",content:A.system},{role:"user",content:A.user}],temperature:.1,maxTokens:256}),B=fi(O);B&&(C.sortConfig=B,C.type=C.filterConfig?"combined":"sort",n==null||n(B))}return C.latencyMs=performance.now()-v,w(C),z(A=>[...A.slice(-9),{query:m,result:C}]),C}catch(u){const h=u instanceof Error?u.message:"AI request failed",$={type:"filter",error:h,latencyMs:performance.now()-v};return w($),s==null||s(h),$}finally{p(!1)}},[I,j,r,n,s]),N=d.useCallback(()=>{g(null),w(null)},[]),_=d.useCallback(()=>{var m;(m=k.current)==null||m.abort(),p(!1)},[]);return d.useEffect(()=>()=>{var m;(m=k.current)==null||m.abort()},[]),{processQuery:o,loading:l,lastQuery:f,lastResult:y,history:S,clearResults:N,abort:_,isConfigured:!!I}}function gi(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.filters&&Array.isArray(l.filters))return{filters:l.filters,logic:l.logic||"and",confidence:l.confidence,explanation:l.explanation}}catch{}return null}function fi(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.sort&&Array.isArray(l.sort))return{sort:l.sort,confidence:l.confidence}}catch{}return null}function xi({columns:t,config:a,onFilter:i,onSort:r,placeholder:n='Ask AI to filter or sort data... (e.g., "show orders from last week")',showHistory:s=!0,showSuggestions:c=!0,className:l,style:p}){const[f,g]=d.useState(""),[y,w]=d.useState(!1),S=d.useRef(null),{processQuery:z,loading:k,lastResult:I,history:j,isConfigured:o}=ma({columns:t,config:a,onFilterGenerated:i,onSortGenerated:r}),N=d.useMemo(()=>{if(!c||t.length===0)return[];const u=[],h=t.filter(A=>A.type==="string");h.length>0&&u.push(`Show ${h[0].label}s containing "example"`);const $=t.filter(A=>A.type==="number");$.length>0&&(u.push(`${$[0].label} greater than 100`),u.push(`Sort by highest ${$[0].label}`));const D=t.filter(A=>A.type==="date");D.length>0&&(u.push(`${D[0].label} in the last 7 days`),u.push(`Sort by newest ${D[0].label}`));const C=t.filter(A=>{var O;return A.type==="enum"&&((O=A.options)==null?void 0:O.length)});return C.length>0&&C[0].options&&u.push(`Where ${C[0].label} is ${C[0].options[0]}`),u.slice(0,5)},[t,c]),_=async()=>{!f.trim()||k||(await z(f.trim()),w(!1))},m=u=>{u.key==="Enter"?(u.preventDefault(),_()):u.key==="Escape"&&w(!1)},v=u=>{var h;g(u),w(!1),(h=S.current)==null||h.focus()},x=u=>{g(u),w(!1),z(u)};return o?e.jsxs("div",{className:`nice-datagrid-ai ${l||""}`,style:p,children:[e.jsxs("div",{className:"nice-datagrid-ai__input-wrapper",children:[e.jsx("span",{className:"nice-datagrid-ai__icon",children:e.jsx(L.NiceIcon,{name:"search",size:16})}),e.jsx("input",{ref:S,type:"text",value:f,onChange:u=>g(u.target.value),onKeyDown:m,onFocus:()=>w(!0),onBlur:()=>setTimeout(()=>w(!1),200),placeholder:n,className:"nice-datagrid-ai__input",disabled:k,"aria-label":"AI query input"}),k?e.jsx("span",{className:"nice-datagrid-ai__spinner"}):e.jsx("button",{type:"button",onClick:_,className:"nice-datagrid-ai__submit",disabled:!f.trim(),"aria-label":"Submit query",children:e.jsx(L.NiceIcon,{name:"send",size:16})})]}),y&&(N.length>0||s&&j.length>0)&&e.jsxs("div",{className:"nice-datagrid-ai__dropdown",children:[c&&N.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:"Suggestions"}),N.map((u,h)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>v(u),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(L.NiceIcon,{name:"lightbulb",size:14})}),u]},h))]}),s&&j.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:"Recent"}),j.slice(-5).reverse().map((u,h)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>x(u.query),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(L.NiceIcon,{name:"clock",size:14})}),u.query,u.result.error&&e.jsx("span",{className:"nice-datagrid-ai__item-error",children:e.jsx(L.NiceIcon,{name:"warning",size:14})})]},h))]})]}),I&&!I.error&&e.jsxs("div",{className:"nice-datagrid-ai__result",children:[I.filterConfig&&e.jsxs("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--filter",children:[I.filterConfig.filters.length," filter",I.filterConfig.filters.length!==1?"s":""," applied"]}),I.sortConfig&&e.jsxs("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--sort",children:["Sorted by ",I.sortConfig.sort.map(u=>u.column).join(", ")]}),I.latencyMs&&e.jsxs("span",{className:"nice-datagrid-ai__latency",children:[Math.round(I.latencyMs),"ms"]})]}),(I==null?void 0:I.error)&&e.jsx("div",{className:"nice-datagrid-ai__error",children:I.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},fe={[ce.id]:ce,[oe.id]:oe,[le.id]:le,[de.id]:de,[ue.id]:ue,[pe.id]:pe,[me.id]:me,[ke.id]:ke,[Ne.id]:Ne,[Se.id]:Se,[Ce.id]:Ce};function wt(i){return fe[i]}function jt(i){return Object.values(fe).filter(a=>a.category===i)}function kt(){return Object.keys(fe)}class $e{constructor(){this.records=new Map}async save(a,t){const r=this.records.get(a)||[];this.records.set(a,[...r,...t])}async load(a,t,r){const n=this.records.get(a)||[];return!t&&!r?n:n.filter(s=>!(t&&s.timestamp<t.getTime()||r&&s.timestamp>r.getTime()))}async clear(a,t){if(!t)this.records.delete(a);else{const r=this.records.get(a)||[];this.records.set(a,r.filter(n=>n.timestamp>=t.getTime()))}}}class pa{constructor(){this.prefix="nice2dev-ai-cost:"}async save(a,t){if(typeof window>"u")return;const r=`${this.prefix}${a}`,s=[...JSON.parse(localStorage.getItem(r)||"[]"),...t],o=Date.now()-720*60*60*1e3,c=s.filter(h=>h.timestamp>o);localStorage.setItem(r,JSON.stringify(c))}async load(a,t,r){if(typeof window>"u")return[];const n=`${this.prefix}${a}`,s=JSON.parse(localStorage.getItem(n)||"[]");return!t&&!r?s:s.filter(o=>!(t&&o.timestamp<t.getTime()||r&&o.timestamp>r.getTime()))}async clear(a,t){if(typeof window>"u")return;const r=`${this.prefix}${a}`;if(!t)localStorage.removeItem(r);else{const n=JSON.parse(localStorage.getItem(r)||"[]");localStorage.setItem(r,JSON.stringify(n.filter(s=>s.timestamp>=t.getTime())))}}}class ma{constructor(a,t){this.pendingRecords=[],this.flushTimer=null,this.alertCallbacks=[],this.minuteCounter=new Map,this.dayCounter=new Map,this.storage=a||new $e,this.budgetConfig={monthlyBudget:100,dailyBudget:10,maxTokensPerRequest:4096,maxRequestsPerMinute:30,maxRequestsPerDay:1e3,alertThresholds:[50,80,90,100],...t}}async recordUsage(a,t){const r={...t,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 t=await this.getBudgetStatus(a);return t.isOverBudget?{allowed:!1,reason:"Budget exceeded"}:this.budgetConfig.maxRequestsPerMinute&&t.requestsThisMinute>=this.budgetConfig.maxRequestsPerMinute?{allowed:!1,reason:"Rate limit exceeded (per minute)"}:this.budgetConfig.maxRequestsPerDay&&t.requestsToday>=this.budgetConfig.maxRequestsPerDay?{allowed:!1,reason:"Daily request limit exceeded"}:{allowed:!0}}async getBudgetStatus(a){const t=new Date,r=new Date(t.getFullYear(),t.getMonth(),t.getDate()),n=new Date(t.getFullYear(),t.getMonth(),1),s=await this.storage.load(a,r),o=await this.storage.load(a,n),c=s.reduce((M,C)=>M+C.estimatedCost,0),h=o.reduce((M,C)=>M+C.estimatedCost,0),p=this.budgetConfig.dailyBudget||1/0,m=this.budgetConfig.monthlyBudget||1/0,b=p?c/p*100:0,w=m?h/m*100:0,k=[];for(const M of this.budgetConfig.alertThresholds||[])b>=M&&k.push(`Daily budget ${M}% used`),w>=M&&k.push(`Monthly budget ${M}% used`);return{dailyUsed:c,dailyRemaining:Math.max(0,p-c),dailyPercent:b,monthlyUsed:h,monthlyRemaining:Math.max(0,m-h),monthlyPercent:w,requestsToday:s.length,requestsThisMinute:this.getMinuteCount(a),isOverBudget:c>=p||h>=m,alerts:k}}async getUsageStats(a,t,r){const n=await this.storage.load(a,t,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 h of n){s.totalTokens+=h.totalTokens,s.totalPromptTokens+=h.promptTokens,s.totalCompletionTokens+=h.completionTokens,s.totalCost+=h.estimatedCost,o+=h.latencyMs,h.error&&s.errorCount++,h.cached&&c++,s.byModel[h.model]||(s.byModel[h.model]={requests:0,tokens:0,cost:0}),s.byModel[h.model].requests++,s.byModel[h.model].tokens+=h.totalTokens,s.byModel[h.model].cost+=h.estimatedCost;const p=h.feature||"unknown";s.byFeature[p]||(s.byFeature[p]={requests:0,tokens:0,cost:0}),s.byFeature[p].requests++,s.byFeature[p].tokens+=h.totalTokens,s.byFeature[p].cost+=h.estimatedCost;const m=new Date(h.timestamp).toISOString().split("T")[0];s.byDay[m]||(s.byDay[m]={requests:0,tokens:0,cost:0}),s.byDay[m].requests++,s.byDay[m].tokens+=h.totalTokens,s.byDay[m].cost+=h.estimatedCost}return n.length>0&&(s.averageLatency=o/n.length,s.cacheHitRate=c/n.length),s}onAlert(a){return this.alertCallbacks.push(a),()=>{const t=this.alertCallbacks.indexOf(a);t>=0&&this.alertCallbacks.splice(t,1)}}setBudgetConfig(a){this.budgetConfig={...this.budgetConfig,...a}}async clearUsage(a,t){await this.storage.clear(a,t)}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}updateCounters(a){const t=Date.now(),r=t-6e4,n=this.minuteCounter.get(a)||[];n.push(t),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,t){if(t.alerts.length!==0)for(const r of t.alerts)for(const n of this.alertCallbacks)try{n(r,t)}catch{}}}function Nt(i,a){const t=d.useRef(null),[r,n]=d.useState(null),[s,o]=d.useState(null),[c,h]=d.useState(!0);d.useEffect(()=>{const w=typeof window<"u"?new pa:new $e;t.current=new ma(w,a);const k=t.current.onAlert(M=>{console.warn(`[AI Cost Alert] ${M}`)});return()=>{k()}},[]);const p=d.useCallback(async()=>{if(t.current){h(!0);try{const[w,k]=await Promise.all([t.current.getBudgetStatus(i),t.current.getUsageStats(i)]);n(w),o(k)}finally{h(!1)}}},[i]);d.useEffect(()=>{p()},[p]);const m=d.useCallback(async w=>{t.current&&(await t.current.recordUsage(i,w),await p())},[i,p]),b=d.useCallback(async()=>t.current?t.current.canMakeRequest(i):{allowed:!0},[i]);return{status:r,stats:s,loading:c,recordUsage:m,canMakeRequest:b,refresh:p}}class St{constructor(a=100,t=36e5){this.cache=new Map,this.maxSize=a,this.ttl=t}hashRequest(a){const t=JSON.stringify({messages:a.messages,model:a.model,temperature:a.temperature});let r=0;for(let n=0;n<t.length;n++){const s=t.charCodeAt(n);r=(r<<5)-r+s,r=r&r}return r.toString(36)}get(a){const t=this.hashRequest(a),r=this.cache.get(t);return r?Date.now()-r.timestamp>this.ttl?(this.cache.delete(t),null):r.response:null}set(a,t){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:t,timestamp:Date.now()})}clear(){this.cache.clear()}}class ga{constructor(a,t){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,...t},this.cache=new St(100,this.config.cacheTTL);for(const r of this.config.backupProviders||[])this.backupProviders.push(ee(r));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 t=await this.primaryProvider.chat(a);return this.cache.set(a,t),this.resetCircuitBreaker(this.primaryProvider.type),t}catch(t){return this.recordFailure(this.primaryProvider.type),this.executeWithFallback(a,t)}}async executeWithFallback(a,t){var r,n;for(const s of this.config.strategies)try{const o=await this.executeStrategy(s,a,t);if(o)return(n=(r=this.config).onFallback)==null||n.call(r,s,t),o}catch{}throw new Error(`All fallback strategies failed. Original error: ${t.message}`)}async executeStrategy(a,t,r){switch(a){case"retry":return this.retryStrategy(t);case"failover":return this.failoverStrategy(t);case"cache":return this.cacheStrategy(t);case"offline":return this.offlineStrategy(t);case"graceful-degrade":return this.gracefulDegradeStrategy(t,r);case"circuit-breaker":return this.openCircuitBreaker(this.primaryProvider.type),null;default:return null}}async retryStrategy(a){let t=this.config.retryDelay;for(let r=0;r<this.config.maxRetries;r++){await this.delay(t);try{const n=await this.primaryProvider.chat(a);return this.cache.set(a,n),n}catch{t*=this.config.backoffMultiplier}}return null}async failoverStrategy(a){for(const t of this.backupProviders)if(!this.isCircuitOpen(t.type))try{const r=await t.chat(a);return this.cache.set(a,r),r}catch{this.recordFailure(t.type)}return null}cacheStrategy(a){const t=this.cache.get(a);return t?{...t,id:`cached-${t.id}`}:null}async offlineStrategy(a){if(!this.offlineProvider)return null;try{return await this.offlineProvider.chat(a)}catch{return null}}gracefulDegradeStrategy(a,t){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)||"",t)},finishReason:"stop"}],usage:{promptTokens:0,completionTokens:0,totalTokens:0}}}generateDegradedResponse(a,t){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: ${t.message.substring(0,50)})`}isCircuitOpen(a){const t=this.circuitBreakers.get(a);return t&&t.isOpen?Date.now()-t.lastFailure>this.config.circuitBreakerResetTime?(this.resetCircuitBreaker(a),!1):!0:!1}recordFailure(a){const t=this.circuitBreakers.get(a)||{failures:0,lastFailure:0,isOpen:!1};t.failures++,t.lastFailure=Date.now(),t.failures>=this.config.circuitBreakerThreshold&&(t.isOpen=!0),this.circuitBreakers.set(a,t)}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(t=>setTimeout(t,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[t,r]of this.circuitBreakers)a[t]={...r};return a}async healthCheck(){const a={};a[this.primaryProvider.type]=await this.primaryProvider.healthCheck();for(const t of this.backupProviders)a[`backup-${t.type}`]=await t.healthCheck();return this.offlineProvider&&(a.offline=await this.offlineProvider.healthCheck()),a}}function ha(i,a){const t=ee(i);return new ga(t,a)}function Ct(i,a){const t={strategies:["retry","failover","cache","graceful-degrade"],maxRetries:3,retryDelay:1e3,backoffMultiplier:2,backupProviders:a?[a]:[],circuitBreakerThreshold:5,circuitBreakerResetTime:6e4};return typeof window>"u"&&(t.offlineConfig={type:"ollama",model:"llama3"}),ha(i,t)}function fa(i){const{columns:a,config:t,onFilterGenerated:r,onSortGenerated:n,onError:s}=i,o=Z(),{t:c,lang:h}=A.useNiceTranslation(),[p,m]=d.useState(!1),[b,w]=d.useState(null),[k,M]=d.useState(null),[C,O]=d.useState([]),_=d.useRef(null),l=t||(o==null?void 0:o.config),y=d.useMemo(()=>a.map(g=>({id:g.id,label:g.label,type:g.type,...g.options?{options:g.options}:{}})),[a]),S=d.useCallback(async g=>{var v;if(!l){const T="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(T),{type:"filter",error:T}}m(!0),w(g);const x=performance.now();(v=_.current)==null||v.abort(),_.current=new AbortController;try{const T=K(l),I=g.toLowerCase(),N=I.includes("sort")||I.includes("order")||I.includes("arrange")||I.includes("by highest")||I.includes("by lowest"),P=I.includes("show")||I.includes("find")||I.includes("filter")||I.includes("where")||I.includes("with")||I.includes("only"),$=h!=="en"&&!N&&!P,D=N||$,F=P||!N,U={type:"combined"};if(F){const W=ae(ce,{columns:y,query:g}),Y=await T.chat({messages:[{role:"system",content:W.system},{role:"user",content:W.user}],temperature:.2,maxTokens:512}),u=Tt(Y);u&&(!$||u.filters.length>0)&&(U.filterConfig=u,U.type="filter",r==null||r(u))}if(D){const W=ae(oe,{columns:y,query:g}),Y=await T.chat({messages:[{role:"system",content:W.system},{role:"user",content:W.user}],temperature:.1,maxTokens:256}),u=At(Y);u&&(!$||u.sort.length>0)&&(U.sortConfig=u,U.type=U.filterConfig?"combined":"sort",n==null||n(u))}return U.latencyMs=performance.now()-x,M(U),O(W=>[...W.slice(-9),{query:g,result:U}]),U}catch(T){const I=T instanceof Error?T.message:c("dataGridAI.requestFailed","AI request failed"),N={type:"filter",error:I,latencyMs:performance.now()-x};return M(N),s==null||s(I),N}finally{m(!1)}},[l,y,r,n,s,c,h]),f=d.useCallback(()=>{w(null),M(null)},[]),j=d.useCallback(()=>{var g;(g=_.current)==null||g.abort(),m(!1)},[]);return d.useEffect(()=>()=>{var g;(g=_.current)==null||g.abort()},[]),{processQuery:S,loading:p,lastQuery:b,lastResult:k,history:C,clearResults:f,abort:j,isConfigured:!!l}}function Tt(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.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 At(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.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 It({columns:i,config:a,onFilter:t,onSort:r,placeholder:n,showHistory:s=!0,showSuggestions:o=!0,className:c,style:h}){const{t:p}=A.useNiceTranslation(),[m,b]=d.useState(""),[w,k]=d.useState(!1),M=d.useRef(null),{processQuery:C,loading:O,lastResult:_,history:l,isConfigured:y}=fa({columns:i,config:a,onFilterGenerated:t,onSortGenerated:r}),S=d.useMemo(()=>{if(!o||i.length===0)return[];const v=[],T=(D,F,U)=>p(D,F).replace("{column}",U.label),I=i.filter(D=>D.type==="string");I.length>0&&v.push(T("dataGridAI.suggest.contains",'Show rows where {column} contains "example"',I[0]));const N=i.filter(D=>D.type==="number");N.length>0&&(v.push(T("dataGridAI.suggest.greaterThan","{column} greater than 100",N[0])),v.push(T("dataGridAI.suggest.sortHighest","Sort by highest {column}",N[0])));const P=i.filter(D=>D.type==="date");P.length>0&&(v.push(T("dataGridAI.suggest.lastDays","{column} in the last 7 days",P[0])),v.push(T("dataGridAI.suggest.sortNewest","Sort by newest {column}",P[0])));const $=i.filter(D=>{var F;return D.type==="enum"&&((F=D.options)==null?void 0:F.length)});return $.length>0&&$[0].options&&v.push(T("dataGridAI.suggest.equals","Where {column} is {value}",$[0]).replace("{value}",$[0].options[0])),v.slice(0,5)},[i,o,p]),f=async()=>{!m.trim()||O||(await C(m.trim()),k(!1))},j=v=>{v.key==="Enter"?(v.preventDefault(),f()):v.key==="Escape"&&k(!1)},g=v=>{var T;b(v),k(!1),(T=M.current)==null||T.focus()},x=v=>{b(v),k(!1),C(v)};return y?e.jsxs("div",{className:`nice-datagrid-ai ${c||""}`,style:h,children:[e.jsxs("div",{className:"nice-datagrid-ai__input-wrapper",children:[e.jsx("span",{className:"nice-datagrid-ai__icon",children:e.jsx(A.NiceIcon,{name:"search",size:16})}),e.jsx("input",{ref:M,type:"text",value:m,onChange:v=>b(v.target.value),onKeyDown:j,onFocus:()=>k(!0),onBlur:()=>setTimeout(()=>k(!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:O,"aria-label":p("dataGridAI.queryInput","AI query input")}),O?e.jsx("span",{className:"nice-datagrid-ai__spinner"}):e.jsx("button",{type:"button",onClick:f,className:"nice-datagrid-ai__submit",disabled:!m.trim(),"aria-label":p("dataGridAI.submitQuery","Submit query"),children:e.jsx(A.NiceIcon,{name:"send",size:16})})]}),w&&(S.length>0||s&&l.length>0)&&e.jsxs("div",{className:"nice-datagrid-ai__dropdown",children:[o&&S.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")}),S.map((v,T)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>g(v),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(A.NiceIcon,{name:"lightbulb",size:14})}),v]},T))]}),s&&l.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")}),l.slice(-5).reverse().map((v,T)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>x(v.query),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(A.NiceIcon,{name:"clock",size:14})}),v.query,v.result.error&&e.jsx("span",{className:"nice-datagrid-ai__item-error",children:e.jsx(A.NiceIcon,{name:"warning",size:14})})]},T))]})]}),_&&!_.error&&e.jsxs("div",{className:"nice-datagrid-ai__result",children:[_.filterConfig&&e.jsx("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--filter",children:_.filterConfig.filters.length===1?p("dataGridAI.filterApplied","1 filter applied"):p("dataGridAI.filtersApplied","{count} filters applied").replace("{count}",String(_.filterConfig.filters.length))}),_.sortConfig&&e.jsx("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--sort",children:p("dataGridAI.sortedBy","Sorted by {columns}").replace("{columns}",_.sortConfig.sort.map(v=>{var T;return((T=i.find(I=>I.id===v.column))==null?void 0:T.label)??v.column}).join(", "))}),_.latencyMs&&e.jsxs("span",{className:"nice-datagrid-ai__latency",children:[Math.round(_.latencyMs),"ms"]})]}),(_==null?void 0:_.error)&&e.jsx("div",{className:"nice-datagrid-ai__error",children:_.error}),e.jsx("style",{children:`
356
370
  .nice-datagrid-ai {
357
371
  position: relative;
358
372
  font-family: var(--nice-font-family, system-ui, sans-serif);
@@ -534,13 +548,13 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
534
548
  border-radius: var(--nice-radius-sm, 4px);
535
549
  font-size: 13px;
536
550
  }
537
- `})]}):e.jsx("div",{className:`nice-datagrid-ai nice-datagrid-ai--disabled ${l||""}`,style:p,children:e.jsx("input",{type:"text",placeholder:"AI not configured",disabled:!0,className:"nice-datagrid-ai__input"})})}function ha(t={}){const{config:a,schema:i,context:r,onFormGenerated:n,onError:s}=t,c=Z(),[l,p]=d.useState(!1),[f,g]=d.useState(null),[y,w]=d.useState(null),[S,z]=d.useState([]),k=d.useRef(null),I=a||(c==null?void 0:c.config),j=d.useCallback(async m=>{var x,u,h;if(!I){const $="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s($),{error:$}}p(!0),g(m);const v=performance.now();(x=k.current)==null||x.abort(),k.current=new AbortController;try{const $=K(I),D=ie(oe,{description:m,schema:i?JSON.stringify(i,null,2):void 0,context:r}),C=await $.chat({messages:[{role:"system",content:D.system},{role:"user",content:D.user}],temperature:.5,maxTokens:2048}),A=bi(C),O={config:A||void 0,rawResponse:(h=(u=C.choices[0])==null?void 0:u.message)==null?void 0:h.content,latencyMs:performance.now()-v,error:A?void 0:"Failed to parse form configuration"};return A&&(n==null||n(A)),w(O),z(B=>[...B.slice(-9),{description:m,result:O}]),O}catch($){const D=$ instanceof Error?$.message:"AI request failed",C={error:D,latencyMs:performance.now()-v};return w(C),s==null||s(D),C}finally{p(!1)}},[I,i,r,n,s]),o=d.useCallback(async m=>{if(!(y!=null&&y.config))return{error:"No form to refine. Generate a form first."};const v=`
551
+ `})]}):e.jsx("div",{className:`nice-datagrid-ai nice-datagrid-ai--disabled ${c||""}`,style:h,children:e.jsx("input",{type:"text",placeholder:p("dataGridAI.notConfigured","AI not configured"),disabled:!0,className:"nice-datagrid-ai__input"})})}function xa(i={}){const{config:a,schema:t,context:r,onFormGenerated:n,onError:s}=i,o=Z(),{t:c}=A.useNiceTranslation(),[h,p]=d.useState(!1),[m,b]=d.useState(null),[w,k]=d.useState(null),[M,C]=d.useState([]),O=d.useRef(null),_=a||(o==null?void 0:o.config),l=d.useCallback(async j=>{var x,v,T;if(!_){const I="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(I),{error:I}}p(!0),b(j);const g=performance.now();(x=O.current)==null||x.abort(),O.current=new AbortController;try{const I=K(_),N=ae(le,{description:j,schema:t?JSON.stringify(t,null,2):void 0,context:r}),P=await I.chat({messages:[{role:"system",content:N.system},{role:"user",content:N.user}],temperature:.5,maxTokens:2048}),$=Rt(P),D={config:$||void 0,rawResponse:(T=(v=P.choices[0])==null?void 0:v.message)==null?void 0:T.content,latencyMs:performance.now()-g,error:$?void 0:c("formBuilderAI.parseFailed","Failed to parse form configuration")};return $&&(n==null||n($)),k(D),C(F=>[...F.slice(-9),{description:j,result:D}]),D}catch(I){const N=I instanceof Error?I.message:c("formBuilderAI.requestFailed","AI request failed"),P={error:N,latencyMs:performance.now()-g};return k(P),s==null||s(N),P}finally{p(!1)}},[_,t,r,n,s,c]),y=d.useCallback(async j=>{if(!(w!=null&&w.config))return{error:c("formBuilderAI.nothingToRefine","No form to refine. Generate a form first.")};const g=`
538
552
  Modify this existing form based on the following instructions:
539
553
 
540
- Current form: ${JSON.stringify(y.config,null,2)}
554
+ Current form: ${JSON.stringify(w.config,null,2)}
541
555
 
542
- Instructions: ${m}
543
- `;return j(v)},[y,j]),N=d.useCallback(()=>{g(null),w(null)},[]),_=d.useCallback(()=>{var m;(m=k.current)==null||m.abort(),p(!1)},[]);return d.useEffect(()=>()=>{var m;(m=k.current)==null||m.abort()},[]),{generateForm:j,refineForm:o,loading:l,lastDescription:f,lastResult:y,history:S,clearResults:N,abort:_,isConfigured:!!I}}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)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.fields&&Array.isArray(l.fields))return{title:l.title,description:l.description,fields:l.fields,layout:l.layout,submitLabel:l.submitLabel,validation:l.validation}}catch{}return null}function yi({config:t,schema:a,context:i,onGenerate:r,placeholder:n='Describe the form you want to create... (e.g., "Contact form with name, email, subject, and message")',showExamples:s=!0,showPreview:c=!0,className:l,style:p,renderForm:f}){const[g,y]=d.useState(""),[w,S]=d.useState(!1),z=d.useRef(null),{generateForm:k,loading:I,lastResult:j,isConfigured:o}=ha({config:t,schema:a,context:i,onFormGenerated:r}),N=["Simple contact form with name, email, and message","User registration with email validation and password confirmation","Product feedback survey with rating scale and comments","Event RSVP with name, attending status, and dietary restrictions","Job application with personal info, experience, and file upload","Newsletter subscription with email and preferences"],_=async()=>{!g.trim()||I||await k(g.trim())},m=u=>{var h;y(u),S(!1),(h=z.current)==null||h.focus()},v=u=>{u.key==="Enter"&&(u.ctrlKey||u.metaKey)&&(u.preventDefault(),_())},x=u=>{y(u.target.value),u.target.style.height="auto",u.target.style.height=Math.min(u.target.scrollHeight,200)+"px"};return o?e.jsxs("div",{className:`nice-form-builder-ai ${l||""}`,style:p,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(L.NiceIcon,{name:"wand",size:16})}),"Describe your form"]}),e.jsxs("div",{className:"nice-form-builder-ai__input-wrapper",children:[e.jsx("textarea",{ref:z,value:g,onChange:x,onKeyDown:v,placeholder:n,className:"nice-form-builder-ai__textarea",disabled:I,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:()=>S(!w),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--secondary",children:"Examples"}),w&&e.jsx("div",{className:"nice-form-builder-ai__dropdown",children:N.map((u,h)=>e.jsx("button",{type:"button",className:"nice-form-builder-ai__dropdown-item",onClick:()=>m(u),children:u},h))})]}),e.jsx("button",{type:"button",onClick:_,disabled:!g.trim()||I,className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--primary",children:I?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"nice-form-builder-ai__spinner"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"rocket",size:14}),"Generate Form"]})})]})]}),e.jsxs("p",{className:"nice-form-builder-ai__hint",children:["Press ",e.jsx("kbd",{children:"Ctrl"}),"+",e.jsx("kbd",{children:"Enter"})," to generate"]})]}),j&&e.jsx("div",{className:"nice-form-builder-ai__result",children:j.error?e.jsxs("div",{className:"nice-form-builder-ai__error",children:[e.jsx("strong",{children:"Error:"})," ",j.error]}):j.config&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-form-builder-ai__result-header",children:[e.jsxs("h3",{className:"nice-form-builder-ai__result-title",children:["Generated Form: ",j.config.title||"Untitled"]}),j.latencyMs&&e.jsxs("span",{className:"nice-form-builder-ai__latency",children:[Math.round(j.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(j.config),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--success",children:"Use This Form"})]}),j.config.description&&e.jsx("p",{className:"nice-form-builder-ai__result-description",children:j.config.description}),c&&e.jsx("div",{className:"nice-form-builder-ai__preview",children:f?f(j.config):e.jsx(vi,{config:j.config})}),e.jsxs("details",{className:"nice-form-builder-ai__json",children:[e.jsx("summary",{children:"View JSON Configuration"}),e.jsx("pre",{children:JSON.stringify(j.config,null,2)})]})]})}),e.jsx("style",{children:`
556
+ Instructions: ${j}
557
+ `;return l(g)},[w,l,c]),S=d.useCallback(()=>{b(null),k(null)},[]),f=d.useCallback(()=>{var j;(j=O.current)==null||j.abort(),p(!1)},[]);return d.useEffect(()=>()=>{var j;(j=O.current)==null||j.abort()},[]),{generateForm:l,refineForm:y,loading:h,lastDescription:m,lastResult:w,history:M,clearResults:S,abort:f,isConfigured:!!_}}function Rt(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.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 zt({config:i,schema:a,context:t,onGenerate:r,placeholder:n,showExamples:s=!0,showPreview:o=!0,className:c,style:h,renderForm:p}){const{t:m}=A.useNiceTranslation(),[b,w]=d.useState(""),[k,M]=d.useState(!1),C=d.useRef(null),{generateForm:O,loading:_,lastResult:l,isConfigured:y}=xa({config:i,schema:a,context:t,onFormGenerated:r}),S=[m("formBuilderAI.example.contact","Simple contact form with name, email, and message"),m("formBuilderAI.example.registration","User registration with email validation and password confirmation"),m("formBuilderAI.example.feedback","Product feedback survey with rating scale and comments"),m("formBuilderAI.example.rsvp","Event RSVP with name, attending status, and dietary restrictions"),m("formBuilderAI.example.jobApplication","Job application with personal info, experience, and file upload"),m("formBuilderAI.example.newsletter","Newsletter subscription with email and preferences")],[f,j=""]=m("formBuilderAI.shortcutHint","Press {keys} to generate").split("{keys}"),g=async()=>{!b.trim()||_||await O(b.trim())},x=I=>{var N;w(I),M(!1),(N=C.current)==null||N.focus()},v=I=>{I.key==="Enter"&&(I.ctrlKey||I.metaKey)&&(I.preventDefault(),g())},T=I=>{w(I.target.value),I.target.style.height="auto",I.target.style.height=Math.min(I.target.scrollHeight,200)+"px"};return y?e.jsxs("div",{className:`nice-form-builder-ai ${c||""}`,style:h,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(A.NiceIcon,{name:"wand",size:16})}),m("formBuilderAI.describeYourForm","Describe your form")]}),e.jsxs("div",{className:"nice-form-builder-ai__input-wrapper",children:[e.jsx("textarea",{"aria-label":m("formBuilderAI.describeYourForm","Describe your form"),ref:C,value:b,onChange:T,onKeyDown:v,placeholder:n??m("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:_,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:()=>M(!k),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--secondary",children:m("formBuilderAI.examples","Examples")}),k&&e.jsx("div",{className:"nice-form-builder-ai__dropdown",children:S.map((I,N)=>e.jsx("button",{type:"button",className:"nice-form-builder-ai__dropdown-item",onClick:()=>x(I),children:I},N))})]}),e.jsx("button",{type:"button",onClick:g,disabled:!b.trim()||_,className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--primary",children:_?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"nice-form-builder-ai__spinner"}),m("formBuilderAI.generating","Generating...")]}):e.jsxs(e.Fragment,{children:[e.jsx(A.NiceIcon,{name:"rocket",size:14}),m("formBuilderAI.generateForm","Generate Form")]})})]})]}),e.jsxs("p",{className:"nice-form-builder-ai__hint",children:[f,e.jsx("kbd",{children:"Ctrl"}),"+",e.jsx("kbd",{children:"Enter"}),j]})]}),l&&e.jsx("div",{className:"nice-form-builder-ai__result",children:l.error?e.jsxs("div",{className:"nice-form-builder-ai__error",children:[e.jsx("strong",{children:m("formBuilderAI.errorLabel","Error:")})," ",l.error]}):l.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:m("formBuilderAI.generatedForm","Generated Form: {title}").replace("{title}",l.config.title||m("formBuilderAI.untitled","Untitled"))}),l.latencyMs&&e.jsxs("span",{className:"nice-form-builder-ai__latency",children:[Math.round(l.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(l.config),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--success",children:m("formBuilderAI.useForm","Use This Form")})]}),l.config.description&&e.jsx("p",{className:"nice-form-builder-ai__result-description",children:l.config.description}),o&&e.jsx("div",{className:"nice-form-builder-ai__preview",children:p?p(l.config):e.jsx(Mt,{config:l.config})}),e.jsxs("details",{className:"nice-form-builder-ai__json",children:[e.jsx("summary",{children:m("formBuilderAI.viewJson","View JSON Configuration")}),e.jsx("pre",{children:JSON.stringify(l.config,null,2)})]})]})}),e.jsx("style",{children:`
544
558
  .nice-form-builder-ai {
545
559
  font-family: var(--nice-font-family, system-ui, sans-serif);
546
560
  }
@@ -761,7 +775,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
761
775
  color: var(--nice-error, #c62828);
762
776
  border-radius: var(--nice-radius-md, 6px);
763
777
  }
764
- `})]}):e.jsx("div",{className:`nice-form-builder-ai nice-form-builder-ai--disabled ${l||""}`,style:p,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function vi({config:t}){var r,n;const a=s=>{var l,p;const c={id:s.id,placeholder:s.placeholder,required:s.required,disabled:!0};switch(s.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.jsxs("option",{value:"",children:["Select ",s.label,"..."]}),(l=s.options)==null?void 0:l.map(f=>e.jsx("option",{value:f.value,children:f.label},f.value))]});case"radio":return e.jsx("div",{className:"nice-form-preview__radio-group",children:(p=s.options)==null?void 0:p.map(f=>e.jsxs("label",{className:"nice-form-preview__radio",children:[e.jsx("input",{type:"radio",name:s.id,value:f.value,disabled:!0}),f.label]},f.value))});case"checkbox":return e.jsxs("label",{className:"nice-form-preview__checkbox",children:[e.jsx("input",{type:"checkbox",disabled:!0}),s.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"})}},i=((r=t.layout)==null?void 0:r.columns)||1;return e.jsxs("form",{className:"nice-form-preview",style:{"--columns":i},children:[(n=t.layout)!=null&&n.sections?t.layout.sections.map((s,c)=>e.jsxs("fieldset",{className:"nice-form-preview__section",children:[s.title&&e.jsx("legend",{children:s.title}),s.description&&e.jsx("p",{className:"nice-form-preview__section-desc",children:s.description}),e.jsx("div",{className:"nice-form-preview__grid",children:s.fields.map(l=>{const p=t.fields.find(f=>f.id===l);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:"*"})]}),a(p)]},p.id):null})})]},c)):e.jsx("div",{className:"nice-form-preview__grid",children:t.fields.map(s=>e.jsxs("div",{className:"nice-form-preview__field",children:[s.type!=="checkbox"&&e.jsxs("label",{className:"nice-form-preview__label",children:[s.label,s.required&&e.jsx("span",{className:"nice-form-preview__required",children:"*"})]}),a(s)]},s.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||"Submit"})}),e.jsx("style",{children:`
778
+ `})]}):e.jsx("div",{className:`nice-form-builder-ai nice-form-builder-ai--disabled ${c||""}`,style:h,children:e.jsx("p",{children:m("formBuilderAI.notConfigured","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function Mt({config:i}){var n,s;const{t:a}=A.useNiceTranslation(),t=o=>{var h,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)}),(h=o.options)==null?void 0:h.map(m=>e.jsx("option",{value:m.value,children:m.label},m.value))]});case"radio":return e.jsx("div",{className:"nice-form-preview__radio-group",children:(p=o.options)==null?void 0:p.map(m=>e.jsxs("label",{className:"nice-form-preview__radio",children:[e.jsx("input",{type:"radio",name:o.id,value:m.value,disabled:!0}),m.label]},m.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=i.layout)==null?void 0:n.columns)||1;return e.jsxs("form",{className:"nice-form-preview",style:{"--columns":r},children:[(s=i.layout)!=null&&s.sections?i.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(h=>{const p=i.fields.find(m=>m.id===h);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:"*"})]}),t(p)]},p.id):null})})]},c)):e.jsx("div",{className:"nice-form-preview__grid",children:i.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:"*"})]}),t(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:i.submitLabel||a("submit","Submit")})}),e.jsx("style",{children:`
765
779
  .nice-form-preview {
766
780
  --columns: 1;
767
781
  }
@@ -866,7 +880,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
866
880
  cursor: not-allowed;
867
881
  opacity: 0.7;
868
882
  }
869
- `})]})}function ga(t={}){const{config:a,dataFields:i,context:r,onChartGenerated:n,onError:s}=t,c=Z(),[l,p]=d.useState(!1),[f,g]=d.useState(null),[y,w]=d.useState(null),[S,z]=d.useState([]),k=d.useRef(null),I=a||(c==null?void 0:c.config),j=d.useMemo(()=>{if(i)return i.map(v=>{var x;return{name:v.name,type:v.type,label:v.label||v.name,...(x=v.sampleValues)!=null&&x.length?{samples:v.sampleValues.slice(0,3)}:{}}})},[i]),o=d.useCallback(async v=>{var u,h,$;if(!I){const D="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(D),{error:D}}p(!0),g(v);const x=performance.now();(u=k.current)==null||u.abort(),k.current=new AbortController;try{const D=K(I),C=ie(le,{request:v,data:j?JSON.stringify(j,null,2):void 0,context:r}),A=await D.chat({messages:[{role:"system",content:C.system},{role:"user",content:C.user}],temperature:.4,maxTokens:1024}),O=_i(A),B={config:O||void 0,rawResponse:($=(h=A.choices[0])==null?void 0:h.message)==null?void 0:$.content,latencyMs:performance.now()-x,error:O?void 0:"Failed to parse chart configuration",suggestions:wi(O)};return O&&(n==null||n(O)),w(B),z(b=>[...b.slice(-9),{request:v,result:B}]),B}catch(D){const C=D instanceof Error?D.message:"AI request failed",A={error:C,latencyMs:performance.now()-x};return w(A),s==null||s(C),A}finally{p(!1)}},[I,j,r,n,s]),N=d.useCallback(async()=>y!=null&&y.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"]}[y.config.type]||[]:[],[y]),_=d.useCallback(()=>{g(null),w(null)},[]),m=d.useCallback(()=>{var v;(v=k.current)==null||v.abort(),p(!1)},[]);return d.useEffect(()=>()=>{var v;(v=k.current)==null||v.abort()},[]),{generateChart:o,suggestAlternatives:N,loading:l,lastRequest:f,lastResult:y,history:S,clearResults:_,abort:m,isConfigured:!!I}}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)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.type)return{type:l.type,title:l.title,subtitle:l.subtitle,data:l.data||{},xAxis:l.xAxis,yAxis:l.yAxis,options:l.options}}catch{}return null}function wi(t){var i;if(!t)return[];const a=[];return(t.type==="line"||t.type==="bar")&&(a.push("Add trend line for forecasting"),a.push("Stack series for comparison")),(t.type==="pie"||t.type==="donut")&&(a.push("Convert to bar chart for better comparison"),a.push("Add data labels for percentages")),(i=t.options)!=null&&i.animation||a.push("Enable animations for better UX"),a.slice(0,3)}function ji({config:t,dataFields:a,context:i,onGenerate:r,placeholder:n='Describe the chart you want... (e.g., "Show monthly sales as a line chart")',showTypeSelector:s=!0,showPreview:c=!0,className:l,style:p,renderChart:f}){const[g,y]=d.useState(""),[w,S]=d.useState(null),z=d.useRef(null),{generateChart:k,suggestAlternatives:I,loading:j,lastResult:o,isConfigured:N}=ga({config:t,dataFields:a,context:i,onChartGenerated:r}),_=[{type:"line",icon:"line",label:"Line"},{type:"bar",icon:"bar-chart",label:"Bar"},{type:"pie",icon:"circle",label:"Pie"},{type:"area",icon:"bar-chart",label:"Area"},{type:"scatter",icon:"grid",label:"Scatter"},{type:"donut",icon:"circle",label:"Donut"},{type:"heatmap",icon:"grid",label:"Heatmap"},{type:"funnel",icon:"filter",label:"Funnel"},{type:"gauge",icon:"target",label:"Gauge"},{type:"radar",icon:"target",label:"Radar"}],m=async()=>{if(!g.trim()||j)return;const h=w?`Create a ${w} chart: ${g}`:g;await k(h)},v=h=>{h.key==="Enter"&&(h.preventDefault(),m())},x=h=>{S(w===h?null:h)},u=async h=>{if(!(o!=null&&o.config))return;const $={...o.config,type:h};r==null||r($)};return N?e.jsxs("div",{className:`nice-chart-ai ${l||""}`,style:p,children:[s&&e.jsx("div",{className:"nice-chart-ai__types",children:_.map(({type:h,icon:$,label:D})=>e.jsxs("button",{type:"button",className:`nice-chart-ai__type ${w===h?"nice-chart-ai__type--selected":""}`,onClick:()=>x(h),title:D,children:[e.jsx("span",{className:"nice-chart-ai__type-icon",children:e.jsx(L.NiceIcon,{name:$,size:20})}),e.jsx("span",{className:"nice-chart-ai__type-label",children:D})]},h))}),e.jsxs("div",{className:"nice-chart-ai__input-wrapper",children:[e.jsx("span",{className:"nice-chart-ai__icon",children:e.jsx(L.NiceIcon,{name:"bar-chart",size:18})}),e.jsx("input",{ref:z,type:"text",value:g,onChange:h=>y(h.target.value),onKeyDown:v,placeholder:n,className:"nice-chart-ai__input",disabled:j}),j?e.jsx("span",{className:"nice-chart-ai__spinner"}):e.jsx("button",{type:"button",onClick:m,className:"nice-chart-ai__submit",disabled:!g.trim(),children:"Generate"})]}),a&&a.length>0&&e.jsxs("div",{className:"nice-chart-ai__fields",children:[e.jsx("span",{className:"nice-chart-ai__fields-label",children:"Available fields:"}),a.map(h=>e.jsx("span",{className:"nice-chart-ai__field-badge",title:h.type,children:h.label||h.name},h.name))]}),o&&e.jsx("div",{className:"nice-chart-ai__result",children:o.error?e.jsx("div",{className:"nice-chart-ai__error",children:o.error}):o.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 $;const h=($=_.find(D=>D.type===o.config.type))==null?void 0:$.icon;return h?e.jsx(L.NiceIcon,{name:h,size:16}):null})(),o.config.type.charAt(0).toUpperCase()+o.config.type.slice(1)," ","Chart"]}),o.config.title&&e.jsx("span",{className:"nice-chart-ai__chart-title",children:o.config.title})]}),o.latencyMs&&e.jsxs("span",{className:"nice-chart-ai__latency",children:[Math.round(o.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(o.config),className:"nice-chart-ai__use-btn",children:"Use This Chart"})]}),e.jsxs("div",{className:"nice-chart-ai__alternatives",children:[e.jsx("span",{children:"Try also:"}),_.filter(h=>h.type!==o.config.type).slice(0,4).map(({type:h,icon:$})=>e.jsx("button",{type:"button",className:"nice-chart-ai__alternative",onClick:()=>u(h),title:`Convert to ${h}`,"aria-label":`Convert to ${h}`,children:e.jsx(L.NiceIcon,{name:$,size:16})},h))]}),c&&e.jsx("div",{className:"nice-chart-ai__preview",children:f?f(o.config):e.jsx(ki,{config:o.config})}),e.jsxs("details",{className:"nice-chart-ai__json",children:[e.jsx("summary",{children:"View Configuration"}),e.jsx("pre",{children:JSON.stringify(o.config,null,2)})]})]})}),e.jsx("style",{children:`
883
+ `})]})}function ba(i={}){const{config:a,dataFields:t,context:r,onChartGenerated:n,onError:s}=i,o=Z(),{t:c}=A.useNiceTranslation(),[h,p]=d.useState(!1),[m,b]=d.useState(null),[w,k]=d.useState(null),[M,C]=d.useState([]),O=d.useRef(null),_=a||(o==null?void 0:o.config),l=d.useMemo(()=>{if(t)return t.map(g=>{var x;return{name:g.name,type:g.type,label:g.label||g.name,...(x=g.sampleValues)!=null&&x.length?{samples:g.sampleValues.slice(0,3)}:{}}})},[t]),y=d.useCallback(async g=>{var v,T,I;if(!_){const N="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(N),{error:N}}p(!0),b(g);const x=performance.now();(v=O.current)==null||v.abort(),O.current=new AbortController;try{const N=K(_),P=ae(de,{request:g,data:l?JSON.stringify(l,null,2):void 0,context:r}),$=await N.chat({messages:[{role:"system",content:P.system},{role:"user",content:P.user}],temperature:.4,maxTokens:1024}),D=Lt($),F={config:D||void 0,rawResponse:(I=(T=$.choices[0])==null?void 0:T.message)==null?void 0:I.content,latencyMs:performance.now()-x,error:D?void 0:c("chartAI.parseFailed","Failed to parse chart configuration"),suggestions:Pt(D,c)};return D&&(n==null||n(D)),k(F),C(U=>[...U.slice(-9),{request:g,result:F}]),F}catch(N){const P=N instanceof Error?N.message:c("chartAI.requestFailed","AI request failed"),$={error:P,latencyMs:performance.now()-x};return k($),s==null||s(P),$}finally{p(!1)}},[_,l,r,n,s,c]),S=d.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]),f=d.useCallback(()=>{b(null),k(null)},[]),j=d.useCallback(()=>{var g;(g=O.current)==null||g.abort(),p(!1)},[]);return d.useEffect(()=>()=>{var g;(g=O.current)==null||g.abort()},[]),{generateChart:y,suggestAlternatives:S,loading:h,lastRequest:m,lastResult:w,history:M,clearResults:f,abort:j,isConfigured:!!_}}function Lt(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.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 Pt(i,a){var r;if(!i)return[];const t=[];return(i.type==="line"||i.type==="bar")&&(t.push(a("chartAI.suggest.trendLine","Add trend line for forecasting")),t.push(a("chartAI.suggest.stack","Stack series for comparison"))),(i.type==="pie"||i.type==="donut")&&(t.push(a("chartAI.suggest.toBar","Convert to bar chart for better comparison")),t.push(a("chartAI.suggest.percentLabels","Add data labels for percentages"))),(r=i.options)!=null&&r.animation||t.push(a("chartAI.suggest.animate","Enable animations for better UX")),t.slice(0,3)}const $t={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"]},Te=(i,a)=>{const t=$t[i];return t?a(t[0],t[1]):i.charAt(0).toUpperCase()+i.slice(1)};function Ot({config:i,dataFields:a,context:t,onGenerate:r,placeholder:n,showTypeSelector:s=!0,showPreview:o=!0,className:c,style:h,renderChart:p}){const{t:m}=A.useNiceTranslation(),[b,w]=d.useState(""),[k,M]=d.useState(null),C=d.useRef(null),{generateChart:O,suggestAlternatives:_,loading:l,lastResult:y,isConfigured:S}=ba({config:i,dataFields:a,context:t,onChartGenerated:r}),f=[["line","line"],["bar","bar-chart"],["pie","circle"],["area","bar-chart"],["scatter","grid"],["donut","circle"],["heatmap","grid"],["funnel","filter"],["gauge","target"],["radar","target"]].map(([T,I])=>({type:T,icon:I,label:Te(T,m)})),j=async()=>{if(!b.trim()||l)return;const T=k?`Create a ${k} chart: ${b}`:b;await O(T)},g=T=>{T.key==="Enter"&&(T.preventDefault(),j())},x=T=>{M(k===T?null:T)},v=async T=>{if(!(y!=null&&y.config))return;const I={...y.config,type:T};r==null||r(I)};return S?e.jsxs("div",{className:`nice-chart-ai ${c||""}`,style:h,children:[s&&e.jsx("div",{className:"nice-chart-ai__types",children:f.map(({type:T,icon:I,label:N})=>e.jsxs("button",{type:"button",className:`nice-chart-ai__type ${k===T?"nice-chart-ai__type--selected":""}`,onClick:()=>x(T),title:N,children:[e.jsx("span",{className:"nice-chart-ai__type-icon",children:e.jsx(A.NiceIcon,{name:I,size:20})}),e.jsx("span",{className:"nice-chart-ai__type-label",children:N})]},T))}),e.jsxs("div",{className:"nice-chart-ai__input-wrapper",children:[e.jsx("span",{className:"nice-chart-ai__icon",children:e.jsx(A.NiceIcon,{name:"bar-chart",size:18})}),e.jsx("input",{ref:C,type:"text",value:b,onChange:T=>w(T.target.value),onKeyDown:g,placeholder:n??m("chartAI.placeholder",'Describe the chart you want... (e.g., "Show monthly sales as a line chart")'),className:"nice-chart-ai__input",disabled:l}),l?e.jsx("span",{className:"nice-chart-ai__spinner"}):e.jsx("button",{type:"button",onClick:j,className:"nice-chart-ai__submit",disabled:!b.trim(),children:m("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:m("chartAI.availableFields","Available fields:")}),a.map(T=>e.jsx("span",{className:"nice-chart-ai__field-badge",title:T.type,children:T.label||T.name},T.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 I;const T=(I=f.find(N=>N.type===y.config.type))==null?void 0:I.icon;return T?e.jsx(A.NiceIcon,{name:T,size:16}):null})(),m("chartAI.chartOfType","{type} Chart").replace("{type}",Te(y.config.type,m))]}),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:()=>r==null?void 0:r(y.config),className:"nice-chart-ai__use-btn",children:m("chartAI.useChart","Use This Chart")})]}),e.jsxs("div",{className:"nice-chart-ai__alternatives",children:[e.jsx("span",{children:m("chartAI.tryAlso","Try also:")}),f.filter(T=>T.type!==y.config.type).slice(0,4).map(({type:T,icon:I,label:N})=>e.jsx("button",{type:"button",className:"nice-chart-ai__alternative",onClick:()=>v(T),title:m("chartAI.convertTo","Convert to {type}").replace("{type}",N),"aria-label":m("chartAI.convertTo","Convert to {type}").replace("{type}",N),children:e.jsx(A.NiceIcon,{name:I,size:16})},T))]}),o&&e.jsx("div",{className:"nice-chart-ai__preview",children:p?p(y.config):e.jsx(Et,{config:y.config})}),e.jsxs("details",{className:"nice-chart-ai__json",children:[e.jsx("summary",{children:m("chartAI.viewConfig","View Configuration")}),e.jsx("pre",{children:JSON.stringify(y.config,null,2)})]})]})}),e.jsx("style",{children:`
870
884
  .nice-chart-ai {
871
885
  font-family: var(--nice-font-family, system-ui, sans-serif);
872
886
  }
@@ -1110,7 +1124,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
1110
1124
  color: var(--nice-error, #c62828);
1111
1125
  border-radius: var(--nice-radius-md, 6px);
1112
1126
  }
1113
- `})]}):e.jsx("div",{className:`nice-chart-ai nice-chart-ai--disabled ${l||""}`,style:p,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function ki({config:t}){var i;const a=()=>{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:"rgba(33, 150, 243, 0.2)"}),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 r=t.type==="donut"?35:40,n=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,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:n,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(L.NiceIcon,{name:"bar-chart",size:32})}),e.jsxs("span",{children:[t.type.charAt(0).toUpperCase()+t.type.slice(1)," Chart"]})]})}};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:a()}),((i=t.options)==null?void 0:i.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)"}}),"Series 1"]}),e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-primary, #2196f3)"}}),"Series 2"]}),e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-warning, #ff9800)"}}),"Series 3"]})]}),e.jsx("style",{children:`
1127
+ `})]}):e.jsx("div",{className:`nice-chart-ai nice-chart-ai--disabled ${c||""}`,style:h,children:e.jsx("p",{children:m("chartAI.notConfigured","AI not configured. Please provide config or wrap in NiceAIProvider.")})})}function Et({config:i}){var n;const{t:a}=A.useNiceTranslation(),t=s=>a("chartAI.series","Series {n}").replace("{n}",String(s)),r=()=>{switch(i.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"}),i.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:"rgba(33, 150, 243, 0.2)"}),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=i.type==="donut"?35:40,o=i.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)"}),i.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(A.NiceIcon,{name:"bar-chart",size:32})}),e.jsx("span",{children:a("chartAI.chartOfType","{type} Chart").replace("{type}",Te(i.type,a))})]})}};return e.jsxs("div",{className:"nice-chart-preview",children:[i.title&&e.jsx("div",{className:"nice-chart-preview__title",children:i.title}),i.subtitle&&e.jsx("div",{className:"nice-chart-preview__subtitle",children:i.subtitle}),e.jsx("div",{className:"nice-chart-preview__chart",children:r()}),((n=i.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)"}}),t(1)]}),e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-primary, #2196f3)"}}),t(2)]}),e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-warning, #ff9800)"}}),t(3)]})]}),e.jsx("style",{children:`
1114
1128
  .nice-chart-preview {
1115
1129
  text-align: center;
1116
1130
  }
@@ -1171,11 +1185,12 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
1171
1185
  height: 12px;
1172
1186
  border-radius: var(--nice-radius-sm, 2px);
1173
1187
  }
1174
- `})]})}function fa(t={}){const{config:a,language:i="typescript",context:r,maxSuggestions:n=3,debounceMs:s=300,onSuggestion:c,onError:l}=t,p=Z(),[f,g]=d.useState(!1),[y,w]=d.useState([]),[S,z]=d.useState(-1),k=d.useRef(null),I=d.useRef(null),j=a||(p==null?void 0:p.config),o=d.useCallback(async(C,A)=>{var B,b,P;if(!j)return{suggestions:[],error:"AI not configured"};g(!0),(B=k.current)==null||B.abort(),k.current=new AbortController;const O=performance.now();try{const H=K(j),J=C.split(`
1175
- `),M=J[A.line]||"",U=M.substring(0,A.column),q=M.substring(A.column),W=J.slice(Math.max(0,A.line-20),A.line).join(`
1176
- `),G=J.slice(A.line+1,A.line+10).join(`
1177
- `),Y=ie(de,{language:i,code_context:W,prefix:U,suffix:q,context_after:G,context:r}),ee=await H.chat({messages:[{role:"system",content:Y.system},{role:"user",content:Y.user}],temperature:.2,maxTokens:512}),Q=Ni(ee,A,n),T={suggestions:Q,rawResponse:(P=(b=ee.choices[0])==null?void 0:b.message)==null?void 0:P.content,latencyMs:performance.now()-O};return w(Q),z(Q.length>0?0:-1),c==null||c(Q),T}catch(H){const J=H instanceof Error?H.message:"Completion failed";return l==null||l(J),{suggestions:[],error:J,latencyMs:performance.now()-O}}finally{g(!1)}},[j,i,r,n,c,l]),N=d.useCallback((C,A)=>{I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{o(C,A)},s)},[o,s]),_=d.useCallback(async C=>{if(!j)return null;g(!0);try{const O=await K(j).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:C}],temperature:.3,maxTokens:1024});return Ci(O)}catch{return null}finally{g(!1)}},[j,i]),m=d.useCallback(async C=>{if(!j)return[];g(!0);try{const O=await K(j).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:C}],temperature:.4,maxTokens:2048});return Si(O)}catch{return[]}finally{g(!1)}},[j,i]),v=d.useCallback(async(C,A)=>{var O,B;if(!j)return null;g(!0);try{const b=K(j),P=A||Ti(i);return((B=(O=(await b.chat({messages:[{role:"system",content:`You are a testing expert. Generate comprehensive unit tests for the following ${i} code using ${P}. Include edge cases and error scenarios. Return only the test code.`},{role:"user",content:C}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:O.message)==null?void 0:B.content)||null}catch{return null}finally{g(!1)}},[j,i]),x=d.useCallback(async(C,A)=>{var O,B;if(!j)return null;g(!0);try{const b=K(j),P=A||Ai(i);return((B=(O=(await b.chat({messages:[{role:"system",content:`Generate ${P} documentation for the following ${i} code. Include descriptions for parameters, return values, and examples where appropriate. Return only the documented code.`},{role:"user",content:C}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:O.message)==null?void 0:B.content)||null}catch{return null}finally{g(!1)}},[j,i]),u=d.useCallback((C=S)=>{const A=y[C];return w([]),z(-1),A},[y,S]),h=d.useCallback(()=>{w([]),z(-1)},[]),$=d.useCallback(C=>{y.length!==0&&z(A=>C==="up"?A<=0?y.length-1:A-1:A>=y.length-1?0:A+1)},[y.length]),D=d.useCallback(()=>{var C;(C=k.current)==null||C.abort(),I.current&&clearTimeout(I.current),g(!1)},[]);return d.useEffect(()=>()=>{var C;(C=k.current)==null||C.abort(),I.current&&clearTimeout(I.current)},[]),{getCompletions:o,getCompletionsDebounced:N,suggestions:y,activeSuggestion:S,acceptSuggestion:u,dismissSuggestions:h,navigateSuggestions:$,explainCode:_,suggestRefactoring:m,generateTests:v,generateDocs:x,loading:f,abort:D,isConfigured:!!j}}function Ni(t,a,i){var r,n;try{return(((n=(r=t.choices[0])==null?void 0:r.message)==null?void 0:n.content)||"").split(`
1178
- `).filter(l=>l.trim()).slice(0,i).map((l,p)=>({id:`suggestion-${Date.now()}-${p}`,text:l.trim(),type:"inline",preview:l.trim().slice(0,50),confidence:.8-p*.1,insertPosition:a}))}catch{return[]}}function Ci(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 Si(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 Ti(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 Ai(t){return{javascript:"jsdoc",typescript:"tsdoc",python:"docstring",java:"javadoc",kotlin:"javadoc"}[t]||"jsdoc"}function Ri({code:t="",language:a="typescript",config:i,onChange:r,onAcceptSuggestion:n,showToolbar:s=!0,enableInlineSuggestions:c=!0,placeholder:l="Start typing code...",className:p,style:f,renderEditor:g}){const[y,w]=d.useState(t),[S,z]=d.useState(null),[k,I]=d.useState(null),[j,o]=d.useState([]),[N,_]=d.useState(null),[m,v]=d.useState(null),x=d.useRef(null),{getCompletionsDebounced:u,suggestions:h,activeSuggestion:$,acceptSuggestion:D,dismissSuggestions:C,navigateSuggestions:A,explainCode:O,suggestRefactoring:B,generateTests:b,generateDocs:P,loading:H,isConfigured:J}=fa({config:i,language:a}),M=R=>{if(w(R),r==null||r(R),c&&x.current){const F=Ii(x.current);u(R,F)}},U=R=>{if(h.length>0)if(R.key==="ArrowUp")R.preventDefault(),A("up");else if(R.key==="ArrowDown")R.preventDefault(),A("down");else if(R.key==="Tab"||R.key==="Enter"){if($>=0){R.preventDefault();const F=D($);F&&(q(F),n==null||n(F))}}else R.key==="Escape"&&C()},q=R=>{if(!x.current)return;const F=x.current,V=F.selectionStart,re=y.slice(0,V)+R.text+y.slice(V);w(re),r==null||r(re);const Le=V+R.text.length;setTimeout(()=>{F.focus(),F.setSelectionRange(Le,Le)},0)},W=async()=>{const R=S||y;if(!R.trim())return;v("explain");const F=await O(R);I(F)},G=async()=>{const R=S||y;if(!R.trim())return;v("refactor");const F=await B(R);o(F)},Y=async()=>{if(!y.trim())return;v("tests");const R=await b(y);_(R)},ee=async()=>{if(!y.trim())return;v("docs");const R=await P(y);_(R)},Q=R=>{const F=y.replace(R.before,R.after);w(F),r==null||r(F),v(null)},T=()=>{N&&navigator.clipboard.writeText(N)},E=()=>{if(x.current){const R=x.current.selectionStart,F=x.current.selectionEnd;z(R!==F?y.slice(R,F):null)}};return J?g?e.jsx("div",{className:`nice-code-editor-ai ${p||""}`,style:f,children:g({code:y,onChange:M,suggestions:h,onAccept:R=>{const F=D(R);F&&(n==null||n(F))}})}):e.jsxs("div",{className:`nice-code-editor-ai ${p||""}`,style:f,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:H||!y.trim(),title:"Explain code",children:[e.jsx(L.NiceIcon,{name:"lightbulb",size:14})," Explain"]}),e.jsxs("button",{type:"button",onClick:G,disabled:H||!y.trim(),title:"Suggest refactoring",children:[e.jsx(L.NiceIcon,{name:"settings",size:14})," Refactor"]}),e.jsxs("button",{type:"button",onClick:Y,disabled:H||!y.trim(),title:"Generate tests",children:[e.jsx(L.NiceIcon,{name:"flask",size:14})," Tests"]}),e.jsxs("button",{type:"button",onClick:ee,disabled:H||!y.trim(),title:"Generate docs",children:[e.jsx(L.NiceIcon,{name:"edit",size:14})," Docs"]})]}),H&&e.jsx("span",{className:"nice-code-editor-ai__loading",children:"Processing..."})]}),e.jsxs("div",{className:"nice-code-editor-ai__editor-wrapper",children:[e.jsx("textarea",{ref:x,value:y,onChange:R=>M(R.target.value),onKeyDown:U,onSelect:E,placeholder:l,className:"nice-code-editor-ai__textarea",spellCheck:!1}),h.length>0&&e.jsxs("div",{className:"nice-code-editor-ai__suggestions",children:[h.map((R,F)=>e.jsxs("div",{className:`nice-code-editor-ai__suggestion ${F===$?"nice-code-editor-ai__suggestion--active":""}`,onClick:()=>{const V=D(F);V&&(q(V),n==null||n(V))},children:[e.jsx("span",{className:"nice-code-editor-ai__suggestion-text",children:R.text}),e.jsxs("span",{className:"nice-code-editor-ai__suggestion-confidence",children:[Math.round(R.confidence*100),"%"]})]},R.id)),e.jsxs("div",{className:"nice-code-editor-ai__suggestions-hint",children:[e.jsx(L.NiceIcon,{name:"arrow-up",size:11}),e.jsx(L.NiceIcon,{name:"arrow-down",size:11})," navigate • Tab accept • Esc dismiss"]})]})]}),m&&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:[m==="explain"&&e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"lightbulb",size:14})," Explanation"]}),m==="refactor"&&e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"settings",size:14})," Refactoring Suggestions"]}),m==="tests"&&e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"flask",size:14})," Generated Tests"]}),m==="docs"&&e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"edit",size:14})," Generated Documentation"]})]}),e.jsx("button",{type:"button",onClick:()=>v(null),"aria-label":"Close panel",children:e.jsx(L.NiceIcon,{name:"close",size:16})})]}),e.jsxs("div",{className:"nice-code-editor-ai__panel-content",children:[m==="explain"&&k&&e.jsxs("div",{className:"nice-code-editor-ai__explanation",children:[e.jsx("div",{className:"nice-code-editor-ai__explanation-summary",children:k.summary}),k.details&&e.jsx("div",{className:"nice-code-editor-ai__explanation-details",children:k.details}),k.complexity&&e.jsxs("span",{className:`nice-code-editor-ai__complexity nice-code-editor-ai__complexity--${k.complexity}`,children:["Complexity: ",k.complexity]}),k.suggestions&&k.suggestions.length>0&&e.jsx("ul",{className:"nice-code-editor-ai__explanation-suggestions",children:k.suggestions.map((R,F)=>e.jsx("li",{children:R},F))})]}),m==="refactor"&&j.length>0&&e.jsx("div",{className:"nice-code-editor-ai__refactorings",children:j.map((R,F)=>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:R.title}),e.jsx("span",{className:`nice-code-editor-ai__refactoring-type nice-code-editor-ai__refactoring-type--${R.type}`,children:R.type})]}),e.jsx("p",{className:"nice-code-editor-ai__refactoring-desc",children:R.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:R.before})]}),e.jsxs("div",{className:"nice-code-editor-ai__refactoring-after",children:[e.jsx("span",{children:"After:"}),e.jsx("pre",{children:R.after})]})]}),e.jsx("button",{type:"button",className:"nice-code-editor-ai__refactoring-apply",onClick:()=>Q(R),children:"Apply"})]},F))}),(m==="tests"||m==="docs")&&N&&e.jsxs("div",{className:"nice-code-editor-ai__generated",children:[e.jsx("pre",{children:N}),e.jsxs("button",{type:"button",onClick:T,children:[e.jsx(L.NiceIcon,{name:"clipboard",size:14})," Copy"]})]})]})]}),e.jsx("style",{children:`
1188
+ `})]})}function ya(i={}){const{config:a,language:t="typescript",context:r,maxSuggestions:n=3,debounceMs:s=300,onSuggestion:o,onError:c}=i,h=Z(),[p,m]=d.useState(!1),[b,w]=d.useState([]),[k,M]=d.useState(-1),C=d.useRef(null),O=d.useRef(null),_=a||(h==null?void 0:h.config),l=d.useCallback(async(N,P)=>{var D,F,U;if(!_)return{suggestions:[],error:"AI not configured"};m(!0),(D=C.current)==null||D.abort(),C.current=new AbortController;const $=performance.now();try{const W=K(_),Y=N.split(`
1189
+ `),u=Y[P.line]||"",R=[...Y.slice(Math.max(0,P.line-20),P.line),u.substring(0,P.column)].join(`
1190
+ `),B=[u.substring(P.column),...Y.slice(P.line+1,P.line+10)].join(`
1191
+ `),H=ae(ue,{language:t,prefix:R,suffix:B,context:r}),q=await W.chat({messages:[{role:"system",content:H.system},{role:"user",content:H.user}],temperature:.2,maxTokens:512}),G=Dt(q,P,n),Q={suggestions:G,rawResponse:(U=(F=q.choices[0])==null?void 0:F.message)==null?void 0:U.content,latencyMs:performance.now()-$};return w(G),M(G.length>0?0:-1),o==null||o(G),Q}catch(W){const Y=W instanceof Error?W.message:"Completion failed";return c==null||c(Y),{suggestions:[],error:Y,latencyMs:performance.now()-$}}finally{m(!1)}},[_,t,r,n,o,c]),y=d.useCallback((N,P)=>{O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{l(N,P)},s)},[l,s]),S=d.useCallback(async N=>{if(!_)return null;m(!0);try{const $=await K(_).chat({messages:[{role:"system",content:`You are a code explanation assistant. Explain the following ${t} 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 Bt($)}catch{return null}finally{m(!1)}},[_,t]),f=d.useCallback(async N=>{if(!_)return[];m(!0);try{const $=await K(_).chat({messages:[{role:"system",content:`You are a code refactoring assistant. Analyze the following ${t} 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 Ft($)}catch{return[]}finally{m(!1)}},[_,t]),j=d.useCallback(async(N,P)=>{var $,D;if(!_)return null;m(!0);try{const F=K(_),U=P||qt(t);return((D=($=(await F.chat({messages:[{role:"system",content:`You are a testing expert. Generate comprehensive unit tests for the following ${t} 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:$.message)==null?void 0:D.content)||null}catch{return null}finally{m(!1)}},[_,t]),g=d.useCallback(async(N,P)=>{var $,D;if(!_)return null;m(!0);try{const F=K(_),U=P||Jt(t);return((D=($=(await F.chat({messages:[{role:"system",content:`Generate ${U} documentation for the following ${t} 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:$.message)==null?void 0:D.content)||null}catch{return null}finally{m(!1)}},[_,t]),x=d.useCallback((N=k)=>{const P=b[N];return w([]),M(-1),P},[b,k]),v=d.useCallback(()=>{w([]),M(-1)},[]),T=d.useCallback(N=>{b.length!==0&&M(P=>N==="up"?P<=0?b.length-1:P-1:P>=b.length-1?0:P+1)},[b.length]),I=d.useCallback(()=>{var N;(N=C.current)==null||N.abort(),O.current&&clearTimeout(O.current),m(!1)},[]);return d.useEffect(()=>()=>{var N;(N=C.current)==null||N.abort(),O.current&&clearTimeout(O.current)},[]),{getCompletions:l,getCompletionsDebounced:y,suggestions:b,activeSuggestion:k,acceptSuggestion:x,dismissSuggestions:v,navigateSuggestions:T,explainCode:S,suggestRefactoring:f,generateTests:j,generateDocs:g,loading:p,abort:I,isConfigured:!!_}}function Dt(i,a,t){var o,c;const r=((c=(o=i.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()||t<1?[]:[{id:`suggestion-${Date.now()}-0`,text:s,type:s.includes(`
1192
+ `)?"block":"inline",preview:s.trim().split(`
1193
+ `)[0].slice(0,50),confidence:.8,insertPosition:a}]}function Bt(i){var a,t;try{const r=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.content)||"",n=r.match(/\{[\s\S]*\}/);return n?JSON.parse(n[0]):{summary:r}}catch{return null}}function Ft(i){var a,t;try{const n=(((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.content)||"").match(/\[[\s\S]*\]/);if(n)return JSON.parse(n[0])}catch{}return[]}function qt(i){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"}[i]||"unit test"}function Jt(i){return{javascript:"jsdoc",typescript:"tsdoc",python:"docstring",java:"javadoc",kotlin:"javadoc"}[i]||"jsdoc"}function Ht({code:i="",language:a="typescript",config:t,onChange:r,onAcceptSuggestion:n,showToolbar:s=!0,enableInlineSuggestions:o=!0,placeholder:c="Start typing code...",className:h,style:p,renderEditor:m}){const[b,w]=d.useState(i),[k,M]=d.useState(null),[C,O]=d.useState(null),[_,l]=d.useState([]),[y,S]=d.useState(null),[f,j]=d.useState(null),g=d.useRef(null),{getCompletionsDebounced:x,suggestions:v,activeSuggestion:T,acceptSuggestion:I,dismissSuggestions:N,navigateSuggestions:P,explainCode:$,suggestRefactoring:D,generateTests:F,generateDocs:U,loading:W,isConfigured:Y}=ya({config:t,language:a}),u=L=>{if(w(L),r==null||r(L),o&&g.current){const J=Ut(g.current);x(L,J)}},R=L=>{if(v.length>0)if(L.key==="ArrowUp")L.preventDefault(),P("up");else if(L.key==="ArrowDown")L.preventDefault(),P("down");else if(L.key==="Tab"||L.key==="Enter"){if(T>=0){L.preventDefault();const J=I(T);J&&(B(J),n==null||n(J))}}else L.key==="Escape"&&N()},B=L=>{if(!g.current)return;const J=g.current,V=J.selectionStart,re=b.slice(0,V)+L.text+b.slice(V);w(re),r==null||r(re);const Oe=V+L.text.length;setTimeout(()=>{J.focus(),J.setSelectionRange(Oe,Oe)},0)},H=async()=>{const L=k||b;if(!L.trim())return;j("explain");const J=await $(L);O(J)},q=async()=>{const L=k||b;if(!L.trim())return;j("refactor");const J=await D(L);l(J)},G=async()=>{if(!b.trim())return;j("tests");const L=await F(b);S(L)},Q=async()=>{if(!b.trim())return;j("docs");const L=await U(b);S(L)},ie=L=>{const J=b.replace(L.before,L.after);w(J),r==null||r(J),j(null)},z=()=>{y&&navigator.clipboard.writeText(y)},E=()=>{if(g.current){const L=g.current.selectionStart,J=g.current.selectionEnd;M(L!==J?b.slice(L,J):null)}};return Y?m?e.jsx("div",{className:`nice-code-editor-ai ${h||""}`,style:p,children:m({code:b,onChange:u,suggestions:v,onAccept:L=>{const J=I(L);J&&(n==null||n(J))}})}):e.jsxs("div",{className:`nice-code-editor-ai ${h||""}`,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:W||!b.trim(),title:"Explain code",children:[e.jsx(A.NiceIcon,{name:"lightbulb",size:14})," Explain"]}),e.jsxs("button",{type:"button",onClick:q,disabled:W||!b.trim(),title:"Suggest refactoring",children:[e.jsx(A.NiceIcon,{name:"settings",size:14})," Refactor"]}),e.jsxs("button",{type:"button",onClick:G,disabled:W||!b.trim(),title:"Generate tests",children:[e.jsx(A.NiceIcon,{name:"flask",size:14})," Tests"]}),e.jsxs("button",{type:"button",onClick:Q,disabled:W||!b.trim(),title:"Generate docs",children:[e.jsx(A.NiceIcon,{name:"edit",size:14})," Docs"]})]}),W&&e.jsx("span",{className:"nice-code-editor-ai__loading",children:"Processing..."})]}),e.jsxs("div",{className:"nice-code-editor-ai__editor-wrapper",children:[e.jsx("textarea",{ref:g,value:b,onChange:L=>u(L.target.value),onKeyDown:R,onSelect:E,placeholder:c,className:"nice-code-editor-ai__textarea",spellCheck:!1}),v.length>0&&e.jsxs("div",{className:"nice-code-editor-ai__suggestions",children:[v.map((L,J)=>e.jsxs("div",{className:`nice-code-editor-ai__suggestion ${J===T?"nice-code-editor-ai__suggestion--active":""}`,onClick:()=>{const V=I(J);V&&(B(V),n==null||n(V))},children:[e.jsx("span",{className:"nice-code-editor-ai__suggestion-text",children:L.text}),e.jsxs("span",{className:"nice-code-editor-ai__suggestion-confidence",children:[Math.round(L.confidence*100),"%"]})]},L.id)),e.jsxs("div",{className:"nice-code-editor-ai__suggestions-hint",children:[e.jsx(A.NiceIcon,{name:"arrow-up",size:11}),e.jsx(A.NiceIcon,{name:"arrow-down",size:11})," navigate • Tab accept • Esc dismiss"]})]})]}),f&&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:[f==="explain"&&e.jsxs(e.Fragment,{children:[e.jsx(A.NiceIcon,{name:"lightbulb",size:14})," Explanation"]}),f==="refactor"&&e.jsxs(e.Fragment,{children:[e.jsx(A.NiceIcon,{name:"settings",size:14})," Refactoring Suggestions"]}),f==="tests"&&e.jsxs(e.Fragment,{children:[e.jsx(A.NiceIcon,{name:"flask",size:14})," Generated Tests"]}),f==="docs"&&e.jsxs(e.Fragment,{children:[e.jsx(A.NiceIcon,{name:"edit",size:14})," Generated Documentation"]})]}),e.jsx("button",{type:"button",onClick:()=>j(null),"aria-label":"Close panel",children:e.jsx(A.NiceIcon,{name:"close",size:16})})]}),e.jsxs("div",{className:"nice-code-editor-ai__panel-content",children:[f==="explain"&&C&&e.jsxs("div",{className:"nice-code-editor-ai__explanation",children:[e.jsx("div",{className:"nice-code-editor-ai__explanation-summary",children:C.summary}),C.details&&e.jsx("div",{className:"nice-code-editor-ai__explanation-details",children:C.details}),C.complexity&&e.jsxs("span",{className:`nice-code-editor-ai__complexity nice-code-editor-ai__complexity--${C.complexity}`,children:["Complexity: ",C.complexity]}),C.suggestions&&C.suggestions.length>0&&e.jsx("ul",{className:"nice-code-editor-ai__explanation-suggestions",children:C.suggestions.map((L,J)=>e.jsx("li",{children:L},J))})]}),f==="refactor"&&_.length>0&&e.jsx("div",{className:"nice-code-editor-ai__refactorings",children:_.map((L,J)=>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:L.title}),e.jsx("span",{className:`nice-code-editor-ai__refactoring-type nice-code-editor-ai__refactoring-type--${L.type}`,children:L.type})]}),e.jsx("p",{className:"nice-code-editor-ai__refactoring-desc",children:L.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:L.before})]}),e.jsxs("div",{className:"nice-code-editor-ai__refactoring-after",children:[e.jsx("span",{children:"After:"}),e.jsx("pre",{children:L.after})]})]}),e.jsx("button",{type:"button",className:"nice-code-editor-ai__refactoring-apply",onClick:()=>ie(L),children:"Apply"})]},J))}),(f==="tests"||f==="docs")&&y&&e.jsxs("div",{className:"nice-code-editor-ai__generated",children:[e.jsx("pre",{children:y}),e.jsxs("button",{type:"button",onClick:z,children:[e.jsx(A.NiceIcon,{name:"clipboard",size:14})," Copy"]})]})]})]}),e.jsx("style",{children:`
1179
1194
  .nice-code-editor-ai {
1180
1195
  font-family: var(--nice-font-family, system-ui, sans-serif);
1181
1196
  display: flex;
@@ -1481,13 +1496,13 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
1481
1496
  border-radius: var(--nice-radius-md, 6px);
1482
1497
  cursor: pointer;
1483
1498
  }
1484
- `})]}):e.jsxs("div",{className:`nice-code-editor-ai nice-code-editor-ai--disabled ${p||""}`,style:f,children:[e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."}),e.jsx("textarea",{value:y,onChange:R=>M(R.target.value),placeholder:l,className:"nice-code-editor-ai__textarea"})]})}function Ii(t){const i=t.value.substring(0,t.selectionStart).split(`
1485
- `);return{line:i.length-1,column:i[i.length-1].length}}function xa(t={}){const{config:a,context:i,existingRoles:r,existingVariables:n,onWorkflowGenerated:s,onError:c}=t,l=Z(),[p,f]=d.useState(!1),[g,y]=d.useState(null),[w,S]=d.useState([]),z=d.useRef(null),k=a||(l==null?void 0:l.config),I=d.useCallback(async v=>{var u,h,$;if(!k){const D="AI not configured";return c==null||c(D),{error:D}}f(!0);const x=performance.now();(u=z.current)==null||u.abort(),z.current=new AbortController;try{const D=K(k),C=[i,r!=null&&r.length?`Available roles: ${r.join(", ")}`:"",n!=null&&n.length?`Existing variables: ${n.join(", ")}`:""].filter(Boolean).join(`
1486
- `),A=ie(ue,{description:C?`${v}
1499
+ `})]}):e.jsxs("div",{className:`nice-code-editor-ai nice-code-editor-ai--disabled ${h||""}`,style:p,children:[e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."}),e.jsx("textarea",{value:b,onChange:L=>u(L.target.value),placeholder:c,className:"nice-code-editor-ai__textarea"})]})}function Ut(i){const t=i.value.substring(0,i.selectionStart).split(`
1500
+ `);return{line:t.length-1,column:t[t.length-1].length}}function va(i={}){const{config:a,context:t,existingRoles:r,existingVariables:n,onWorkflowGenerated:s,onError:o}=i,c=Z(),[h,p]=d.useState(!1),[m,b]=d.useState(null),[w,k]=d.useState([]),M=d.useRef(null),C=a||(c==null?void 0:c.config),O=d.useCallback(async j=>{var x,v,T;if(!C){const I="AI not configured";return o==null||o(I),{error:I}}p(!0);const g=performance.now();(x=M.current)==null||x.abort(),M.current=new AbortController;try{const I=K(C),N=[t,r!=null&&r.length?`Available roles: ${r.join(", ")}`:"",n!=null&&n.length?`Existing variables: ${n.join(", ")}`:""].filter(Boolean).join(`
1501
+ `),P=ae(pe,{description:N?`${j}
1487
1502
 
1488
- ${C}`:v}),O=await D.chat({messages:[{role:"system",content:A.system},{role:"user",content:A.user}],temperature:.5,maxTokens:2048}),B=De(O),b={workflow:B||void 0,rawResponse:($=(h=O.choices[0])==null?void 0:h.message)==null?void 0:$.content,latencyMs:performance.now()-x,error:B?void 0:"Failed to generate workflow",suggestions:Mi(B)};return B&&(s==null||s(B)),y(b),S(P=>[...P.slice(-9),{request:v,result:b}]),b}catch(D){const C=D instanceof Error?D.message:"Workflow generation failed",A={error:C,latencyMs:performance.now()-x};return y(A),c==null||c(C),A}finally{f(!1)}},[k,i,r,n,s,c]),j=d.useCallback(async v=>{if(!k)return{error:"AI not configured"};f(!0);const x=performance.now();try{const h=await K(k).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:De(h)||void 0,latencyMs:performance.now()-x}}catch(u){return{error:u instanceof Error?u.message:"Optimization failed"}}finally{f(!1)}},[k]),o=d.useCallback(async(v,x)=>{var u,h;if(!k)return[];f(!0);try{const $=K(k),D=v.nodes.find(B=>B.id===x),O=(((h=(u=(await $.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}
1489
- Current node: ${(D==null?void 0:D.label)||x}
1490
- Existing nodes: ${v.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxTokens:512})).choices[0])==null?void 0:u.message)==null?void 0:h.content)||"").match(/\[[\s\S]*\]/);if(O)return JSON.parse(O[0])}catch{}finally{f(!1)}return[]},[k]),N=d.useCallback(async v=>{var x,u;if(!k)return[];f(!0);try{const C=(((u=(x=(await K(k).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:x.message)==null?void 0:u.content)||"").match(/\[[\s\S]*\]/);if(C)return JSON.parse(C[0]).map(O=>`[${O.severity}] ${O.message}`)}catch{}finally{f(!1)}return[]},[k]),_=d.useCallback(()=>{y(null)},[]),m=d.useCallback(()=>{var v;(v=z.current)==null||v.abort(),f(!1)},[]);return d.useEffect(()=>()=>{var v;(v=z.current)==null||v.abort()},[]),{generateWorkflow:I,optimizeWorkflow:j,suggestNextStep:o,validateWorkflow:N,loading:p,lastResult:g,history:w,clearResults:_,abort:m,isConfigured:!!k}}function De(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.nodes&&Array.isArray(l.nodes)){const p={gateway:"gateway-exclusive",event:"event-intermediate"},f=l.nodes.map((w,S)=>({...w,id:w.id||`node_${S}`,label:w.label??w.name??w.id??`Step ${S+1}`,type:p[w.type]??w.type})),g=zi(f),y=f.map((w,S)=>({...w,position:w.position||g[S]}));return{id:l.id||`workflow_${Date.now()}`,name:l.name||"Generated Workflow",description:l.description,version:l.version||"1.0",nodes:y,edges:l.edges||[],lanes:l.lanes??l.swimlanes,variables:l.variables,metadata:l.metadata}}}catch{}return null}function ba(t){return t.type==="start"||t.type==="end"||t.type.startsWith("gateway")?40:Math.round((t.label??"").length*7.2+64)}function zi(t){let n=20,s=40;return t.map(c=>{const l=ba(c);n>20&&n+l>640&&(n=20,s+=110);const p={x:n,y:s};return n+=l+48,p})}function Mi(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 Li=["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 Pi({config:t,context:a,roles:i,onGenerate:r,placeholder:n='Describe the workflow process... (e.g., "Leave request with manager approval")',showExamples:s=!0,showPreview:c=!0,className:l,style:p,renderWorkflow:f}){const[g,y]=d.useState(""),[w,S]=d.useState([]),z=d.useRef(null),{generateWorkflow:k,validateWorkflow:I,loading:j,lastResult:o,isConfigured:N}=xa({config:t,context:a,existingRoles:i,onWorkflowGenerated:r}),_=async()=>{!g.trim()||j||await k(g)},m=u=>{var h;y(u),(h=z.current)==null||h.focus()},v=async()=>{if(!(o!=null&&o.workflow))return;const u=await I(o.workflow);S(u)},x=()=>{if(!(o!=null&&o.workflow))return;const u=Oi(o.workflow),h=new Blob([u],{type:"application/xml"}),$=URL.createObjectURL(h),D=document.createElement("a");D.href=$,D.download=`${o.workflow.name.replace(/\s+/g,"_")}.bpmn`,D.click(),URL.revokeObjectURL($)};return N?e.jsxs("div",{className:`nice-workflow-ai ${l||""}`,style:p,children:[e.jsxs("div",{className:"nice-workflow-ai__input-section",children:[e.jsx("textarea",{ref:z,value:g,onChange:u=>y(u.target.value),placeholder:n,className:"nice-workflow-ai__input",rows:3,disabled:j}),e.jsx("button",{type:"button",onClick:_,className:"nice-workflow-ai__submit",disabled:j||!g.trim(),children:j?e.jsx("span",{className:"nice-workflow-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"refresh",size:14})," Generate Workflow"]})})]}),s&&e.jsxs("div",{className:"nice-workflow-ai__examples",children:[e.jsx("span",{className:"nice-workflow-ai__examples-label",children:"Try:"}),Li.slice(0,3).map((u,h)=>e.jsx("button",{type:"button",className:"nice-workflow-ai__example",onClick:()=>m(u),children:u},h))]}),o&&e.jsx("div",{className:"nice-workflow-ai__result",children:o.error?e.jsx("div",{className:"nice-workflow-ai__error",children:o.error}):o.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:o.workflow.name}),o.workflow.description&&e.jsx("span",{className:"nice-workflow-ai__workflow-desc",children:o.workflow.description})]}),e.jsxs("div",{className:"nice-workflow-ai__result-meta",children:[e.jsxs("span",{className:"nice-workflow-ai__stat",children:[o.workflow.nodes.length," nodes"]}),e.jsxs("span",{className:"nice-workflow-ai__stat",children:[o.workflow.edges.length," connections"]}),o.latencyMs&&e.jsxs("span",{className:"nice-workflow-ai__latency",children:[Math.round(o.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-workflow-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>r==null?void 0:r(o.workflow),children:[e.jsx(L.NiceIcon,{name:"check",size:14})," Use Workflow"]}),e.jsxs("button",{type:"button",onClick:v,children:[e.jsx(L.NiceIcon,{name:"search",size:14})," Validate"]}),e.jsxs("button",{type:"button",onClick:x,children:[e.jsx(L.NiceIcon,{name:"download",size:14})," Export BPMN"]})]}),w.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:w.map((u,h)=>e.jsx("li",{className:`nice-workflow-ai__issue nice-workflow-ai__issue--${u.startsWith("[error]")?"error":u.startsWith("[warning]")?"warning":"info"}`,children:u},h))})]}),c&&e.jsx("div",{className:"nice-workflow-ai__preview",children:f?f(o.workflow):e.jsx($i,{workflow:o.workflow})}),o.suggestions&&o.suggestions.length>0&&e.jsxs("div",{className:"nice-workflow-ai__suggestions",children:[e.jsxs("span",{className:"nice-workflow-ai__suggestions-title",children:[e.jsx(L.NiceIcon,{name:"lightbulb",size:14})," Suggestions:"]}),e.jsx("ul",{children:o.suggestions.map((u,h)=>e.jsx("li",{children:u},h))})]}),e.jsxs("details",{className:"nice-workflow-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(o.workflow,null,2)})]})]})}),e.jsx("style",{children:`
1503
+ ${N}`:j}),$=await I.chat({messages:[{role:"system",content:P.system},{role:"user",content:P.user}],temperature:.5,maxTokens:2048}),D=qe($),F={workflow:D||void 0,rawResponse:(T=(v=$.choices[0])==null?void 0:v.message)==null?void 0:T.content,latencyMs:performance.now()-g,error:D?void 0:"Failed to generate workflow",suggestions:Wt(D)};return D&&(s==null||s(D)),b(F),k(U=>[...U.slice(-9),{request:j,result:F}]),F}catch(I){const N=I instanceof Error?I.message:"Workflow generation failed",P={error:N,latencyMs:performance.now()-g};return b(P),o==null||o(N),P}finally{p(!1)}},[C,t,r,n,s,o]),_=d.useCallback(async j=>{if(!C)return{error:"AI not configured"};p(!0);const g=performance.now();try{const v=await K(C).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(j,null,2)}],temperature:.4,maxTokens:2048});return{workflow:qe(v)||void 0,latencyMs:performance.now()-g}}catch(x){return{error:x instanceof Error?x.message:"Optimization failed"}}finally{p(!1)}},[C]),l=d.useCallback(async(j,g)=>{var x,v;if(!C)return[];p(!0);try{const T=K(C),I=j.nodes.find(D=>D.id===g),$=(((v=(x=(await T.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: ${j.name}
1504
+ Current node: ${(I==null?void 0:I.label)||g}
1505
+ Existing nodes: ${j.nodes.map(D=>D.label).join(", ")}`}],temperature:.6,maxTokens:512})).choices[0])==null?void 0:x.message)==null?void 0:v.content)||"").match(/\[[\s\S]*\]/);if($)return JSON.parse($[0])}catch{}finally{p(!1)}return[]},[C]),y=d.useCallback(async j=>{var g,x;if(!C)return[];p(!0);try{const N=(((x=(g=(await K(C).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(j,null,2)}],temperature:.3,maxTokens:1024})).choices[0])==null?void 0:g.message)==null?void 0:x.content)||"").match(/\[[\s\S]*\]/);if(N)return JSON.parse(N[0]).map($=>`[${$.severity}] ${$.message}`)}catch{}finally{p(!1)}return[]},[C]),S=d.useCallback(()=>{b(null)},[]),f=d.useCallback(()=>{var j;(j=M.current)==null||j.abort(),p(!1)},[]);return d.useEffect(()=>()=>{var j;(j=M.current)==null||j.abort()},[]),{generateWorkflow:O,optimizeWorkflow:_,suggestNextStep:l,validateWorkflow:y,loading:h,lastResult:m,history:w,clearResults:S,abort:f,isConfigured:!!C}}function qe(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.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 h={gateway:"gateway-exclusive",event:"event-intermediate"},p=c.nodes.map((w,k)=>({...w,id:w.id||`node_${k}`,label:w.label??w.name??w.id??`Step ${k+1}`,type:h[w.type]??w.type})),m=Gt(p),b=p.map((w,k)=>({...w,position:w.position||m[k]}));return{id:c.id||`workflow_${Date.now()}`,name:c.name||"Generated Workflow",description:c.description,version:c.version||"1.0",nodes:b,edges:c.edges||[],lanes:c.lanes??c.swimlanes,variables:c.variables,metadata:c.metadata}}}catch{}return null}function _a(i){return i.type==="start"||i.type==="end"||i.type.startsWith("gateway")?40:Math.round((i.label??"").length*7.2+64)}function Gt(i){let n=20,s=40;return i.map(o=>{const c=_a(o);n>20&&n+c>640&&(n=20,s+=110);const h={x:n,y:s};return n+=c+48,h})}function Wt(i){if(!i)return[];const a=[];return i.nodes.some(s=>s.type==="event-error")||a.push("Add error boundary events for critical tasks"),!i.nodes.some(s=>s.type==="gateway-parallel")&&i.nodes.length>5&&a.push("Consider parallel gateways for independent tasks"),(!i.lanes||i.lanes.length===0)&&a.push("Add swimlanes to clarify responsibilities"),i.nodes.some(s=>s.type==="event-timer")||a.push("Add timer events for SLA monitoring"),a.slice(0,3)}const Vt=["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 Kt({config:i,context:a,roles:t,onGenerate:r,placeholder:n='Describe the workflow process... (e.g., "Leave request with manager approval")',showExamples:s=!0,showPreview:o=!0,className:c,style:h,renderWorkflow:p}){const[m,b]=d.useState(""),[w,k]=d.useState([]),M=d.useRef(null),{generateWorkflow:C,validateWorkflow:O,loading:_,lastResult:l,isConfigured:y}=va({config:i,context:a,existingRoles:t,onWorkflowGenerated:r}),S=async()=>{!m.trim()||_||await C(m)},f=x=>{var v;b(x),(v=M.current)==null||v.focus()},j=async()=>{if(!(l!=null&&l.workflow))return;const x=await O(l.workflow);k(x)},g=()=>{if(!(l!=null&&l.workflow))return;const x=Xt(l.workflow),v=new Blob([x],{type:"application/xml"}),T=URL.createObjectURL(v),I=document.createElement("a");I.href=T,I.download=`${l.workflow.name.replace(/\s+/g,"_")}.bpmn`,I.click(),URL.revokeObjectURL(T)};return y?e.jsxs("div",{className:`nice-workflow-ai ${c||""}`,style:h,children:[e.jsxs("div",{className:"nice-workflow-ai__input-section",children:[e.jsx("textarea",{ref:M,value:m,onChange:x=>b(x.target.value),placeholder:n,className:"nice-workflow-ai__input",rows:3,disabled:_}),e.jsx("button",{type:"button",onClick:S,className:"nice-workflow-ai__submit",disabled:_||!m.trim(),children:_?e.jsx("span",{className:"nice-workflow-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(A.NiceIcon,{name:"refresh",size:14})," Generate Workflow"]})})]}),s&&e.jsxs("div",{className:"nice-workflow-ai__examples",children:[e.jsx("span",{className:"nice-workflow-ai__examples-label",children:"Try:"}),Vt.slice(0,3).map((x,v)=>e.jsx("button",{type:"button",className:"nice-workflow-ai__example",onClick:()=>f(x),children:x},v))]}),l&&e.jsx("div",{className:"nice-workflow-ai__result",children:l.error?e.jsx("div",{className:"nice-workflow-ai__error",children:l.error}):l.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:l.workflow.name}),l.workflow.description&&e.jsx("span",{className:"nice-workflow-ai__workflow-desc",children:l.workflow.description})]}),e.jsxs("div",{className:"nice-workflow-ai__result-meta",children:[e.jsxs("span",{className:"nice-workflow-ai__stat",children:[l.workflow.nodes.length," nodes"]}),e.jsxs("span",{className:"nice-workflow-ai__stat",children:[l.workflow.edges.length," connections"]}),l.latencyMs&&e.jsxs("span",{className:"nice-workflow-ai__latency",children:[Math.round(l.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-workflow-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>r==null?void 0:r(l.workflow),children:[e.jsx(A.NiceIcon,{name:"check",size:14})," Use Workflow"]}),e.jsxs("button",{type:"button",onClick:j,children:[e.jsx(A.NiceIcon,{name:"search",size:14})," Validate"]}),e.jsxs("button",{type:"button",onClick:g,children:[e.jsx(A.NiceIcon,{name:"download",size:14})," Export BPMN"]})]}),w.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:w.map((x,v)=>e.jsx("li",{className:`nice-workflow-ai__issue nice-workflow-ai__issue--${x.startsWith("[error]")?"error":x.startsWith("[warning]")?"warning":"info"}`,children:x},v))})]}),o&&e.jsx("div",{className:"nice-workflow-ai__preview",children:p?p(l.workflow):e.jsx(Yt,{workflow:l.workflow})}),l.suggestions&&l.suggestions.length>0&&e.jsxs("div",{className:"nice-workflow-ai__suggestions",children:[e.jsxs("span",{className:"nice-workflow-ai__suggestions-title",children:[e.jsx(A.NiceIcon,{name:"lightbulb",size:14})," Suggestions:"]}),e.jsx("ul",{children:l.suggestions.map((x,v)=>e.jsx("li",{children:x},v))})]}),e.jsxs("details",{className:"nice-workflow-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(l.workflow,null,2)})]})]})}),e.jsx("style",{children:`
1491
1506
  .nice-workflow-ai {
1492
1507
  font-family: var(--nice-font-family, system-ui, sans-serif);
1493
1508
  }
@@ -1751,7 +1766,7 @@ Existing nodes: ${v.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxToken
1751
1766
  color: var(--nice-error, #c62828);
1752
1767
  border-radius: var(--nice-radius-md, 6px);
1753
1768
  }
1754
- `})]}):e.jsx("div",{className:`nice-workflow-ai nice-workflow-ai--disabled ${l||""}`,style:p,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function $i({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(L.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(g=>g.id===r.source),s=t.nodes.find(g=>g.id===r.target);if(!(n!=null&&n.position)||!(s!=null&&s.position))return null;const c=n.position.x+ba(n),l=n.position.y+20,p=s.position.x,f=s.position.y+20;return e.jsxs("g",{children:[e.jsx("line",{x1:c,y1:l,x2:p,y2:f,stroke:"var(--nice-text-secondary, #666)",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),r.label&&e.jsx("text",{x:(c+p)/2,y:(l+f)/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:h,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Yt({workflow:i}){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",t=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:[i.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:t(r.type)},children:[e.jsx("span",{className:"workflow-preview__node-icon",children:e.jsx(A.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:[i.edges.map(r=>{const n=i.nodes.find(m=>m.id===r.source),s=i.nodes.find(m=>m.id===r.target);if(!(n!=null&&n.position)||!(s!=null&&s.position))return null;const o=n.position.x+_a(n),c=n.position.y+20,h=s.position.x,p=s.position.y+20;return e.jsxs("g",{children:[e.jsx("line",{x1:o,y1:c,x2:h,y2:p,stroke:"var(--nice-text-secondary, #666)",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),r.label&&e.jsx("text",{x:(o+h)/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)"})})})]})]}),i.lanes&&i.lanes.length>0&&e.jsxs("div",{className:"workflow-preview__lanes",children:[e.jsx("span",{className:"workflow-preview__lanes-title",children:"Swimlanes:"}),i.lanes.map(r=>e.jsx("span",{className:"workflow-preview__lane",children:r.name},r.id))]}),e.jsx("style",{children:`
1755
1770
  .workflow-preview {
1756
1771
  min-height: 200px;
1757
1772
  }
@@ -1856,23 +1871,23 @@ Existing nodes: ${v.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxToken
1856
1871
  border-radius: var(--nice-radius-sm, 4px);
1857
1872
  font-size: 12px;
1858
1873
  }
1859
- `})]})}function Oi(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="${fe(n.label)}" />`).join(`
1860
- `),r=t.edges.map(n=>` <bpmn:sequenceFlow id="${n.id}" sourceRef="${n.source}" targetRef="${n.target}"${n.label?` name="${fe(n.label)}"`:""} />`).join(`
1874
+ `})]})}function Xt(i){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"},t=i.nodes.map(n=>` <${a[n.type]||"bpmn:task"} id="${n.id}" name="${xe(n.label)}" />`).join(`
1875
+ `),r=i.edges.map(n=>` <bpmn:sequenceFlow id="${n.id}" sourceRef="${n.source}" targetRef="${n.target}"${n.label?` name="${xe(n.label)}"`:""} />`).join(`
1861
1876
  `);return`<?xml version="1.0" encoding="UTF-8"?>
1862
1877
  <bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL"
1863
1878
  xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
1864
- id="${t.id}"
1879
+ id="${i.id}"
1865
1880
  targetNamespace="http://nice2dev.com/bpmn">
1866
- <bpmn:process id="Process_${t.id}" name="${fe(t.name)}" isExecutable="true">
1867
- ${i}
1881
+ <bpmn:process id="Process_${i.id}" name="${xe(i.name)}" isExecutable="true">
1882
+ ${t}
1868
1883
  ${r}
1869
1884
  </bpmn:process>
1870
- </bpmn:definitions>`}function fe(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function ya(t={}){const{config:a,dataSources:i,context:r,onReportGenerated:n,onError:s}=t,c=Z(),[l,p]=d.useState(!1),[f,g]=d.useState(null),[y,w]=d.useState([]),S=d.useRef(null),z=a||(c==null?void 0:c.config),k=d.useCallback(async m=>{var x,u,h;if(!z){const $="AI not configured";return s==null||s($),{error:$}}p(!0);const v=performance.now();(x=S.current)==null||x.abort(),S.current=new AbortController;try{const $=K(z),D=i?i.map(b=>`- ${b.name} (${b.id}): ${b.fields.join(", ")}`).join(`
1871
- `):void 0,C=ie(pe,{description:r?`${m}
1885
+ </bpmn:definitions>`}function xe(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function wa(i={}){const{config:a,dataSources:t,context:r,onReportGenerated:n,onError:s}=i,o=Z(),[c,h]=d.useState(!1),[p,m]=d.useState(null),[b,w]=d.useState([]),k=d.useRef(null),M=a||(o==null?void 0:o.config),C=d.useCallback(async f=>{var g,x,v;if(!M){const T="AI not configured";return s==null||s(T),{error:T}}h(!0);const j=performance.now();(g=k.current)==null||g.abort(),k.current=new AbortController;try{const T=K(M),I=t?t.map(F=>`- ${F.name} (${F.id}): ${F.fields.join(", ")}`).join(`
1886
+ `):void 0,N=ae(me,{description:r?`${f}
1872
1887
 
1873
- Context: ${r}`:m,dataSources:D}),A=await $.chat({messages:[{role:"system",content:C.system},{role:"user",content:C.user}],temperature:.5,maxTokens:2048}),O=Bi(A),B={layout:O||void 0,rawResponse:(h=(u=A.choices[0])==null?void 0:u.message)==null?void 0:h.content,latencyMs:performance.now()-v,error:O?void 0:"Failed to generate report layout",suggestions:Fi(O)};return O&&(n==null||n(O)),g(B),w(b=>[...b.slice(-9),{request:m,result:B}]),B}catch($){const D=$ instanceof Error?$.message:"Report generation failed",C={error:D,latencyMs:performance.now()-v};return g(C),s==null||s(D),C}finally{p(!1)}},[z,i,r,n,s]),I=d.useCallback(async m=>{var v,x;if(!z)return[];p(!0);try{const D=(((x=(v=(await K(z).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: ${m.name}
1874
- Existing sections: ${m.sections.map(C=>C.type).join(", ")}`}],temperature:.6,maxTokens:1024})).choices[0])==null?void 0:v.message)==null?void 0:x.content)||"").match(/\[[\s\S]*\]/);if(D)return JSON.parse(D[0])}catch{}finally{p(!1)}return[]},[z]),j=d.useCallback(async m=>{var v,x;if(!z)return null;p(!0);try{return((x=(v=(await K(z).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(m,null,2)}],temperature:.5,maxTokens:512})).choices[0])==null?void 0:v.message)==null?void 0:x.content)||null}catch{return null}finally{p(!1)}},[z]),o=d.useCallback(async(m,v)=>{var x,u,h;if(!z)return"bar";try{const $=K(z),D=m.slice(0,5),A=(h=(u=(x=(await $.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(D)}
1875
- Purpose: ${v}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:x.message)==null?void 0:u.content)==null?void 0:h.toLowerCase().trim();return["line","bar","pie","donut","area","column","scatter","combo","gauge","heatmap"].find(B=>A==null?void 0:A.includes(B))||"bar"}catch{return"bar"}},[z]),N=d.useCallback(()=>{g(null)},[]),_=d.useCallback(()=>{var m;(m=S.current)==null||m.abort(),p(!1)},[]);return d.useEffect(()=>()=>{var m;(m=S.current)==null||m.abort()},[]),{generateReport:k,suggestSections:I,generateSummary:j,suggestChartType:o,loading:l,lastResult:f,history:y,clearResults:N,abort:_,isConfigured:!!z}}const Ei=new Set(["header","summary","kpi","table","chart","text","image","divider","spacer","pageBreak","footer","toc","customBlock"]),Di={title:"header",subtitle:"text","kpi-card":"kpi",metric:"kpi","pivot-table":"table","page-break":"pageBreak","section-break":"divider",logo:"image"};function Be(t){const a=typeof t=="string"?t:"";return Di[a]??(Ei.has(a)?a:"customBlock")}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)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.sections&&Array.isArray(l.sections)){const p=l.sections.flatMap(g=>Array.isArray(g.elements)&&!g.type?g.elements.map((y,w)=>({type:Be(y.type),title:w===0?g.title:void 0,config:y.config??{}})):[{...g,type:Be(g.type)}]);l.header&&!p.some(g=>g.type==="header")&&p.unshift({type:"header",title:"Header",config:l.header}),l.footer&&!p.some(g=>g.type==="footer")&&p.push({type:"footer",title:"Footer",config:l.footer});const f=p.map((g,y)=>({...g,id:g.id||`section_${y}`,order:g.order??y,config:g.config||{}}));return{id:l.id||`report_${Date.now()}`,name:l.name||l.title||"Generated Report",description:l.description,orientation:l.orientation||"portrait",pageSize:l.pageSize||"A4",margins:l.margins||{top:20,right:20,bottom:20,left:20},sections:f,dataSources:l.dataSources,parameters:l.parameters,styles:l.styles}}}catch{}return null}function Fi(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 Ji=[{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 Ui({config:t,dataSources:a,context:i,onGenerate:r,placeholder:n='Describe the report you need... (e.g., "Monthly sales report with KPIs and charts")',showTemplates:s=!0,showPreview:c=!0,className:l,style:p,renderReport:f}){const[g,y]=d.useState(""),w=d.useRef(null),{generateReport:S,loading:z,lastResult:k,isConfigured:I}=ya({config:t,dataSources:a,context:i,onReportGenerated:r}),j=async()=>{!g.trim()||z||await S(g)},o=_=>{var m;y(_.prompt),(m=w.current)==null||m.focus()},N=()=>{if(!(k!=null&&k.layout))return;const _=JSON.stringify(k.layout,null,2),m=new Blob([_],{type:"application/json"}),v=URL.createObjectURL(m),x=document.createElement("a");x.href=v,x.download=`${k.layout.name.replace(/\s+/g,"_")}.json`,x.click(),URL.revokeObjectURL(v)};return I?e.jsxs("div",{className:`nice-report-ai ${l||""}`,style:p,children:[s&&e.jsx("div",{className:"nice-report-ai__templates",children:Ji.map((_,m)=>e.jsxs("button",{type:"button",className:"nice-report-ai__template",onClick:()=>o(_),children:[e.jsx("span",{className:"nice-report-ai__template-icon",children:e.jsx(L.NiceIcon,{name:_.icon,size:24})}),e.jsx("span",{className:"nice-report-ai__template-name",children:_.name})]},m))}),e.jsxs("div",{className:"nice-report-ai__input-section",children:[e.jsx("textarea",{ref:w,value:g,onChange:_=>y(_.target.value),placeholder:n,className:"nice-report-ai__input",rows:3,disabled:z}),e.jsx("button",{type:"button",onClick:j,className:"nice-report-ai__submit",disabled:z||!g.trim(),children:z?e.jsx("span",{className:"nice-report-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"file",size:14})," 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(_=>e.jsx("span",{className:"nice-report-ai__datasource",children:_.name},_.id))]}),k&&e.jsx("div",{className:"nice-report-ai__result",children:k.error?e.jsx("div",{className:"nice-report-ai__error",children:k.error}):k.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:k.layout.name}),k.layout.description&&e.jsx("span",{className:"nice-report-ai__report-desc",children:k.layout.description})]}),e.jsxs("div",{className:"nice-report-ai__result-meta",children:[e.jsxs("span",{className:"nice-report-ai__stat",children:[k.layout.sections.length," sections"]}),e.jsxs("span",{className:"nice-report-ai__stat",children:[k.layout.pageSize," ",k.layout.orientation]}),k.latencyMs&&e.jsxs("span",{className:"nice-report-ai__latency",children:[Math.round(k.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-report-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>r==null?void 0:r(k.layout),children:[e.jsx(L.NiceIcon,{name:"check",size:14})," Use Report"]}),e.jsxs("button",{type:"button",onClick:N,children:[e.jsx(L.NiceIcon,{name:"download",size:14})," 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:k.layout.sections.map((_,m)=>e.jsxs("div",{className:"nice-report-ai__section",children:[e.jsx("span",{className:"nice-report-ai__section-number",children:m+1}),e.jsx("span",{className:"nice-report-ai__section-icon",children:e.jsx(L.NiceIcon,{name:va(_.type),size:16})}),e.jsx("span",{className:"nice-report-ai__section-type",children:_.type}),_.title&&e.jsx("span",{className:"nice-report-ai__section-title",children:_.title})]},_.id))})]}),c&&e.jsx("div",{className:"nice-report-ai__preview",children:f?f(k.layout):e.jsx(qi,{layout:k.layout})}),k.suggestions&&k.suggestions.length>0&&e.jsxs("div",{className:"nice-report-ai__suggestions",children:[e.jsxs("span",{className:"nice-report-ai__suggestions-title",children:[e.jsx(L.NiceIcon,{name:"lightbulb",size:14})," Suggestions:"]}),e.jsx("ul",{children:k.suggestions.map((_,m)=>e.jsx("li",{children:_},m))})]}),e.jsxs("details",{className:"nice-report-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(k.layout,null,2)})]})]})}),e.jsx("style",{children:`
1888
+ Context: ${r}`:f,dataSources:I}),P=await T.chat({messages:[{role:"system",content:N.system},{role:"user",content:N.user}],temperature:.5,maxTokens:2048}),$=ei(P),D={layout:$||void 0,rawResponse:(v=(x=P.choices[0])==null?void 0:x.message)==null?void 0:v.content,latencyMs:performance.now()-j,error:$?void 0:"Failed to generate report layout",suggestions:ai($)};return $&&(n==null||n($)),m(D),w(F=>[...F.slice(-9),{request:f,result:D}]),D}catch(T){const I=T instanceof Error?T.message:"Report generation failed",N={error:I,latencyMs:performance.now()-j};return m(N),s==null||s(I),N}finally{h(!1)}},[M,t,r,n,s]),O=d.useCallback(async f=>{var j,g;if(!M)return[];h(!0);try{const I=(((g=(j=(await K(M).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: ${f.name}
1889
+ Existing sections: ${f.sections.map(N=>N.type).join(", ")}`}],temperature:.6,maxTokens:1024})).choices[0])==null?void 0:j.message)==null?void 0:g.content)||"").match(/\[[\s\S]*\]/);if(I)return JSON.parse(I[0])}catch{}finally{h(!1)}return[]},[M]),_=d.useCallback(async f=>{var j,g;if(!M)return null;h(!0);try{return((g=(j=(await K(M).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(f,null,2)}],temperature:.5,maxTokens:512})).choices[0])==null?void 0:j.message)==null?void 0:g.content)||null}catch{return null}finally{h(!1)}},[M]),l=d.useCallback(async(f,j)=>{var g,x,v;if(!M)return"bar";try{const T=K(M),I=f.slice(0,5),P=(v=(x=(g=(await T.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(I)}
1890
+ Purpose: ${j}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:g.message)==null?void 0:x.content)==null?void 0:v.toLowerCase().trim();return["line","bar","pie","donut","area","column","scatter","combo","gauge","heatmap"].find(D=>P==null?void 0:P.includes(D))||"bar"}catch{return"bar"}},[M]),y=d.useCallback(()=>{m(null)},[]),S=d.useCallback(()=>{var f;(f=k.current)==null||f.abort(),h(!1)},[]);return d.useEffect(()=>()=>{var f;(f=k.current)==null||f.abort()},[]),{generateReport:C,suggestSections:O,generateSummary:_,suggestChartType:l,loading:c,lastResult:p,history:b,clearResults:y,abort:S,isConfigured:!!M}}const Qt=new Set(["header","summary","kpi","table","chart","text","image","divider","spacer","pageBreak","footer","toc","customBlock"]),Zt={title:"header",subtitle:"text","kpi-card":"kpi",metric:"kpi","pivot-table":"table","page-break":"pageBreak","section-break":"divider",logo:"image"};function Je(i){const a=typeof i=="string"?i:"";return Zt[a]??(Qt.has(a)?a:"customBlock")}function ei(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.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 h=c.sections.flatMap(m=>Array.isArray(m.elements)&&!m.type?m.elements.map((b,w)=>({type:Je(b.type),title:w===0?m.title:void 0,config:b.config??{}})):[{...m,type:Je(m.type)}]);c.header&&!h.some(m=>m.type==="header")&&h.unshift({type:"header",title:"Header",config:c.header}),c.footer&&!h.some(m=>m.type==="footer")&&h.push({type:"footer",title:"Footer",config:c.footer});const p=h.map((m,b)=>({...m,id:m.id||`section_${b}`,order:m.order??b,config:m.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 ai(i){if(!i)return[];const a=[],t=new Set(i.sections.map(r=>r.type));return t.has("summary")||a.push("Add an executive summary for quick insights"),t.has("kpi")||a.push("Include KPI cards for key metrics"),t.has("chart")||a.push("Add visualizations to make data more accessible"),t.has("footer")||a.push("Add a footer with page numbers and date"),i.sections.length>5&&!t.has("toc")&&a.push("Consider adding a table of contents"),a.slice(0,3)}const ti=[{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 ii({config:i,dataSources:a,context:t,onGenerate:r,placeholder:n='Describe the report you need... (e.g., "Monthly sales report with KPIs and charts")',showTemplates:s=!0,showPreview:o=!0,className:c,style:h,renderReport:p}){const[m,b]=d.useState(""),w=d.useRef(null),{generateReport:k,loading:M,lastResult:C,isConfigured:O}=wa({config:i,dataSources:a,context:t,onReportGenerated:r}),_=async()=>{!m.trim()||M||await k(m)},l=S=>{var f;b(S.prompt),(f=w.current)==null||f.focus()},y=()=>{if(!(C!=null&&C.layout))return;const S=JSON.stringify(C.layout,null,2),f=new Blob([S],{type:"application/json"}),j=URL.createObjectURL(f),g=document.createElement("a");g.href=j,g.download=`${C.layout.name.replace(/\s+/g,"_")}.json`,g.click(),URL.revokeObjectURL(j)};return O?e.jsxs("div",{className:`nice-report-ai ${c||""}`,style:h,children:[s&&e.jsx("div",{className:"nice-report-ai__templates",children:ti.map((S,f)=>e.jsxs("button",{type:"button",className:"nice-report-ai__template",onClick:()=>l(S),children:[e.jsx("span",{className:"nice-report-ai__template-icon",children:e.jsx(A.NiceIcon,{name:S.icon,size:24})}),e.jsx("span",{className:"nice-report-ai__template-name",children:S.name})]},f))}),e.jsxs("div",{className:"nice-report-ai__input-section",children:[e.jsx("textarea",{ref:w,value:m,onChange:S=>b(S.target.value),placeholder:n,className:"nice-report-ai__input",rows:3,disabled:M}),e.jsx("button",{type:"button",onClick:_,className:"nice-report-ai__submit",disabled:M||!m.trim(),children:M?e.jsx("span",{className:"nice-report-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(A.NiceIcon,{name:"file",size:14})," 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(S=>e.jsx("span",{className:"nice-report-ai__datasource",children:S.name},S.id))]}),C&&e.jsx("div",{className:"nice-report-ai__result",children:C.error?e.jsx("div",{className:"nice-report-ai__error",children:C.error}):C.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:C.layout.name}),C.layout.description&&e.jsx("span",{className:"nice-report-ai__report-desc",children:C.layout.description})]}),e.jsxs("div",{className:"nice-report-ai__result-meta",children:[e.jsxs("span",{className:"nice-report-ai__stat",children:[C.layout.sections.length," sections"]}),e.jsxs("span",{className:"nice-report-ai__stat",children:[C.layout.pageSize," ",C.layout.orientation]}),C.latencyMs&&e.jsxs("span",{className:"nice-report-ai__latency",children:[Math.round(C.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-report-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>r==null?void 0:r(C.layout),children:[e.jsx(A.NiceIcon,{name:"check",size:14})," Use Report"]}),e.jsxs("button",{type:"button",onClick:y,children:[e.jsx(A.NiceIcon,{name:"download",size:14})," 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:C.layout.sections.map((S,f)=>e.jsxs("div",{className:"nice-report-ai__section",children:[e.jsx("span",{className:"nice-report-ai__section-number",children:f+1}),e.jsx("span",{className:"nice-report-ai__section-icon",children:e.jsx(A.NiceIcon,{name:ja(S.type),size:16})}),e.jsx("span",{className:"nice-report-ai__section-type",children:S.type}),S.title&&e.jsx("span",{className:"nice-report-ai__section-title",children:S.title})]},S.id))})]}),o&&e.jsx("div",{className:"nice-report-ai__preview",children:p?p(C.layout):e.jsx(ri,{layout:C.layout})}),C.suggestions&&C.suggestions.length>0&&e.jsxs("div",{className:"nice-report-ai__suggestions",children:[e.jsxs("span",{className:"nice-report-ai__suggestions-title",children:[e.jsx(A.NiceIcon,{name:"lightbulb",size:14})," Suggestions:"]}),e.jsx("ul",{children:C.suggestions.map((S,f)=>e.jsx("li",{children:S},f))})]}),e.jsxs("details",{className:"nice-report-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(C.layout,null,2)})]})]})}),e.jsx("style",{children:`
1876
1891
  .nice-report-ai {
1877
1892
  font-family: var(--nice-font-family, system-ui, sans-serif);
1878
1893
  }
@@ -2184,7 +2199,7 @@ Purpose: ${v}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:x.messa
2184
2199
  color: var(--nice-error, #c62828);
2185
2200
  border-radius: var(--nice-radius-md, 6px);
2186
2201
  }
2187
- `})]}):e.jsx("div",{className:`nice-report-ai nice-report-ai--disabled ${l||""}`,style:p,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function va(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 qi({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(L.NiceIcon,{name:va(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:h,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function ja(i){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"}[i]||"file"}function ri({layout:i}){return e.jsxs("div",{className:"report-preview",style:{aspectRatio:i.orientation==="landscape"?"1.414":"0.707",maxWidth:i.orientation==="landscape"?"100%":"60%"},children:[e.jsx("div",{className:"report-preview__paper",children:i.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(A.NiceIcon,{name:ja(a.type),size:14})}),e.jsx("span",{className:"report-preview__section-label",children:a.title||a.type})]},a.id))}),e.jsx("style",{children:`
2188
2203
  .report-preview {
2189
2204
  display: flex;
2190
2205
  justify-content: center;
@@ -2264,7 +2279,7 @@ Purpose: ${v}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:x.messa
2264
2279
  text-overflow: ellipsis;
2265
2280
  white-space: nowrap;
2266
2281
  }
2267
- `})]})}function Hi(t,a){return{system:`You are a UI/UX designer specializing in design systems. Create a complete theme for the request, with WCAG 2.1 AA contrast (4.5:1 for text).
2282
+ `})]})}function ni(i,a){return{system:`You are a UI/UX designer specializing in design systems. Create a complete theme for the request, with WCAG 2.1 AA contrast (4.5:1 for text).
2268
2283
  Return only JSON: ${a?'{ "light": THEME, "dark": THEME }, the dark one with "mode": "dark",':'{ "light": THEME },'} where THEME is
2269
2284
  {
2270
2285
  "name": "Theme name",
@@ -2279,19 +2294,19 @@ Return only JSON: ${a?'{ "light": THEME, "dark": THEME }, the dark one with "mod
2279
2294
  },
2280
2295
  "typography": { "fontFamily": "...", "fontFamilyMono": "..." },
2281
2296
  "borderRadius": { "sm": "4px", "md": "8px", "lg": "12px" }
2282
- }`,user:t}}function _a(t={}){const{config:a,generateDarkMode:i=!0,onThemeGenerated:r,onError:n}=t,s=Z(),[c,l]=d.useState(!1),[p,f]=d.useState(null),g=d.useRef(null),y=a||(s==null?void 0:s.config),w=d.useCallback(async o=>{var _,m,v,x;if(!y){const u="AI not configured";return n==null||n(u),{error:u}}l(!0);const N=performance.now();(_=g.current)==null||_.abort(),g.current=new AbortController;try{const u=K(y);let h="";switch(o.type){case"description":h=o.value;break;case"brand":h=`Create a theme for "${o.value.name}"${o.value.industry?` in the ${o.value.industry} industry`:""}${(m=o.value.keywords)!=null&&m.length?`. Keywords: ${o.value.keywords.join(", ")}`:""}`;break;case"colors":h=`Create a theme based on primary color ${o.value.primary}${o.value.secondary?` and secondary color ${o.value.secondary}`:""}`;break;case"image":h="Extract colors and create a theme from the provided image palette";break}const $=Hi(h,i),D=await u.chat({messages:[{role:"system",content:$.system},{role:"user",content:$.user}],temperature:.6,maxTokens:2048}),C=Fe(D),A={theme:C.light||void 0,darkTheme:C.dark||void 0,rawResponse:(x=(v=D.choices[0])==null?void 0:v.message)==null?void 0:x.content,latencyMs:performance.now()-N,error:C.light?void 0:"Failed to generate theme",suggestions:Wi(C.light)};return C.light&&(r==null||r(C.light,C.dark??void 0)),f(A),A}catch(u){const h=u instanceof Error?u.message:"Theme generation failed",$={error:h,latencyMs:performance.now()-N};return f($),n==null||n(h),$}finally{l(!1)}},[y,i,r,n]),S=d.useCallback(async(o,N)=>{if(!y)return null;l(!0);try{const m=await K(y).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:
2283
- ${JSON.stringify(o,null,2)}
2284
-
2285
- Adjustments: ${N}`}],temperature:.4,maxTokens:2048});return Fe(m).light||null}catch{return null}finally{l(!1)}},[y]),z=d.useCallback(o=>{const N=[];return N.push(" /* Colors */"),Object.entries(o.colors).forEach(([_,m])=>{N.push(` --nice-${be(_)}: ${m};`)}),N.push(`
2286
- /* Typography */`),Object.entries(o.typography).forEach(([_,m])=>{N.push(` --nice-${be(_)}: ${m};`)}),N.push(`
2287
- /* Spacing */`),Object.entries(o.spacing).forEach(([_,m])=>{N.push(` --nice-spacing-${_}: ${m};`)}),N.push(`
2288
- /* Border Radius */`),Object.entries(o.borderRadius).forEach(([_,m])=>{N.push(` --nice-radius-${_}: ${m};`)}),N.push(`
2289
- /* Shadows */`),Object.entries(o.shadows).forEach(([_,m])=>{N.push(` --nice-shadow-${_}: ${m};`)}),N.push(`
2290
- /* Animations */`),Object.entries(o.animations).forEach(([_,m])=>{N.push(` --nice-${be(_)}: ${m};`)}),`:root {
2291
- ${N.join(`
2297
+ }`,user:i}}function ka(i={}){const{config:a,generateDarkMode:t=!0,onThemeGenerated:r,onError:n}=i,s=Z(),[o,c]=d.useState(!1),[h,p]=d.useState(null),m=d.useRef(null),b=a||(s==null?void 0:s.config),w=d.useCallback(async l=>{var S,f,j,g;if(!b){const x="AI not configured";return n==null||n(x),{error:x}}c(!0);const y=performance.now();(S=m.current)==null||S.abort(),m.current=new AbortController;try{const x=K(b);let v="";switch(l.type){case"description":v=l.value;break;case"brand":v=`Create a theme for "${l.value.name}"${l.value.industry?` in the ${l.value.industry} industry`:""}${(f=l.value.keywords)!=null&&f.length?`. Keywords: ${l.value.keywords.join(", ")}`:""}`;break;case"colors":v=`Create a theme based on primary color ${l.value.primary}${l.value.secondary?` and secondary color ${l.value.secondary}`:""}`;break;case"image":v="Extract colors and create a theme from the provided image palette";break}const T=ni(v,t),I=await x.chat({messages:[{role:"system",content:T.system},{role:"user",content:T.user}],temperature:.6,maxTokens:2048}),N=He(I),P={theme:N.light||void 0,darkTheme:N.dark||void 0,rawResponse:(g=(j=I.choices[0])==null?void 0:j.message)==null?void 0:g.content,latencyMs:performance.now()-y,error:N.light?void 0:"Failed to generate theme",suggestions:si(N.light)};return N.light&&(r==null||r(N.light,N.dark??void 0)),p(P),P}catch(x){const v=x instanceof Error?x.message:"Theme generation failed",T={error:v,latencyMs:performance.now()-y};return p(T),n==null||n(v),T}finally{c(!1)}},[b,t,r,n]),k=d.useCallback(async(l,y)=>{if(!b)return null;c(!0);try{const f=await K(b).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(l,null,2)}
2299
+
2300
+ Adjustments: ${y}`}],temperature:.4,maxTokens:2048});return He(f).light||null}catch{return null}finally{c(!1)}},[b]),M=d.useCallback(l=>{const y=[];return y.push(" /* Colors */"),Object.entries(l.colors).forEach(([S,f])=>{y.push(` --nice-${ye(S)}: ${f};`)}),y.push(`
2301
+ /* Typography */`),Object.entries(l.typography).forEach(([S,f])=>{y.push(` --nice-${ye(S)}: ${f};`)}),y.push(`
2302
+ /* Spacing */`),Object.entries(l.spacing).forEach(([S,f])=>{y.push(` --nice-spacing-${S}: ${f};`)}),y.push(`
2303
+ /* Border Radius */`),Object.entries(l.borderRadius).forEach(([S,f])=>{y.push(` --nice-radius-${S}: ${f};`)}),y.push(`
2304
+ /* Shadows */`),Object.entries(l.shadows).forEach(([S,f])=>{y.push(` --nice-shadow-${S}: ${f};`)}),y.push(`
2305
+ /* Animations */`),Object.entries(l.animations).forEach(([S,f])=>{y.push(` --nice-${ye(S)}: ${f};`)}),`:root {
2306
+ ${y.join(`
2292
2307
  `)}
2293
- }`},[]),k=d.useCallback(o=>{const N={theme:{extend:{colors:{primary:{DEFAULT:o.colors.primary,light:o.colors.primaryLight,dark:o.colors.primaryDark},secondary:{DEFAULT:o.colors.secondary,light:o.colors.secondaryLight,dark:o.colors.secondaryDark},accent:o.colors.accent,success:o.colors.success,warning:o.colors.warning,error:o.colors.error,info:o.colors.info},fontFamily:{sans:[o.typography.fontFamily],mono:[o.typography.fontFamilyMono]},borderRadius:o.borderRadius,boxShadow:o.shadows}}};return`// tailwind.config.js
2294
- module.exports = ${JSON.stringify(N,null,2)}`},[]),I=d.useCallback(()=>{f(null)},[]),j=d.useCallback(()=>{var o;(o=g.current)==null||o.abort(),l(!1)},[]);return d.useEffect(()=>()=>{var o;(o=g.current)==null||o.abort()},[]),{generateTheme:w,adjustTheme:S,toCSSVariables:z,toTailwindConfig:k,loading:c,lastResult:p,clearResults:I,abort:j,isConfigured:!!y}}function Fe(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.light||l.theme)return{light:xe(l.light||l.theme),dark:l.dark?xe(l.dark):null};if(l.colors)return{light:xe(l),dark:null}}catch{}return{light:null,dark:null}}function xe(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 Wi(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 be(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}const Gi=[{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 Vi({config:t,generateDarkMode:a=!0,onGenerate:i,showPresets:r=!0,showPreview:n=!0,className:s,style:c}){const[l,p]=d.useState("description"),[f,g]=d.useState(""),[y,w]=d.useState(""),[S,z]=d.useState(""),[k,I]=d.useState("#0066cc"),[j,o]=d.useState("light"),{generateTheme:N,toCSSVariables:_,toTailwindConfig:m,loading:v,lastResult:x,isConfigured:u}=_a({config:t,generateDarkMode:a,onThemeGenerated:i}),h=async()=>{if(v)return;let O;switch(l){case"brand":if(!y.trim())return;O={type:"brand",value:{name:y,industry:S||void 0}};break;case"colors":O={type:"colors",value:{primary:k}};break;default:if(!f.trim())return;O={type:"description",value:f}}await N(O)},$=O=>{p("description"),g(O.prompt)},D=()=>{if(!(x!=null&&x.theme))return;const O=_(x.theme),B=new Blob([O],{type:"text/css"}),b=URL.createObjectURL(B),P=document.createElement("a");P.href=b,P.download=`${x.theme.name.replace(/\s+/g,"-").toLowerCase()}.css`,P.click(),URL.revokeObjectURL(b)},C=()=>{if(!(x!=null&&x.theme))return;const O=m(x.theme),B=new Blob([O],{type:"text/javascript"}),b=URL.createObjectURL(B),P=document.createElement("a");P.href=b,P.download="tailwind.config.js",P.click(),URL.revokeObjectURL(b)},A=j==="dark"&&(x!=null&&x.darkTheme)?x.darkTheme:x==null?void 0:x.theme;return u?e.jsxs("div",{className:`nice-theme-ai ${s||""}`,style:c,children:[r&&e.jsx("div",{className:"nice-theme-ai__presets",children:Gi.map((O,B)=>e.jsxs("button",{type:"button",className:"nice-theme-ai__preset",onClick:()=>$(O),children:[e.jsx("span",{className:"nice-theme-ai__preset-icon",children:e.jsx(L.NiceIcon,{name:O.icon,size:24})}),e.jsx("span",{className:"nice-theme-ai__preset-name",children:O.name})]},B))}),e.jsxs("div",{className:"nice-theme-ai__tabs",children:[e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${l==="description"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("description"),children:[e.jsx(L.NiceIcon,{name:"edit",size:14})," Description"]}),e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${l==="brand"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("brand"),children:[e.jsx(L.NiceIcon,{name:"tag",size:14})," Brand"]}),e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${l==="colors"?"nice-theme-ai__tab--active":""}`,onClick:()=>p("colors"),children:[e.jsx(L.NiceIcon,{name:"palette",size:14})," Colors"]})]}),e.jsxs("div",{className:"nice-theme-ai__input-section",children:[l==="description"&&e.jsx("textarea",{value:f,onChange:O=>g(O.target.value),placeholder:"Describe the theme you want... (e.g., 'Modern tech startup with blue and green')",className:"nice-theme-ai__textarea",rows:3,disabled:v}),l==="brand"&&e.jsxs("div",{className:"nice-theme-ai__brand-inputs",children:[e.jsx("input",{type:"text",value:y,onChange:O=>w(O.target.value),placeholder:"Brand name",className:"nice-theme-ai__input",disabled:v}),e.jsx("input",{type:"text",value:S,onChange:O=>z(O.target.value),placeholder:"Industry (optional)",className:"nice-theme-ai__input",disabled:v})]}),l==="colors"&&e.jsx("div",{className:"nice-theme-ai__color-input",children:e.jsxs("label",{children:["Primary Color:",e.jsx("input",{type:"color",value:k,onChange:O=>I(O.target.value),className:"nice-theme-ai__color-picker",disabled:v}),e.jsx("span",{className:"nice-theme-ai__color-value",children:k})]})}),e.jsx("button",{type:"button",onClick:h,className:"nice-theme-ai__submit",disabled:v,children:v?e.jsx("span",{className:"nice-theme-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"wand",size:14})," Generate Theme"]})})]}),(x==null?void 0:x.error)&&e.jsx("div",{className:"nice-theme-ai__error",role:"alert",children:x.error}),x&&A&&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:A.name}),A.description&&e.jsx("span",{className:"nice-theme-ai__theme-desc",children:A.description})]}),e.jsxs("div",{className:"nice-theme-ai__actions",children:[x.darkTheme&&e.jsxs("div",{className:"nice-theme-ai__mode-toggle",children:[e.jsx("button",{type:"button","aria-label":"Light mode",className:j==="light"?"active":"",onClick:()=>o("light"),children:e.jsx(L.NiceIcon,{name:"sun",size:16})}),e.jsx("button",{type:"button","aria-label":"Dark mode",className:j==="dark"?"active":"",onClick:()=>o("dark"),children:e.jsx(L.NiceIcon,{name:"moon",size:16})})]}),e.jsxs("button",{type:"button",onClick:D,children:[e.jsx(L.NiceIcon,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:C,children:[e.jsx(L.NiceIcon,{name:"download",size:14})," Tailwind"]})]})]}),n&&e.jsx(Ki,{theme:A}),e.jsxs("div",{className:"nice-theme-ai__palette",children:[e.jsx("div",{className:"nice-theme-ai__palette-title",children:"Color Palette"}),e.jsx("div",{className:"nice-theme-ai__colors",children:Object.entries(A.colors).map(([O,B])=>e.jsxs("div",{className:"nice-theme-ai__color",children:[e.jsx("div",{className:"nice-theme-ai__color-swatch",style:{backgroundColor:B}}),e.jsx("span",{className:"nice-theme-ai__color-name",children:O}),e.jsx("span",{className:"nice-theme-ai__color-hex",children:B})]},O))})]}),e.jsxs("div",{className:"nice-theme-ai__typography",children:[e.jsx("div",{className:"nice-theme-ai__typography-title",children:"Typography"}),e.jsxs("div",{style:{fontFamily:A.typography.fontFamily},children:[e.jsx("p",{style:{fontSize:A.typography.fontSize3xl,fontWeight:A.typography.fontWeightBold},children:"Heading 1"}),e.jsx("p",{style:{fontSize:A.typography.fontSizeLg},children:"Body text: The quick brown fox jumps over the lazy dog."}),e.jsx("p",{style:{fontFamily:A.typography.fontFamilyMono,fontSize:A.typography.fontSizeSm},children:'const code = "Monospace font"'})]})]})]}),e.jsx("style",{children:`
2308
+ }`},[]),C=d.useCallback(l=>{const y={theme:{extend:{colors:{primary:{DEFAULT:l.colors.primary,light:l.colors.primaryLight,dark:l.colors.primaryDark},secondary:{DEFAULT:l.colors.secondary,light:l.colors.secondaryLight,dark:l.colors.secondaryDark},accent:l.colors.accent,success:l.colors.success,warning:l.colors.warning,error:l.colors.error,info:l.colors.info},fontFamily:{sans:[l.typography.fontFamily],mono:[l.typography.fontFamilyMono]},borderRadius:l.borderRadius,boxShadow:l.shadows}}};return`// tailwind.config.js
2309
+ module.exports = ${JSON.stringify(y,null,2)}`},[]),O=d.useCallback(()=>{p(null)},[]),_=d.useCallback(()=>{var l;(l=m.current)==null||l.abort(),c(!1)},[]);return d.useEffect(()=>()=>{var l;(l=m.current)==null||l.abort()},[]),{generateTheme:w,adjustTheme:k,toCSSVariables:M,toTailwindConfig:C,loading:o,lastResult:h,clearResults:O,abort:_,isConfigured:!!b}}function He(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.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:be(c.light||c.theme),dark:c.dark?be(c.dark):null};if(c.colors)return{light:be(c),dark:null}}catch{}return{light:null,dark:null}}function be(i){return{id:i.id||`theme_${Date.now()}`,name:i.name||"Generated Theme",description:i.description,mode:i.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",...i.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",...i.typography},spacing:{xs:"4px",sm:"8px",md:"16px",lg:"24px",xl:"32px","2xl":"48px","3xl":"64px","4xl":"80px",...i.spacing},borderRadius:{none:"0",sm:"4px",md:"8px",lg:"12px",xl:"16px",full:"9999px",...i.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)",...i.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)",...i.animations},components:i.components,cssVariables:i.cssVariables}}function si(i){if(!i)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 ye(i){return i.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}const ci=[{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 oi({config:i,generateDarkMode:a=!0,onGenerate:t,showPresets:r=!0,showPreview:n=!0,className:s,style:o}){const[c,h]=d.useState("description"),[p,m]=d.useState(""),[b,w]=d.useState(""),[k,M]=d.useState(""),[C,O]=d.useState("#0066cc"),[_,l]=d.useState("light"),{generateTheme:y,toCSSVariables:S,toTailwindConfig:f,loading:j,lastResult:g,isConfigured:x}=ka({config:i,generateDarkMode:a,onThemeGenerated:t}),v=async()=>{if(j)return;let $;switch(c){case"brand":if(!b.trim())return;$={type:"brand",value:{name:b,industry:k||void 0}};break;case"colors":$={type:"colors",value:{primary:C}};break;default:if(!p.trim())return;$={type:"description",value:p}}await y($)},T=$=>{h("description"),m($.prompt)},I=()=>{if(!(g!=null&&g.theme))return;const $=S(g.theme),D=new Blob([$],{type:"text/css"}),F=URL.createObjectURL(D),U=document.createElement("a");U.href=F,U.download=`${g.theme.name.replace(/\s+/g,"-").toLowerCase()}.css`,U.click(),URL.revokeObjectURL(F)},N=()=>{if(!(g!=null&&g.theme))return;const $=f(g.theme),D=new Blob([$],{type:"text/javascript"}),F=URL.createObjectURL(D),U=document.createElement("a");U.href=F,U.download="tailwind.config.js",U.click(),URL.revokeObjectURL(F)},P=_==="dark"&&(g!=null&&g.darkTheme)?g.darkTheme:g==null?void 0:g.theme;return x?e.jsxs("div",{className:`nice-theme-ai ${s||""}`,style:o,children:[r&&e.jsx("div",{className:"nice-theme-ai__presets",children:ci.map(($,D)=>e.jsxs("button",{type:"button",className:"nice-theme-ai__preset",onClick:()=>T($),children:[e.jsx("span",{className:"nice-theme-ai__preset-icon",children:e.jsx(A.NiceIcon,{name:$.icon,size:24})}),e.jsx("span",{className:"nice-theme-ai__preset-name",children:$.name})]},D))}),e.jsxs("div",{className:"nice-theme-ai__tabs",children:[e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${c==="description"?"nice-theme-ai__tab--active":""}`,onClick:()=>h("description"),children:[e.jsx(A.NiceIcon,{name:"edit",size:14})," Description"]}),e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${c==="brand"?"nice-theme-ai__tab--active":""}`,onClick:()=>h("brand"),children:[e.jsx(A.NiceIcon,{name:"tag",size:14})," Brand"]}),e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${c==="colors"?"nice-theme-ai__tab--active":""}`,onClick:()=>h("colors"),children:[e.jsx(A.NiceIcon,{name:"palette",size:14})," Colors"]})]}),e.jsxs("div",{className:"nice-theme-ai__input-section",children:[c==="description"&&e.jsx("textarea",{value:p,onChange:$=>m($.target.value),placeholder:"Describe the theme you want... (e.g., 'Modern tech startup with blue and green')",className:"nice-theme-ai__textarea",rows:3,disabled:j}),c==="brand"&&e.jsxs("div",{className:"nice-theme-ai__brand-inputs",children:[e.jsx("input",{type:"text",value:b,onChange:$=>w($.target.value),placeholder:"Brand name",className:"nice-theme-ai__input",disabled:j}),e.jsx("input",{type:"text",value:k,onChange:$=>M($.target.value),placeholder:"Industry (optional)",className:"nice-theme-ai__input",disabled:j})]}),c==="colors"&&e.jsx("div",{className:"nice-theme-ai__color-input",children:e.jsxs("label",{children:["Primary Color:",e.jsx("input",{type:"color",value:C,onChange:$=>O($.target.value),className:"nice-theme-ai__color-picker",disabled:j}),e.jsx("span",{className:"nice-theme-ai__color-value",children:C})]})}),e.jsx("button",{type:"button",onClick:v,className:"nice-theme-ai__submit",disabled:j,children:j?e.jsx("span",{className:"nice-theme-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(A.NiceIcon,{name:"wand",size:14})," Generate Theme"]})})]}),(g==null?void 0:g.error)&&e.jsx("div",{className:"nice-theme-ai__error",role:"alert",children:g.error}),g&&P&&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:P.name}),P.description&&e.jsx("span",{className:"nice-theme-ai__theme-desc",children:P.description})]}),e.jsxs("div",{className:"nice-theme-ai__actions",children:[g.darkTheme&&e.jsxs("div",{className:"nice-theme-ai__mode-toggle",children:[e.jsx("button",{type:"button","aria-label":"Light mode",className:_==="light"?"active":"",onClick:()=>l("light"),children:e.jsx(A.NiceIcon,{name:"sun",size:16})}),e.jsx("button",{type:"button","aria-label":"Dark mode",className:_==="dark"?"active":"",onClick:()=>l("dark"),children:e.jsx(A.NiceIcon,{name:"moon",size:16})})]}),e.jsxs("button",{type:"button",onClick:I,children:[e.jsx(A.NiceIcon,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:N,children:[e.jsx(A.NiceIcon,{name:"download",size:14})," Tailwind"]})]})]}),n&&e.jsx(li,{theme:P}),e.jsxs("div",{className:"nice-theme-ai__palette",children:[e.jsx("div",{className:"nice-theme-ai__palette-title",children:"Color Palette"}),e.jsx("div",{className:"nice-theme-ai__colors",children:Object.entries(P.colors).map(([$,D])=>e.jsxs("div",{className:"nice-theme-ai__color",children:[e.jsx("div",{className:"nice-theme-ai__color-swatch",style:{backgroundColor:D}}),e.jsx("span",{className:"nice-theme-ai__color-name",children:$}),e.jsx("span",{className:"nice-theme-ai__color-hex",children:D})]},$))})]}),e.jsxs("div",{className:"nice-theme-ai__typography",children:[e.jsx("div",{className:"nice-theme-ai__typography-title",children:"Typography"}),e.jsxs("div",{style:{fontFamily:P.typography.fontFamily},children:[e.jsx("p",{style:{fontSize:P.typography.fontSize3xl,fontWeight:P.typography.fontWeightBold},children:"Heading 1"}),e.jsx("p",{style:{fontSize:P.typography.fontSizeLg},children:"Body text: The quick brown fox jumps over the lazy dog."}),e.jsx("p",{style:{fontFamily:P.typography.fontFamilyMono,fontSize:P.typography.fontSizeSm},children:'const code = "Monospace font"'})]})]})]}),e.jsx("style",{children:`
2295
2310
  .nice-theme-ai {
2296
2311
  font-family: var(--nice-font-family, system-ui, sans-serif);
2297
2312
  }
@@ -2572,7 +2587,7 @@ module.exports = ${JSON.stringify(N,null,2)}`},[]),I=d.useCallback(()=>{f(null)}
2572
2587
  color: var(--nice-error, #c62828);
2573
2588
  border-radius: var(--nice-radius-md, 6px);
2574
2589
  }
2575
- `})]}):e.jsx("div",{className:`nice-theme-ai nice-theme-ai--disabled ${s||""}`,style:c,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Ki({theme:t}){return e.jsxs("div",{className:"theme-preview",style:{"--preview-primary":t.colors.primary,"--preview-bg":t.colors.background,"--preview-surface":t.colors.surface,"--preview-text":t.colors.text,"--preview-border":t.colors.border,"--preview-radius":t.borderRadius.md,fontFamily:t.typography.fontFamily},children:[e.jsxs("div",{className:"theme-preview__header",children:[e.jsx("span",{style:{color:t.colors.primary,fontWeight:t.typography.fontWeightBold},children:t.name}),e.jsxs("div",{className:"theme-preview__dots",children:[e.jsx("span",{style:{background:t.colors.error}}),e.jsx("span",{style:{background:t.colors.warning}}),e.jsx("span",{style:{background:t.colors.success}})]})]}),e.jsxs("div",{className:"theme-preview__content",children:[e.jsx("button",{style:{background:t.colors.primary,color:t.colors.textInverse,borderRadius:t.borderRadius.md,padding:`${t.spacing.sm} ${t.spacing.md}`},children:"Primary Button"}),e.jsx("button",{style:{background:t.colors.secondary,color:t.colors.textInverse,borderRadius:t.borderRadius.md,padding:`${t.spacing.sm} ${t.spacing.md}`},children:"Secondary"}),e.jsx("input",{type:"text",placeholder:"Input field",readOnly:!0,style:{border:`1px solid ${t.colors.border}`,borderRadius:t.borderRadius.md,padding:t.spacing.sm,background:t.colors.surface}})]}),e.jsx("style",{children:`
2590
+ `})]}):e.jsx("div",{className:`nice-theme-ai nice-theme-ai--disabled ${s||""}`,style:o,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function li({theme:i}){return e.jsxs("div",{className:"theme-preview",style:{"--preview-primary":i.colors.primary,"--preview-bg":i.colors.background,"--preview-surface":i.colors.surface,"--preview-text":i.colors.text,"--preview-border":i.colors.border,"--preview-radius":i.borderRadius.md,fontFamily:i.typography.fontFamily},children:[e.jsxs("div",{className:"theme-preview__header",children:[e.jsx("span",{style:{color:i.colors.primary,fontWeight:i.typography.fontWeightBold},children:i.name}),e.jsxs("div",{className:"theme-preview__dots",children:[e.jsx("span",{style:{background:i.colors.error}}),e.jsx("span",{style:{background:i.colors.warning}}),e.jsx("span",{style:{background:i.colors.success}})]})]}),e.jsxs("div",{className:"theme-preview__content",children:[e.jsx("button",{style:{background:i.colors.primary,color:i.colors.textInverse,borderRadius:i.borderRadius.md,padding:`${i.spacing.sm} ${i.spacing.md}`},children:"Primary Button"}),e.jsx("button",{style:{background:i.colors.secondary,color:i.colors.textInverse,borderRadius:i.borderRadius.md,padding:`${i.spacing.sm} ${i.spacing.md}`},children:"Secondary"}),e.jsx("input",{type:"text",placeholder:"Input field",readOnly:!0,style:{border:`1px solid ${i.colors.border}`,borderRadius:i.borderRadius.md,padding:i.spacing.sm,background:i.colors.surface}})]}),e.jsx("style",{children:`
2576
2591
  .theme-preview {
2577
2592
  background: var(--preview-bg);
2578
2593
  border: 1px solid var(--preview-border);
@@ -2618,13 +2633,13 @@ module.exports = ${JSON.stringify(N,null,2)}`},[]),I=d.useCallback(()=>{f(null)}
2618
2633
  cursor: text;
2619
2634
  width: 150px;
2620
2635
  }
2621
- `})]})}function wa(t={}){const{config:a,targetDevice:i="responsive",onLayoutGenerated:r,onError:n}=t,s=Z(),[c,l]=d.useState(!1),[p,f]=d.useState(null),g=d.useRef(null),y=a||(s==null?void 0:s.config),w=d.useCallback(async(j,o)=>{var _,m,v;if(!y){const x="AI not configured";return n==null||n(x),{error:x}}l(!0);const N=performance.now();(_=g.current)==null||_.abort(),g.current=new AbortController;try{const x=K(y),u=`You are a UI layout expert. Generate a responsive layout based on the description.
2636
+ `})]})}function Na(i={}){const{config:a,targetDevice:t="responsive",onLayoutGenerated:r,onError:n}=i,s=Z(),[o,c]=d.useState(!1),[h,p]=d.useState(null),m=d.useRef(null),b=a||(s==null?void 0:s.config),w=d.useCallback(async(_,l)=>{var S,f,j;if(!b){const g="AI not configured";return n==null||n(g),{error:g}}c(!0);const y=performance.now();(S=m.current)==null||S.abort(),m.current=new AbortController;try{const g=K(b),x=`You are a UI layout expert. Generate a responsive layout based on the description.
2622
2637
  Return JSON with this structure:
2623
2638
  {
2624
2639
  "id": "unique_id",
2625
2640
  "name": "Layout Name",
2626
2641
  "description": "Description",
2627
- "type": "${o||"dashboard"}",
2642
+ "type": "${l||"dashboard"}",
2628
2643
  "container": {
2629
2644
  "direction": "row|column|grid",
2630
2645
  "gap": "16px",
@@ -2653,45 +2668,45 @@ Return JSON with this structure:
2653
2668
  "xl": "1280px",
2654
2669
  "2xl": "1536px"
2655
2670
  }
2656
- }`,h=await x.chat({messages:[{role:"system",content:u},{role:"user",content:`Create a ${i} layout: ${j}${o?` (type: ${o})`:""}`}],temperature:.5,maxTokens:2048}),$=Yi(h),D={layout:$||void 0,rawResponse:(v=(m=h.choices[0])==null?void 0:m.message)==null?void 0:v.content,latencyMs:performance.now()-N,error:$?void 0:"Failed to generate layout",suggestions:Xi($)};return $&&(r==null||r($)),f(D),D}catch(x){const u=x instanceof Error?x.message:"Layout generation failed",h={error:u,latencyMs:performance.now()-N};return f(h),n==null||n(u),h}finally{l(!1)}},[y,i,r,n]),S=d.useCallback(j=>{let o=`.${j.id} {
2657
- `;if(o+=` display: ${j.container.direction==="grid"?"grid":"flex"};
2658
- `,j.container.direction==="grid"){if(j.container.gridColumns){const N=typeof j.container.gridColumns=="number"?`repeat(${j.container.gridColumns}, 1fr)`:j.container.gridColumns;o+=` grid-template-columns: ${N};
2659
- `}j.container.gridRows&&(o+=` grid-template-rows: ${j.container.gridRows};
2660
- `)}else o+=` flex-direction: ${j.container.direction};
2661
- `,j.container.wrap&&(o+=` flex-wrap: wrap;
2662
- `);return j.container.gap&&(o+=` gap: ${j.container.gap};
2663
- `),j.container.padding&&(o+=` padding: ${j.container.padding};
2664
- `),j.container.align&&(o+=` align-items: ${j.container.align};
2665
- `),j.container.justify&&(o+=` justify-content: ${{start:"flex-start",end:"flex-end",center:"center",between:"space-between",around:"space-around",evenly:"space-evenly"}[j.container.justify]||j.container.justify};
2666
- `),o+=`}
2667
-
2668
- `,j.regions.forEach(N=>{var _,m,v,x,u,h;o+=`.${j.id}__${N.id} {
2669
- `,(_=N.position)!=null&&_.gridColumn&&(o+=` grid-column: ${N.position.gridColumn};
2670
- `),(m=N.position)!=null&&m.gridRow&&(o+=` grid-row: ${N.position.gridRow};
2671
- `),(v=N.size)!=null&&v.width&&(o+=` width: ${N.size.width};
2672
- `),(x=N.size)!=null&&x.height&&(o+=` height: ${N.size.height};
2673
- `),(u=N.size)!=null&&u.minWidth&&(o+=` min-width: ${N.size.minWidth};
2674
- `),(h=N.size)!=null&&h.maxWidth&&(o+=` max-width: ${N.size.maxWidth};
2675
- `),o+=`}
2676
-
2677
- `}),j.breakpoints&&Object.entries(j.breakpoints).forEach(([N,_])=>{const m=j.regions.filter(v=>{var x;return(x=v.responsive)==null?void 0:x[N]});m.length>0&&(o+=`@media (max-width: ${_}) {
2678
- `,m.forEach(v=>{var u,h;const x=v.responsive[N];o+=` .${j.id}__${v.id} {
2679
- `,(u=x.size)!=null&&u.width&&(o+=` width: ${x.size.width};
2680
- `),(h=x.size)!=null&&h.height&&(o+=` height: ${x.size.height};
2681
- `),o+=` }
2682
- `}),o+=`}
2683
-
2684
- `)}),o},[]),z=d.useCallback(j=>{const o=j.regions.map(N=>` <div className="${j.id}__${N.id}">{/* ${N.type} */}</div>`).join(`
2671
+ }`,v=await g.chat({messages:[{role:"system",content:x},{role:"user",content:`Create a ${t} layout: ${_}${l?` (type: ${l})`:""}`}],temperature:.5,maxTokens:2048}),T=di(v),I={layout:T||void 0,rawResponse:(j=(f=v.choices[0])==null?void 0:f.message)==null?void 0:j.content,latencyMs:performance.now()-y,error:T?void 0:"Failed to generate layout",suggestions:ui(T)};return T&&(r==null||r(T)),p(I),I}catch(g){const x=g instanceof Error?g.message:"Layout generation failed",v={error:x,latencyMs:performance.now()-y};return p(v),n==null||n(x),v}finally{c(!1)}},[b,t,r,n]),k=d.useCallback(_=>{let l=`.${_.id} {
2672
+ `;if(l+=` display: ${_.container.direction==="grid"?"grid":"flex"};
2673
+ `,_.container.direction==="grid"){if(_.container.gridColumns){const y=typeof _.container.gridColumns=="number"?`repeat(${_.container.gridColumns}, 1fr)`:_.container.gridColumns;l+=` grid-template-columns: ${y};
2674
+ `}_.container.gridRows&&(l+=` grid-template-rows: ${_.container.gridRows};
2675
+ `)}else l+=` flex-direction: ${_.container.direction};
2676
+ `,_.container.wrap&&(l+=` flex-wrap: wrap;
2677
+ `);return _.container.gap&&(l+=` gap: ${_.container.gap};
2678
+ `),_.container.padding&&(l+=` padding: ${_.container.padding};
2679
+ `),_.container.align&&(l+=` align-items: ${_.container.align};
2680
+ `),_.container.justify&&(l+=` justify-content: ${{start:"flex-start",end:"flex-end",center:"center",between:"space-between",around:"space-around",evenly:"space-evenly"}[_.container.justify]||_.container.justify};
2681
+ `),l+=`}
2682
+
2683
+ `,_.regions.forEach(y=>{var S,f,j,g,x,v;l+=`.${_.id}__${y.id} {
2684
+ `,(S=y.position)!=null&&S.gridColumn&&(l+=` grid-column: ${y.position.gridColumn};
2685
+ `),(f=y.position)!=null&&f.gridRow&&(l+=` grid-row: ${y.position.gridRow};
2686
+ `),(j=y.size)!=null&&j.width&&(l+=` width: ${y.size.width};
2687
+ `),(g=y.size)!=null&&g.height&&(l+=` height: ${y.size.height};
2688
+ `),(x=y.size)!=null&&x.minWidth&&(l+=` min-width: ${y.size.minWidth};
2689
+ `),(v=y.size)!=null&&v.maxWidth&&(l+=` max-width: ${y.size.maxWidth};
2690
+ `),l+=`}
2691
+
2692
+ `}),_.breakpoints&&Object.entries(_.breakpoints).forEach(([y,S])=>{const f=_.regions.filter(j=>{var g;return(g=j.responsive)==null?void 0:g[y]});f.length>0&&(l+=`@media (max-width: ${S}) {
2693
+ `,f.forEach(j=>{var x,v;const g=j.responsive[y];l+=` .${_.id}__${j.id} {
2694
+ `,(x=g.size)!=null&&x.width&&(l+=` width: ${g.size.width};
2695
+ `),(v=g.size)!=null&&v.height&&(l+=` height: ${g.size.height};
2696
+ `),l+=` }
2697
+ `}),l+=`}
2698
+
2699
+ `)}),l},[]),M=d.useCallback(_=>{const l=_.regions.map(y=>` <div className="${_.id}__${y.id}">{/* ${y.type} */}</div>`).join(`
2685
2700
  `);return`import React from 'react';
2686
- import './${j.id}.css';
2701
+ import './${_.id}.css';
2687
2702
 
2688
- export function ${ja(j.name)}() {
2703
+ export function ${Sa(_.name)}() {
2689
2704
  return (
2690
- <div className="${j.id}">
2691
- ${o}
2705
+ <div className="${_.id}">
2706
+ ${l}
2692
2707
  </div>
2693
2708
  );
2694
- }`},[]),k=d.useCallback(()=>{f(null)},[]),I=d.useCallback(()=>{var j;(j=g.current)==null||j.abort(),l(!1)},[]);return d.useEffect(()=>()=>{var j;(j=g.current)==null||j.abort()},[]),{generateLayout:w,toCSS:S,toReactComponent:z,loading:c,lastResult:p,clearResults:k,abort:I,isConfigured:!!y}}function Yi(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",c=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,l=JSON.parse(c);if(l.regions||l.container)return{id:l.id||`layout_${Date.now()}`,name:l.name||"Generated Layout",description:l.description,type:l.type||"dashboard",container:{direction:"grid",gap:"16px",padding:"20px",gridColumns:12,...l.container},regions:l.regions||[],breakpoints:l.breakpoints||{xs:"320px",sm:"640px",md:"768px",lg:"1024px",xl:"1280px","2xl":"1536px"},cssGrid:l.cssGrid,cssVariables:l.cssVariables}}catch{}return null}function Xi(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 ja(t){return t.replace(/[^a-zA-Z0-9]+(.)/g,(a,i)=>i.toUpperCase()).replace(/^./,a=>a.toUpperCase())}const Zi=[{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 Qi({config:t,targetDevice:a="responsive",onGenerate:i,showTypeSelector:r=!0,showPreview:n=!0,className:s,style:c,renderLayout:l}){const[p,f]=d.useState(""),[g,y]=d.useState(null),{generateLayout:w,toCSS:S,toReactComponent:z,loading:k,lastResult:I,isConfigured:j}=wa({config:t,targetDevice:a,onLayoutGenerated:i}),o=async()=>{!p.trim()||k||await w(p,g||void 0)},N=()=>{if(!(I!=null&&I.layout))return;const m=S(I.layout),v=new Blob([m],{type:"text/css"}),x=URL.createObjectURL(v),u=document.createElement("a");u.href=x,u.download=`${I.layout.id}.css`,u.click(),URL.revokeObjectURL(x)},_=()=>{if(!(I!=null&&I.layout))return;const m=z(I.layout),v=new Blob([m],{type:"text/javascript"}),x=URL.createObjectURL(v),u=document.createElement("a");u.href=x,u.download=`${ja(I.layout.name)}.tsx`,u.click(),URL.revokeObjectURL(x)};return j?e.jsxs("div",{className:`nice-layout-ai ${s||""}`,style:c,children:[r&&e.jsx("div",{className:"nice-layout-ai__types",children:Zi.map(({type:m,icon:v,label:x})=>e.jsxs("button",{type:"button",className:`nice-layout-ai__type ${g===m?"nice-layout-ai__type--selected":""}`,onClick:()=>y(g===m?null:m),children:[e.jsx("span",{className:"nice-layout-ai__type-icon",children:e.jsx(L.NiceIcon,{name:v,size:20})}),e.jsx("span",{className:"nice-layout-ai__type-label",children:x})]},m))}),e.jsxs("div",{className:"nice-layout-ai__input-section",children:[e.jsx("textarea",{value:p,onChange:m=>f(m.target.value),placeholder:"Describe the layout you need... (e.g., 'Admin dashboard with sidebar navigation and header')",className:"nice-layout-ai__input",rows:3,disabled:k}),e.jsx("button",{type:"button",onClick:o,className:"nice-layout-ai__submit",disabled:k||!p.trim(),children:k?e.jsx("span",{className:"nice-layout-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"palette",size:14})," Generate Layout"]})})]}),(I==null?void 0:I.error)&&e.jsx("div",{className:"nice-layout-ai__error",role:"alert",children:I.error}),I&&I.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:I.layout.name}),e.jsx("span",{className:"nice-layout-ai__layout-type",children:I.layout.type})]}),e.jsxs("div",{className:"nice-layout-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>i==null?void 0:i(I.layout),children:[e.jsx(L.NiceIcon,{name:"check",size:14})," Use Layout"]}),e.jsxs("button",{type:"button",onClick:N,children:[e.jsx(L.NiceIcon,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:_,children:[e.jsx(L.NiceIcon,{name:"download",size:14})," 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:I.layout.regions.map(m=>e.jsx("span",{className:`nice-layout-ai__region nice-layout-ai__region--${m.type}`,children:m.type},m.id))})]}),n&&e.jsx("div",{className:"nice-layout-ai__preview",children:l?l(I.layout):e.jsx(et,{layout:I.layout})}),e.jsxs("details",{className:"nice-layout-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(I.layout,null,2)})]})]}),e.jsx("style",{children:`
2709
+ }`},[]),C=d.useCallback(()=>{p(null)},[]),O=d.useCallback(()=>{var _;(_=m.current)==null||_.abort(),c(!1)},[]);return d.useEffect(()=>()=>{var _;(_=m.current)==null||_.abort()},[]),{generateLayout:w,toCSS:k,toReactComponent:M,loading:o,lastResult:h,clearResults:C,abort:O,isConfigured:!!b}}function di(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.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 ui(i){if(!i)return[];const a=[],t=new Set(i.regions.map(r=>r.type));return t.has("header")||a.push("Consider adding a header region for navigation"),!t.has("sidebar")&&i.type==="dashboard"&&a.push("Add a sidebar for dashboard navigation"),i.regions.some(r=>!r.responsive)&&a.push("Add responsive breakpoints for mobile compatibility"),a.slice(0,3)}function Sa(i){return i.replace(/[^a-zA-Z0-9]+(.)/g,(a,t)=>t.toUpperCase()).replace(/^./,a=>a.toUpperCase())}const pi=[{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 mi({config:i,targetDevice:a="responsive",onGenerate:t,showTypeSelector:r=!0,showPreview:n=!0,className:s,style:o,renderLayout:c}){const[h,p]=d.useState(""),[m,b]=d.useState(null),{generateLayout:w,toCSS:k,toReactComponent:M,loading:C,lastResult:O,isConfigured:_}=Na({config:i,targetDevice:a,onLayoutGenerated:t}),l=async()=>{!h.trim()||C||await w(h,m||void 0)},y=()=>{if(!(O!=null&&O.layout))return;const f=k(O.layout),j=new Blob([f],{type:"text/css"}),g=URL.createObjectURL(j),x=document.createElement("a");x.href=g,x.download=`${O.layout.id}.css`,x.click(),URL.revokeObjectURL(g)},S=()=>{if(!(O!=null&&O.layout))return;const f=M(O.layout),j=new Blob([f],{type:"text/javascript"}),g=URL.createObjectURL(j),x=document.createElement("a");x.href=g,x.download=`${Sa(O.layout.name)}.tsx`,x.click(),URL.revokeObjectURL(g)};return _?e.jsxs("div",{className:`nice-layout-ai ${s||""}`,style:o,children:[r&&e.jsx("div",{className:"nice-layout-ai__types",children:pi.map(({type:f,icon:j,label:g})=>e.jsxs("button",{type:"button",className:`nice-layout-ai__type ${m===f?"nice-layout-ai__type--selected":""}`,onClick:()=>b(m===f?null:f),children:[e.jsx("span",{className:"nice-layout-ai__type-icon",children:e.jsx(A.NiceIcon,{name:j,size:20})}),e.jsx("span",{className:"nice-layout-ai__type-label",children:g})]},f))}),e.jsxs("div",{className:"nice-layout-ai__input-section",children:[e.jsx("textarea",{value:h,onChange:f=>p(f.target.value),placeholder:"Describe the layout you need... (e.g., 'Admin dashboard with sidebar navigation and header')",className:"nice-layout-ai__input",rows:3,disabled:C}),e.jsx("button",{type:"button",onClick:l,className:"nice-layout-ai__submit",disabled:C||!h.trim(),children:C?e.jsx("span",{className:"nice-layout-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(A.NiceIcon,{name:"palette",size:14})," Generate Layout"]})})]}),(O==null?void 0:O.error)&&e.jsx("div",{className:"nice-layout-ai__error",role:"alert",children:O.error}),O&&O.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:O.layout.name}),e.jsx("span",{className:"nice-layout-ai__layout-type",children:O.layout.type})]}),e.jsxs("div",{className:"nice-layout-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>t==null?void 0:t(O.layout),children:[e.jsx(A.NiceIcon,{name:"check",size:14})," Use Layout"]}),e.jsxs("button",{type:"button",onClick:y,children:[e.jsx(A.NiceIcon,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:S,children:[e.jsx(A.NiceIcon,{name:"download",size:14})," 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:O.layout.regions.map(f=>e.jsx("span",{className:`nice-layout-ai__region nice-layout-ai__region--${f.type}`,children:f.type},f.id))})]}),n&&e.jsx("div",{className:"nice-layout-ai__preview",children:c?c(O.layout):e.jsx(gi,{layout:O.layout})}),e.jsxs("details",{className:"nice-layout-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(O.layout,null,2)})]})]}),e.jsx("style",{children:`
2695
2710
  .nice-layout-ai {
2696
2711
  font-family: var(--nice-font-family, system-ui, sans-serif);
2697
2712
  }
@@ -2926,7 +2941,7 @@ ${o}
2926
2941
  color: var(--nice-error, #c62828);
2927
2942
  border-radius: var(--nice-radius-md, 6px);
2928
2943
  }
2929
- `})]}):e.jsx("div",{className:`nice-layout-ai nice-layout-ai--disabled ${s||""}`,style:c,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function et({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,c,l,p;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:((c=i.size)==null?void 0:c.height)||"80px",minWidth:(l=i.size)==null?void 0:l.minWidth,maxWidth:(p=i.size)==null?void 0:p.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 ka(t={}){const{config:a,wcagLevel:i="AA",onAuditComplete:r,onError:n}=t,s=Z(),[c,l]=d.useState(!1),[p,f]=d.useState(null),g=d.useRef(null),y=a||(s==null?void 0:s.config),w=d.useCallback(async(o,N)=>{var _;if(!y){const m="AI not configured";return n==null||n(m),Ce("html",i,m)}l(!0),(_=g.current)==null||_.abort(),g.current=new AbortController;try{const m=K(y),v=`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:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function gi({layout:i}){const a=t=>({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)"})[t]||"var(--nice-bg-secondary, #f5f5f5)";return e.jsx("div",{className:"layout-preview",style:{display:i.container.direction==="grid"?"grid":"flex",flexDirection:i.container.direction==="column"?"column":"row",gridTemplateColumns:i.container.direction==="grid"&&i.container.gridColumns?typeof i.container.gridColumns=="number"?`repeat(${i.container.gridColumns}, 1fr)`:i.container.gridColumns:void 0,gap:i.container.gap||"8px",minHeight:"300px"},children:i.regions.map(t=>{var r,n,s,o,c,h;return e.jsx("div",{className:"layout-preview__region",style:{gridColumn:(r=t.position)==null?void 0:r.gridColumn,gridRow:(n=t.position)==null?void 0:n.gridRow,width:(s=t.size)==null?void 0:s.width,height:((o=t.size)==null?void 0:o.height)||"80px",minWidth:(c=t.size)==null?void 0:c.minWidth,maxWidth:(h=t.size)==null?void 0:h.maxWidth,background:a(t.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:t.type},t.id)})})}function Ca(i={}){const{config:a,wcagLevel:t="AA",onAuditComplete:r,onError:n}=i,s=Z(),[o,c]=d.useState(!1),[h,p]=d.useState(null),m=d.useRef(null),b=a||(s==null?void 0:s.config),w=d.useCallback(async(l,y)=>{var S;if(!b){const f="AI not configured";return n==null||n(f),Ae("html",t,f)}c(!0),(S=m.current)==null||S.abort(),m.current=new AbortController;try{const f=K(b),j=`You are a WCAG accessibility expert. Analyze the provided HTML code for accessibility issues at WCAG ${t} level.
2930
2945
 
2931
2946
  Return JSON with this exact structure:
2932
2947
  {
@@ -2960,10 +2975,10 @@ Focus on:
2960
2975
  7. Heading hierarchy
2961
2976
  8. Landmark regions
2962
2977
  9. Semantic HTML usage
2963
- 10. Language attributes`,x=await m.chat({messages:[{role:"system",content:v},{role:"user",content:`Analyze this HTML for accessibility:
2964
- ${N?`Context: ${N}
2978
+ 10. Language attributes`,g=await f.chat({messages:[{role:"system",content:j},{role:"user",content:`Analyze this HTML for accessibility:
2979
+ ${y?`Context: ${y}
2965
2980
 
2966
- `:""}${o}`}],temperature:.3,maxTokens:4096}),u=at(x,"html",i);return f(u),r==null||r(u),u}catch(m){const v=m instanceof Error?m.message:"Audit failed";return n==null||n(v),Ce("html",i,v)}finally{l(!1)}},[y,i,r,n]),S=d.useCallback((o,N)=>{const _=he(me(o)),m=he(me(N)),v=(Math.max(_,m)+.05)/(Math.min(_,m)+.05),x={foreground:o,background:N,ratio:Math.round(v*100)/100,passesAA:v>=4.5,passesAALarge:v>=3,passesAAA:v>=7,passesAAALarge:v>=4.5};return x.passesAA||(x.suggestions=tt(o,N,4.5)),x},[]),z=d.useCallback(async o=>{var N,_;if(!y)return n==null||n("AI not configured"),[];try{const h=(((_=(N=(await K(y).chat({messages:[{role:"system",content:`Analyze the HTML for ARIA attribute issues.
2981
+ `:""}${l}`}],temperature:.3,maxTokens:4096}),x=hi(g,"html",t);return p(x),r==null||r(x),x}catch(f){const j=f instanceof Error?f.message:"Audit failed";return n==null||n(j),Ae("html",t,j)}finally{c(!1)}},[b,t,r,n]),k=d.useCallback((l,y)=>{const S=he(ge(l)),f=he(ge(y)),j=(Math.max(S,f)+.05)/(Math.min(S,f)+.05),g={foreground:l,background:y,ratio:Math.round(j*100)/100,passesAA:j>=4.5,passesAALarge:j>=3,passesAAA:j>=7,passesAAALarge:j>=4.5};return g.passesAA||(g.suggestions=xi(l,y,4.5)),g},[]),M=d.useCallback(async l=>{var y,S;if(!b)return n==null||n("AI not configured"),[];try{const v=(((S=(y=(await K(b).chat({messages:[{role:"system",content:`Analyze the HTML for ARIA attribute issues.
2967
2982
  Return JSON array:
2968
2983
  [{
2969
2984
  "element": "<button>...",
@@ -2974,10 +2989,10 @@ Return JSON array:
2974
2989
  "issues": ["Missing aria-label"],
2975
2990
  "suggestions": ["Add aria-label='Submit form'"]
2976
2991
  }]`},{role:"user",content:`Validate ARIA in:
2977
- ${o}`}],temperature:.2,maxTokens:2048})).choices[0])==null?void 0:N.message)==null?void 0:_.content)||"").match(/\[[\s\S]*\]/);if(h)return JSON.parse(h[0])}catch{}return[]},[y,n]),k=d.useCallback(async o=>{var N,_;if(!y)return n==null||n("AI not configured"),o;try{const x=((_=(N=(await K(y).chat({messages:[{role:"system",content:`You are an accessibility expert. Improve the HTML to be fully WCAG ${i} compliant.
2992
+ ${l}`}],temperature:.2,maxTokens:2048})).choices[0])==null?void 0:y.message)==null?void 0:S.content)||"").match(/\[[\s\S]*\]/);if(v)return JSON.parse(v[0])}catch{}return[]},[b,n]),C=d.useCallback(async l=>{var y,S;if(!b)return n==null||n("AI not configured"),l;try{const g=((S=(y=(await K(b).chat({messages:[{role:"system",content:`You are an accessibility expert. Improve the HTML to be fully WCAG ${t} compliant.
2978
2993
  Add proper ARIA attributes, semantic HTML, keyboard handlers, focus management.
2979
2994
  Return only the improved HTML code.`},{role:"user",content:`Make this accessible:
2980
- ${o}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:N.message)==null?void 0:_.content)||"",u=x.match(/```(?:html)?\s*([\s\S]*?)```/);return u?u[1].trim():x.trim()}catch{return o}},[y,i,n]),I=d.useCallback(()=>{f(null)},[]),j=d.useCallback(()=>{var o;(o=g.current)==null||o.abort(),l(!1)},[]);return d.useEffect(()=>()=>{var o;(o=g.current)==null||o.abort()},[]),{analyzeHTML:w,checkContrast:S,validateARIA:z,suggestAccessibleCode:k,loading:c,lastAudit:p,clearAudit:I,abort:j,isConfigured:!!y}}function Ce(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 at(t,a,i){var r,n,s;try{const c=((n=(r=t.choices[0])==null?void 0:r.message)==null?void 0:n.content)||"",p=((s=(c.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,c])[1])==null?void 0:s.trim())||c,f=JSON.parse(p),g=(f.issues||[]).map((w,S)=>({id:w.id||`issue_${S}`,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})),y={critical:g.filter(w=>w.severity==="critical").length,serious:g.filter(w=>w.severity==="serious").length,moderate:g.filter(w=>w.severity==="moderate").length,minor:g.filter(w=>w.severity==="minor").length,passed:0};return{timestamp:new Date,target:a,wcagLevel:i,issues:g,score:f.score??it(y),summary:y,recommendations:f.recommendations||[]}}catch{return Ce(a,i,"Failed to parse audit results")}}function it(t){const a=t.critical*25+t.serious*15+t.moderate*5+t.minor*2;return Math.max(0,100-a)}function me(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 he(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 tt(t,a,i){const r=[],n=me(t),s=me(a),c={r:Math.max(0,n.r-40),g:Math.max(0,n.g-40),b:Math.max(0,n.b-40)},l=`#${c.r.toString(16).padStart(2,"0")}${c.g.toString(16).padStart(2,"0")}${c.b.toString(16).padStart(2,"0")}`,p=he(c),f=he(s);(Math.max(p,f)+.05)/(Math.min(p,f)+.05)>=i&&r.push(`Try darker foreground: ${l}`);const y={r:Math.min(255,s.r+40),g:Math.min(255,s.g+40),b:Math.min(255,s.b+40)},w=`#${y.r.toString(16).padStart(2,"0")}${y.g.toString(16).padStart(2,"0")}${y.b.toString(16).padStart(2,"0")}`;return r.push(`Try lighter background: ${w}`),r}const ye={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 rt({config:t,wcagLevel:a="AA",onAuditComplete:i,showContrastChecker:r=!0,className:n,style:s,renderIssue:c}){const[l,p]=d.useState(""),[f,g]=d.useState("#333333"),[y,w]=d.useState("#ffffff"),[S,z]=d.useState(null),{analyzeHTML:k,checkContrast:I,suggestAccessibleCode:j,loading:o,lastAudit:N,isConfigured:_}=ka({config:t,wcagLevel:a,onAuditComplete:i}),m=async()=>{!l.trim()||o||await k(l)},v=()=>{const u=I(f,y);z(u)},x=async()=>{if(!l.trim())return;const u=await j(l);p(u)};return _?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:"Color Contrast Checker"}),e.jsxs("div",{className:"nice-a11y-ai__contrast-inputs",children:[e.jsxs("label",{children:["Foreground",e.jsx("input",{type:"color",value:f,onChange:u=>g(u.target.value)}),e.jsx("input",{type:"text",value:f,onChange:u=>g(u.target.value)})]}),e.jsxs("label",{children:["Background",e.jsx("input",{type:"color",value:y,onChange:u=>w(u.target.value)}),e.jsx("input",{type:"text",value:y,onChange:u=>w(u.target.value)})]}),e.jsx("button",{type:"button",onClick:v,children:"Check"})]}),S&&e.jsxs("div",{className:"nice-a11y-ai__contrast-result",children:[e.jsx("div",{className:"nice-a11y-ai__contrast-preview",style:{color:f,background:y},children:"Sample Text Aa"}),e.jsxs("div",{className:"nice-a11y-ai__contrast-ratio",children:[e.jsxs("span",{className:"nice-a11y-ai__ratio-value",children:[S.ratio,":1"]}),e.jsxs("div",{className:"nice-a11y-ai__passes",children:[e.jsxs("span",{className:S.passesAA?"pass":"fail",children:["AA: ",e.jsx(L.NiceIcon,{name:S.passesAA?"check":"close",size:14})]}),e.jsxs("span",{className:S.passesAALarge?"pass":"fail",children:["AA Large:"," ",e.jsx(L.NiceIcon,{name:S.passesAALarge?"check":"close",size:14})]}),e.jsxs("span",{className:S.passesAAA?"pass":"fail",children:["AAA: ",e.jsx(L.NiceIcon,{name:S.passesAAA?"check":"close",size:14})]})]})]}),S.suggestions&&S.suggestions.length>0&&e.jsx("div",{className:"nice-a11y-ai__suggestions",children:S.suggestions.map((u,h)=>e.jsx("div",{children:u},h))})]})]}),e.jsxs("div",{className:"nice-a11y-ai__analyzer",children:[e.jsxs("h3",{children:["HTML Accessibility Analyzer (WCAG ",a,")"]}),e.jsx("textarea",{value:l,onChange:u=>p(u.target.value),placeholder:"Paste HTML code to analyze...",className:"nice-a11y-ai__input",rows:8,disabled:o}),e.jsxs("div",{className:"nice-a11y-ai__actions",children:[e.jsx("button",{type:"button",onClick:m,disabled:o||!l.trim(),children:o?e.jsx("span",{className:"nice-a11y-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"search",size:14})," Analyze"]})}),e.jsxs("button",{type:"button",onClick:x,disabled:o||!l.trim(),children:[e.jsx(L.NiceIcon,{name:"settings",size:14})," Auto-Fix"]})]})]}),N&&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:N.score}),e.jsx("span",{className:"nice-a11y-ai__score-label",children:"Score"})]}),e.jsxs("div",{className:"nice-a11y-ai__summary",children:[e.jsxs("span",{className:"critical",children:[N.summary.critical," Critical"]}),e.jsxs("span",{className:"serious",children:[N.summary.serious," Serious"]}),e.jsxs("span",{className:"moderate",children:[N.summary.moderate," Moderate"]}),e.jsxs("span",{className:"minor",children:[N.summary.minor," Minor"]})]})]}),e.jsx("div",{className:"nice-a11y-ai__issues",children:N.issues.map(u=>c?c(u):e.jsxs("div",{className:"nice-a11y-ai__issue",style:{background:ye[u.severity].bg,borderLeftColor:ye[u.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(L.NiceIcon,{name:ye[u.severity].icon,size:16})}),e.jsx("span",{className:"nice-a11y-ai__issue-title",children:u.title}),e.jsxs("span",{className:"nice-a11y-ai__issue-wcag",children:["WCAG ",u.wcagCriteria," (",u.wcagLevel,")"]})]}),e.jsx("p",{className:"nice-a11y-ai__issue-desc",children:u.description}),u.element&&e.jsx("code",{className:"nice-a11y-ai__issue-element",children:u.element}),e.jsxs("div",{className:"nice-a11y-ai__issue-suggestion",children:[e.jsx("strong",{children:"Fix:"})," ",u.suggestion]}),u.codeExample&&e.jsx("pre",{className:"nice-a11y-ai__issue-example",children:u.codeExample})]},u.id))}),N.recommendations.length>0&&e.jsxs("div",{className:"nice-a11y-ai__recommendations",children:[e.jsx("h4",{children:"General Recommendations"}),e.jsx("ul",{children:N.recommendations.map((u,h)=>e.jsx("li",{children:u},h))})]})]}),e.jsx("style",{children:`
2995
+ ${l}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:y.message)==null?void 0:S.content)||"",x=g.match(/```(?:html)?\s*([\s\S]*?)```/);return x?x[1].trim():g.trim()}catch{return l}},[b,t,n]),O=d.useCallback(()=>{p(null)},[]),_=d.useCallback(()=>{var l;(l=m.current)==null||l.abort(),c(!1)},[]);return d.useEffect(()=>()=>{var l;(l=m.current)==null||l.abort()},[]),{analyzeHTML:w,checkContrast:k,validateARIA:M,suggestAccessibleCode:C,loading:o,lastAudit:h,clearAudit:O,abort:_,isConfigured:!!b}}function Ae(i,a,t){return{timestamp:new Date,target:i,wcagLevel:a,issues:t?[{id:"error",category:"semantic-html",severity:"critical",wcagCriteria:"N/A",wcagLevel:"A",title:"Audit Error",description:t,impact:"Audit could not complete",suggestion:"Try again or check configuration"}]:[],score:t?0:100,summary:{critical:t?1:0,serious:0,moderate:0,minor:0,passed:0},recommendations:[]}}function hi(i,a,t){var r,n,s;try{const o=((n=(r=i.choices[0])==null?void 0:r.message)==null?void 0:n.content)||"",h=((s=(o.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,o])[1])==null?void 0:s.trim())||o,p=JSON.parse(h),m=(p.issues||[]).map((w,k)=>({id:w.id||`issue_${k}`,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})),b={critical:m.filter(w=>w.severity==="critical").length,serious:m.filter(w=>w.severity==="serious").length,moderate:m.filter(w=>w.severity==="moderate").length,minor:m.filter(w=>w.severity==="minor").length,passed:0};return{timestamp:new Date,target:a,wcagLevel:t,issues:m,score:p.score??fi(b),summary:b,recommendations:p.recommendations||[]}}catch{return Ae(a,t,"Failed to parse audit results")}}function fi(i){const a=i.critical*25+i.serious*15+i.moderate*5+i.minor*2;return Math.max(0,100-a)}function ge(i){const a=i.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 he(i){const[a,t,r]=[i.r,i.g,i.b].map(n=>(n/=255,n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4)));return .2126*a+.7152*t+.0722*r}function xi(i,a,t){const r=[],n=ge(i),s=ge(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")}`,h=he(o),p=he(s);(Math.max(h,p)+.05)/(Math.min(h,p)+.05)>=t&&r.push(`Try darker foreground: ${c}`);const b={r:Math.min(255,s.r+40),g:Math.min(255,s.g+40),b:Math.min(255,s.b+40)},w=`#${b.r.toString(16).padStart(2,"0")}${b.g.toString(16).padStart(2,"0")}${b.b.toString(16).padStart(2,"0")}`;return r.push(`Try lighter background: ${w}`),r}const ve={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 bi({config:i,wcagLevel:a="AA",onAuditComplete:t,showContrastChecker:r=!0,className:n,style:s,renderIssue:o}){const[c,h]=d.useState(""),[p,m]=d.useState("#333333"),[b,w]=d.useState("#ffffff"),[k,M]=d.useState(null),{analyzeHTML:C,checkContrast:O,suggestAccessibleCode:_,loading:l,lastAudit:y,isConfigured:S}=Ca({config:i,wcagLevel:a,onAuditComplete:t}),f=async()=>{!c.trim()||l||await C(c)},j=()=>{const x=O(p,b);M(x)},g=async()=>{if(!c.trim())return;const x=await _(c);h(x)};return S?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:"Color Contrast Checker"}),e.jsxs("div",{className:"nice-a11y-ai__contrast-inputs",children:[e.jsxs("label",{children:["Foreground",e.jsx("input",{type:"color",value:p,onChange:x=>m(x.target.value)}),e.jsx("input",{type:"text",value:p,onChange:x=>m(x.target.value)})]}),e.jsxs("label",{children:["Background",e.jsx("input",{type:"color",value:b,onChange:x=>w(x.target.value)}),e.jsx("input",{type:"text",value:b,onChange:x=>w(x.target.value)})]}),e.jsx("button",{type:"button",onClick:j,children:"Check"})]}),k&&e.jsxs("div",{className:"nice-a11y-ai__contrast-result",children:[e.jsx("div",{className:"nice-a11y-ai__contrast-preview",style:{color:p,background:b},children:"Sample Text Aa"}),e.jsxs("div",{className:"nice-a11y-ai__contrast-ratio",children:[e.jsxs("span",{className:"nice-a11y-ai__ratio-value",children:[k.ratio,":1"]}),e.jsxs("div",{className:"nice-a11y-ai__passes",children:[e.jsxs("span",{className:k.passesAA?"pass":"fail",children:["AA: ",e.jsx(A.NiceIcon,{name:k.passesAA?"check":"close",size:14})]}),e.jsxs("span",{className:k.passesAALarge?"pass":"fail",children:["AA Large:"," ",e.jsx(A.NiceIcon,{name:k.passesAALarge?"check":"close",size:14})]}),e.jsxs("span",{className:k.passesAAA?"pass":"fail",children:["AAA: ",e.jsx(A.NiceIcon,{name:k.passesAAA?"check":"close",size:14})]})]})]}),k.suggestions&&k.suggestions.length>0&&e.jsx("div",{className:"nice-a11y-ai__suggestions",children:k.suggestions.map((x,v)=>e.jsx("div",{children:x},v))})]})]}),e.jsxs("div",{className:"nice-a11y-ai__analyzer",children:[e.jsxs("h3",{children:["HTML Accessibility Analyzer (WCAG ",a,")"]}),e.jsx("textarea",{value:c,onChange:x=>h(x.target.value),placeholder:"Paste HTML code to analyze...",className:"nice-a11y-ai__input",rows:8,disabled:l}),e.jsxs("div",{className:"nice-a11y-ai__actions",children:[e.jsx("button",{type:"button",onClick:f,disabled:l||!c.trim(),children:l?e.jsx("span",{className:"nice-a11y-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(A.NiceIcon,{name:"search",size:14})," Analyze"]})}),e.jsxs("button",{type:"button",onClick:g,disabled:l||!c.trim(),children:[e.jsx(A.NiceIcon,{name:"settings",size:14})," 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:"Score"})]}),e.jsxs("div",{className:"nice-a11y-ai__summary",children:[e.jsxs("span",{className:"critical",children:[y.summary.critical," Critical"]}),e.jsxs("span",{className:"serious",children:[y.summary.serious," Serious"]}),e.jsxs("span",{className:"moderate",children:[y.summary.moderate," Moderate"]}),e.jsxs("span",{className:"minor",children:[y.summary.minor," Minor"]})]})]}),e.jsx("div",{className:"nice-a11y-ai__issues",children:y.issues.map(x=>o?o(x):e.jsxs("div",{className:"nice-a11y-ai__issue",style:{background:ve[x.severity].bg,borderLeftColor:ve[x.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(A.NiceIcon,{name:ve[x.severity].icon,size:16})}),e.jsx("span",{className:"nice-a11y-ai__issue-title",children:x.title}),e.jsxs("span",{className:"nice-a11y-ai__issue-wcag",children:["WCAG ",x.wcagCriteria," (",x.wcagLevel,")"]})]}),e.jsx("p",{className:"nice-a11y-ai__issue-desc",children:x.description}),x.element&&e.jsx("code",{className:"nice-a11y-ai__issue-element",children:x.element}),e.jsxs("div",{className:"nice-a11y-ai__issue-suggestion",children:[e.jsx("strong",{children:"Fix:"})," ",x.suggestion]}),x.codeExample&&e.jsx("pre",{className:"nice-a11y-ai__issue-example",children:x.codeExample})]},x.id))}),y.recommendations.length>0&&e.jsxs("div",{className:"nice-a11y-ai__recommendations",children:[e.jsx("h4",{children:"General Recommendations"}),e.jsx("ul",{children:y.recommendations.map((x,v)=>e.jsx("li",{children:x},v))})]})]}),e.jsx("style",{children:`
2981
2996
  .nice-a11y-ai {
2982
2997
  font-family: var(--nice-font-family, system-ui, sans-serif);
2983
2998
  }
@@ -3276,14 +3291,14 @@ ${o}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:N.message)==nu
3276
3291
  margin-bottom: var(--nice-space-1-5, 6px);
3277
3292
  font-size: 14px;
3278
3293
  }
3279
- `})]}):e.jsx("div",{className:`nice-a11y-ai nice-a11y-ai--disabled ${n||""}`,style:s,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}const ve=[{name:"home",category:"navigation",keywords:["home","house","start","main"],svgPath:"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"},{name:"menu",category:"navigation",keywords:["menu","hamburger","nav","bars"],svgPath:"M4 6h16M4 12h16M4 18h16"},{name:"arrow-left",category:"navigation",keywords:["back","previous","left","arrow"],svgPath:"M10 19l-7-7m0 0l7-7m-7 7h18"},{name:"arrow-right",category:"navigation",keywords:["next","forward","right","arrow"],svgPath:"M14 5l7 7m0 0l-7 7m7-7H3"},{name:"chevron-down",category:"navigation",keywords:["expand","dropdown","down","chevron"],svgPath:"M19 9l-7 7-7-7"},{name:"chevron-up",category:"navigation",keywords:["collapse","up","chevron"],svgPath:"M5 15l7-7 7 7"},{name:"plus",category:"action",keywords:["add","create","new","plus"],svgPath:"M12 4v16m8-8H4"},{name:"minus",category:"action",keywords:["remove","subtract","minus"],svgPath:"M20 12H4"},{name:"x",category:"action",keywords:["close","cancel","delete","remove","x"],svgPath:"M6 18L18 6M6 6l12 12"},{name:"check",category:"action",keywords:["done","complete","success","check","tick"],svgPath:"M5 13l4 4L19 7"},{name:"edit",category:"action",keywords:["edit","modify","pencil","write"],svgPath:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"},{name:"trash",category:"action",keywords:["delete","remove","trash","bin"],svgPath:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"},{name:"search",category:"action",keywords:["search","find","magnify","lookup"],svgPath:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"},{name:"filter",category:"action",keywords:["filter","sort","funnel"],svgPath:"M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"},{name:"download",category:"action",keywords:["download","save","export"],svgPath:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"},{name:"upload",category:"action",keywords:["upload","import","send"],svgPath:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"},{name:"refresh",category:"action",keywords:["refresh","reload","sync"],svgPath:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"},{name:"copy",category:"action",keywords:["copy","duplicate","clone"],svgPath:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"},{name:"mail",category:"communication",keywords:["email","mail","message","envelope"],svgPath:"M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"},{name:"phone",category:"communication",keywords:["phone","call","telephone","contact"],svgPath:"M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"},{name:"chat",category:"communication",keywords:["chat","message","comment","bubble"],svgPath:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"},{name:"bell",category:"notification",keywords:["notification","bell","alert","alarm"],svgPath:"M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"},{name:"file",category:"file",keywords:["file","document","page"],svgPath:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"},{name:"folder",category:"file",keywords:["folder","directory","category"],svgPath:"M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"},{name:"image",category:"image",keywords:["image","photo","picture","gallery"],svgPath:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"},{name:"video",category:"av",keywords:["video","movie","film","camera"],svgPath:"M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"},{name:"user",category:"social",keywords:["user","person","account","profile"],svgPath:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"},{name:"users",category:"social",keywords:["users","group","team","people"],svgPath:"M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"},{name:"settings",category:"action",keywords:["settings","config","gear","cog","preferences"],svgPath:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z"},{name:"calendar",category:"business",keywords:["calendar","date","schedule","event"],svgPath:"M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"},{name:"clock",category:"business",keywords:["time","clock","schedule","hour"],svgPath:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"credit-card",category:"finance",keywords:["payment","card","credit","money"],svgPath:"M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"},{name:"chart",category:"business",keywords:["chart","graph","analytics","statistics"],svgPath:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"},{name:"lock",category:"security",keywords:["lock","secure","private","password"],svgPath:"M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"},{name:"unlock",category:"security",keywords:["unlock","open","access"],svgPath:"M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"},{name:"shield",category:"security",keywords:["shield","security","protect","safe"],svgPath:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"},{name:"eye",category:"action",keywords:["view","show","visible","eye","visibility"],svgPath:"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"},{name:"eye-off",category:"action",keywords:["hide","invisible","hidden","eye-off"],svgPath:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"},{name:"info",category:"alert",keywords:["info","information","help","about"],svgPath:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"warning",category:"alert",keywords:["warning","caution","alert","attention"],svgPath:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"},{name:"error",category:"alert",keywords:["error","danger","fail","problem"],svgPath:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"success",category:"alert",keywords:["success","done","complete","check-circle"],svgPath:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"star",category:"action",keywords:["star","favorite","bookmark","rating"],svgPath:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"},{name:"heart",category:"social",keywords:["heart","love","like","favorite"],svgPath:"M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"},{name:"share",category:"social",keywords:["share","send","forward"],svgPath:"M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z"},{name:"link",category:"action",keywords:["link","url","chain","hyperlink"],svgPath:"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"},{name:"external-link",category:"action",keywords:["external","open","new-window"],svgPath:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"}];function Na(t={}){const{config:a,defaultLibrary:i="lucide",defaultStyle:r="outline",maxSuggestions:n=10,onSuggestion:s,onError:c}=t,l=Z(),[p,f]=d.useState(!1),[g,y]=d.useState(null),w=d.useRef(null),S=a||(l==null?void 0:l.config),z=d.useCallback(_=>{const m=_.toLowerCase(),v=m.split(/\s+/);return ve.map(x=>{let u=0;return x.name===m?u+=100:x.name.includes(m)&&(u+=50),v.forEach(h=>{x.keywords.forEach($=>{$===h?u+=30:($.includes(h)||h.includes($))&&(u+=15)})}),x.category===m&&(u+=20),{id:`icon_${x.name}`,name:x.name,displayName:x.name.replace(/-/g," ").replace(/\b\w/g,h=>h.toUpperCase()),category:x.category,style:r,library:i,relevanceScore:u,keywords:x.keywords,svgPath:x.svgPath}}).filter(x=>x.relevanceScore>0).sort((x,u)=>u.relevanceScore-x.relevanceScore).slice(0,n)},[i,r,n]),k=d.useCallback(async(_,m)=>{var u,h,$,D;const v=performance.now(),x=z(_);if(!S){const C={query:_,suggestions:x,latencyMs:performance.now()-v};return y(C),s==null||s(C),C}f(!0),(u=w.current)==null||u.abort(),w.current=new AbortController;try{const C=K(S),A=m?`
3294
+ `})]}):e.jsx("div",{className:`nice-a11y-ai nice-a11y-ai--disabled ${n||""}`,style:s,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}const _e=[{name:"home",category:"navigation",keywords:["home","house","start","main"],svgPath:"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"},{name:"menu",category:"navigation",keywords:["menu","hamburger","nav","bars"],svgPath:"M4 6h16M4 12h16M4 18h16"},{name:"arrow-left",category:"navigation",keywords:["back","previous","left","arrow"],svgPath:"M10 19l-7-7m0 0l7-7m-7 7h18"},{name:"arrow-right",category:"navigation",keywords:["next","forward","right","arrow"],svgPath:"M14 5l7 7m0 0l-7 7m7-7H3"},{name:"chevron-down",category:"navigation",keywords:["expand","dropdown","down","chevron"],svgPath:"M19 9l-7 7-7-7"},{name:"chevron-up",category:"navigation",keywords:["collapse","up","chevron"],svgPath:"M5 15l7-7 7 7"},{name:"plus",category:"action",keywords:["add","create","new","plus"],svgPath:"M12 4v16m8-8H4"},{name:"minus",category:"action",keywords:["remove","subtract","minus"],svgPath:"M20 12H4"},{name:"x",category:"action",keywords:["close","cancel","delete","remove","x"],svgPath:"M6 18L18 6M6 6l12 12"},{name:"check",category:"action",keywords:["done","complete","success","check","tick"],svgPath:"M5 13l4 4L19 7"},{name:"edit",category:"action",keywords:["edit","modify","pencil","write"],svgPath:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"},{name:"trash",category:"action",keywords:["delete","remove","trash","bin"],svgPath:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"},{name:"search",category:"action",keywords:["search","find","magnify","lookup"],svgPath:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"},{name:"filter",category:"action",keywords:["filter","sort","funnel"],svgPath:"M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"},{name:"download",category:"action",keywords:["download","save","export"],svgPath:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"},{name:"upload",category:"action",keywords:["upload","import","send"],svgPath:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"},{name:"refresh",category:"action",keywords:["refresh","reload","sync"],svgPath:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"},{name:"copy",category:"action",keywords:["copy","duplicate","clone"],svgPath:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"},{name:"mail",category:"communication",keywords:["email","mail","message","envelope"],svgPath:"M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"},{name:"phone",category:"communication",keywords:["phone","call","telephone","contact"],svgPath:"M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"},{name:"chat",category:"communication",keywords:["chat","message","comment","bubble"],svgPath:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"},{name:"bell",category:"notification",keywords:["notification","bell","alert","alarm"],svgPath:"M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"},{name:"file",category:"file",keywords:["file","document","page"],svgPath:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"},{name:"folder",category:"file",keywords:["folder","directory","category"],svgPath:"M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"},{name:"image",category:"image",keywords:["image","photo","picture","gallery"],svgPath:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"},{name:"video",category:"av",keywords:["video","movie","film","camera"],svgPath:"M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"},{name:"user",category:"social",keywords:["user","person","account","profile"],svgPath:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"},{name:"users",category:"social",keywords:["users","group","team","people"],svgPath:"M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"},{name:"settings",category:"action",keywords:["settings","config","gear","cog","preferences"],svgPath:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z"},{name:"calendar",category:"business",keywords:["calendar","date","schedule","event"],svgPath:"M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"},{name:"clock",category:"business",keywords:["time","clock","schedule","hour"],svgPath:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"credit-card",category:"finance",keywords:["payment","card","credit","money"],svgPath:"M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"},{name:"chart",category:"business",keywords:["chart","graph","analytics","statistics"],svgPath:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"},{name:"lock",category:"security",keywords:["lock","secure","private","password"],svgPath:"M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"},{name:"unlock",category:"security",keywords:["unlock","open","access"],svgPath:"M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"},{name:"shield",category:"security",keywords:["shield","security","protect","safe"],svgPath:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"},{name:"eye",category:"action",keywords:["view","show","visible","eye","visibility"],svgPath:"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"},{name:"eye-off",category:"action",keywords:["hide","invisible","hidden","eye-off"],svgPath:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"},{name:"info",category:"alert",keywords:["info","information","help","about"],svgPath:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"warning",category:"alert",keywords:["warning","caution","alert","attention"],svgPath:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"},{name:"error",category:"alert",keywords:["error","danger","fail","problem"],svgPath:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"success",category:"alert",keywords:["success","done","complete","check-circle"],svgPath:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"star",category:"action",keywords:["star","favorite","bookmark","rating"],svgPath:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"},{name:"heart",category:"social",keywords:["heart","love","like","favorite"],svgPath:"M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"},{name:"share",category:"social",keywords:["share","send","forward"],svgPath:"M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z"},{name:"link",category:"action",keywords:["link","url","chain","hyperlink"],svgPath:"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"},{name:"external-link",category:"action",keywords:["external","open","new-window"],svgPath:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"}];function Ta(i={}){const{config:a,defaultLibrary:t="lucide",defaultStyle:r="outline",maxSuggestions:n=10,onSuggestion:s,onError:o}=i,c=Z(),[h,p]=d.useState(!1),[m,b]=d.useState(null),w=d.useRef(null),k=a||(c==null?void 0:c.config),M=d.useCallback(S=>{const f=S.toLowerCase(),j=f.split(/\s+/);return _e.map(g=>{let x=0;return g.name===f?x+=100:g.name.includes(f)&&(x+=50),j.forEach(v=>{g.keywords.forEach(T=>{T===v?x+=30:(T.includes(v)||v.includes(T))&&(x+=15)})}),g.category===f&&(x+=20),{id:`icon_${g.name}`,name:g.name,displayName:g.name.replace(/-/g," ").replace(/\b\w/g,v=>v.toUpperCase()),category:g.category,style:r,library:t,relevanceScore:x,keywords:g.keywords,svgPath:g.svgPath}}).filter(g=>g.relevanceScore>0).sort((g,x)=>x.relevanceScore-g.relevanceScore).slice(0,n)},[t,r,n]),C=d.useCallback(async(S,f)=>{var x,v,T,I;const j=performance.now(),g=M(S);if(!k){const N={query:S,suggestions:g,latencyMs:performance.now()-j};return b(N),s==null||s(N),N}p(!0),(x=w.current)==null||x.abort(),w.current=new AbortController;try{const N=K(k),P=f?`
3280
3295
  Context:
3281
- - Component type: ${m.componentType||"any"}
3282
- - Purpose: ${m.purpose||"general"}
3283
- - Related icons: ${((h=m.relatedIcons)==null?void 0:h.join(", "))||"none"}
3284
- - Theme: ${m.theme||"light"}
3285
- - Preferred style: ${m.preferredStyle||r}
3286
- - Preferred library: ${m.preferredLibrary||i}`:"",b=(((D=($=(await C.chat({messages:[{role:"system",content:`You are an icon recommendation expert. Suggest icons based on user query.
3296
+ - Component type: ${f.componentType||"any"}
3297
+ - Purpose: ${f.purpose||"general"}
3298
+ - Related icons: ${((v=f.relatedIcons)==null?void 0:v.join(", "))||"none"}
3299
+ - Theme: ${f.theme||"light"}
3300
+ - Preferred style: ${f.preferredStyle||r}
3301
+ - Preferred library: ${f.preferredLibrary||t}`:"",F=(((I=(T=(await N.chat({messages:[{role:"system",content:`You are an icon recommendation expert. Suggest icons based on user query.
3287
3302
  Return JSON array of 5-10 icon suggestions:
3288
3303
  [{
3289
3304
  "name": "icon-name",
@@ -3294,7 +3309,7 @@ Return JSON array of 5-10 icon suggestions:
3294
3309
  "usage": "Brief usage description"
3295
3310
  }]
3296
3311
 
3297
- Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Suggest icons for: "${_}"${A}`}],temperature:.5,maxTokens:1024})).choices[0])==null?void 0:$.message)==null?void 0:D.content)||"").match(/\[[\s\S]*\]/);let P=[];if(b)try{P=JSON.parse(b[0]).map((U,q)=>({id:U.id||`ai_icon_${q}`,name:U.name||"unknown",displayName:U.displayName||U.name||"Unknown",category:U.category||"action",style:(m==null?void 0:m.preferredStyle)||r,library:(m==null?void 0:m.preferredLibrary)||i,relevanceScore:U.relevanceScore||50,keywords:U.keywords||[],usage:U.usage}))}catch{}const H=nt(x,P,n),J={query:_,suggestions:H,latencyMs:performance.now()-v};return y(J),s==null||s(J),J}catch(C){const A=C instanceof Error?C.message:"Suggestion failed",O={query:_,suggestions:x,latencyMs:performance.now()-v,error:A};return y(O),c==null||c(A),O}finally{f(!1)}},[S,i,r,n,z,s,c]),I=d.useCallback(_=>ve.filter(m=>m.category===_).map(m=>({id:`icon_${m.name}`,name:m.name,displayName:m.name.replace(/-/g," ").replace(/\b\w/g,v=>v.toUpperCase()),category:m.category,style:r,library:i,relevanceScore:100,keywords:m.keywords,svgPath:m.svgPath})),[i,r]),j=d.useMemo(()=>{const _=new Set;return ve.forEach(m=>_.add(m.category)),Array.from(_)},[]),o=d.useCallback(()=>{y(null)},[]),N=d.useCallback(()=>{var _;(_=w.current)==null||_.abort(),f(!1)},[]);return d.useEffect(()=>()=>{var _;(_=w.current)==null||_.abort()},[]),{suggestIcons:k,localSearch:z,getByCategory:I,categories:j,loading:p,lastResult:g,clearResults:o,abort:N,isConfigured:!!S}}function nt(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 st({config:t,defaultLibrary:a="lucide",defaultStyle:i="outline",maxSuggestions:r=10,onSelect:n,showCategories:s=!0,showPreview:c=!0,className:l,style:p}){const[f,g]=d.useState(""),[y,w]=d.useState(null),[S,z]=d.useState(null),{suggestIcons:k,getByCategory:I,categories:j,loading:o,lastResult:N}=Na({config:t,defaultLibrary:a,defaultStyle:i,maxSuggestions:r}),_=async()=>{f.trim()&&(w(null),await k(f))},m=h=>{h.key==="Enter"&&_()},v=h=>{y===h?w(null):(w(h),g(""))},x=h=>{z(h),n==null||n(h)},u=y?I(y):(N==null?void 0:N.suggestions)||[];return e.jsxs("div",{className:`nice-icon-ai ${l||""}`,style:p,children:[e.jsxs("div",{className:"nice-icon-ai__search",children:[e.jsx("input",{type:"text",value:f,onChange:h=>g(h.target.value),onKeyDown:m,placeholder:"Search icons... (e.g., 'save', 'notification', 'user profile')",className:"nice-icon-ai__input",disabled:o}),e.jsx("button",{type:"button",onClick:_,className:"nice-icon-ai__search-btn",disabled:o||!f.trim(),children:o?e.jsx("span",{className:"nice-icon-ai__spinner"}):e.jsx(L.NiceIcon,{name:"search",size:16})})]}),s&&e.jsx("div",{className:"nice-icon-ai__categories",children:j.map(h=>e.jsx("button",{type:"button",className:`nice-icon-ai__category ${y===h?"nice-icon-ai__category--selected":""}`,onClick:()=>v(h),children:h},h))}),u.length>0&&e.jsx("div",{className:"nice-icon-ai__results",children:u.map(h=>e.jsxs("button",{type:"button",className:`nice-icon-ai__icon ${(S==null?void 0:S.id)===h.id?"nice-icon-ai__icon--selected":""}`,onClick:()=>x(h),title:h.displayName,children:[e.jsx(Je,{icon:h}),e.jsx("span",{className:"nice-icon-ai__icon-name",children:h.displayName})]},h.id))}),c&&S&&e.jsxs("div",{className:"nice-icon-ai__preview",children:[e.jsx("div",{className:"nice-icon-ai__preview-icon",children:e.jsx(Je,{icon:S,size:64})}),e.jsxs("div",{className:"nice-icon-ai__preview-info",children:[e.jsx("div",{className:"nice-icon-ai__preview-name",children:S.displayName}),e.jsxs("div",{className:"nice-icon-ai__preview-details",children:[e.jsxs("span",{children:["Category: ",S.category]}),e.jsxs("span",{children:["Library: ",S.library]})]}),e.jsx("div",{className:"nice-icon-ai__preview-keywords",children:S.keywords.map(h=>e.jsx("span",{className:"nice-icon-ai__keyword",children:h},h))}),S.usage&&e.jsx("div",{className:"nice-icon-ai__preview-usage",children:S.usage}),e.jsxs("div",{className:"nice-icon-ai__preview-actions",children:[e.jsxs("button",{type:"button",onClick:()=>n==null?void 0:n(S),children:[e.jsx(L.NiceIcon,{name:"check",size:14})," Use Icon"]}),e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(S.name)},children:[e.jsx(L.NiceIcon,{name:"clipboard",size:14})," Copy Name"]}),S.svgPath&&e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(`<svg viewBox="0 0 24 24"><path d="${S.svgPath}" /></svg>`)},children:[e.jsx(L.NiceIcon,{name:"clipboard",size:14})," Copy SVG"]})]})]})]}),e.jsx("style",{children:`
3312
+ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Suggest icons for: "${S}"${P}`}],temperature:.5,maxTokens:1024})).choices[0])==null?void 0:T.message)==null?void 0:I.content)||"").match(/\[[\s\S]*\]/);let U=[];if(F)try{U=JSON.parse(F[0]).map((R,B)=>({id:R.id||`ai_icon_${B}`,name:R.name||"unknown",displayName:R.displayName||R.name||"Unknown",category:R.category||"action",style:(f==null?void 0:f.preferredStyle)||r,library:(f==null?void 0:f.preferredLibrary)||t,relevanceScore:R.relevanceScore||50,keywords:R.keywords||[],usage:R.usage}))}catch{}const W=yi(g,U,n),Y={query:S,suggestions:W,latencyMs:performance.now()-j};return b(Y),s==null||s(Y),Y}catch(N){const P=N instanceof Error?N.message:"Suggestion failed",$={query:S,suggestions:g,latencyMs:performance.now()-j,error:P};return b($),o==null||o(P),$}finally{p(!1)}},[k,t,r,n,M,s,o]),O=d.useCallback(S=>_e.filter(f=>f.category===S).map(f=>({id:`icon_${f.name}`,name:f.name,displayName:f.name.replace(/-/g," ").replace(/\b\w/g,j=>j.toUpperCase()),category:f.category,style:r,library:t,relevanceScore:100,keywords:f.keywords,svgPath:f.svgPath})),[t,r]),_=d.useMemo(()=>{const S=new Set;return _e.forEach(f=>S.add(f.category)),Array.from(S)},[]),l=d.useCallback(()=>{b(null)},[]),y=d.useCallback(()=>{var S;(S=w.current)==null||S.abort(),p(!1)},[]);return d.useEffect(()=>()=>{var S;(S=w.current)==null||S.abort()},[]),{suggestIcons:C,localSearch:M,getByCategory:O,categories:_,loading:h,lastResult:m,clearResults:l,abort:y,isConfigured:!!k}}function yi(i,a,t){const r=new Set,n=[];for(const s of i)r.has(s.name)||(r.add(s.name),n.push(s));for(const s of a)!r.has(s.name)&&n.length<t&&(r.add(s.name),n.push(s));return n.slice(0,t)}function vi({config:i,defaultLibrary:a="lucide",defaultStyle:t="outline",maxSuggestions:r=10,onSelect:n,showCategories:s=!0,showPreview:o=!0,className:c,style:h}){const[p,m]=d.useState(""),[b,w]=d.useState(null),[k,M]=d.useState(null),{suggestIcons:C,getByCategory:O,categories:_,loading:l,lastResult:y}=Ta({config:i,defaultLibrary:a,defaultStyle:t,maxSuggestions:r}),S=async()=>{p.trim()&&(w(null),await C(p))},f=v=>{v.key==="Enter"&&S()},j=v=>{b===v?w(null):(w(v),m(""))},g=v=>{M(v),n==null||n(v)},x=b?O(b):(y==null?void 0:y.suggestions)||[];return e.jsxs("div",{className:`nice-icon-ai ${c||""}`,style:h,children:[e.jsxs("div",{className:"nice-icon-ai__search",children:[e.jsx("input",{type:"text",value:p,onChange:v=>m(v.target.value),onKeyDown:f,placeholder:"Search icons... (e.g., 'save', 'notification', 'user profile')",className:"nice-icon-ai__input",disabled:l}),e.jsx("button",{type:"button",onClick:S,className:"nice-icon-ai__search-btn",disabled:l||!p.trim(),children:l?e.jsx("span",{className:"nice-icon-ai__spinner"}):e.jsx(A.NiceIcon,{name:"search",size:16})})]}),s&&e.jsx("div",{className:"nice-icon-ai__categories",children:_.map(v=>e.jsx("button",{type:"button",className:`nice-icon-ai__category ${b===v?"nice-icon-ai__category--selected":""}`,onClick:()=>j(v),children:v},v))}),x.length>0&&e.jsx("div",{className:"nice-icon-ai__results",children:x.map(v=>e.jsxs("button",{type:"button",className:`nice-icon-ai__icon ${(k==null?void 0:k.id)===v.id?"nice-icon-ai__icon--selected":""}`,onClick:()=>g(v),title:v.displayName,children:[e.jsx(Ue,{icon:v}),e.jsx("span",{className:"nice-icon-ai__icon-name",children:v.displayName})]},v.id))}),o&&k&&e.jsxs("div",{className:"nice-icon-ai__preview",children:[e.jsx("div",{className:"nice-icon-ai__preview-icon",children:e.jsx(Ue,{icon:k,size:64})}),e.jsxs("div",{className:"nice-icon-ai__preview-info",children:[e.jsx("div",{className:"nice-icon-ai__preview-name",children:k.displayName}),e.jsxs("div",{className:"nice-icon-ai__preview-details",children:[e.jsxs("span",{children:["Category: ",k.category]}),e.jsxs("span",{children:["Library: ",k.library]})]}),e.jsx("div",{className:"nice-icon-ai__preview-keywords",children:k.keywords.map(v=>e.jsx("span",{className:"nice-icon-ai__keyword",children:v},v))}),k.usage&&e.jsx("div",{className:"nice-icon-ai__preview-usage",children:k.usage}),e.jsxs("div",{className:"nice-icon-ai__preview-actions",children:[e.jsxs("button",{type:"button",onClick:()=>n==null?void 0:n(k),children:[e.jsx(A.NiceIcon,{name:"check",size:14})," Use Icon"]}),e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(k.name)},children:[e.jsx(A.NiceIcon,{name:"clipboard",size:14})," Copy Name"]}),k.svgPath&&e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(`<svg viewBox="0 0 24 24"><path d="${k.svgPath}" /></svg>`)},children:[e.jsx(A.NiceIcon,{name:"clipboard",size:14})," Copy SVG"]})]})]})]}),e.jsx("style",{children:`
3298
3313
  .nice-icon-ai {
3299
3314
  font-family: var(--nice-font-family, system-ui, sans-serif);
3300
3315
  }
@@ -3495,4 +3510,4 @@ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Sugges
3495
3510
  color: white;
3496
3511
  border: none;
3497
3512
  }
3498
- `})]})}function Je({icon:t,size:a=32}){return t.svgPath?e.jsx("svg",{viewBox:"0 0 24 24",width:a,height:a,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:t.svgPath})}):e.jsx("div",{style:{width:a,height:a,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-bg-secondary, #f0f0f0)",borderRadius:6,fontSize:a*.5,fontWeight:600,color:"var(--nice-text-secondary, #666)"},children:t.name.charAt(0).toUpperCase()})}exports.ACCESSIBILITY_CHECKER_TEMPLATE=je;exports.AnthropicProvider=na;exports.AzureOpenAIProvider=sa;exports.CHART_CONFIG_TEMPLATE=le;exports.CODE_COMPLETION_TEMPLATE=de;exports.CostTracker=da;exports.DATA_GRID_FILTER_TEMPLATE=se;exports.DATA_GRID_SORT_TEMPLATE=ce;exports.FORM_BUILDER_TEMPLATE=oe;exports.GroqProvider=oa;exports.InMemoryCostStorage=Me;exports.LocalStorageCostStorage=la;exports.NiceAIHintBubble=Se;exports.NiceAIProvider=Sa;exports.NiceAccessibilityAI=rt;exports.NiceChartAI=ji;exports.NiceCodeEditorAI=Ri;exports.NiceDataGridAI=xi;exports.NiceDataLabeler=si;exports.NiceFormBuilderAI=yi;exports.NiceIconSuggestorAI=st;exports.NiceLayoutAI=Qi;exports.NiceMLStudio=ri;exports.NiceModelInference=oi;exports.NiceReportBuilderAI=Ui;exports.NiceThemeGeneratorAI=Vi;exports.NiceWorkflowDesignerAI=Pi;exports.OllamaProvider=ca;exports.OpenAIProvider=_e;exports.PROMPT_TEMPLATES=ge;exports.REPORT_LAYOUT_TEMPLATE=pe;exports.RateLimiter=Ue;exports.ResilientLLMClient=ua;exports.SUMMARIZE_DATA_TEMPLATE=Ne;exports.THEME_GENERATOR_TEMPLATE=we;exports.TRANSLATION_TEMPLATE=ke;exports.WORKFLOW_GENERATOR_TEMPLATE=ue;exports.build3DSceneContext=Ze;exports.buildAudioContext=Xe;exports.buildChartContext=za;exports.buildCodeEditorContext=Ke;exports.buildColorPickerContext=ze;exports.buildDataGridContext=Ia;exports.buildDatePickerContext=Ie;exports.buildDiagramLayoutContext=ia;exports.buildFormFillContext=Ge;exports.buildGameEngineContext=aa;exports.buildGraphicsContext=Qe;exports.buildHtmlEditorContext=Ye;exports.buildIconSearchContext=ea;exports.buildNumberInputContext=Ae;exports.buildPresentationGenerateContext=ta;exports.buildSelectContext=Re;exports.buildSlideDesignContext=ra;exports.buildTextInputContext=Te;exports.buildValidationContext=Ve;exports.colorControlContext=ai;exports.compileTemplate=ie;exports.createLLMProvider=ae;exports.createProviderFromConfig=K;exports.createResilientClient=pa;exports.createResilientClientWithDefaults=hi;exports.dateControlContext=ei;exports.getTemplate=li;exports.getTemplatesByCategory=di;exports.listTemplates=ui;exports.numberControlContext=Za;exports.parseJSONResponse=We;exports.parseSSEStream=He;exports.selectControlContext=Qa;exports.textControlContext=Xa;exports.useAI3DHint=Ua;exports.useAIAudioHint=Ja;exports.useAICodeHint=Ba;exports.useAIColorHint=Oa;exports.useAIContext=Z;exports.useAIDateHint=$a;exports.useAIDiagramLayout=Ga;exports.useAIFormFill=Da;exports.useAIGraphicsHint=qa;exports.useAIHtmlHint=Fa;exports.useAIIconSearch=Ha;exports.useAINpcHint=Wa;exports.useAINumberHint=La;exports.useAIPresentationGenerate=Va;exports.useAISelectHint=Pa;exports.useAISlideDesign=Ka;exports.useAITextHint=Ma;exports.useAIValidation=Ea;exports.useAccessibilityAI=ka;exports.useChartAI=ga;exports.useCodeEditorAI=fa;exports.useCostTracker=pi;exports.useDataGridAI=ma;exports.useFormBuilderAI=ha;exports.useIconSuggestorAI=Na;exports.useLayoutAI=wa;exports.useNiceAIHint=X;exports.useReportBuilderAI=ya;exports.useThemeGeneratorAI=_a;exports.useWorkflowDesignerAI=xa;exports.withAIHint=Ya;
3513
+ `})]})}function Ue({icon:i,size:a=32}){return i.svgPath?e.jsx("svg",{viewBox:"0 0 24 24",width:a,height:a,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:i.svgPath})}):e.jsx("div",{style:{width:a,height:a,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-bg-secondary, #f0f0f0)",borderRadius:6,fontSize:a*.5,fontWeight:600,color:"var(--nice-text-secondary, #666)"},children:i.name.charAt(0).toUpperCase()})}exports.ACCESSIBILITY_CHECKER_TEMPLATE=Ne;exports.AnthropicProvider=oa;exports.AzureOpenAIProvider=la;exports.CHART_CONFIG_TEMPLATE=de;exports.CODE_COMPLETION_TEMPLATE=ue;exports.CostTracker=ma;exports.DATA_GRID_FILTER_TEMPLATE=ce;exports.DATA_GRID_SORT_TEMPLATE=oe;exports.FORM_BUILDER_TEMPLATE=le;exports.GroqProvider=ua;exports.InMemoryCostStorage=$e;exports.LocalStorageCostStorage=pa;exports.NiceAIHintBubble=Ie;exports.NiceAIProvider=Ia;exports.NiceAccessibilityAI=bi;exports.NiceChartAI=Ot;exports.NiceCodeEditorAI=Ht;exports.NiceDataGridAI=It;exports.NiceDataLabeler=yt;exports.NiceFormBuilderAI=zt;exports.NiceIconSuggestorAI=vi;exports.NiceLayoutAI=mi;exports.NiceMLStudio=ft;exports.NiceModelInference=_t;exports.NiceReportBuilderAI=ii;exports.NiceThemeGeneratorAI=oi;exports.NiceWorkflowDesignerAI=Kt;exports.OllamaProvider=da;exports.OpenAIProvider=je;exports.PROMPT_TEMPLATES=fe;exports.REPORT_LAYOUT_TEMPLATE=me;exports.RateLimiter=Ge;exports.ResilientLLMClient=ga;exports.SUMMARIZE_DATA_TEMPLATE=Ce;exports.THEME_GENERATOR_TEMPLATE=ke;exports.TRANSLATION_TEMPLATE=Se;exports.WORKFLOW_GENERATOR_TEMPLATE=pe;exports.build3DSceneContext=aa;exports.buildAudioContext=ea;exports.buildChartContext=Pa;exports.buildCodeEditorContext=Qe;exports.buildColorPickerContext=Pe;exports.buildDataGridContext=La;exports.buildDatePickerContext=Le;exports.buildDiagramLayoutContext=na;exports.buildFormFillContext=Ye;exports.buildGameEngineContext=ra;exports.buildGraphicsContext=ta;exports.buildHtmlEditorContext=Ze;exports.buildIconSearchContext=ia;exports.buildNumberInputContext=ze;exports.buildPresentationGenerateContext=sa;exports.buildSelectContext=Me;exports.buildSlideDesignContext=ca;exports.buildTextInputContext=Re;exports.buildValidationContext=Xe;exports.colorControlContext=rt;exports.compileTemplate=ae;exports.createLLMProvider=ee;exports.createProviderFromConfig=K;exports.createResilientClient=ha;exports.createResilientClientWithDefaults=Ct;exports.dateControlContext=it;exports.getTemplate=wt;exports.getTemplatesByCategory=jt;exports.listTemplates=kt;exports.numberControlContext=at;exports.parseJSONResponse=Ke;exports.parseSSEStream=Ve;exports.selectControlContext=tt;exports.textControlContext=et;exports.useAI3DHint=Ga;exports.useAIAudioHint=Ua;exports.useAICodeHint=Ja;exports.useAIColorHint=Ba;exports.useAIContext=Z;exports.useAIDateHint=Da;exports.useAIDiagramLayout=Ya;exports.useAIFormFill=qa;exports.useAIGraphicsHint=Wa;exports.useAIHtmlHint=Ha;exports.useAIIconSearch=Va;exports.useAINpcHint=Ka;exports.useAINumberHint=Oa;exports.useAIPresentationGenerate=Xa;exports.useAISelectHint=Ea;exports.useAISlideDesign=Qa;exports.useAITextHint=$a;exports.useAIValidation=Fa;exports.useAccessibilityAI=Ca;exports.useChartAI=ba;exports.useCodeEditorAI=ya;exports.useCostTracker=Nt;exports.useDataGridAI=fa;exports.useFormBuilderAI=xa;exports.useIconSuggestorAI=Ta;exports.useLayoutAI=Na;exports.useNiceAIHint=X;exports.useReportBuilderAI=wa;exports.useThemeGeneratorAI=ka;exports.useWorkflowDesignerAI=va;exports.withAIHint=Za;